Python Functions and Scope

  • Admin
  • 1 min read

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.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated August 9, 2026.

Ask a question

Be specific about what you tried. Questions with a code sample and the exact error message are answered fastest.