Basics
Variables & Types
# Variables (no type declaration needed)
name = "Alice"
age = 25
height = 5.7
is_student = True
nothing = None
# Type checking
type(name) #
isinstance(age, int) # True
# Type conversion
int("42") # 42
float("3.14") # 3.14
str(100) # "100"
bool(0) # False
# Multiple assignment
a, b, c = 1, 2, 3
x = y = z = 0
# Print
print("Hello", name, sep=", ", end="!\n")
Numbers & Math
10 + 3 # 13 addition
10 - 3 # 7 subtraction
10 * 3 # 30 multiplication
10 / 3 # 3.333 division (float)
10 // 3 # 3 floor division
10 % 3 # 1 modulo
10 ** 3 # 1000 exponent
import math
math.sqrt(16) # 4.0
math.ceil(3.2) # 4
math.floor(3.8) # 3
math.pi # 3.14159...
math.pow(2, 8) # 256.0
abs(-5) # 5
round(3.7) # 4
max(1,2,3) # 3
min(1,2,3) # 1
Strings
String Methods
s = "Hello World"
len(s) # 11
s.upper() # "HELLO WORLD"
s.lower() # "hello world"
s.strip() # remove leading/trailing spaces
s.lstrip() # left strip
s.rstrip() # right strip
s.replace("World","Python") # "Hello Python"
s.split(" ") # ["Hello","World"]
s.startswith("He") # True
s.endswith("ld") # True
s.find("World") # 6 (index or -1)
s.count("l") # 3
s.isdigit() # False
s.isalpha() # False
# f-string (recommended)
name = "Alice"
print(f"Hello, {name}! Age: {25*1}")
# Slicing
s[0:5] # "Hello"
s[-5:] # "World"
s[::-1] # reverse
" ".join(["a","b","c"]) # "a b c"
Control Flow
if / elif / else
score = 85
if score >= 90:
print("A")
elif score >= 70:
print("B")
else:
print("F")
# One-liner ternary
result = "pass" if score >= 50 else "fail"
# Logical operators
if age >= 18 and has_id:
print("allowed")
if not is_banned:
print("welcome")
Loops
# for loop
for i in range(5): # 0,1,2,3,4
print(i)
for i in range(1, 10, 2): # 1,3,5,7,9
print(i)
# for with enumerate
for i, item in enumerate(["a","b","c"]):
print(i, item)
# for with zip
for a, b in zip([1,2,3], ["x","y","z"]):
print(a, b)
# while loop
n = 0
while n < 5:
print(n)
n += 1
# break / continue / else
for i in range(10):
if i == 5: break
if i % 2 == 0: continue
print(i)
Functions
Function Syntax
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
# *args (variable positional)
def total(*args):
return sum(args)
total(1, 2, 3) # 6
# **kwargs (variable keyword)
def show(**kwargs):
for k, v in kwargs.items():
print(f"{k}: {v}")
# Lambda (anonymous)
square = lambda x: x ** 2
add = lambda a, b: a + b
# Type hints (Python 3.5+)
def add(a: int, b: int) -> int:
return a + b
Lists & Tuples
List Methods
nums = [3, 1, 4, 1, 5, 9]
nums.append(2) # add to end
nums.insert(0, 0) # insert at index
nums.extend([6,7]) # extend with list
nums.remove(1) # remove first occurrence
nums.pop() # remove & return last
nums.pop(0) # remove at index
nums.index(5) # get index
nums.count(1) # count occurrences
nums.sort() # sort in place
nums.sort(reverse=True)
nums.reverse() # reverse in place
nums.clear() # empty the list
len(nums) # length
sum(nums) # sum
sorted(nums) # returns new sorted list
list(reversed(nums))# returns new reversed list
# Tuple (immutable)
t = (1, 2, 3)
t[0] # 1
Dicts & Sets
Dictionary
person = {"name": "Alice", "age": 25}
person["name"] # "Alice"
person.get("age", 0) # 25 (with default)
person["city"] = "NYC" # add/update
del person["age"] # delete key
"name" in person # True
person.keys() # dict_keys(["name","city"])
person.values() # dict_values(["Alice","NYC"])
person.items() # dict_items([...])
# Loop
for key, val in person.items():
print(key, val)
person.update({"age": 26, "job": "dev"})
person.pop("job") # remove & return
# Set
s = {1, 2, 3, 2} # {1, 2, 3}
s.add(4); s.remove(2)
s1 | s2 # union
s1 & s2 # intersection
s1 - s2 # difference
Comprehensions
List, Dict, Set
# List comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
flat = [x for row in matrix for x in row]
# Dict comprehension
sq_dict = {x: x**2 for x in range(5)}
# Set comprehension
unique_sq = {x**2 for x in [-1, 0, 1, 2, 2]}
# Generator expression (lazy, memory-efficient)
total = sum(x**2 for x in range(1000))
# Conditional in value
labels = ["even" if x%2==0 else "odd" for x in range(5)]
OOP — Classes
Class Syntax
class Animal:
# Class variable
kingdom = "Animalia"
def __init__(self, name, age):
self.name = name # instance variable
self.age = age
def speak(self):
return f"{self.name} makes a sound."
def __str__(self):
return f"Animal({self.name}, {self.age})"
@classmethod
def create(cls, name):
return cls(name, 0)
@staticmethod
def is_animal(x):
return isinstance(x, Animal)
class Dog(Animal): # inheritance
def speak(self):
return f"{self.name} barks!"
d = Dog("Rex", 3)
print(d.speak())
print(isinstance(d, Animal)) # True
File I/O
Read & Write Files
# Read file
with open("file.txt", "r") as f:
content = f.read() # whole file
lines = f.readlines() # list of lines
for line in open("file.txt"):
print(line.strip())
# Write file
with open("output.txt", "w") as f:
f.write("Hello\n")
f.writelines(["line1\n","line2\n"])
# Append
with open("log.txt", "a") as f:
f.write("new entry\n")
# JSON
import json
data = json.loads('{"key":"val"}') # parse
text = json.dumps(data, indent=2) # stringify
with open("data.json","w") as f:
json.dump(data, f, indent=2)
Exceptions
try / except / finally
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except (TypeError, ValueError):
print("Type or Value error")
except Exception as e:
print(f"Unexpected: {e}")
else:
print("No exception occurred")
finally:
print("Always runs")
# Raise exceptions
raise ValueError("Invalid input")
raise TypeError(f"Expected int, got {type(x)}")
# Custom exception
class MyError(Exception):
pass
raise MyError("Something went wrong")
Built-in Functions
Useful Builtins
len([1,2,3]) # 3
range(5) # 0-4
range(1, 10, 2) # 1,3,5,7,9
enumerate(lst) # (index, value) pairs
zip(a, b) # pair elements
map(fn, lst) # apply fn to each
filter(fn, lst) # filter by fn
sorted(lst, key=..., reverse=True)
all([True,True]) # True
any([False,True]) # True
sum([1,2,3]) # 6
min([3,1,2]) # 1
max([3,1,2]) # 3
abs(-5) # 5
round(3.7) # 4
print(f"{val:.2f}") # format float
hex(255) # "0xff"
bin(10) # "0b1010"
input("Enter: ") # user input