1 Python Tutorial
This tutorial introduces Python programming, covering basic concepts with examples to illustrate key points. We will start by using Python as a calculator, then explore variables, functions, and control flow.
1.1 Requirements
To follow this tutorial, you must have Python (version 3.10 or later) installed on your computer. Python is available for Windows, macOS, and Linux. Additionally, ensure you have a text editor or an Integrated Development Environment (IDE) to write Python code. We recommend Positron, a user-friendly IDE with a built-in terminal for running Python scripts, though other editors like VS Code or PyCharm are also suitable.
1.2 Basic Syntax
Python uses indentation (typically four spaces) to define code blocks. A colon (:) introduces a block, and statements within the block must be indented consistently. Python is case-sensitive, so Variable and variable are distinct identifiers. Statements typically end with a newline, but you can use a backslash (\) to continue a statement across multiple lines.
total = 1 + 2 + 3 + \
4 + 5
print(total) # Output: 15Basic syntax rules:
- Comments start with
#and extend to the end of the line. - Strings can be enclosed in single quotes (
'), double quotes ("), or triple quotes ('''or""") for multi-line strings. - Python is case-sensitive, so
Variableandvariableare different identifiers.
1.3 The print() Function
The print() function displays output in Python.
name = "Rudolf Diesel"
year = 1858
print(f"{name} was born in {year}.")Output: Rudolf Diesel was born in 1858.
1.4 Formatting in print()
The following table illustrates common f-string formatting options for the print() function:
| Format | Code | Example | Output |
|---|---|---|---|
| Round to 2 decimals | f"{x:.2f}" |
print(f"{3.14159:.2f}") |
3.14 |
| Round to whole number | f"{x:.0f}" |
print(f"{3.9:.0f}") |
4 |
| Thousands separator | f"{x:,.2f}" |
print(f"{1234567.89:,.2f}") |
1,234,567.89 |
| Percentage | f"{x:.1%}" |
print(f"{0.756:.1%}") |
75.6% |
| Currency style | f"${x:,.2f}" |
print(f"${1234.5:,.2f}") |
$1,234.50 |
Note: The currency symbol (e.g., $) can be modified for other currencies (e.g., €, £) based on the desired locale.
1.5 Variables and Data Types
Variables store data and are assigned values using the = operator.
x = 10
y = 3.14
name = "Rudolph"Python has several built-in data types, including:
- Integers (
int): Whole numbers, e.g.,10,-5 - Floating-point numbers (
float): Decimal numbers, e.g.,3.14,-0.001 - Strings (
str): Text, e.g.,"Hello",'World' - Booleans (
bool):TrueorFalse
1.5.1 Arithmetic Operations
a = 10
b = 3
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a / b) # Division: 3.3333...
print(a // b) # Integer Division: 3
print(a ** b) # Exponentiation: 10001.5.2 String Operations
first_name = "Rudolph"
last_name = "Diesel"
full_name = first_name + " " + last_name # Concatenation using +
print(full_name) # Output: Rudolph Diesel
print(f"{first_name} {last_name}") # Concatenation using f-string
print(full_name * 2) # Repetition: Rudolph DieselRudolph Diesel
print(full_name.upper()) # Uppercase: RUDOLPH DIESELNote: String repetition (*) concatenates the string multiple times without spaces. For example, full_name * 2 produces Rudolph DieselRudolph Diesel.
1.6 Python as a Calculator in Interactive Mode
Python’s interactive mode allows you to enter commands and see results immediately, ideal for quick calculations. To start, open a terminal (on macOS, Linux, or Windows) and type:
python3 # Use 'python' on Windows if 'python3' is not recognizedYou should see the Python prompt:
>>>Enter expressions and press Enter to see results:
2 + 3 # Output: 5
7 - 4 # Output: 3
6 * 9 # Output: 54
8 / 2 # Output: 4.0
8 // 2 # Output: 4
2 ** 3 # Output: 81.6.1 Parentheses for Grouping
(2 + 3) * 4 # Output: 20
2 + (3 * 4) # Output: 141.6.2 Variables
x = 10
y = 3
x / y # Output: 3.33333333333333351.6.3 Exiting Interactive Mode
To exit, type:
exit()Alternatively, use: - Ctrl+D (macOS/Linux) - Ctrl+Z then Enter (Windows)
1.7 Control Flow
Control flow statements direct the execution of code based on conditions.
1.7.1 Conditional Statements
Conditional statements allow you to execute different code blocks based on specific conditions. Python provides three keywords for this purpose:
if: Evaluates a condition and executes its code block if the condition isTrue.elif: Short for “else if,” it checks an additional condition if the precedingiforelifconditions areFalse. You can use multipleelifstatements to test multiple conditions sequentially, and Python will execute the firstTruecondition’s block, skipping the rest.else: Executes a code block if none of the precedingiforelifconditions areTrue. It serves as a fallback and does not require a condition.
The following example uses age to categorize a person as a Minor, Adult, or Senior, demonstrating how if, elif, and else work together.
# Categorize a person based on their age
age = 19
if age < 18:
print("Minor")
elif age <= 64:
print("Adult")
else:
print("Senior")Output: Adult
1.7.2 For Loop
A for loop iterates over a sequence (e.g., list or string).
components = ["piston", "liner", "connecting rod"]
for component in components:
print(component)Output:
piston
liner
connecting rod
1.7.3 While Loop
A while loop executes as long as a condition is true. Ensure the condition eventually becomes false to avoid infinite loops.
count = 0
while count <= 5:
print(count)
count += 1Output:
0
1
2
3
4
5
1.8 Functions
1.8.1 The def Keyword
Functions are reusable code blocks defined using the def keyword. They can include default parameters for optional arguments.
def add(a, b=0):
return a + b
print(add(5)) # Output: 5
print(add(5, 3)) # Output: 8
def multiply(*args):
result = 1
for num in args:
result *= num
return result
print(multiply(2, 3, 4)) # Output: 241.8.2 The lambda Keyword
The lambda keyword creates anonymous functions for short, one-off operations, often used in functional programming.
celsius_to_fahrenheit = lambda c: (c * 9 / 5) + 32
print(celsius_to_fahrenheit(25)) # Output: 77.01.9 The math Module
The math module provides mathematical functions and constants.
import math
print(math.sqrt(16)) # Output: 4.0
print(math.pi) # Output: 3.141592653589793import math
angle = math.pi / 4 # 45 degrees in radians
print(math.sin(angle)) # Output: 0.7071067811865475 (approximately √2/2)
print(math.cos(angle)) # Output: 0.7071067811865476 (approximately √2/2)
print(math.tan(angle)) # Output: 1.0Note: Floating-point arithmetic may result in small precision differences, as seen in the sin and cos outputs.
import math
print(math.log(10)) # Natural logarithm of 10: 2.302585092994046
print(math.log(100, 10)) # Logarithm of 100 with base 10: 2.01.9.1 Converting Between Radians and Degrees
The math module provides math.radians() to convert degrees to radians and math.degrees() to convert radians to degrees, which is useful for trigonometric calculations.
import math
degrees = 180
radians = math.radians(degrees)
print(f"{degrees} degrees is {radians:.3f} radians") # Output: 180 degrees is 3.142 radians
radians = math.pi / 2
degrees = math.degrees(radians)
print(f"{radians:.3f} radians is {degrees:.1f} degrees") # Output: 1.571 radians is 90.0 degrees1.10 Writing Python Scripts
Write Python code in a .py file and run it as a script. Create a file named script.py:
# script.py
import math
print("Square root of 16 is:", math.sqrt(16))
print("Value of pi is:", math.pi)
print("Sine of 90 degrees is:", math.sin(math.pi / 2))
print("Natural logarithm of 10 is:", math.log(10))
print("Logarithm of 100 with base 10 is:", math.log(100, 10))To run the script, open a terminal, navigate to the directory containing script.py using the cd command (e.g., cd /path/to/directory), and type:
python3 script.py # or python script.py on WindowsOutput:
Square root of 16 is: 4.0
Value of pi is: 3.141592653589793
Sine of 90 degrees is: 1.0
Natural logarithm of 10 is: 2.302585092994046
Logarithm of 100 with base 10 is: 2.0
1.11 Summary
This tutorial covered Python basics, including syntax, variables, data types, operations, control flow, and functions. Python’s rich ecosystem includes libraries like:
- NumPy: For numerical computations and array manipulations.
- Matplotlib: For data visualization and plotting.
- Pandas: For data manipulation and analysis with tabular data structures.
- Pint: For handling physical quantities and performing unit conversions.
You can explore these libraries to enhance your Python programming skills further. For example installing them can be done using pip:
pip install numpy matplotlib pandas pintpip is Python’s package manager for installing and managing additional libraries.