Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
A function is a recipe: write it once, hand in ingredients, get a dish back. input and import, def and return, defaults, returning a tuple, functions as objects, the LEGB scope rule, global and nonlocal, then *args and **kwargs, with real output.
What you will learn
- Define a function, pass arguments into parameters, use defaults and keyword arguments, and return one or more values
- Explain print versus return and why a function with no return gives None
- Use the LEGB rule to predict which name Python finds, and when global and nonlocal are needed
- Collect any number of values with *args and **kwargs, and spread a list or dict into a call
Before you start
- Python Conditionals and Loops
- Python Lists, Tuples, Sets and Dicts
So far every file has run from top to bottom, and if you needed something twice, you wrote it twice. A function lets you give a job a name and use it whenever you want.
Think about a recipe. You write it once, and writing it cooks nothing; it just sits there with a name on top. When you want the dish, you hand over the ingredients and the cooking starts, and a dish comes back. Hand over different ingredients and you get a different dish from the same recipe. The recipe is the function, the ingredients are what you pass in, and the dish is what it returns.
Two things Python gives you: input and import
value = input("Number: ")
print(type(value))
print(type(int(value)))
print(int(value) + 1)
Number: <class 'str'>
<class 'int'>
43
Given 42, input shows the message, waits, and hands back what was typed. The answer was fed in from outside here, which is why it sits on the prompt line. The thing to remember: input always gives a string, even when it looks like a number. Convert it with int before doing maths.
import math
from math import pi, ceil
import statistics as st
print(math.sqrt(16))
print(pi)
print(ceil(4.2))
print(st.mean([2, 4, 9]))
4.0
3.141592653589793
5
5
Three ways to import: the whole module (math.sqrt), just some names (pi with nothing in front), or the module with a short alias (st). ceil rounds up. Use whichever keeps your code easy to read.
Your first function
def greet(name):
return f"Hello, {name}!"
message = greet("Alice")
print(message)
print(greet("Bob"))
Hello, Alice!
Hello, Bob!
def means define. Nothing runs yet; Python only remembers the recipe. greet("Alice") is the call: "Alice" is the argument, and it goes into the parameter name. The return line builds the text, and that value comes back to where the call was. A parameter is the name waiting in the definition; an argument is the value you pass in the call.
Defaults and keyword arguments
def power(base, exp=2):
return base ** exp
print(power(5))
print(power(2, 10))
print(power(exp=3, base=2))
25
1024
8
exp defaults to 2, so power(5) is 25. Passing 10 replaces the default. You can also pass by name in any order; those are keyword arguments. Parameters with a default go after the ones without.
Returning two values
def min_max(numbers):
return min(numbers), max(numbers)
result = min_max([3, 1, 7, 2])
print(result)
print(type(result))
lo, hi = min_max([3, 1, 7, 2])
print(lo, hi)
(1, 7)
<class 'tuple'>
1 7
Python packs the two values into one tuple, and you can unpack it right at the call.
No return gives None
def say_hi(name):
print("Hi", name)
value = say_hi("Alice")
print(value)
Hi Alice
None
print put "Hi Alice" in the Terminal, but nothing was returned, so Python hands back None. Print shows something to you; return hands something to your code. Beginners mix these up a lot.
Docstrings and help
def add(a, b):
"""Return the sum of a and b."""
return a + b
print(add(3, 4))
print(add.__doc__)
7
Return the sum of a and b.
The string in triple quotes is a docstring. It doesn't change what add does, but Python keeps it on the function and your IDE reads it too. help(greet) prints it along with how to call the function, type() tells you what something is, and dir() lists everything an object can do. When you meet something new, try those three first.
Functions are objects
def shout(text):
return text.upper() + "!"
def whisper(text):
return text.lower() + "..."
def speak(func, msg):
return func(msg)
print(speak(shout, "hello"))
print(speak(whisper, "Hi"))
print(type(shout))
louder = shout
print(louder("hey"))
HELLO!
hi...
<class 'function'>
HEY!
In speak(shout, "hello") there are no brackets after shout, so you aren't calling it; you're handing it over. A function is an object like a number or a string, and louder = shout gives it a second name. This idea comes back in map, filter and lambda and decorators.
Scope and the LEGB rule
Scope is where a name can be seen. Think about looking for your keys: first your pocket, then your room, then the whole house, and last the front desk of the building. Python searches for a name the same way, nearest box first.
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x)
inner()
print(x)
outer()
print(x)
local
enclosing
global
Each box has its own x. inner finds its own. Back in outer, the inner box is gone, so the search starts at outer's box. At the top of the file you're in the global box. And print itself isn't in any of your boxes, so that search goes all the way out to built-in.
A local name stays local
def make_secret():
secret = 42
return secret
make_secret()
print(secret)
Traceback (most recent call last):
File "S02L01_Functions\scope_error.py", line 7, in <module>
print(secret)
^^^^^^
NameError: name 'secret' is not defined
When the function finishes, its box is gone along with secret. To get a value out of a function, return it and catch it in a variable: secret = make_secret().
Why += fails inside a function
counter = 0
def increment():
counter += 1
increment()
print(counter)
Traceback (most recent call last):
File "S02L01_Functions\unbound_local.py", line 8, in <module>
increment()
~~~~~~~~~^^
File "S02L01_Functions\unbound_local.py", line 5, in increment
counter += 1
^^^^^^^
UnboundLocalError: cannot access local variable 'counter' where it is not associated with a value
Reading a global is fine, but += also assigns. Because of that assignment, Python treats counter as local for the whole function, and the local one has no value yet. The global one is never even looked at.
global and nonlocal
counter = 0
def increment():
global counter
counter += 1
increment()
increment()
print(counter)
2
global counter makes the name inside mean the one at the top of the file. It works, but any function can now change that value, which makes bugs hard to find. Use it rarely, and prefer passing values in and returning them.
def outer():
msg = "hello"
def inner():
nonlocal msg
msg = "world"
inner()
print(msg)
outer()
world
nonlocal is the same idea one level in: it reaches the function around you. Without that line, inner would make its own local msg, and outer would still print hello.
Any number of values: *args
def sum_numbers(*numbers):
print(f"Received: {numbers}")
return sum(numbers)
print(sum_numbers(1, 2, 3))
print(sum_numbers(10, 20, 30, 40, 50))
Received: (1, 2, 3)
6
Received: (10, 20, 30, 40, 50)
150
The star collects every value into one tuple. You'll usually see it written *args, but args is only a name; the star is what matters. Normal parameters fill up first, and the star takes what's left:
def make_pizza(size, *toppings):
print(f"{size}-inch pizza with:")
for topping in toppings:
print(f" - {topping}")
make_pizza(12, "cheese", "olives")
12-inch pizza with:
- cheese
- olives
Named values: **kwargs
def create_user(**user_info):
print(f"Type: {type(user_info)}")
print("User Profile:")
for key, value in user_info.items():
print(f" {key}: {value}")
create_user(
username="alice",
email="[email protected]",
age=28,
)
Type: <class 'dict'>
User Profile:
username: alice
email: [email protected]
age: 28
Double star is the same idea for named values: each pair lands in a dictionary. **kwargs means keyword arguments. Star gives you a tuple; double star gives you a dict.
Collect in a definition, spread in a call
def super_func(*args, **kwargs):
print("args:", args)
print("kwargs:", kwargs)
nums = [1, 2, 3]
info = {"name": "Bob", "age": 25}
super_func(*nums, **info)
args: (1, 2, 3)
kwargs: {'name': 'Bob', 'age': 25}
*args always comes before **kwargs. In a call, *nums spreads the list into separate values and **info spreads the dict into named values. In a definition the stars collect; in a call the stars spread.
Passing everything along
def log_call(func, *args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
def add(a, b):
return a + b
print(log_call(add, 2, 3))
print(log_call(max, 4, 9, 6))
Calling add
5
Calling max
9
log_call takes a function plus whatever else comes, prints its name, and spreads the values back out. It wraps any function without knowing its parameters, which is exactly how decorators work.
Common mistakes
- Doing maths on
input()withoutint(). - Printing inside a function when the caller needed the value returned.
- Expecting a variable made inside a function to exist outside it.
- Using
+=on a global inside a function and gettingUnboundLocalError. - Putting a parameter without a default after one with a default.
Quick recap
| Idea | Remember |
|---|---|
def / return | an argument goes into a parameter; return sends a value back |
| no return | the call gives None |
| LEGB | Local, Enclosing, Global, Built-in; outward only |
global / nonlocal | change a name at file level / in the function around you |
*args | extra positional values as a tuple |
**kwargs | extra named values as a dict |
Next, label what a function takes and returns in Type hints on functions.
Try it yourself
Write a function with *args that returns the smallest and the largest value. Or prompt an AI tool to write it, and then read every line it gives you.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Type Hints on Python Functions: Parameters, Returns, None and Collections
A type hint is a label on a jar: it says what belongs inside but stops nothing. Hint parameters and returns, -> None, str | None, list[str] and dict[str, int], see add("2", "3") print 23, and read hints back with __annotations__.
Python lambda, map, filter, Modules and Packages (with pip and venv)
A lambda is a sticky note next to a def recipe card. Sort words and students with key, map as a conveyor belt, filter as a gate, then your own package with __init__.py, two import errors, and pip install into an activated .venv.
Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
Three work-style use cases (an HR bonus calculator, a product discount pipeline, and a mathkit package) turned into requirement lists and prompts, with one possible result for each read against the list, including the empty-input crash the list forgot.
