Structure your code into reusable functions, master default values and understand variable scope.
Open this lesson in KodokonYou already know how to write loops and conditions; now it's time to structure your code. A function isolates a specific task behind a clear name: you write it once, you test it once, you call it everywhere. def declares the function, parameters receive the input values and return sends the result back to the caller. Remember one thing that's often overlooked: a function with no return returns None.
def net_price(price, tax_rate):
total = price * (1 + tax_rate)
return round(total, 2)
result = net_price(100, 0.2)
print(result) # 120.0Default values make a function flexible without multiplying variants: declare them after the required parameters. When calling, keyword arguments (currency="USD") document your intent. In professional code, you use them as soon as a function has more than two parameters: the call reads clearly without opening the definition.
def format_price(amount, currency="EUR", digits=2):
return f"{amount:.{digits}f} {currency}"
print(format_price(19.9)) # 19.90 EUR
print(format_price(19.9, currency="USD")) # 19.90 USD
print(format_price(19.9, digits=0)) # 20 EURdef add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item("pen")) # ['pen']
print(add_item("book")) # ['book']Scope determines where a variable exists. A variable created inside a function is local: it disappears when the call ends. A function can read a global variable, but any assignment creates a new local variable - the global stays untouched. Good habit: rather than modifying globals, pass parameters and return results; your code becomes predictable and testable.
rate = 0.2
def apply_tax(price):
return round(price * (1 + rate), 2)
def set_rate(new_rate):
rate = new_rate # local variable, no effect
print(apply_tax(100)) # 120.0
set_rate(0.1)
print(apply_tax(100)) # 120.0, the global is untouched