Of course! Here is a comprehensive Python cheat sheet designed for quick reference, covering fundamentals to more advanced topics.
Python Cheat Sheet
1. Basic Syntax & Variables
# This is a single-line comment
"""
This is a
multi-line comment
or docstring.
"""
# Variables are dynamically typed
variable_name = "Hello" # String
age = 30 # Integer
price = 19.99 # Float
is_active = True # Boolean
no_value = None # NoneType (Python's null)
# Print to console
print(f"User {variable_name} is {age} years old.")
2. Data Types & Structures
Strings (str)
s = "Hello, World!"
len(s) # 13
s.upper() # "HELLO, WORLD!"
s.lower() # "hello, world!"
s.startswith("Hello") # True
s.endswith("!") # True
s.split(',') # ['Hello', ' World!']
s.strip() # "Hello, World!" (removes leading/trailing whitespace)
s[0] # 'H' (first character)
s[-1] # '!' (last character)
s[0:5] # 'Hello' (slicing)
Lists (list) - Mutable, ordered sequence
my_list = [1, "two", 3.0, True]
my_list.append(5) # [1, "two", 3.0, True, 5]
my_list.insert(1, "new") # [1, "new", "two", 3.0, True, 5]
my_list.pop() # Returns 5, my_list is now [1, "new", "two", 3.0, True]
my_list.remove("two") # Removes the first occurrence of "two"
my_list[0] = "one" # Change an element
combined = my_list + [8, 9] # Concatenation
Tuples (tuple) - Immutable, ordered sequence
my_tuple = (1, "two", 3.0)
# Cannot be changed: my_tuple[0] = 5 will raise a TypeError
x, y, z = my_tuple # Unpacking
Dictionaries (dict) - Unordered (ordered in Python 3.7+), key-value pairs
my_dict = {"name": "Alice", "age": 25}
my_dict["city"] = "New York" # Add/update a key-value pair
print(my_dict["name"]) # "Alice"
my_dict.get("country", "USA") # Get value, with a default if key doesn't exist
my_dict.keys() # dict_keys(['name', 'age', 'city'])
my_dict.values() # dict_values(['Alice', 25, 'New York'])
my_dict.items() # dict_items([('name', 'Alice'), ...])
Sets (set) - Unordered, unique elements
my_set = {1, 2, 3, 3, 4} # {1, 2, 3, 4}
my_set.add(5) # {1, 2, 3, 4, 5}
my_set.remove(2) # {1, 3, 4, 5}
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2) # Union: {1, 2, 3, 4, 5}
print(set1 & set2) # Intersection: {3}
print(set1 - set2) # Difference: {1, 2}
3. Control Flow
Conditional Statements
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is 5")
else:
print("x is less than 5")
# Ternary operator
message = "Success" if x > 0 else "Failure"
Loops
# For loop (iterating over a sequence)
for item in ["a", "b", "c"]:
print(item)
# For loop with range
for i in range(5): # 0, 1, 2, 3, 4
print(i)
# For loop with index and value
for i, item in enumerate(["a", "b", "c"]):
print(f"Index {i}: {item}")
# While loop
count = 0
while count < 3:
print(f"Count is {count}")
count += 1
# Loop control
for i in range(10):
if i == 2:
continue # Skip to the next iteration
if i == 5:
break # Exit the loop
4. Functions
# Basic function
def greet(name):
return f"Hello, {name}!"
# Function with default arguments
def power(base, exponent=2):
return base ** exponent
# Function with variable arguments
def sum_all(*args): # Gathers arguments into a tuple
total = 0
for num in args:
total += num
return total
# Function with keyword arguments
def print_info(**kwargs): # Gathers keyword args into a dictionary
for key, value in kwargs.items():
print(f"{key}: {value}")
# Lambda (anonymous) function
multiply = lambda a, b: a * b
print(multiply(5, 4)) # 20
5. Comprehensions (A concise way to create lists, dicts, etc.)
# List comprehension
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# List comprehension with condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]
# Dictionary comprehension
square_dict = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Set comprehension
unique_items = {s.upper() for s in ['a', 'b', 'a', 'c']}
# {'A', 'C', 'B'}
6. Exception Handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except TypeError as e:
print(f"A type error occurred: {e}")
else:
# Runs only if no exceptions were raised
print("Division was successful.")
finally:
# Runs no matter what
print("Execution finished.")
7. File Handling
The with statement ensures the file is closed automatically.
# Writing to a file (overwrites existing content)
with open("file.txt", "w") as f:
f.write("Hello, file!\n")
f.write("This is a new line.")
# Appending to a file
with open("file.txt", "a") as f:
f.write("\nAppending this line.")
# Reading from a file
with open("file.txt", "r") as f:
content = f.read() # Read the entire file
# content = f.readlines() # Read file into a list of lines
# for line in f: # Iterate over lines (memory efficient)
# print(line.strip())
8. Classes & Objects (OOP)
class Dog:
# Class attribute
species = "Canis familiaris"
# Initializer / Instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# Instance method
def bark(self):
return "Woof!"
# Another instance method
def describe(self):
return f"{self.name} is {self.age} years old."
# Inheritance
class GoldenRetriever(Dog):
def __init__(self, name, age):
super().__init__(name, age) # Call parent's __init__
# Override a method
def bark(self):
return "Yap!"
# Creating an object (instance)
my_dog = Dog("Buddy", 3)
print(my_dog.describe()) # "Buddy is 3 years old."
print(my_dog.bark()) # "Woof!"
my_golden = GoldenRetriever("Goldie", 2)
print(my_golden.describe()) # "Goldie is 2 years old."
print(my_golden.bark()) # "Yap!"
9. Common Modules & Imports
# Import entire module
import math
print(math.sqrt(16)) # 4.0
# Import specific functions/classes
from datetime import datetime
print(datetime.now())
# Import with an alias
import numpy as np
my_array = np.array([1, 2, 3])
# Other useful modules
import os # Operating system interactions (os.path.join, os.listdir)
import sys # System-specific parameters (sys.argv)
import json # Work with JSON data (json.dumps, json.loads)
import random # Generate random numbers (random.choice, random.randint)
import re # Regular expressions (re.search, re.findall)