🐍
Programming
Python Syntax Quick Reference
Essential Python syntax, built-ins, data structures, list comprehensions, and common patterns.
Back to Notes Library
Python Syntax Quick Reference
Variables & Types
python
name = "Alex" # str
age = 25 # int
score = 98.5 # float
is_active = True # bool
data = None # NoneType
# Type checking
type(name) # <class 'str'>
isinstance(age, int) # True
# Type casting
int("42") # 42
str(42) # "42"
float("3.14") # 3.14
list("abc") # ['a', 'b', 'c']String Operations
python
s = "Hello, World!"
# Methods
s.upper() # "HELLO, WORLD!"
s.lower() # "hello, world!"
s.strip() # removes whitespace
s.split(", ") # ["Hello", "World!"]
s.replace("o","0") # "Hell0, W0rld!"
s.startswith("He") # True
s.endswith("!") # True
"lo" in s # True
# f-strings (best way)
name = "Alex"
age = 25
f"Name: {name}, Age: {age}" # "Name: Alex, Age: 25"
f"{3.14159:.2f}" # "3.14"
f"{1000000:,}" # "1,000,000"Collections
python
# List — ordered, mutable
fruits = ["apple", "banana", "cherry"]
fruits.append("date") # add to end
fruits.insert(0, "avocado") # insert at index
fruits.pop() # remove last
fruits.remove("banana") # remove by value
fruits[0] # first item
fruits[-1] # last item
fruits[1:3] # slice
# Tuple — ordered, immutable
coords = (10.5, 20.3)
x, y = coords # unpacking
# Dict — key-value pairs
person = {"name": "Alex", "age": 25}
person["name"] # "Alex"
person.get("email", "N/A") # safe get with default
person["city"] = "NYC" # add/update
person.keys() # dict_keys
person.values() # dict_values
person.items() # dict_items
# Set — unique values
unique = {1, 2, 3, 3} # {1, 2, 3}
unique.add(4)
unique.discard(1)
a & b # intersection
a | b # union
a - b # differenceControl Flow
python
# If / elif / else
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")
# Ternary
status = "adult" if age >= 18 else "minor"
# Match (Python 3.10+)
match command:
case "quit":
quit()
case "hello":
print("Hello!")
case _:
print("Unknown")Loops
python
# For loop
for item in ["a", "b", "c"]:
print(item)
for i in range(10): # 0-9
print(i)
for i, val in enumerate(["a","b","c"]):
print(i, val) # 0 a, 1 b, 2 c
for k, v in dict.items():
print(k, v)
# While loop
count = 0
while count < 5:
count += 1
# Loop control
break # exit loop
continue # skip to next iteration
pass # do nothing (placeholder)Functions
python
# Basic function
def greet(name: str, greeting: str = "Hello") -> str:
return f"{greeting}, {name}!"
# *args — variable positional args
def sum_all(*args):
return sum(args)
# **kwargs — variable keyword args
def print_info(**kwargs):
for key, val in kwargs.items():
print(f"{key}: {val}")
# Lambda
square = lambda x: x ** 2
double = lambda x: x * 2
# Decorators
def timer(func):
def wrapper(*args, **kwargs):
import time
start = time.time()
result = func(*args, **kwargs)
print(f"Time: {time.time() - start:.4f}s")
return result
return wrapper
@timer
def slow_function():
import time
time.sleep(1)List Comprehensions
python
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
pairs = [(x, y) for x in range(3) for y in range(3)]
# Dict comprehension
squared_dict = {x: x**2 for x in range(5)}
# Set comprehension
unique_lengths = {len(w) for w in ["hi","hello","hey"]}Classes & OOP
python
class Animal:
species = "Unknown" # class variable
def __init__(self, name: str, age: int):
self.name = name # instance variable
self.age = age
def speak(self) -> str:
return f"{self.name} makes a sound"
def __repr__(self) -> str:
return f"Animal(name={self.name!r}, age={self.age})"
class Dog(Animal): # inheritance
def speak(self) -> str: # override
return f"{self.name} says Woof!"
dog = Dog("Rex", 3)
dog.speak() # "Rex says Woof!"Error Handling
python
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except (TypeError, ValueError):
print("Type or value error")
else:
print("No error occurred")
finally:
print("Always runs")
# Raise custom exception
class CustomError(Exception):
pass
raise CustomError("Something went wrong")File I/O
python
# Read
with open("file.txt", "r") as f:
content = f.read() # full file
lines = f.readlines() # list of lines
# Write
with open("file.txt", "w") as f:
f.write("Hello World\n")
# JSON
import json
data = {"key": "value"}
json.dumps(data) # to string
json.loads('{"key": "v"}') # from string
with open("data.json", "w") as f:
json.dump(data, f, indent=2)Common Built-ins
python
len([1,2,3]) # 3
range(0, 10, 2) # 0,2,4,6,8
map(str, [1,2,3]) # ['1','2','3']
filter(None, [0,1,None]) # [1]
zip([1,2], ['a','b']) # [(1,'a'),(2,'b')]
sorted([3,1,2]) # [1, 2, 3]
sorted(items, key=lambda x: x.name)
enumerate(["a","b","c"]) # (0,'a'),(1,'b'),(2,'c')
any([False, True, False]) # True
all([True, True, True]) # True
min([3,1,2]) # 1
max([3,1,2]) # 3
sum([1,2,3]) # 6
abs(-5) # 5
round(3.14159, 2) # 3.1410K+ Members Growing Daily
Get Free AI Notes Daily
Join AiTechWorlds on Telegram and get daily AI tips, prompt engineering templates, coding resources, and exclusive content — 100% free!
📚 Free Study Notes🤖 AI Tips Daily⚡ Prompt Templates💻 Coding Resources
Join Free Channel
No spam. Leave anytime.