Python Programming Language Cheat Sheets


1. PYTHON BASICS

Variables and Data Types

# Variable assignment (no type declaration needed)
name = "Alice"          # String
age = 25               # Integer
height = 5.8           # Float
is_student = True      # Boolean
items = None           # None type

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

# Type conversion
int("123")     # → 123
float("3.14")  # → 3.14
str(42)        # → "42"
bool(1)        # → True

Print and Input

# Print statements
print("Hello, World!")
print("Name:", name, "Age:", age)
print(f"Hello, {name}!")  # f-string (Python 3.6+)

# Input from user
name = input("Enter your name: ")
age = int(input("Enter your age: "))

Comments

# Single-line comment

"""
Multi-line comment
or docstring
"""


2. OPERATORS

Arithmetic Operators

+    # Addition
-    # Subtraction
*    # Multiplication
/    # Division (float)
//   # Floor division
%    # Modulus (remainder)
**   # Exponentiation

# Examples
10 + 3    # → 13
10 / 3    # → 3.333...
10 // 3   # → 3
10 % 3    # → 1
2 ** 3    # → 8

Comparison Operators

==   # Equal to
!=   # Not equal to
>    # Greater than
<    # Less than
>=   # Greater than or equal to
<=   # Less than or equal to

Logical Operators

and  # Logical AND
or   # Logical OR
not  # Logical NOT

# Examples
(5 > 3) and (8 > 5)  # → True
(5 > 3) or (5 > 8)   # → True
not (5 > 3)          # → False

Assignment Operators

=     # Assign
+=    # Add and assign (x += 5 same as x = x + 5)
-=    # Subtract and assign
*=    # Multiply and assign
/=    # Divide and assign
//=   # Floor divide and assign
%=    # Modulus and assign
**=   # Exponent and assign


3. STRINGS

String Operations

# String creation
text = "Hello"
text = 'World'
text = """Multiple
lines"""

# String concatenation
greeting = "Hello" + " " + "World"

# String repetition
"Ha" * 3  # → "HaHaHa"

# String indexing (0-based)
text = "Python"
text[0]    # → 'P'
text[-1]   # → 'n' (last character)

# String slicing
text[0:3]   # → 'Pyt'
text[:3]    # → 'Pyt'
text[3:]    # → 'hon'
text[-3:]   # → 'hon' (last 3 characters)

String Methods

text = "Hello World"

text.lower()              # → 'hello world'
text.upper()              # → 'HELLO WORLD'
text.capitalize()         # → 'Hello world'
text.title()              # → 'Hello World'

text.strip()              # Remove whitespace
text.replace("H", "J")    # → 'Jello World'
text.split()              # → ['Hello', 'World']
"-".join(['a','b','c'])   # → 'a-b-c'

text.startswith("Hello")  # → True
text.endswith("World")    # → True
text.find("World")        # → 6 (index, -1 if not found)
text.count("l")           # → 3

len(text)                 # → 11 (length)

String Formatting

name = "Alice"
age = 25

# f-strings (Python 3.6+)
f"My name is {name} and I am {age} years old"

# format() method
"My name is {} and I am {} years old".format(name, age)
"My name is {n} and I am {a} years old".format(n=name, a=age)

# %-formatting (older style)
"My name is %s and I am %d years old" % (name, age)


4. CONTROL FLOW

If Statements

# Basic if
if condition:
    # code

# if-else
if condition:
    # code
else:
    # code

# if-elif-else
if condition1:
    # code
elif condition2:
    # code
else:
    # code

# Ternary operator
result = value_if_true if condition else value_if_false

Loops

For Loop

# Iterate over sequence
for item in sequence:
    # code

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

for i in range(2, 10):       # 2, 3, 4, 5, 6, 7, 8, 9
    print(i)

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

for char in "Python":
    print(char)

for item in [1, 2, 3]:
    print(item)

# Enumerate (get index and value)
for index, value in enumerate(['a', 'b', 'c']):
    print(index, value)

While Loop

# Basic while
while condition:
    # code

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

Loop Control

break     # Exit loop completely
continue  # Skip to next iteration
pass      # Do nothing (placeholder)

# Example
for i in range(10):
    if i == 3:
        continue  # Skip 3
    if i == 7:
        break     # Stop at 7
    print(i)


5. DATA STRUCTURES

Lists

# List creation
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
empty = []

# Accessing elements
fruits[0]      # → 'apple'
fruits[-1]     # → 'cherry' (last element)
fruits[0:2]    # → ['apple', 'banana'] (slicing)

# List methods
fruits.append("orange")           # Add to end
fruits.insert(1, "grape")         # Insert at index
fruits.remove("banana")           # Remove by value
fruits.pop()                      # Remove and return last item
fruits.pop(0)                     # Remove and return item at index
fruits.clear()                    # Remove all items
fruits.sort()                     # Sort in place
fruits.reverse()                  # Reverse in place
fruits.copy()                     # Shallow copy

len(fruits)                       # Length
fruits.count("apple")             # Count occurrences
fruits.index("apple")             # Find index

# List comprehension
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]

Tuples (Immutable)

# Tuple creation
point = (10, 20)
colors = ("red", "green", "blue")
single = (42,)    # Single element tuple needs comma

# Accessing elements
point[0]          # → 10
point[-1]         # → 20

# Tuple unpacking
x, y = point

Sets (Unique elements)

# Set creation
fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 3, 4, 5}
empty_set = set()   # NOT {} (that's a dict)

# Set methods
fruits.add("orange")              # Add element
fruits.remove("banana")           # Remove (error if not found)
fruits.discard("grape")           # Remove (no error if not found)
fruits.clear()                    # Remove all

# Set operations
a = {1, 2, 3}
b = {3, 4, 5}
a | b         # Union → {1, 2, 3, 4, 5}
a & b         # Intersection → {3}
a - b         # Difference → {1, 2}
a ^ b         # Symmetric difference → {1, 2, 4, 5}

Dictionaries (Key-Value pairs)

# Dictionary creation
person = {"name": "Alice", "age": 25, "city": "NYC"}
empty_dict = {}

# Accessing elements
person["name"]              # → 'Alice'
person.get("name")          # → 'Alice'
person.get("country", "USA")  # → 'USA' (default if not found)

# Dictionary methods
person["age"] = 26                    # Update value
person["country"] = "USA"             # Add new key-value
del person["city"]                    # Delete key
person.pop("age")                     # Remove and return value
person.clear()                        # Remove all items

person.keys()                         # Get all keys
person.values()                       # Get all values
person.items()                        # Get all key-value pairs

# Looping through dictionary
for key in person:
    print(key, person[key])

for key, value in person.items():
    print(key, value)

# Dictionary comprehension
squares = {x: x**2 for x in range(5)}


6. FUNCTIONS

Basic Functions

# Function definition
def greet():
    print("Hello!")

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

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

# Function with default parameters
def greet(name="Guest"):
    print(f"Hello, {name}!")

# Multiple return values
def get_min_max(numbers):
    return min(numbers), max(numbers)

minimum, maximum = get_min_max([1, 2, 3, 4, 5])

Advanced Function Features

# *args (variable positional arguments)
def sum_all(*args):
    return sum(args)

sum_all(1, 2, 3, 4)  # → 10

# **kwargs (variable keyword arguments)
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25, city="NYC")

# Lambda functions (anonymous functions)
square = lambda x: x**2
add = lambda x, y: x + y

# Map, Filter, Reduce
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))

from functools import reduce
product = reduce(lambda x, y: x * y, numbers)

Docstrings

def function_name(param):
    """
    Brief description of function.
   
    Args:
        param: Description of parameter
       
    Returns:
        Description of return value
    """
    return param


7. FILE HANDLING

Reading Files

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

# Read line by line
with open('file.txt', 'r') as file:
    for line in file:
        print(line.strip())

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

Writing Files

# Write to file (overwrites)
with open('file.txt', 'w') as file:
    file.write("Hello, World!\n")

# Append to file
with open('file.txt', 'a') as file:
    file.write("New line\n")

# Write multiple lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('file.txt', 'w') as file:
    file.writelines(lines)

File Modes

'r'   # Read (default)
'w'   # Write (overwrites)
'a'   # Append
'r+'  # Read and write
'rb'  # Read binary
'wb'  # Write binary


8. EXCEPTION HANDLING

Try-Except

# Basic try-except
try:
    result = 10 / 0
except:
    print("An error occurred")

# Specific exception
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

# Multiple exceptions
try:
    # code
except (ValueError, TypeError):
    print("Value or Type error")

# Exception with message
try:
    result = int("abc")
except ValueError as e:
    print(f"Error: {e}")

# Else and finally
try:
    result = 10 / 2
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("Success!")  # Runs if no exception
finally:
    print("Always runs")  # Cleanup code

Raising Exceptions

# Raise an exception
raise ValueError("Invalid value")

# Raise with condition
if age < 0:
    raise ValueError("Age cannot be negative")

Common Exceptions

ValueError      # Invalid value
TypeError       # Invalid type
KeyError        # Key not found in dictionary
IndexError      # Index out of range
FileNotFoundError  # File not found
ZeroDivisionError  # Division by zero
AttributeError  # Attribute not found
ImportError     # Import failed


9. OBJECT-ORIENTED PROGRAMMING

Classes and Objects

# Basic class
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
   
    def greet(self):
        return f"Hello, I'm {self.name}"

# Create object
person = Person("Alice", 25)
print(person.name)      # → Alice
print(person.greet())   # → Hello, I'm Alice

Class Attributes and Methods

class Dog:
    # Class attribute (shared by all instances)
    species = "Canis familiaris"
   
    def __init__(self, name, age):
        # Instance attributes
        self.name = name
        self.age = age
   
    # Instance method
    def bark(self):
        return f"{self.name} says Woof!"
   
    # Class method
    @classmethod
    def get_species(cls):
        return cls.species
   
    # Static method
    @staticmethod
    def info():
        return "Dogs are domesticated animals"

Inheritance

# Parent class
class Animal:
    def __init__(self, name):
        self.name = name
   
    def speak(self):
        pass

# Child class
class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

dog = Dog("Buddy")
print(dog.speak())  # → Buddy says Woof!

Magic Methods

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
   
    def __str__(self):
        return f"Point({self.x}, {self.y})"
   
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)
   
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y


10. MODULES AND PACKAGES

Importing Modules

# Import entire module
import math
print(math.sqrt(16))

# Import specific items
from math import sqrt, pi
print(sqrt(16))

# Import with alias
import numpy as np
import pandas as pd

# Import all (not recommended)
from math import *

Creating Modules

# mymodule.py
def greet(name):
    return f"Hello, {name}!"

PI = 3.14159

# main.py
import mymodule
print(mymodule.greet("Alice"))
print(mymodule.PI)

Common Built-in Modules

import math          # Mathematical functions
import random        # Random number generation
import datetime      # Date and time
import os            # Operating system interface
import sys           # System-specific parameters
import json          # JSON encoder/decoder
import re            # Regular expressions
import collections   # Specialized container datatypes


11. COMMON STANDARD LIBRARY FUNCTIONS

Math Module

import math

math.sqrt(16)        # Square root → 4.0
math.pow(2, 3)       # Power → 8.0
math.floor(3.7)      # Floor → 3
math.ceil(3.2)       # Ceiling → 4
math.pi              # π → 3.14159...
math.e               # e → 2.71828...
math.sin(math.pi/2)  # Sine → 1.0
math.cos(0)          # Cosine → 1.0
math.log(10)         # Natural log
math.log10(100)      # Log base 10 → 2.0

Random Module

import random

random.random()              # Random float [0.0, 1.0)
random.randint(1, 10)        # Random integer [1, 10]
random.choice([1, 2, 3])     # Random element from list
random.shuffle(my_list)      # Shuffle list in place
random.sample([1,2,3,4], 2)  # Sample 2 items without replacement

Datetime Module

from datetime import datetime, date, time, timedelta

# Current date and time
now = datetime.now()
today = date.today()

# Create specific date
birthday = date(1990, 5, 15)

# Format date
now.strftime("%Y-%m-%d")      # → '2024-02-12'
now.strftime("%B %d, %Y")     # → 'February 12, 2024'

# Parse string to date
date_obj = datetime.strptime("2024-02-12", "%Y-%m-%d")

# Date arithmetic
tomorrow = today + timedelta(days=1)
next_week = today + timedelta(weeks=1)

OS Module

import os

os.getcwd()                  # Current working directory
os.listdir('.')              # List directory contents
os.mkdir('new_folder')       # Create directory
os.remove('file.txt')        # Delete file
os.rename('old.txt', 'new.txt')  # Rename file
os.path.exists('file.txt')   # Check if file exists
os.path.isfile('file.txt')   # Check if it's a file
os.path.isdir('folder')      # Check if it's a directory
os.path.join('folder', 'file.txt')  # Join paths


12. LIST COMPREHENSIONS AND GENERATORS

List Comprehensions

# Basic list comprehension
squares = [x**2 for x in range(10)]

# With condition
evens = [x for x in range(10) if x % 2 == 0]

# With if-else
labels = ["even" if x % 2 == 0 else "odd" for x in range(10)]

# Nested comprehension
matrix = [[i*j for j in range(5)] for i in range(5)]

# Flatten nested list
nested = [[1, 2], [3, 4], [5, 6]]
flat = [item for sublist in nested for item in sublist]

Dictionary and Set Comprehensions

# Dictionary comprehension
squares = {x: x**2 for x in range(5)}

# Set comprehension
unique_squares = {x**2 for x in range(-5, 6)}

Generators

# Generator expression
squares_gen = (x**2 for x in range(10))

# Generator function
def countdown(n):
    while n > 0:
        yield n
        n -= 1

# Use generator
for num in countdown(5):
    print(num)


13. USEFUL BUILT-IN FUNCTIONS

# Type conversion
int(), float(), str(), bool(), list(), tuple(), set(), dict()

# Math functions
abs(-5)              # Absolute value → 5
min(1, 2, 3)         # Minimum → 1
max(1, 2, 3)         # Maximum → 3
sum([1, 2, 3])       # Sum → 6
round(3.14159, 2)    # Round to 2 decimals → 3.14
pow(2, 3)            # Power → 8

# Sequence functions
len([1, 2, 3])       # Length → 3
sorted([3, 1, 2])    # Sorted list → [1, 2, 3]
reversed([1, 2, 3])  # Reversed iterator
enumerate(['a','b']) # (index, value) pairs
zip([1,2], ['a','b']) # Pair elements → [(1,'a'), (2,'b')]

# Type checking
type(42)             # → <class 'int'>
isinstance(42, int)  # → True

# Object info
dir(obj)             # List object attributes
help(obj)            # Documentation
id(obj)              # Object identity

# Input/Output
input("Prompt: ")    # Get user input
print("text")        # Print to console


14. REGULAR EXPRESSIONS

import re

# Pattern matching
re.match(r'pattern', string)    # Match at beginning
re.search(r'pattern', string)   # Search anywhere
re.findall(r'pattern', string)  # Find all matches
re.finditer(r'pattern', string) # Iterator of matches

# Replace
re.sub(r'pattern', 'replacement', string)

# Split
re.split(r'pattern', string)

# Common patterns
r'\d'      # Digit
r'\D'      # Non-digit
r'\w'      # Word character
r'\W'      # Non-word character
r'\s'      # Whitespace
r'\S'      # Non-whitespace
r'.'       # Any character
r'^'       # Start of string
r'$'       # End of string
r'*'       # 0 or more
r'+'       # 1 or more
r'?'       # 0 or 1
r'{n}'     # Exactly n
r'{n,m}'   # n to m times
r'[abc]'   # Any of a, b, or c
r'[^abc]'  # Not a, b, or c
r'(abc)'   # Capture group

# Example
email_pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
phone_pattern = r'\d{3}-\d{3}-\d{4}'


15. COMMON PATTERNS AND IDIOMS

Swapping Variables

a, b = b, a

Checking Multiple Conditions

# Check if value in multiple items
if x in [1, 2, 3, 4, 5]:
    print("Found")

# Check multiple conditions
if x > 0 and x < 10:
    print("Between 0 and 10")

# Chained comparison
if 0 < x < 10:
    print("Between 0 and 10")

Default Dictionary Values

from collections import defaultdict

# Regular dictionary with default
count = {}
count.setdefault('key', 0)

# defaultdict
count = defaultdict(int)
count['key'] += 1  # No KeyError if 'key' doesn't exist

Context Managers

# Automatically handle resource cleanup
with open('file.txt', 'r') as file:
    content = file.read()
# File automatically closed

Enumerate Instead of Range

# Instead of this:
for i in range(len(items)):
    print(i, items[i])

# Use this:
for i, item in enumerate(items):
    print(i, item)

Unpacking

# Unpack sequences
first, *rest, last = [1, 2, 3, 4, 5]
# first=1, rest=[2,3,4], last=5

# Unpack dictionaries
def func(**kwargs):
    print(kwargs)

func(a=1, b=2)  # {'a': 1, 'b': 2}


16. DEBUGGING AND TESTING

Print Debugging

print(f"Variable x: {x}")
print(f"Type: {type(x)}, Value: {x}")

Assert Statements

assert condition, "Error message"

# Example
assert x > 0, "x must be positive"

Simple Testing

def add(a, b):
    return a + b

# Test
assert add(2, 3) == 5
assert add(-1, 1) == 0
print("All tests passed!")

Using unittest

import unittest

class TestMath(unittest.TestCase):
    def test_add(self):
        self.assertEqual(2 + 3, 5)
   
    def test_subtract(self):
        self.assertEqual(5 - 3, 2)

if __name__ == '__main__':
    unittest.main()


17. VIRTUAL ENVIRONMENTS

# Create virtual environment
python -m venv myenv

# Activate (Windows)
myenv\Scripts\activate

# Activate (Unix/Mac)
source myenv/bin/activate

# Install packages
pip install package_name

# List installed packages
pip list

# Freeze requirements
pip freeze > requirements.txt

# Install from requirements
pip install -r requirements.txt

# Deactivate
deactivate


18. PYTHON STYLE GUIDE (PEP 8)

Naming Conventions

# Variables and functions: lowercase_with_underscores
my_variable = 10
def my_function():
    pass

# Constants: UPPERCASE_WITH_UNDERSCORES
MAX_SIZE = 100

# Classes: CapitalizedWords
class MyClass:
    pass

# Private: _leading_underscore
_internal_variable = 5

# Protected: __double_leading_underscore
__private_variable = 10

Code Layout

# Indentation: 4 spaces
if True:
    print("Indented")

# Line length: max 79 characters
# Blank lines: 2 between top-level functions/classes

# Imports at top, grouped:
# 1. Standard library
# 2. Third-party
# 3. Local application

import os
import sys

import numpy as np

from mymodule import myfunction

Best Practices

# Use is for None
if x is None:
    pass

# Use not for boolean
if not success:
    pass

# Explicit comparison for empty sequences
if len(my_list) == 0:  # or just: if not my_list:
    pass


QUICK REFERENCE SUMMARY

Basic Operations: Variables, print(), input(), operators, comments
Strings: Concatenation, slicing, methods (upper, lower, split, join)
Control Flow: if/elif/else, for, while, break, continue
Data Structures: Lists, tuples, sets, dictionaries
Functions: def, return, *args, kwargs, lambda
Files: open(), read(), write(), with statement
Exceptions: try/except/else/finally, raise
OOP: class, init, inheritance, methods
Modules:** import, from…import, common modules (math, random, os)

Remember: - Python is case-sensitive - Indentation matters (use 4 spaces) - Index starts at 0 - Use meaningful variable names - Follow PEP 8 style guide - Comment your code - Practice regularly!