Introduction to Python
Python is a high-level, general-purpose programming language known for its simplicity, readability, and versatility. It's widely used in various fields, including web development, data science, scientific computing, and automation. Python's clean syntax and emphasis on readability make it a great choice for both beginners and experienced programmers. Its vast ecosystem of libraries and frameworks provides powerful tools for solving a wide range of problems. This unit covers the basics of Python in preparation for the more complex programs we will be creating in the course.
Hello World
The "Hello World" program is a simple, universally recognized program used to test Integrated Development Environments (IDEs). It serves as a fundamental test case to ensure that an IDE is functioning correctly and is ready for more complex programming tasks.
print("Hello, World!")
What does it test?
- Basic Functionality: It's a minimal program that involves input, processing, and output. If the IDE can successfully execute this program, it's a good indication that the core functionalities of the environment are working correctly.
- Syntax and Compiler Compatibility: The "Hello World" program uses basic programming constructs like variables, data types, and output statements. If the IDE can compile and run this program without errors, it suggests that the IDE is compatible with the chosen programming language's syntax and compiler.
- Debugging and Troubleshooting: If the "Hello World" program doesn't run as expected, it can help identify and troubleshoot issues with the IDE's configuration, settings, or the installation of necessary tools.
- Learning and Familiarization: For beginners, writing and running a "Hello World" program can be a helpful introduction to the IDE's interface, features, and workflow.
- Benchmarking and Performance: While not a rigorous benchmark, comparing the execution time of a "Hello World" program in different IDEs can provide a basic sense of performance differences.
Variables
Variables in Python are like containers that store data. They are named labels that refer to values. You can assign different types of values to variables, such as numbers (integers, floats), text (strings), or even more complex data structures like lists, dictionaries, and tuples.
Key Points:
- Dynamic Typing: Python is dynamically typed, meaning you don't need to specify the data type of a variable when you declare it. The type is determined at runtime based on the value assigned.
- Case-Sensitive: Variable names are case-sensitive.
x
andX
are considered different variables. - Naming Conventions: Variable names should be descriptive and follow Python's style guidelines (e.g., using lowercase letters and underscores to separate words).
## VARIABLES EXAMPLE ##
my_age = 13 # Assigns the integer 13 to the variable named age
my_weight = 123.4 # Assigns the float 123.4 to the variable named my_weight
fav_band = "Bad Religion" # Assigns the string "The Descendents" to the variable named fav_band
wears_glasses = True # Assigns the boolean True to the variable named wears_glasses
User Input
In Python, user input refers to the ability to capture data entered by the user during program execution.
This is typically achieved using the built-in input()
function.
Key Points:
- Data Type: By default, the
input()
function returns a string. If you need to convert the input to a different data type (e.g., integer or float), you can use functions likeint()
orfloat()
. - Error Handling: It's important to handle potential errors that might occur during input. For example, if the user enters a non-numeric value when you expect an integer, you can use a
try-except
block to catch the error and provide appropriate feedback. - Custom Prompts: You can customize the prompt message displayed to the user by passing a string argument to the
input()
function.
## USER INPUT EXAMPLE ##
name = input("Enter your name: ")
print("Hello, " + name + "!")
## USER INPUT EXAMPLE WITH ERROR HANDLING ##
while True:
try:
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative")
break
except ValueError:
print("Invalid age. Please enter a positive number.")
print("You are", age, "years old.")
By understanding user input in Python, you can create interactive programs that respond to user actions and gather data for further processing.
Basic Math
Python offers a wide range of mathematical operations, including basic arithmetic, trigonometric functions,
logarithmic functions, and more. The math done in Python, like all programming languages, follow the Order
of Operations. Most arithmetic operations can be done by using the operators on the keyboard, but the more
advanced functions require importing the math
library.
Arithmetic Operations
- Addition:
+
- Subtraction:
-
- Multiplication:
*
- Division:
/
- Floor Division:
//
(returns the integer part of the division) - Modulus:
%
(returns the remainder of the division) - Exponentiation:
**
result = 2 + 3 * 4
print(result)
14
Trignometric Functions
- Sine:
math.sin(x)
- Cosine:
math.cos(x)
- Tangent:
math.tan(x)
- Arcsine:
math.asin(x)
- Arccosine:
math.acos(x)
- Arctangent:
math.sin(x)
import math
angle = math.pi / 4
sine = math.sin(angle)
cosine = math.cos(angle)
print(sine, cosine)
0.7071067811865476 0.7071067811865476
Logarithmic Operations
- Natural Logarithm:
math.log(x)
- Base-10 Logarithm:
math.log10(x)
import math
number = 100
natural_log = math.log(number)
base_10_log = math.log10(number)
print(natural_log, base_10_log)
4.605170185988092 2.0
Beyond the standard math
module, Python offers a variety of third-party libraries that provide advanced
mathematical functionalities. Below are a few of the more popular general purpose libraries, but their are numerous
others you can find with a quick search on pypi.org.
- NumPy: The fundamental package for scientific computing with Python. It provides high-performance multidimensional arrays and matrices, along with a vast collection of mathematical functions.
- SciPy: Built on top of NumPy, SciPy offers a wide range of algorithms for scientific and technical computing, including optimization, integration, interpolation, and linear algebra.
- SymPy: A Python library for symbolic mathematics, enabling symbolic computations, equation solving, and calculus.
- Pandas: Designed for data manipulation and analysis, Pandas provides data structures like DataFrames and Series, which are essential for working with structured data.