Python Cheat Sheet
Complete reference guide for Python with interactive examples and live playground links
Basic Syntax
Hello World
The classic first program: outputting text to the console.
# Print Hello World
print("Hello, World!")
Variables and Data Types
Basic variable assignment and data type conversion
# Variables
name = "Python"
age = 30
height = 5.9
is_active = True
# Data Types
text = str("Hello")
number = int(42)
decimal = float(3.14)
boolean = bool(True)
String Operations
Common string operations and formatting techniques
# String methods
text = "Hello World"
print(text.upper()) # HELLO WORLD
print(text.lower()) # hello world
print(text.replace("World", "Python")) # Hello Python
print(text.split()) # ['Hello', 'World']
print(len(text)) # 11
# String formatting
name = "Alice"
age = 25
print(f"My name is {name} and I'm {age} years old")
Lists and Tuples
Working with lists and tuples, basic operations
# Lists (mutable)
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
fruits.insert(1, "grape")
fruits.remove("banana")
print(fruits[0]) # apple
# Tuples (immutable)
coordinates = (10, 20)
x, y = coordinates # unpacking
print(f"X: {x}, Y: {y}")
Print & Input
Output and input operations
# Print statements
print("Hello World")
print(f"My name is {name}")
print("Age:", age)
# User input
user_name = input("Enter your name: ")
user_age = int(input("Enter your age: "))
Comments
Different ways to add comments
# Single line comment
"""
Multi-line comment
This is a docstring
"""
'''
Another way to write
multi-line comments
'''
Control Flow
Conditional Statements
Conditional logic and decision making
# If-elif-else
age = 18
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")
# Ternary operator
status = "Adult" if age >= 18 else "Minor"
Loops
Different types of loops and comprehensions
# For loop
for i in range(5):
print(i)
for fruit in ["apple", "banana"]:
print(fruit)
for i, value in enumerate(["a", "b", "c"]):
print(f"{i}: {value}")
# While loop
count = 0
while count < 5:
print(count)
count += 1
# List comprehension
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
Loops Control
Different types of loops and comprehensions
# Loop control
for i in range(10):
if i == 3:
continue
if i == 7:
break
print(i)
Exception Handling
Error handling with try-catch blocks
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")
else:
print("No errors occurred")
finally:
print("This always executes")
If Statements
Conditional statements and logic
# Basic if-else
age = 18
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")
# Ternary operator
status = "Adult" if age >= 18 else "Minor"
# Multiple conditions
if age >= 18 and age <= 65:
print("Working age")
Functions
Function Definition
Function definition, parameters, and lambda functions
# Basic function
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
# Function with default parameters
def greet_with_title(name, title="Mr."):
return f"Hello, {title} {name}!"
# Lambda function
square = lambda x: x**2
print(square(5)) # 25
# Function with *args and **kwargs
def flexible_func(*args, **kwargs):
print(f"Args: {args}")
print(f"Kwargs: {kwargs}")
Decorators
Creating and using decorators
# Simple decorator
def timer_decorator(func):
def wrapper(*args, **kwargs):
import time
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Function took {end - start:.4f} seconds")
return result
return wrapper
@timer_decorator
def slow_function():
import time
time.sleep(1)
return "Done"
Data Structures
Dictionaries
Dictionary operations and comprehensions
# Dictionary operations
person = {"name": "Alice", "age": 30, "city": "New York"}
person["job"] = "Engineer" # Add key
print(person.get("age", 0)) # Safe access
print(person.keys()) # dict_keys(['name', 'age', 'city', 'job'])
print(person.values()) # dict_values(['Alice', 30, 'New York', 'Engineer'])
# Dictionary comprehension
squares_dict = {x: x**2 for x in range(5)}
Sets
Set operations and mathematical set functions
# Set operations
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1.union(set2)) # {1, 2, 3, 4, 5, 6}
print(set1.intersection(set2)) # {3, 4}
print(set1.difference(set2)) # {1, 2}
# Set comprehension
even_set = {x for x in range(10) if x % 2 == 0}
Lists
List operations and comprehensions
# List creation and operations
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
# List methods
fruits.append("orange")
fruits.insert(1, "grape")
fruits.remove("banana")
fruits.pop()
# List comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in numbers if x % 2 == 0]
File I/O
File Operations
File reading, writing, and JSON handling
# Reading files
with open('file.txt', 'r') as file:
content = file.read()
lines = file.readlines()
# Writing files
with open('output.txt', 'w') as file:
file.write("Hello, World!")
file.writelines(["Line 1\n", "Line 2\n"])
# JSON operations
import json
data = {"name": "Alice", "age": 30}
with open('data.json', 'w') as file:
json.dump(data, file, indent=2)
with open("data.json", "r") as file:
loaded_data = json.load(file)
Popular Libraries
Essential Imports
Common imports and library usage
# Standard library
import os
import sys
import datetime
import random
import math
# Usage examples
current_time = datetime.datetime.now()
random_number = random.randint(1, 100)
current_directory = os.getcwd()
square_root = math.sqrt(16)
# Popular third-party libraries
import requests
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# HTTP request
response = requests.get("https://api.github.com")
data = response.json()
NumPy Basics
NumPy array creation and basic operations
import numpy as np
# Create arrays
arr = np.array([1, 2, 3, 4, 5])
matrix = np.array([[1, 2], [3, 4]])
# Array operations
print(arr * 2) # [2 4 6 8 10]
print(np.mean(arr)) # 3.0
print(np.max(arr)) # 5
print(arr.reshape(5, 1)) # Reshape array
Pandas Basics
Pandas DataFrame creation and manipulation
import pandas as pd
# Create DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['NYC', 'LA', 'Chicago']}
df = pd.DataFrame(data)
# DataFrame operations
print(df.head())
print(df.describe())
print(df[df['Age'] > 25]) # Filter rows
print(df.groupby('City')['Age'].mean()) # Group by
Requests Library
HTTP requests with the requests library
import requests
# GET request
response = requests.get('https://api.github.com/users/octocat')
data = response.json()
print(f"Status: {response.status_code}")
# POST request
payload = {'key': 'value'}
response = requests.post('https://httpbin.org/post', json=payload)
# Headers and parameters
headers = {'Authorization': 'Bearer token'}
params = {'page': 1, 'limit': 10}
response = requests.get(url, headers=headers, params=params)
Regex
Using the re module for regular expressions: matching, finding, and replacing.
import re
# Match a pattern
pattern = r"\d{3}-\d{2}-\d{4}"
text = "My number is 123-45-6789."
match = re.search(pattern, text)
if match:
print("Found:", match.group())
# Find all matches
numbers = re.findall(r"\d+", "There are 24 apples and 17 oranges.")
print(numbers) # ['24', '17']
# Replace with regex
result = re.sub(r"apples", "bananas", "I like apples.")
print(result) # I like bananas.
Object-Oriented Programming
Class Definition
Class definition with methods and properties
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
self._private_var = "hidden"
def introduce(self):
return f"Hi, I'm {self.name} and I'm {self.age} years old"
@property
def adult(self):
return self.age >= 18
@staticmethod
def species():
return "Homo sapiens"
# Usage
person = Person("Alice", 25)
print(person.introduce())
Inheritance
Class inheritance and method overriding
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
# Usage
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # Buddy says Woof!
Advanced Topics
Generators
Generator functions and expressions
# Generator function
def fibonacci_generator(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# Generator expression
squares_gen = (x**2 for x in range(10))
# Usage
fib = fibonacci_generator(5)
for num in fib:
print(num) # 0, 1, 1, 2, 3
Context Managers
Creating and using context managers
from contextlib import contextmanager
@contextmanager
def timer():
import time
start = time.time()
try:
yield
finally:
end = time.time()
print(f"Time taken: {end - start:.4f} seconds")
# Usage
with timer():
# Some time-consuming operation
sum(range(1000000))
Python - Interactive Developer Reference
Hover over code blocks to copy or run in live playground