Functions, parameters & return values
Split a program into small functions with default and keyword arguments.
By Invicly Tech, , in Python Programming from Zero. About 12 minutes to read.
In short
A function is a named, reusable block of code. You define it once with def, call it with arguments, and it hands a value back with return. Small functions make programs easier to read, test and change.
Think of it like this: A function is like a vending machine: put in inputs, press the button, get one result back.
Explained simply
A function is a named piece of code you can run as often as you like. You write it once with def, and run it by calling its name with parentheses. Parameters are the inputs it expects; return sends a result back to whoever called it.
Functions make programs readable. A good name like calculate_tax tells the reader what happens without reading every line. They also stop copy-paste: when a calculation lives in one function, you fix a bug in one place and every caller gets the fix.
You can pass arguments by position, in order, or by name, like greet(name="Ana"). Default values make some parameters optional. A parameter written with one star, like *args, collects any number of extra positional values, and the two-star kwargs parameter collects extra named values.
A good function does one job, is short enough to read without scrolling, returns its result instead of printing it, and starts with a docstring that says what it does. Functions like that are easy to test, reuse and change.
Press Play on a diagram to walk through it one step at a time.
- Caller to area(): area(3, 4.5)1area(3, 4.5)
- 2width=3, height=4.5area() to area(): width=3, height=4.5
- area() to round(): round(13.5)3round(13.5)
- round() to area(): returns 144returns 14
- area() to Caller: return 145return 14
- 1Positional first
Filled left to right
- 2Then keywords
Matched by name
- 3Extras collected
Into *args or the kwargs dict, if present
- 4Defaults fill gaps
For parameters nobody passed
- 5Anything missing?
A required parameter left empty raises TypeError
- Shows text to a person
- Function returns None
- Caller cannot reuse the value
- Hard to test
- Hands the value to the caller
- Caller decides to print, save or combine
- Easy to check with assert
- The normal choice
In depth
What happens during a call
When you call area(3, 4), Python first evaluates the arguments. Then it creates a fresh frame, a private workspace for this one call, and binds each parameter name to the argument object. Nothing is copied: the parameter is a new name for the same object the caller passed. The body runs, and return hands one object back and throws the frame away. A function that ends without return gives back None.
Calls can nest: main() calls total(), which calls round(). Python keeps a call stack of frames, one per active call, and returns to the right place when each one finishes. A traceback is simply a printout of that stack at the moment of an error.
Functions are objects too. You can store them in variables and pass them around without calling them. sorted(words, key=len) passes the len function itself, and sorted calls it on each word.
- 1round(13.5)
Running now; returns first
- 2total(prices)
Paused, waiting for round()
- 3main()
Paused, waiting for total()
- 4Module level
The script that called main()
Parameter kinds and the order rules
Python has several kinds of parameters, and the def line must list them in this order. Plain parameters can be passed by position or by name. Parameters with defaults come after the ones without. *args then collects any extra positional arguments into a tuple. Any parameter after *args, or after a bare *, is keyword-only: callers must write its name. Last comes the two-star kwargs parameter, which collects extra named arguments into a dict. Since Python 3.8 you can also put a / in the list: parameters before it are positional-only.
Keyword-only parameters are great for options: def connect(host, *, timeout=10) forces connect("db", timeout=5), so nobody writes a mysterious connect("db", 5).
Calls have rules too: positional arguments first, then keywords. Passing the same parameter twice, or forgetting a required one, raises TypeError with a clear message. A star in a call does the opposite of a star in def: f(*point) spreads a list or tuple into separate arguments.
- Normal
- def f(a, b)
- f(1, 2) or f(b=2, a=1)
- Default
- def f(a, b=2)
- Caller may leave b out
- *args
- Extra positional values
- Arrives as a tuple
- Keyword-only
- Names after * or *args
- Must be passed by name
- kwargs (two stars)
- Extra named values
- Arrives as a dict
- Positional-only
- Names before /
- Cannot be passed by name
Return values: one, many, or None
return ends the function immediately, even in the middle of a loop. That makes early returns a clean way to handle special cases first.
A function always returns exactly one object, but that object can be a tuple, so return low, high effectively returns two values. The caller unpacks them with low, high = min_max(data).
The difference between print and return confuses many beginners. print() shows text to a human and the function still returns None. return gives the value to the calling code, which can store it, test it or pass it on. Most functions should return; only the outer layer of a program should print.
Try to return one kind of thing. A function that returns a number on success but the string "error" on failure forces every caller to check the type. Raise an exception for failures instead, and the normal return value stays simple.
Docstrings, names and lambdas
A docstring is a string literal written as the first statement in the function body. Python stores it, help(func) prints it, and editors show it when you hover over a call. The common convention (PEP 257) is a one-line summary in command form, such as "Return the area of a rectangle.", then a blank line and details: arguments, the return value and errors it may raise.
Names matter as much as code. Use verbs for actions (parse_date, send_email, load_config) and is_ or has_ prefixes for functions that return True or False (is_valid, has_access). If you cannot name a function without the word and, it probably does two jobs.
lambda creates a tiny unnamed function from one expression, like lambda p: p[1]. It is handy as a key for sorted() or max(). If you need a name, a docstring or more than one expression, write a normal def.
Refactoring a script into small functions
Most programs start as one long script that reads input, calculates and prints. Refactoring means restructuring that code without changing what it does. Read through and mark blocks that do one job: parse the input, validate it, compute a result, format the output. Move each block into a function, turn the variables it reads into parameters, and return what it produces instead of setting globals.
Finally, write a main() function that calls the pieces in order; that is the only place that talks to the user. Run the program after each step to check that it still behaves the same.
The payoff is testability. A function like apply_discount(total, percent) can be checked with a few assert lines in seconds, with no typing at a prompt. The rule of thumb: pure calculation in small functions, input and output at the edges.
- 1Spot one job
A block that parses, checks or computes
- 2Name it
A verb that says what it does
- 3Move into def
Variables it reads become parameters
- 4Return the result
No print or global changes inside
- 5Call from main()
main() is the only place doing I/O
- 6Test with assert
Check a few inputs in seconds
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Define functions with def and return~50m
- 2Use default and keyword arguments~50m
- 3Accept *args and **kwargs~50m
- 4Write docstrings for your functions~50m
- 5Refactor a script into small functions~50m
Key points
- Define with def name(params): and send a result back with return.
- A function without return gives back None.
- Default values make parameters optional; keyword arguments make calls readable.
- *args collects extra positional arguments; **kwargs collects extra keyword arguments.
- Write a docstring as the first line to explain what the function does.
Key terms
Tap a card to flip it. 0/6 known
Examples
def greet(name, greeting="Hello"):
"""Return a friendly greeting."""
return f"{greeting}, {name}!"
print(greet("Ana")) # Hello, Ana!
print(greet("Bo", greeting="Hi")) # Hi, Bo!
def total(*prices, tax=0.0):
return sum(prices) * (1 + tax)
def show(**info):
print(info)
print(total(10, 20, 5, tax=0.2)) # 42.0
show(city="Pune", year=2026) # {'city': 'Pune', 'year': 2026}A logging helper with *args and keyword options
You want log("info", "User", "logged in", user="ana") to print one tidy line. Step 1: level is a normal parameter. Step 2: *parts collects any number of message pieces into a tuple. Step 3: sep is keyword-only because it comes after *parts, so it can never be filled by accident. Step 4: the two-star context parameter collects all other named arguments into a dict. Step 5: a caller with a ready-made dict can spread it into the call with two stars.
def log(level, *parts, sep=" ", **context):
"""Print a log line with optional key=value context."""
message = sep.join(str(p) for p in parts)
extras = " ".join(f"{k}={v}" for k, v in context.items())
print(f"[{level.upper()}] {message} {extras}".rstrip())
log("info", "User", "logged in", user="ana", ip="10.0.0.5")
# [INFO] User logged in user=ana ip=10.0.0.5
log("debug", "a", "b", "c", sep="/")
# [DEBUG] a/b/c
settings = {"user": "bo", "attempt": 3}
log("warn", "Retrying", **settings)
# [WARN] Retrying user=bo attempt=3Turning a script into three small functions
The original script read a line of prices, added them, took 10% off and printed the total, all in one block. Step 1: parsing the text becomes parse_prices(), which returns a list. Step 2: the discount becomes apply_discount() with a default of 0 and a guard against silly percentages. Step 3: main() is the only part that uses input() and print(). Now both helpers can be tested with assert without typing anything.
def parse_prices(text):
"""Turn "3.50, 2, 4.25" into a list of floats."""
return [float(p) for p in text.split(",") if p.strip()]
def apply_discount(total, percent=0):
"""Return total reduced by percent (0 to 100)."""
if not 0 <= percent <= 100:
raise ValueError("percent must be between 0 and 100")
return total * (1 - percent / 100)
def main():
prices = parse_prices(input("Prices: "))
total = apply_discount(sum(prices), percent=10)
print(f"{len(prices)} items, total {total:.2f}")
main()Quick reference
- A function without a return statement returns None
- return a, b returns a tuple; unpack it with x, y = f()
- def connect(host, *, timeout=10): names after * must be passed by keyword
- def f(a, /, b): a is positional-only (Python 3.8+)
- f(*point) spreads a list or tuple into separate positional arguments
- help(func) prints its docstring; editors show it on hover
- Defaults are evaluated once, when def runs: use None for list and dict defaults
- Name functions with verbs (parse_date) and yes/no functions with is_ or has_
Common mistakes
- Printing a result inside the function instead of returning it, so callers get None.
- Forgetting the parentheses: greet refers to the function, greet() calls it.
- Writing one huge function instead of several small, named steps.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write bmi(weight_kg, height_m) with a docstring that returns the body mass index rounded to 1 decimal. Call it once with positional and once with keyword arguments.
- Exercise 2medium
Write stats(*numbers) that returns (minimum, maximum, average) as a tuple and raises ValueError when called with no numbers. Unpack the result at the call site.
- Exercise 3hard
Write build_url(base, *parts, plus a two-star query parameter) so that build_url("https://api.example.com", "users", 42, page=2, sort="name") returns https://api.example.com/users/42?page=2&sort=name.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between a parameter and an argument?
- A parameter is the name in the def line; an argument is the actual value passed in a call. In def greet(name), name is the parameter; in greet("Ana"), "Ana" is the argument.
- What do *args and kwargs mean in Python?
- *args collects extra positional arguments into a tuple, and the two-star kwargs parameter collects extra keyword arguments into a dict. The names are only a convention; the stars do the work.
- How long should a function be?
- Long enough to do one clear job, often under 20 to 30 lines. If you need the word and to describe it, or you must scroll to read it, split it up.
- Can a Python function return more than one value?
- It returns one object, but that object can be a tuple: return low, high. The caller unpacks it with low, high = f().