Python
Updated: September 10, 2025Categories: Languages, Backend, Scientific
Printed from:
Python Cheatsheet
Language Overview
Python is a high-level, interpreted programming language known for its simplicity and readability. It supports multiple programming paradigms including procedural, object-oriented, and functional programming. Python is widely used in web development, data science, AI/ML, automation, and scientific computing.
Basic Syntax
Python
12345678910# Single line comment
"""
Multi-line comment
or docstring
"""
# Print statement
print("Hello, World!")
# Python uses indentation for code blocks
if True:
print("Indented block")
Data Types
Primitive Types
Python
1234567891011121314151617181920# Integer
age = 25
count = -10
# Float
price = 99.99
temperature = -5.5
# String
name = "John"
message = f"Hello, {name}!" # f-string
text = """Multi-line
string"""
# Boolean
is_active = True
is_complete = False
# None (null equivalent)
value = None
Collection Types
Python
12345678910111213141516171819# List (mutable, ordered)
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
# Tuple (immutable, ordered)
coordinates = (10, 20)
rgb = (255, 128, 0)
# Dictionary (mutable, key-value pairs)
person = {
"name": "John",
"age": 30,
"city": "New York"
}
# Set (mutable, unique elements)
unique_numbers = {1, 2, 3, 4, 5}
empty_set = set()
Variables and Constants
Python
12345678910111213# Variables (snake_case convention)
user_name = "john_doe"
total_count = 100
# Constants (UPPER_CASE convention)
PI = 3.14159
MAX_SIZE = 1000
API_URL = "https://api.example.com"
# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0
Operators
Arithmetic Operators
Python
12345678910a, b = 10, 3
print(a + b) # 13 (addition)
print(a - b) # 7 (subtraction)
print(a * b) # 30 (multiplication)
print(a / b) # 3.333... (division)
print(a // b) # 3 (floor division)
print(a % b) # 1 (modulus)
print(a ** b) # 1000 (exponentiation)
Comparison Operators
Python
1234567print(5 == 5) # True
print(5 != 3) # True
print(5 > 3) # True
print(5 >= 5) # True
print(3 < 5) # True
print(3 <= 3) # True
Logical Operators
Python
12345678print(True and False) # False
print(True or False) # True
print(not True) # False
# Short-circuit evaluation
x = 5
print(x > 0 and x < 10) # True
Membership and Identity
Python
1234567891011# Membership operators
fruits = ["apple", "banana"]
print("apple" in fruits) # True
print("grape" not in fruits) # True
# Identity operators
x = [1, 2, 3]
y = x
print(x is y) # True
print(x is not [1, 2, 3]) # True (different objects)
Control Structures
If/Elif/Else
Python
123456789101112131415161718score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Grade: {grade}")
# Ternary operator
result = "Pass" if score >= 60 else "Fail"
Loops
For Loops
Python
12345678910111213141516171819# Iterate over sequence
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# Range function
for i in range(5): # 0 to 4
print(i)
for i in range(1, 6): # 1 to 5
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
# Enumerate for index and value
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
While Loops
Python
12345678910111213count = 0
while count < 5:
print(count)
count += 1
# While with else clause
x = 0
while x < 3:
print(x)
x += 1
else:
print("Loop completed normally")
Loop Control
Python
1234567for i in range(10):
if i == 3:
continue # Skip iteration
if i == 7:
break # Exit loop
print(i)
Functions
Basic Functions
Python
1234567891011121314151617181920212223def greet(name):
return f"Hello, {name}!"
def add(x, y):
return x + y
# Function with default parameters
def greet_with_title(name, title="Mr."):
return f"Hello, {title} {name}!"
# Variable arguments
def sum_all(*args):
return sum(args)
# Keyword arguments
def create_profile(**kwargs):
return kwargs
# Usage
print(greet("Alice"))
print(sum_all(1, 2, 3, 4))
profile = create_profile(name="John", age=30, city="NYC")
Lambda Functions
Python
123456789# Lambda (anonymous) functions
square = lambda x: x ** 2
add = lambda x, y: x + y
# Using with higher-order functions
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))
Decorators
Python
12345678910111213141516def timing_decorator(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.2f} seconds")
return result
return wrapper
@timing_decorator
def slow_function():
import time
time.sleep(1)
return "Done"
Data Structures
Lists
Python
12345678910111213141516171819202122232425# List operations
fruits = ["apple", "banana", "orange"]
# Adding elements
fruits.append("grape") # Add to end
fruits.insert(1, "mango") # Insert at index
fruits.extend(["kiwi", "peach"]) # Add multiple
# Removing elements
fruits.remove("banana") # Remove by value
popped = fruits.pop() # Remove and return last
del fruits[0] # Remove by index
# List comprehensions
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
# Slicing
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5]) # [2, 3, 4]
print(numbers[:3]) # [0, 1, 2]
print(numbers[7:]) # [7, 8, 9]
print(numbers[::2]) # [0, 2, 4, 6, 8]
print(numbers[::-1]) # Reverse
Dictionaries
Python
1234567891011121314151617# Dictionary operations
person = {"name": "John", "age": 30, "city": "NYC"}
# Accessing and modifying
print(person["name"]) # Direct access
print(person.get("age", 0)) # Safe access with default
person["job"] = "Developer" # Add new key
person.update({"salary": 75000, "married": True})
# Dictionary methods
keys = person.keys()
values = person.values()
items = person.items()
# Dictionary comprehension
squares = {x: x**2 for x in range(5)}
Sets
Python
1234567891011121314# Set operations
numbers = {1, 2, 3, 4, 5}
evens = {2, 4, 6, 8}
# Set operations
union = numbers | evens # Union
intersection = numbers & evens # Intersection
difference = numbers - evens # Difference
# Set methods
numbers.add(6)
numbers.discard(1) # Remove if exists
numbers.update([7, 8, 9])
Object-Oriented Programming
Classes and Objects
Python
123456789101112131415161718192021222324252627282930313233class Person:
# Class variable
species = "Homo sapiens"
def __init__(self, name, age):
# Instance variables
self.name = name
self.age = age
def greet(self):
return f"Hello, I'm {self.name}"
def have_birthday(self):
self.age += 1
return f"Happy birthday! Now {self.age} years old"
def __str__(self):
return f"Person(name={self.name}, age={self.age})"
@staticmethod
def is_adult(age):
return age >= 18
@classmethod
def from_string(cls, person_str):
name, age = person_str.split('-')
return cls(name, int(age))
# Usage
person = Person("Alice", 25)
print(person.greet())
print(Person.is_adult(person.age))
Inheritance
Python
12345678910111213141516171819202122232425262728293031323334class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def speak(self):
return f"{self.name} makes a sound"
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, "Canine")
self.breed = breed
def speak(self):
return f"{self.name} barks"
def fetch(self):
return f"{self.name} fetches the ball"
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name, "Feline")
self.color = color
def speak(self):
return f"{self.name} meows"
# Usage
dog = Dog("Buddy", "Golden Retriever")
cat = Cat("Whiskers", "Orange")
print(dog.speak())
print(cat.speak())
Error Handling
Python
1234567891011121314151617181920212223242526272829# Try-except-else-finally
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
else:
print("No exceptions occurred")
finally:
print("This always executes")
# Raising exceptions
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
# Custom exceptions
class CustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
try:
raise CustomError("This is a custom error")
except CustomError as e:
print(f"Caught custom error: {e}")
File I/O
Python
12345678910111213141516171819202122232425262728293031323334353637383940414243444546# Reading files
with open('file.txt', 'r') as file:
content = file.read() # Read entire file
with open('file.txt', 'r') as file:
lines = file.readlines() # Read all lines
with open('file.txt', 'r') as file:
for line in file: # Read line by line
print(line.strip())
# Writing files
with open('output.txt', 'w') as file:
file.write("Hello, World!")
with open('output.txt', 'a') as file: # Append mode
file.write("\nAppended text")
# Working with JSON
import json
data = {"name": "John", "age": 30}
# Write JSON
with open('data.json', 'w') as file:
json.dump(data, file, indent=2)
# Read JSON
with open('data.json', 'r') as file:
loaded_data = json.load(file)
# Working with CSV
import csv
# Write CSV
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age'])
writer.writerow(['John', 30])
# Read CSV
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
Common Libraries and Frameworks
Standard Library
Python
123456789101112131415import os # Operating system interface
import sys # System-specific parameters
import datetime # Date and time handling
import random # Generate random numbers
import math # Mathematical functions
import re # Regular expressions
import collections # Specialized container types
import itertools # Iteration utilities
# Examples
print(os.getcwd())
print(datetime.datetime.now())
print(random.randint(1, 10))
print(math.sqrt(16))
Popular Third-Party Libraries
Data Science
Python
123456789101112131415# NumPy - Numerical computing
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(np.mean(arr))
# Pandas - Data manipulation
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
print(df.head())
# Matplotlib - Plotting
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.show()
Web Development
Python
12345678910111213141516# Flask - Micro web framework
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello, World!"
# Django - Full-featured web framework
# (Typically used in larger projects)
# Requests - HTTP library
import requests
response = requests.get('https://api.github.com')
data = response.json()
Machine Learning
Python
12345678# Scikit-learn - Machine learning
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
# TensorFlow/PyTorch - Deep learning
# import tensorflow as tf
# import torch
Best Practices
Code Style (PEP 8)
Python
1234567891011121314151617181920212223# Use snake_case for variables and functions
user_name = "john_doe"
def calculate_total_price():
pass
# Use PascalCase for classes
class UserAccount:
pass
# Constants in UPPER_CASE
MAX_CONNECTIONS = 100
# Use meaningful names
# Bad
d = datetime.date.today()
# Good
today = datetime.date.today()
# Function docstrings
def calculate_area(length, width):
"""
Calculate the area of a rectangle.
Args:
length (float): The length of the rectangle
width (float): The width of the rectangle
Returns:
float: The area of the rectangle
"""
return length * width
Performance Tips
Python
123456789101112131415161718# Use list comprehensions instead of loops
# Good
squares = [x**2 for x in range(10)]
# Use generator expressions for memory efficiency
sum_of_squares = sum(x**2 for x in range(1000000))
# Use enumerate instead of range(len())
# Good
for i, item in enumerate(items):
print(f"{i}: {item}")
# Use zip for parallel iteration
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
Virtual Environments
Bash
12345678910111213141516# Create virtual environment
python -m venv myenv
# Activate (Windows)
myenv\Scripts\activate
# Activate (Unix/MacOS)
source myenv/bin/activate
# Install packages
pip install requests pandas numpy
# Requirements file
pip freeze > requirements.txt
pip install -r requirements.txt
Testing
Python
123456789101112131415161718192021# Using unittest module
import unittest
class TestMathOperations(unittest.TestCase):
def test_addition(self):
self.assertEqual(2 + 2, 4)
def test_division(self):
with self.assertRaises(ZeroDivisionError):
10 / 0
if __name__ == '__main__':
unittest.main()
# Using pytest (third-party)
def test_addition():
assert 2 + 2 == 4
def test_string_contains():
assert "hello" in "hello world"
Resources for Further Learning
Official Documentation
- Python.org - Official Python website
- Python Documentation - Comprehensive documentation
Books
- "Python Crash Course" by Eric Matthes
- "Automate the Boring Stuff with Python" by Al Sweigart
- "Fluent Python" by Luciano Ramalho
- "Effective Python" by Brett Slatkin
Online Learning
Practice Platforms
Community
Continue Learning
Discover more cheatsheets to boost your productivity