Variables starting with underscore are considered “private” or temporary.
# Valid
var = 'Hello'
my_var = 'Hello'
my_var_2 = 'Hello'
_underscore = 'hidden' # valid but discouraged
# Invalid
# 3var = 'no' # starts with a number
# my variable = 'no spaces allowed'
Comments
# This is a single line comment
# This is a
# multiline comment
a = 1 # inline comment
Function Docstring
def foo():
"""
This is a function docstring.
Describe your function here.
"""
print() Function
print('Hello world!') # Hello world!
print('Hello world!', 1) # Hello world! 1
# end keyword (suppress newline/change end char)
for word in ['printed', 'with', 'dashes']:
print(word, end='-')
# Output: printed-with-dashes-
# sep keyword (separator between items)
print('cats', 'dogs', 'mice', sep=',') # cats,dogs,mice
input() Function
my_name = input('What is your name? ')
print(f'Hi, {my_name}')
len() Function
len('hello') # 5
len(['cat', 3, 'dog']) # 3
# Testing emptiness (preferred over len check)
a = [1, 2, 3]
if a: # True if list is not empty
print("List is not empty!")
Type Conversion
# To string
str(29) # '29'
# To int
int('11') # 11
# To float
float('3.14') # 3.14
Control Flow
If, Elif, Else
if condition:
# do something
elif another_condition:
# do something else
else:
# fallback code
For Loop
for item in iterable:
# do something with item
for i in range(5):
print(i) # 0 1 2 3 4
While Loop
while condition:
# loop body
# remember to update condition or break
Loop Controls
break # exit the loop immediately
continue # skip rest of current loop iteration and continue
Functions and Lambdas
Function Definition
def function_name(parameters):
"""
Describe function behavior here.
"""
# function body
return value # optional
try:
# code that might raise exception
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"Error: {e}")
else:
print("No errors!")
finally:
print("Always runs!")
Modules & Imports
# Import whole module
import math
print(math.sqrt(16)) # 4.0
# Import specific functions or variables
from math import sqrt, pi
print(sqrt(25)) # 5.0
# Import with alias
import numpy as np
print(np.array([1, 2, 3]))
Classes & Object-Oriented Programming
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
d = Dog("Buddy")
print(d.speak()) # Buddy says Woof!
File Handling
# Writing to a file
with open('file.txt', 'w') as f:
f.write("Hello, file!\n")
# Reading from a file
with open('file.txt', 'r') as f:
content = f.read()
print(content)
Common Built-in Functions
abs(x) - absolute value
all(iterable) - True if all elements are true
any(iterable) - True if any element is true
enumerate(iterable) - get index and value pairs
filter(function, iterable) - filter elements by function
map(function, iterable) - apply function to each element
max(iterable) - maximum element
min(iterable) - minimum element
sorted(iterable) - sorted list
sum(iterable) - sum of elements
type(object) - get object's type
Advanced Data Types and Collections
Namedtuples
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, y=22)
print(p.x, p.y) # 11 22
Dataclasses (Python 3.7+)
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
p = Person('Alice', 30)
print(p.name, p.age)
import re
pattern = r'\b\w{3}\b' # words with exactly 3 chars
text = "The cat and dog ran."
matches = re.findall(pattern, text)
print(matches) # ['The', 'cat', 'and', 'dog', 'ran']
# Common functions:
# re.match() - check beginning of string
# re.search() - search anywhere
# re.findall() - all matches
# re.sub() - substitution
Context Managers and the with Statement
# Using built-in context manager for file handling
with open('file.txt', 'r') as f:
content = f.read()
# Custom context manager example
class ManagedResource:
def __enter__(self):
print("Resource acquired")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Resource released")
with ManagedResource() as r:
print("Using the resource")
contextlib utilities
from contextlib import contextmanager
@contextmanager
def simple_manager():
print("Acquire")
yield
print("Release")
with simple_manager():
print("Inside the context")
Typing and Annotations
from typing import List, Optional, Union
def greet(name: str) -> str:
return f"Hello, {name}"
def process_items(items: List[int]) -> int:
return sum(items)
def foo(bar: Optional[str] = None) -> Union[str, None]:
if bar:
return bar.upper()
return None
Python Standard Library Highlights
os and sys
import os, sys
print(os.getcwd()) # current working directory
print(sys.platform) # platform info
print(os.listdir('.')) # list files in cwd
datetime and time
import datetime, time
now = datetime.datetime.now()
print(now.isoformat())
time.sleep(1) # sleep for 1 second
json and csv
import json, csv
data = {'name': 'Alice', 'age': 30}
json_str = json.dumps(data)
print(json_str)
with open('data.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
Testing
unittest example
import unittest
def add(a, b):
return a + b
class TestAdd(unittest.TestCase):
def test_positive(self):
self.assertEqual(add(1, 2), 3)
def test_negative(self):
self.assertEqual(add(-1, -1), -2)
if __name__ == '__main__':
unittest.main()
# Generate a single executable from a Python script
pyinstaller --onefile your_script.py
Common Options
--onefile # Bundle everything into a single executable
--noconsole # Do not open a console window (GUI apps)
--name NAME # Specify the name of the executable
--icon ICON.ico # Add an icon to the executable
--add-data "SRC;DEST" # Include additional files or folders
--clean # Clean PyInstaller cache and remove temporary files
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
element = wait.until(EC.presence_of_element_located((By.ID, 'result')))
Closing the Browser
driver.quit() # Close all windows and stop the WebDriver
driver.close() # Close current window
Jupyter Notebook Cheat Sheet
Running Cells
Shift + Enter: Run current cell and select next
Ctrl + Enter: Run current cell and stay
Alt + Enter: Run current cell and insert below
Cell Types
Code: Python code (default)
Markdown: Formatted text, LaTeX support
Raw: Unformatted text
Magic Commands
# Line magics start with %
%timeit sum(range(1000))
%matplotlib inline
# Cell magics start with %%
%%writefile example.py
print("Hello world")
Useful Shortcuts
A: Insert cell above
B: Insert cell below
M: Change cell to Markdown
Y: Change cell to Code
D,D (press D twice): Delete cell
Z: Undo cell deletion
SQLAlchemy Cheat Sheet
Setup
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///example.db')
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()
Define Models
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
Base.metadata.create_all(engine)
# Get all users
users = session.query(User).all()
# Filtered query
young_users = session.query(User).filter(User.age < 25).all()
# Get one
user = session.query(User).filter_by(name='Alice').first()
Update and Delete
user = session.query(User).filter_by(name='Alice').first()
user.age = 31
session.commit()
session.delete(user)
session.commit()