for item in items:
print(item)
for index, item in enumerate(items, start=1):
print(index, item)
squares = [n * n for n in range(5)]
evens = [n for n in range(10) if n % 2 == 0]
Functions and imports
def greet(name, title="Mr/Ms"):
return f"Hi, {title} {name}!"
from pathlib import Path
from datetime import datetime
print(Path("notes.txt").exists())
print(datetime.now())
Exceptions
try:
value = int(user_input)
except ValueError:
value = 0
finally:
print("Done")
assert value >= 0, "Value must be non-negative"
raise ValueError("Invalid input")
Classes and dataclasses
class Person:
def __init__(self, name, age=0):
self.name = name
self.age = age
def greet(self):
return f"Hi, I'm {self.name}"
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
Files and JSON
with open("notes.txt", "r", encoding="utf-8") as f:
content = f.read()
import json
data = {"name": "Alex", "active": True}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
with open("data.json", "r", encoding="utf-8") as f:
loaded = json.load(f)