Python uses indentation instead of braces. Statements normally need no semicolon.
print("Hello, world!")
name = "Susan"
count = 3
print(f"Hello {name}")
print(f"Count: {count}")01 — Structure & Output
count = 10 # int
price = 29.95 # float
name = "Susan" # str
available = True # bool
painting = None # no value
number = int("25")
price = float("29.95")
text = str(25)
TAX_RATE = 0.06625 # constant by conventionPython is dynamically typed. Core types: int, float, str, bool, None. Boolean literals are True/False.
02 — Variables & Types
+ - * / %
** # exponent
// # floor division
score += 1
== != > < >= <=
if age >= 18 and member:
print("Access")
if not member:
print("Not a member")
animal = "Great Blue Heron"
print(len(animal))
print(animal.upper())
print(animal.lower())
print("Heron" in animal)
print(f"${29.956:.2f}")Python uses and, or, not. It has no ++/--.
03 — Operators & Strings
# list
birds = ["Heron", "Egret", "Pelican"]
print(birds[0])
print(birds[-1])
birds.append("Osprey")
# tuple
coordinates = (10, 20)
# dictionary
painting = {"title": "Blue Heron", "price": 125, "sold": False}
print(painting["title"])
painting["price"] = 150
# set
tags = {"bird", "wildlife", "painting"}[] list · () tuple · {key: value} dictionary · {values} set.
04 — Collections
if paintings > 10:
print("Large")
elif paintings > 5:
print("Medium")
else:
print("Low")
for bird in birds:
print(bird)
for i in range(5):
print(i)
for i in range(0, 10, 2):
print(i)
count = 0
while count < 5:
count += 1
# loop controls
break
continuerange(start, stop, step) excludes the stop value. Python uses elif, not else if.
05 — Control Flow & Loops
def add(a, b):
return a + b
def greet(name="Guest"):
print(f"Hello {name}")
def typed_add(a: int, b: int) -> int:
return a + b
count: int = 5
birds: list[str] = ["Heron", "Egret"]Pattern: def function_name(parameters):. A function without an explicit return value returns None. Type hints aid readability and tooling.
06 — Functions & Type Hints
class Painting:
def __init__(self, title, price):
self.title = title
self.price = price
def display(self):
print(f"{self.title}: ${self.price}")
painting = Painting("Blue Heron", 125)
painting.display()
import math
print(math.sqrt(25))
from math import sqrt
if __name__ == "__main__":
print("Run directly")__init__ initializes an instance. self refers to the current instance. Use import to load modules.
07 — Classes & Modules
try:
number = int("hello")
except ValueError:
print("Not a number")
finally:
print("Always runs")
name = input("Name: ")
age = int(input("Age: "))
# CORE PATTERNS
name = value
print(...)
if condition:
...
for item in collection:
...
def function_name(parameters):
...input() returns a string. Convert it when numeric input is required.