Variable Scope
Local variables are defined inside a function and are only accessible within that function's body. Trying to access a local variable from the outside raises a NameError.
def calculate():
result = 42
print(result)
calculate() # prints 42
# print(result) # NameError: name 'result' is not defined
Global variables are declared outside any function. They can be read inside a function without any special syntax. However, to modify a global variable, you must use the global keyword; otherwise Python creates a new local variable with the same name.
counter = 0
def show():
print(counter) # reads the global variable
def increase():
global counter
counter += 1
show() # 0
increase()
show() # 1
Sharing Data Across Functions
When several functions need to work with the same data, two common approaches are:
- using a shared global variable,
- passing data through return values and parameters.
Shared global variable
balance = 0
def deposit(amount):
global balance
balance += amount
def print_balance():
print(balance)
deposit(100)
print_balance() # 100
Return values as parameters – the cleaner recommendation:
def build_product(code):
return {"code": code, "active": True}
def show_product(prod):
print(f"Product {prod['code']} is {'active' if prod['active'] else 'inactive'}")
item = build_product("P-200")
show_product(item)
Function Return Values
A return statement immediately exits the function, so only the first encountered return is executed. Any code after it becomes unreachable.
def first_only():
return "alpha"
return "beta" # never executes
result = first_only()
print(result) # alpha
To return multiple values, separate them with commas. Python automatically packs them into a tuple.
def extremes(seq):
return min(seq), max(seq)
lowest, highest = extremes([8, 3, 9, 1, 6])
print(lowest, highest) # 1 9
You can also explicitly return a tuple, list, or dictionary when you need to send back more structured data.
Function Parameters
Positional Arguments
Arguments are assigned to parameters based on their position in the call.
def register(name, age, city):
print(f"{name} is {age} years old and lives in {city}")
register("Mia", 28, "Oslo")
Keyword Arguments
Using key=value makes the call more readable and independent of parameter order. Positional arguments must still appear before any keyword arguments.
register(city="Paris", name="Liam", age=34)
Default Parameters (Optional Parameters)
You can supply a default value in the function definition. Default parameters must follow all non‑default (positional) parameters.
def greet(username, message="Hello"):
print(f"{message}, {username}!")
greet("Noah")
greet("Emma", message="Hi")
Variable-Length Arguments
*args – Packing Extra Positional Arguments
A single asterisk collects any remaining positional arguments into a tuple.
def concatenate(separator, *words):
return separator.join(words)
print(concatenate("-", "high", "level", "api")) # high-level-api
**kwargs – Packing Extra Keyword Arguments
Double asterisks collect addditional keyword arguments into a dictionary.
def display_config(**settings):
for key, value in settings.items():
print(f"{key} = {value}")
display_config(host="0.0.0.0", port=8080, debug=True)
Parameter Order and Matching Rules
When defining a function, place the parameters in this order:
- positional parameters
- default parameters
*args- keyword‑only parameters (after
*or*args) **kwargs
Example:
def entry_point(name, status="new", *flags, category, **meta):
return {
"name": name,
"status": status,
"flags": flags,
"category": category,
"meta": meta
}
record = entry_point("ticket", "open", "priority", category="bug", assignee="alex")
print(record)
When calling, non‑keyword arguments first fill positional parameters, then default parameters, and the remaining ones go into *args. Keyword arguments are matched by name and can set default parameters, keyword‑only parameters, or be collected by **kwargs.
Unpacking
Tuple Unpacking
You can assign tuple elements to multiple variables in one statement.
def get_position():
return 15, 25, 35
x, y, z = get_position()
print(x, y, z) # 15 25 35
Dictionary Unpacking
When you unpack a dictionary (e.g., during iteration), you obtain its keys.
info = {"language": "Python", "version": 3.12}
key1, key2 = info
print(key1, info[key1]) # language Python
print(key2, info[key2]) # version 3.12
Swapping Variable Values
Python allows you to swap two variables without a temporary variable using simultaneous assignment (tuple packing/unpacking).
a = 5
b = 10
a, b = b, a
print(a, b) # 10 5