Functions and Scope

Site Admin · 11 Sep 2026 · 8 views

Functions and Scope

Why Functions Exist

As programs grow, repeating the same code becomes a maintenance nightmare. Functions let you package a piece of logic under a name, call it whenever you need it, and change it in one place. A function takes inputs (arguments), does its work, and optionally returns a result.

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

print(greet("Ada"))     # Hello, Ada!

The def keyword defines the function, the parentheses declare parameters, and the body is indented. The return statement sends a value back to the caller; without it, the function returns None.

Parameters and Defaults

You can give parameters default values so the caller can omit them. Arguments can be passed positionally or by name, which improves readability for functions with many parameters.

def describe(name, age=0):
    return f"{name} is {age} years old"

print(describe("Ada"))                  # Ada is 0 years old
print(describe("Grace", age=36))        # Grace is 36 years old

Scope: Where Variables Live

Scope determines which variables a piece of code can see. Variables assigned inside a function belong to that function's local scope and disappear when the function ends. Variables assigned at the top level of a script are global and visible everywhere after their creation.

tax_rate = 0.2          # global
def add_tax(price):
    return price * (1 + tax_rate)   # reads the global

If a function assigns a variable with the same name as a global, Python treats it as a new local variable unless you declare global. Prefer passing values as arguments and returning the result; it keeps functions predictable and easy to test.

Docstrings

Every function deserves a short docstring, a triple-quoted string right after the def line that explains what the function does. Tools and other programmers read docstrings to understand your code quickly.

def square(x):
    """Return the square of x."""
    return x * x

Key Points

  • def defines a function; return sends a value back to the caller.
  • Parameters can have defaults, and arguments can be passed by name.
  • Local variables exist only inside their function; globals live at the top level.
  • Prefer arguments and return values over global variables.
  • Write a docstring for every function to explain its purpose.
Share this post:

Comments (0)

Please login or register to comment.