Cheatsheet
Programming with Python
Lecture I
Python Basics
- Python is an interpreted language - code is executed line by line
- Comments start with
#
- Code blocks are defined by indentation
Variables
- Created using assignment operator
=
- Must start with letter or underscore
- Case sensitive
- Cannot use reserved words
Data Types
- Strings (str)
- Enclosed in quotes:
"Hello"
or'Hello'
- F-strings:
f"Value is {variable}"
- Format:
f"{variable:<width>.<precision>f}"
- Enclosed in quotes:
- Numbers
- Integers (int):
1
,-3
,0
- Floats:
-4.78
,0.1
,1.23e2
- Integers (int):
- Booleans (bool)
True
orFalse
Basic Operators
# Arithmetic
= 1 + 2 # 3
addition = 1 - 2 # -1
subtraction = 3 * 4 # 12
multiplication = 7 / 4 # 1.75
division = 7 // 4 # 1
floor_division = 9 ** 0.5 # 3.0
exponentiation = 10 % 3 # 1 modulo
Common Functions
# Input/Output
print("Hello") # Display output
= input("Enter name: ") # Get user input
name
# Type Conversion
= int("123") # String to integer
int_val = float("12.34") # String to float
float_val = str(123) # Number to string
str_val
# Other
round(3.14159, 2) # Round to 2 decimals
len("Hello") # Get length
type(variable) # Get type of variable
Best Practices
- Use meaningful variable names
- Add comments to explain complex code
- Follow Python’s naming conventions
- Use f-strings for string formatting
- Be consistent with quote usage (
"
or'
)
Lecture II
String Methods
= "Hello, World!"
text # Convert to uppercase: "HELLO, WORLD!"
text.upper() # Convert to lowercase: "hello, world!"
text.lower() # Title case: "Hello, World!"
text.title() # Remove leading/trailing whitespace
text.strip() "Hello", "Hi") # Replace text: "Hi, World!"
text.replace("World") # Find substring index: 7
text.find("l") # Count occurrences: 3 text.count(
Indexing and Slicing
= "Hello, World!"
text 0] # First character: "H"
text[-1] # Last character: "!"
text[7:12] # Slice: "World"
text[2] # Every second character: "Hlo ol!"
text[::-1] # Reverse string: "!dlroW ,olleH" text[::
Comparison Operators
==
Equal to!=
Not equal to<
Less than>
Greater than<=
Less than or equal to>=
Greater than or equal to
Logical Operators
# and: Both conditions must be True
> 0 and x < 10 # True if x is between 0 and 10
x
# or: At least one condition must be True
< 0 or x > 10 # True if x is outside 0-10
x
# not: Inverts the condition
not x == 10 # True if x is not 10
Membership Operators
"a" in "apple" # True
"z" not in "apple" # True
Control Structures
If Statements
if condition:
# code if condition is True
elif other_condition:
# code if other_condition is True
else:
# code if all conditions are False
For Loops
# Loop with range
for i in range(5): # 0 to 4
print(i)
# Loop with range and step
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
# Loop through string
for char in "Hello":
print(char)
While Loops
# Basic while loop
= 0
i while i < 5:
print(i)
+= 1
i
# While loop with break
while True:
if condition:
break # Exit loop
Best Practices
- Use clear and descriptive variable names
- Maintain consistent indentation (4 spaces)
- Use comments to explain complex logic
- Avoid infinite loops
- Keep code blocks focused and manageable
Lecture III
Functions
Basic Function Syntax
def function_name(parameter1, parameter2):
"""Docstring explaining what the function does"""
# Function body
return result
Function Parameters
# No parameters
def greet():
print("Hello!")
# Multiple parameters
def greet(name, age):
print(f"Hello {name}, you are {age} years old")
# Default parameters
def greet(name="Stranger"):
print(f"Hello {name}")
# Keyword arguments
="Alice") # Calling with named parameter greet(name
Return Values
# Return single value
def multiply(a, b):
return a * b
# Return None (implicit)
def greet(name):
print(f"Hello {name}")
# No return statement = returns None
# Multiple return points
def check_number(n):
if n > 0:
return "positive"
elif n < 0:
return "negative"
return None # if n == 0
Function Scope
# Global scope
= 10
global_var
def function():
# Local scope
= 20
local_var print(global_var) # Can access global
# Modify global variable
global global_var
= 30 global_var
Classes
Basic Class Syntax
class ClassName:
# Class attribute
= value
class_attribute
# Constructor
def __init__(self, parameter):
# Instance attribute
self.instance_attribute = parameter
# Method
def method_name(self):
return self.instance_attribute
Class Example
class Student:
# Class attribute
= "Python University"
school
def __init__(self, name):
# Instance attribute
self.name = name
def introduce(self):
return f"Hi, I'm {self.name}"
# Create instance
= Student("Alice")
student print(student.introduce()) # "Hi, I'm Alice"
Inheritance
class Parent:
def method(self):
print("Parent method")
class Child(Parent):
def method(self):
print("Child method")
Best Practices
- Use descriptive function and class names
- Write clear docstrings
- Keep functions focused on a single task
- Use meaningful parameter names
- Follow Python naming conventions:
- function_name (snake_case)
- ClassName (PascalCase)
- variable_name (snake_case)
Lecture IV
Tuples
# Creating tuples
= (1, 2, 3) # Using parentheses
my_tuple = 1, 2, 3 # Using just commas
my_tuple = tuple([1, 2, 3]) # Using tuple() function
my_tuple
# Tuple operations
0] # Accessing elements
my_tuple[1:3] # Slicing
my_tuple[+ (4, 5, 6) # Concatenation
my_tuple * 2 # Repetition
my_tuple
# Tuple methods
2) # Count occurrences
my_tuple.count(3) # Find index of element
my_tuple.index(
# Tuple unpacking
= my_tuple # Basic unpacking
name, age, city *rest = my_tuple # Using * for remaining elements name,
Lists
# Creating lists
= [1, 2, 3] # Using square brackets
my_list = list((1, 2, 3)) # Using list() function
my_list
# Common list methods
4) # Add element to end
my_list.append(0, 0) # Insert at index
my_list.insert(1) # Remove first occurrence
my_list.remove(# Remove and return last element
my_list.pop() # Sort in place
my_list.sort() # Reverse in place
my_list.reverse() 2) # Count occurrences
my_list.count(3) # Find index of element my_list.index(
Sets
# Creating sets
= {1, 2, 3} # Using curly braces
my_set = set([1, 2, 3]) # Using set() function
my_set
# Common set methods
4) # Add element
my_set.add(1) # Remove element (raises error if not found)
my_set.remove(1) # Remove element (no error if not found)
my_set.discard(# Remove and return arbitrary element
my_set.pop() 4, 5, 6}) # Add multiple elements
my_set.update({
# Set operations
# Union of sets
set1.union(set2) # Intersection of sets
set1.intersection(set2) # Check if sets have no common elements
set1.isdisjoint(set2) # Check if set1 is subset of set2 set1.issubset(set2)
Dictionaries
# Creating dictionaries
= {"name": "John", "age": 30} # Using curly braces
my_dict = dict(name="John", age=30) # Using dict() function
my_dict
# Dictionary operations
"name"] # Access value by key
my_dict["city"] = "Hamburg" # Add or update key-value pair
my_dict[del my_dict["age"] # Remove key-value pair
"name" in my_dict # Check if key exists
# Dictionary methods
# Get all keys
my_dict.keys() # Get all values
my_dict.values() # Get all key-value pairs
my_dict.items() "name") # Safe way to get value
my_dict.get("name") # Remove and return value my_dict.pop(
File Handling
# Basic file operations
file = open("file.txt", "r") # Open for reading
file = open("file.txt", "w") # Open for writing
file = open("file.txt", "a") # Open for appending
# Reading files
= file.read() # Read entire file
content = file.readlines() # Read lines into list
lines
# Writing files
file.write("Hello") # Write string to file
file.writelines(lines) # Write list of strings
# Using with statement (recommended)
with open("file.txt", "r") as file:
= file.read() content
Data Type Comparison
- Tuples: Immutable, ordered, allows duplicates
- Lists: Mutable, ordered, allows duplicates
- Sets: Mutable, unordered, no duplicates
- Dictionaries: Mutable, unordered, unique keys
Best Practices
- Use tuples for immutable sequences
- Use lists when order matters and items need to be modified
- Use sets for unique collections
- Use dictionaries for key-value relationships
- Always use
with
statement for file operations - Close files after use if not using
with
Lecture V
Common Built-in Exceptions
- ValueError: Wrong value type (e.g., converting “hello” to int)
- TypeError: Wrong operation for type (e.g., “hello” + 5)
- NameError: Variable not found
- IndexError: List index out of range
- KeyError: Dictionary key not found
- FileNotFoundError: File/directory not found
- ZeroDivisionError: Division by zero
- AttributeError: Object has no attribute/method
- ImportError: Module import fails
- SyntaxError: Invalid Python syntax
- IndentationError: Incorrect indentation
- RuntimeError: Generic runtime error
Try-Except Blocks
# Basic try-except
try:
= risky_operation()
result except Exception as e:
print(f"Error occurred: {e}")
# Multiple exception handling
try:
= risky_operation()
result except ValueError as e:
print(f"Value error: {e}")
except TypeError as e:
print(f"Type error: {e}")
except Exception as e:
print(f"Other error: {e}")
Raising Exceptions
# Basic raise
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
# Custom exception
class CustomError(Exception):
pass
def custom_operation():
if error_condition:
raise CustomError("Custom error message")
Assertions
# Basic assertions
assert condition, "Error message"
assert x > 0, "x must be positive"
assert isinstance(x, int), "x must be integer"
# Common assertion patterns
def process_list(lst):
assert isinstance(lst, list), "Input must be a list"
assert all(isinstance(x, int) for x in lst), "All elements must be integers"
assert len(lst) > 0, "List cannot be empty"
Debugging Tips
- Print Debugging
print(f"Variable x = {x}")
print(f"Type of x: {type(x)}")
print(f"Debug: Entering function {function_name}")
- Assertions for Debugging
assert x == expected_value, f"x should be {expected_value}, but got {x}"
- IDE Debugging
- Set breakpoints
- Step through code
- Inspect variables
- Use watch windows
Best Practices
- Always handle specific exceptions before generic ones
- Use meaningful error messages
- Don’t catch exceptions without handling them
- Use assertions for debugging and testing
- Include relevant information in error messages
- Clean up resources in try-finally blocks
Common Debugging Workflow
- Identify the error (error message or unexpected behavior)
- Locate the source of the error
- Add print statements or use debugger
- Test the fix
- Add error handling if needed
Lecture VI
Modules
Importing Modules
# Basic import
import module_name
module_name.function_name()
# Import specific items
from module_name import function_name, another_function
function_name()
# Import with alias
import module_name as alias
alias.function_name()
Common Built-in Modules
Module | Description | Common Functions/Constants |
---|---|---|
math |
Mathematical functions | pi , sqrt() , cos() |
random |
Random number generation | random() , randint() |
datetime |
Date and time handling | datetime , timedelta |
os |
Operating system interaction | listdir() , path.exists() |
csv |
CSV file operations | reader() , writer() |
re |
Regular expressions | search() , findall() |
Random Module
import random
# Float between 0 and 1
random.random() 1, 10) # Float between 1 and 10
random.uniform(1, 10) # Integer between 1 and 10
random.randint(list) # Random item from list
random.choice(list) # Shuffle list in place random.shuffle(
OS Module
import os
'path') # List directory contents
os.listdir('path') # Check if path exists
os.path.exists('path') # Check if path is file
os.path.isfile('path') # Create directories
os.makedirs(# Get current working directory
os.getcwd() 'dir', 'file') # Join path components os.path.join(
CSV Module
import csv
# Writing CSV
with open('file.csv', 'w') as file:
= csv.writer(file)
writer 'header1', 'header2'])
writer.writerow(['data1', 'data2'])
writer.writerow([
# Reading CSV
with open('file.csv', 'r') as file:
= csv.reader(file)
reader for row in reader:
print(row)
Regular Expressions (re)
import re
# Basic patterns
# Search for pattern
re.search(pattern, string) # Find all occurrences
re.findall(pattern, string) # Replace pattern
re.sub(pattern, repl, string) # Split string by pattern
re.split(pattern, string)
# Common special characters
# Any character
. * # Zero or more
+ # One or more
# Zero or one
? # Character set
[] # Any digit
\d # Word character
\w # Whitespace \s
Package Management
# Installing packages
pip install package_name
pip install package1 package2
# Upgrading packages
pip install --upgrade package_name
# List installed packages
pip list
Best Practices
- Import modules at the beginning of the file
- Use specific imports instead of importing everything
- Use meaningful aliases when needed
- Keep virtual environments project-specific
- Document package dependencies
- Use regular expressions carefully and test them thoroughly
Lecture VII
NumPy Basics
Creating Arrays
import numpy as np
# Basic array creation
= np.array([1, 2, 3, 4, 5])
arr = np.array([[1, 2], [3, 4]])
arr_2d
# Pre-filled arrays
= np.zeros((3, 3)) # Array of zeros
zeros = np.ones((2, 2)) # Array of ones
ones = np.random.rand(3, 3) # Random values
rand = np.arange(0, 10, 2) # Values from 0 to 10, step 2
arange = np.linspace(0, 1, 5) # 5 evenly spaced values linspace
Array Operations
# Basic operations
+ 1 # Add 1 to all elements
arr * 2 # Multiply all elements by 2
arr > 3 # Boolean comparison
arr
# Array methods
# Sort array
arr.sort() 2, 3) # Reshape array
arr.reshape(# Convert to 1D array
arr.flatten() # Transpose array
arr.transpose() # Remove single-dimensional entries
arr.squeeze()
# Joining arrays
# Join arrays
np.concatenate((arr1, arr2)) # Vertical stack
np.vstack((arr1, arr2)) # Horizontal stack np.hstack((arr1, arr2))
Data Types
# Common dtypes
'i' # integer
'b' # boolean
'f' # float
'S' # string
'U' # unicode
# Setting dtype
= np.array([1, 2, 3], dtype='f')
arr = arr.astype('i') # Convert type arr
Best Practices
- Use NumPy for numerical computations
- Keep array types homogeneous for better performance
- Use appropriate data types to optimize memory
- Prefer vectorized operations over loops
Lecture VIII
Pandas Basics
Creating DataFrames
import pandas as pd
# From dictionary
= pd.DataFrame({
df 'Name': ['John', 'Anna'],
'Age': [25, 28]
})
# From CSV/Excel
= pd.read_csv('file.csv')
df = pd.read_excel('file.xlsx') df
Basic Operations
# Viewing data
# First 5 rows
df.head() # Last 5 rows
df.tail() # DataFrame info
df.info() # Summary statistics
df.describe()
# Accessing data
'column_name'] # Access column
df[0] # Access by position
df.iloc['label'] # Access by label
df.loc[
# Filtering
'Age'] > 25] # Filter by condition df[df[
Grouping and Aggregation
# Basic grouping
'column').mean()
df.groupby('col1', 'col2']).sum()
df.groupby([
# Common aggregations
sum() # Sum of values
.# Mean of values
.mean() max() # Maximum value
.min() # Minimum value
.# Count of values .count()
Reshaping Data
# Melting (wide to long)
=['ID'])
pd.melt(df, id_vars
# Combining DataFrames
# Concatenate
pd.concat([df1, df2]) # Join on index
df1.join(df2) ='column') # Merge on column df1.merge(df2, on
Excel Operations
# Reading Excel
= pd.read_excel('file.xlsx', sheet_name='Sheet1')
df
# Writing to Excel
'output.xlsx',
df.to_excel(='Sheet1',
sheet_name=False) index
Best Practices
- Use pandas for structured data analysis
- Always check data types and missing values