Python Cheat Sheet
BASIC SYNTAX
# Comments
# This is a comment
''' Multi-line
comment '''
# Variables
x = 10
name = "Alice"
pi = 3.14
is_valid = True
DATA TYPES
int # 1, 100, -34
float # 3.14, -0.5
str # 'hello', "world"
bool # True, False
list # [1, 2, 3]
tuple # (1, 2, 3)
set # {1, 2, 3}
dict # {'a': 1, 'b': 2}
CONTROL STRUCTURES
# If-else
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Zero")
# Loops
for i in range(5):
print(i)
while x < 10:
x += 1
# Loop control
break # exit loop
continue # skip to next iteration
FUNCTIONS
Python Cheat Sheet
def greet(name):
return "Hello " + name
# Lambda
square = lambda x: x ** 2
COLLECTIONS
# Lists
fruits = ['apple', 'banana']
fruits.append('orange')
fruits[0] # 'apple'
# Tuples
point = (10, 20)
x, y = point
# Sets
s = {1, 2, 3}
s.add(4)
# Dictionaries
person = {'name': 'Bob', 'age': 25}
person['name'] # 'Bob'
RANDOM & MATH
import math
math.sqrt(16)
math.pi
import random
random.randint(1, 10)
random.choice([1, 2, 3])
STRINGS
s = "hello"
s.upper() # "HELLO"
s.lower() # "hello"
s.strip() # remove spaces
s.split(",") # split string
s.replace("h", "y")
len(s)
FILE I/O
Python Cheat Sheet
# Write
with open("file.txt", "w") as f:
f.write("Hello")
# Read
with open("file.txt", "r") as f:
data = f.read()
CLASSES & OBJECTS
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print("Woof!")
d = Dog("Max")
d.bark()
EXCEPTION HANDLING
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Done")
LIST COMPREHENSION
squares = [x ** 2 for x in range(10)]
MODULES
import math
from datetime import datetime
ASSERTIONS & TESTING
assert 2 + 2 == 4
ADVANCED TOPICS
Python Cheat Sheet
# Generators
def gen():
yield 1
yield 2
# Decorators
def decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
@decorator
def say_hello():
print("Hello")
COMMON BUILT-IN FUNCTIONS
len(), type(), range(), print(), input()
str(), int(), float(), list(), set(), dict()
sum(), min(), max(), sorted(), zip(), map(), filter()
VIRTUAL ENV & PACKAGE MANAGEMENT
python -m venv env
source env/bin/activate # Linux/macOS
env\Scripts\activate # Windows
pip install requests
pip list
USEFUL LIBRARIES
| Purpose | Library |
|---------------|----------------|
| HTTP Requests | requests |
| Data Analysis | pandas |
| Plotting | matplotlib |
| ML/AI | scikit-learn, tensorflow, transformers |
| Web Dev | flask, django |
| GUI Apps | tkinter, PyQt5 |