Python

Python Functions and Scope

Defining a Function

Functions let you package up reusable logic. Define one with the def keyword:

def greet(name): return f"Hello, {name}!" print(greet("Priya"))

Default and Keyword Arguments

You can give parameters default values, and call them by name for clarity:

def power(base, exponent=2): return base ** exponent print(power(5)) # 25 print(power(2, exponent=5)) # 32

Understanding Scope

A variable created inside a function only exists inside that function — this is called local scope. Variables defined outside any function are in the global scope and can be read (but not modified) from inside a function without extra steps.

count = 0 # global def increment(): count = count + 1 # ERROR: local variable referenced before assignment return count

The global Keyword

To modify a global variable from inside a function, declare it explicitly:

count = 0 def increment(): global count count += 1 return count print(increment()) # 1 print(increment()) # 2

Why Scope Matters

Keeping variables local by default prevents functions from accidentally interfering with each other’s data — a common source of bugs in larger programs. As a rule of thumb, avoid global unless you have a good reason; pass values in as arguments and return results instead.

Practice Exercise

Write a function calculate_total(price, tax_rate=0.18) that returns the price including tax, then call it with just a price and separately with a custom tax rate.

Leave a Reply

Your email address will not be published. Required fields are marked *