Basics
Python variables, types, functions, and scope rules.
Python uses snake_case for variables and functions, and PascalCase for classes. The language is dynamically typed but supports optional type hints.
Comments
# Single-line comment
"""
Multi-line
comment / docstring
"""
Variables
Python has no keyword to declare a variable — assignment creates it:
name = "Ada" # str
age = 30 # int
price = 9.99 # float
active = True # bool
Type Hints (3.5+)
name: str = "Ada"
age: int = 30
prices: list[float] = [9.99, 4.50]
Functions
def greet(name: str) -> str:
return f"Hello, {name}"
# Default arguments
def connect(host: str = "localhost", port: int = 5432):
...
Lambda
square = lambda x: x ** 2
Scope
- Local — inside a function
- Global — module-level; use
globalkeyword to modify inside a function - Nonlocal — enclosing function scope; use
nonlocalkeyword
count = 0 # global
def increment():
global count
count += 1
Next: Conditions & Switches