Skip to main content

Basics

Variables & Data Types

Variable Assignment

# Simple assignment
name = "Alice"
age = 25
height = 5.6
is_student = True

# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0

# Swapping variables
x, y = y, x

Data Types

# Integers
count = 42
negative = -10
binary = 0b1010 # Binary: 10
octal = 0o12 # Octal: 10
hex_num = 0xFF # Hexadecimal: 255

# Floats
price = 19.99
scientific = 1.5e-4 # 0.00015
infinity = float('inf')
not_a_number = float('nan')

# Strings
name = "John Doe"
message = 'Hello World'
multiline = """This is
a multiline
string"""

# Boolean
is_active = True
is_complete = False

# None (null equivalent)
result = None

Type Checking & Conversion

# Check type
type(42) # <class 'int'>
type("hello") # <class 'str'>
isinstance(42, int) # True

# Type conversion
int("42") # 42
float("3.14") # 3.14
str(42) # "42"
bool(1) # True
bool(0) # False
bool("") # False
bool("hello") # True

Operators

Arithmetic Operators

# Basic arithmetic
x = 10
y = 3

addition = x + y # 13
subtraction = x - y # 7
multiplication = x * y # 30
division = x / y # 3.333...
floor_division = x // y # 3
modulo = x % y # 1
exponentiation = x ** y # 1000

# Augmented assignment
x += 5 # x = x + 5
x -= 3 # x = x - 3
x *= 2 # x = x * 2
x /= 4 # x = x / 4
x //= 2 # x = x // 2
x %= 3 # x = x % 3
x **= 2 # x = x ** 2

Walrus Operator (Python 3.8+)

# Assignment expression - assign and return value in one operation
# Basic syntax: (variable := expression)

# Traditional approach
data = input("Enter a number: ")
if len(data) > 0:
print(f"You entered: {data}")

# With walrus operator
if (data := input("Enter a number: ")):
print(f"You entered: {data}")

# Useful in loops
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
while (n := len(numbers)) > 5:
print(f"List has {n} items, removing one...")
numbers.pop()

# In list comprehensions
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [square for x in data if (square := x**2) > 25]
print(squares) # [36, 49, 64, 81, 100]

# File processing
with open('file.txt', 'r') as f:
while (line := f.readline()):
print(line.strip())

# Regex matching
import re
pattern = r'\d+'
text = "The price is $25.99"
if (match := re.search(pattern, text)):
print(f"Found number: {match.group()}")

# Avoiding repeated calculations
def expensive_function(x):
print(f"Computing for {x}")
return x * x

# Traditional approach
x = 5
result = expensive_function(x)
if result > 20:
print(f"Result {result} is large")

# With walrus operator
x = 5
if (result := expensive_function(x)) > 20:
print(f"Result {result} is large")

# Dictionary operations
data = {"name": "Alice", "age": 30, "city": "New York"}
if (age := data.get("age")) and age >= 18:
print(f"Adult: {age} years old")

# List processing
items = ["apple", "banana", "cherry", "date"]
processed = [(item, length) for item in items if (length := len(item)) > 5]
print(processed) # [('banana', 6), ('cherry', 6)]

Comparison Operators

x = 10
y = 5

# Comparisons
equal = x == y # False
not_equal = x != y # True
greater = x > y # True
less = x < y # False
greater_equal = x >= y # True
less_equal = x <= y # False

# Chained comparisons
age = 25
is_adult = 18 <= age <= 65 # True

# Identity operators
a = [1, 2, 3]
b = [1, 2, 3]
c = a

a is b # False (different objects)
a is c # True (same object)
a == b # True (same content)

Logical Operators

# Boolean logic
a = True
b = False

and_result = a and b # False
or_result = a or b # True
not_result = not a # False

# Short-circuit evaluation
x = 5
result = x > 0 and x < 10 # True
result = x < 0 or x > 10 # False

# Membership operators
numbers = [1, 2, 3, 4, 5]
has_three = 3 in numbers # True
no_six = 6 not in numbers # True

Control Structures

If/Else Statements

age = 18

# Basic if-else
if age >= 18:
print("You are an adult")
else:
print("You are a minor")

# elif (else if)
if age < 13:
print("Child")
elif age < 18:
print("Teenager")
else:
print("Adult")

# Ternary operator
status = "Adult" if age >= 18 else "Minor"

# Multiple conditions
has_license = True
if age >= 16 and has_license:
print("Can drive")
elif age >= 16:
print("Can get a license")
else:
print("Too young to drive")

For Loops

# Iterate over a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)

# Range function
for i in range(5): # 0, 1, 2, 3, 4
print(i)

for i in range(1, 6): # 1, 2, 3, 4, 5
print(i)

for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)

# Enumerate (get index and value)
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")

# Enumerate with start
for i, fruit in enumerate(fruits, 1):
print(f"{i}. {fruit}")

# Iterate over dictionary
person = {"name": "John", "age": 30}
for key in person:
print(key, person[key])

for key, value in person.items():
print(f"{key}: {value}")

While Loops

# Basic while loop
count = 0
while count < 5:
print(count)
count += 1

# While with else
count = 0
while count < 3:
print(count)
count += 1
else:
print("Loop completed normally")

# Infinite loop with break
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == 'quit':
break
print(f"You entered: {user_input}")

Loop Control

# Break and continue
for i in range(10):
if i == 3:
continue # Skip this iteration
if i == 7:
break # Exit loop
print(i)

# Nested loops with labels (using functions)
def find_item():
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
target = 5

for row in matrix:
for item in row:
if item == target:
return f"Found {target}"
return "Not found"

# Pass statement (placeholder)
for i in range(5):
if i == 2:
pass # Do nothing, placeholder
print(i)

Input/Output

# Basic printing
print("Hello, World!")

# Multiple arguments
print("Name:", "John", "Age:", 25)

# Separator and end
print("A", "B", "C", sep="-") # A-B-C
print("Hello", end=" ")
print("World") # Hello World

# Formatted printing
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old")
print("My name is {} and I am {} years old".format(name, age))
print("My name is %s and I am %d years old" % (name, age))

# Print to file
with open("output.txt", "w") as f:
print("Hello, File!", file=f)

Input Function

# Basic input
name = input("Enter your name: ")
print(f"Hello, {name}!")

# Input with type conversion
age = int(input("Enter your age: "))
height = float(input("Enter your height: "))

# Input validation
while True:
try:
age = int(input("Enter your age: "))
if age < 0:
print("Age cannot be negative")
continue
break
except ValueError:
print("Please enter a valid number")

# Multiple inputs
data = input("Enter three numbers separated by spaces: ").split()
numbers = [int(x) for x in data]

Comments & Documentation

Comments

# Single line comment
print("Hello") # End of line comment

# Multi-line comment using multiple # symbols
# This is a longer comment
# that spans multiple lines
# to explain complex logic

"""
Multi-line comment using triple quotes
This is typically used for documentation
Can span many lines
"""

# TODO: Implement error handling
# FIXME: This function has a bug
# NOTE: This is important information

Docstrings

def greet(name, greeting="Hello"):
"""
Greet a person with a custom message.

Args:
name (str): The person's name
greeting (str, optional): The greeting message. Defaults to "Hello".

Returns:
str: The formatted greeting message

Examples:
>>> greet("Alice")
'Hello, Alice!'
>>> greet("Bob", "Hi")
'Hi, Bob!'
"""
return f"{greeting}, {name}!"

class Person:
"""
A class to represent a person.

Attributes:
name (str): The person's name
age (int): The person's age
"""

def __init__(self, name, age):
"""
Initialize a Person object.

Args:
name (str): The person's name
age (int): The person's age
"""
self.name = name
self.age = age

String Operations

String Methods

text = "  Hello World  "

# Case conversion
text.upper() # " HELLO WORLD "
text.lower() # " hello world "
text.title() # " Hello World "
text.capitalize() # " hello world "
text.swapcase() # " hELLO wORLD "

# Whitespace handling
text.strip() # "Hello World"
text.lstrip() # "Hello World "
text.rstrip() # " Hello World"

# Searching and checking
text.find("World") # 8 (index of first occurrence)
text.index("World") # 8 (raises error if not found)
text.count("l") # 3
text.startswith(" H") # True
text.endswith("d ") # True
"World" in text # True

# String validation
"123".isdigit() # True
"abc".isalpha() # True
"abc123".isalnum() # True
" ".isspace() # True

String Formatting

name = "Alice"
age = 25
score = 95.5

# f-strings (Python 3.6+)
message = f"Hello, {name}! You are {age} years old."
formatted = f"Score: {score:.1f}%" # Score: 95.5%
padded = f"Name: {name:>10}" # Right-aligned in 10 chars

# str.format()
message = "Hello, {}! You are {} years old.".format(name, age)
message = "Hello, {name}! You are {age} years old.".format(name=name, age=age)
formatted = "Score: {:.1f}%".format(score)

# % formatting (older style)
message = "Hello, %s! You are %d years old." % (name, age)
formatted = "Score: %.1f%%" % score

# Format specifiers
number = 42
print(f"{number:d}") # 42 (decimal)
print(f"{number:b}") # 101010 (binary)
print(f"{number:x}") # 2a (hexadecimal)
print(f"{number:04d}") # 0042 (zero-padded)

String Slicing

text = "Hello World"

# Basic slicing
first_five = text[:5] # "Hello"
last_five = text[-5:] # "World"
middle = text[2:7] # "llo W"

# Step slicing
every_other = text[::2] # "HloWrd"
reversed_text = text[::-1] # "dlroW olleH"

# Negative indices
last_char = text[-1] # "d"
second_last = text[-2] # "l"

String Splitting & Joining

# Splitting
sentence = "apple,banana,orange"
fruits = sentence.split(",") # ["apple", "banana", "orange"]
words = "hello world".split() # ["hello", "world"]
parts = "a.b.c".split(".", 1) # ["a", "b.c"] (max 1 split)

# Joining
fruits = ["apple", "banana", "orange"]
sentence = ",".join(fruits) # "apple,banana,orange"
sentence = " and ".join(fruits) # "apple and banana and orange"
path = "/".join(["home", "user", "docs"]) # "home/user/docs"

# String replacement
text = "Hello World"
new_text = text.replace("World", "Python") # "Hello Python"
new_text = text.replace("l", "L", 1) # "HeLlo World" (replace only first)

File I/O

Reading Files

# Read entire file
with open("file.txt", "r") as f:
content = f.read()

# Read line by line
with open("file.txt", "r") as f:
for line in f:
print(line.strip()) # Remove newline characters

# Read all lines into a list
with open("file.txt", "r") as f:
lines = f.readlines()

# Read specific number of characters
with open("file.txt", "r") as f:
chunk = f.read(10) # Read first 10 characters

# Read one line at a time
with open("file.txt", "r") as f:
first_line = f.readline()
second_line = f.readline()

Writing Files

# Write to file (overwrite)
with open("output.txt", "w") as f:
f.write("Hello, World!")

# Append to file
with open("output.txt", "a") as f:
f.write("\nNew line")

# Write multiple lines
lines = ["First line", "Second line", "Third line"]
with open("output.txt", "w") as f:
f.writelines(line + "\n" for line in lines)

# Write with print
with open("output.txt", "w") as f:
print("Hello, World!", file=f)
print("Second line", file=f)

File Modes & Error Handling

# Different file modes
# "r" - read (default)
# "w" - write (overwrites)
# "a" - append
# "r+" - read and write
# "b" - binary mode (e.g., "rb", "wb")

# Error handling
try:
with open("nonexistent.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("File not found!")
except PermissionError:
print("Permission denied!")
except Exception as e:
print(f"An error occurred: {e}")

# Check if file exists
import os
if os.path.exists("file.txt"):
with open("file.txt", "r") as f:
content = f.read()

Working with Paths

import os
from pathlib import Path

# Using os module
current_dir = os.getcwd()
file_path = os.path.join(current_dir, "data", "file.txt")
directory = os.path.dirname(file_path)
filename = os.path.basename(file_path)

# Using pathlib (modern approach)
path = Path("data/file.txt")
path.exists() # Check if exists
path.is_file() # Check if file
path.is_dir() # Check if directory
path.parent # Get parent directory
path.name # Get filename
path.suffix # Get file extension
path.stem # Get filename without extension

# Create directories
path.parent.mkdir(parents=True, exist_ok=True)

Code Structure & Indentation

Indentation Rules

# Python uses indentation to define code blocks
# Standard is 4 spaces per indentation level

if True:
print("This is indented")
if True:
print("This is double indented")
print("Back to single indent")

# Avoid mixing tabs and spaces
# Use consistent indentation throughout

# Good
def function_name():
if condition:
do_something()
return result

# Bad - inconsistent indentation
def function_name():
if condition:
do_something()
return result # This will cause an IndentationError

Code Organization

# Module-level docstring
"""
This module demonstrates Python code organization.
"""

# Imports at the top
import os
import sys
from datetime import datetime

# Constants (uppercase)
MAX_SIZE = 100
DEFAULT_NAME = "Unknown"

# Global variables (if necessary)
counter = 0

# Function definitions
def helper_function():
"""Helper function with proper spacing."""
pass

def main_function():
"""Main function that does the work."""
global counter
counter += 1
return counter

# Class definitions
class MyClass:
"""A sample class."""

def __init__(self):
self.value = 0

def method(self):
"""A method with proper indentation."""
if self.value > 0:
return self.value
return 0

# Main execution
if __name__ == "__main__":
main_function()

Line Length & Continuation

# Keep lines under 79-88 characters
# Use backslash for line continuation
long_string = "This is a very long string that needs to be " \
"split across multiple lines for readability"

# Implicit line continuation with parentheses
total = (first_value + second_value +
third_value + fourth_value)

# Function arguments
def long_function_name(parameter_one, parameter_two,
parameter_three, parameter_four):
return parameter_one + parameter_two

# List/dict continuation
long_list = [
"item1",
"item2",
"item3",
"item4"
]

config = {
"database_host": "localhost",
"database_port": 5432,
"database_name": "myapp"
}

Basic Functions

Function Definition

# Simple function
def greet():
print("Hello, World!")

# Function with parameters
def greet_person(name):
print(f"Hello, {name}!")

# Function with return value
def add_numbers(a, b):
return a + b

# Function with default parameters
def greet_with_title(name, title="Mr."):
return f"Hello, {title} {name}!"

# Function with multiple return values
def get_name_age():
return "Alice", 25

name, age = get_name_age()

Function Parameters

# Positional arguments
def describe_pet(name, animal_type):
print(f"I have a {animal_type} named {name}")

describe_pet("Buddy", "dog")

# Keyword arguments
describe_pet(animal_type="cat", name="Whiskers")

# Default parameters
def make_shirt(size, message="I love Python"):
print(f"Making a {size} shirt with message: {message}")

make_shirt("Large")
make_shirt("Medium", "Hello World")

# Variable arguments (*args)
def sum_all(*numbers):
return sum(numbers)

result = sum_all(1, 2, 3, 4, 5) # 15

# Keyword arguments (**kwargs)
def create_profile(**info):
for key, value in info.items():
print(f"{key}: {value}")

create_profile(name="Alice", age=30, city="New York")

Quick Reference

Common Built-in Functions

# Type conversion
int("42") # 42
float("3.14") # 3.14
str(42) # "42"
bool(1) # True
list("hello") # ['h', 'e', 'l', 'l', 'o']

# Math functions
abs(-5) # 5
min(1, 2, 3) # 1
max(1, 2, 3) # 3
sum([1, 2, 3]) # 6
round(3.7) # 4
pow(2, 3) # 8

# Sequence functions
len("hello") # 5
reversed([1, 2, 3]) # [3, 2, 1]
sorted([3, 1, 2]) # [1, 2, 3]
enumerate(["a", "b", "c"]) # [(0, 'a'), (1, 'b'), (2, 'c')]
zip([1, 2, 3], ["a", "b", "c"]) # [(1, 'a'), (2, 'b'), (3, 'c')]

# Input/Output
input("Enter name: ") # Get user input
print("Hello") # Print to console

Useful Patterns

# Check if variable is defined
try:
variable
except NameError:
variable = "default value"

# Get user input with validation
while True:
try:
age = int(input("Enter your age: "))
break
except ValueError:
print("Please enter a valid number")

# Read file safely
filename = "data.txt"
try:
with open(filename, "r") as f:
content = f.read()
except FileNotFoundError:
print(f"File {filename} not found")
content = ""

# Multiple conditions
age = 25
if 18 <= age <= 65:
print("Working age")

# String validation
text = input("Enter text: ")
if text and text.strip():
print("Valid input")
else:
print("Empty input")

Best Practices

# Use descriptive variable names
user_age = 25 # Good
ua = 25 # Bad

# Use constants for magic numbers
MAX_ATTEMPTS = 3
for attempt in range(MAX_ATTEMPTS):
# Try something
pass

# Use f-strings for formatting
name = "Alice"
greeting = f"Hello, {name}!" # Good
greeting = "Hello, " + name + "!" # Less readable

# Handle exceptions appropriately
try:
result = risky_operation()
except SpecificError:
# Handle specific error
pass
except Exception as e:
# Handle general error
print(f"Error: {e}")

# Use with statement for file operations
with open("file.txt", "r") as f:
content = f.read()
# File is automatically closed

This cheatsheet covers the fundamental Python concepts you'll use daily. Master these basics before moving on to more advanced topics like classes, modules, and libraries.