Skip to main content

Default Parameters & Variable Scope

Sometimes you want a function parameter to be optional. You can give it a default fallback value inside the definition.

Default Parameter Values​

If whoever calls the function does not provide an argument, Python automatically uses the default value:

def greet(name="Guest"):
print(f"Welcome, {name}!")

greet() # Uses default: Welcome, Guest!
greet("Alice") # Uses argument: Welcome, Alice!
Never Use Lists as Default Parameters

When creating optional arguments, never put an empty list [] or dictionary {} as a default parameter! Python creates default parameters only once when reading the program. If you modify that list, every subsequent function call shares the exact same modified list:

# Wrong - shares the same list across all calls
def add_item(item, box=[]):
box.append(item)
return box

# Right - use None as a placeholder
def add_item_safe(item, box=None):
if box is None:
box = []
box.append(item)
return box

Local vs. Global Variables (Scope)​

Scope determines where variables can be seen and used in your program.

1. Local Variables (Private to the Function)​

Any variable created inside a function only exists inside that function. As soon as the function finishes running, Python destroys the local variable:

def calculate():
secret = "hidden_code"

# print(secret) # NameError: name 'secret' is not defined outside the function!

2. Global Variables (Visible Everywhere)​

Variables created outside at the top level of your script are global. Functions inside the script can read them:

APP_NAME = "Python Lab"

def show_banner():
print(f"Running on {APP_NAME}")
Common Beginner Mistakes
  • Local Variable Leak: Trying to access a variable declared inside a function from outside raises NameError.
  • Fix: Use return to pass the local result out to the caller (total = calculate()).

Quick Summary​

  • Default Parameters: Provide fallback values when callers omit arguments (e.g., def connect(port=8080):).
  • Parameter Ordering: Default parameters must always follow non-default parameters.
  • Local Scope: Variables created inside a function are destroyed when the function finishes.
  • Global Scope: Variables defined at the module level are readable globally.

What's Next?​

Let's explore how to write functions that accept any number of inputs using *args and **kwargs in the next lesson!