Explain it simply
Explain it simply
Think of a recipe card. The card called "fried eggs" lists the steps once, and only the input changes: how many eggs. You never rewrite the steps each time you cook; you just say "fried eggs, three eggs".
A function is a recipe card for code. You write it once with def and it runs every time you call it by name. It takes input through parameters and hands the result back with return. It only runs when called: def on its own does nothing yet.
Problem → Why → Solution
The problem: a bug fixed in only one of three copies
A shop script repeats the same add-5%-tax calculation in three places. When the rate changes to 7%, the developer finds and updates only two of them. One receipt still uses 5%, customers pay the wrong amount, and since no error is raised nobody notices for months.
cart_total = 20000 * 1.07 # updated to 7%
delivery_total = 3000 * 1.07 # updated to 7%
gift_total = 15000 * 1.05 # missed: still 5%!
print(cart_total, delivery_total, gift_total)Why does this bug happen?
One rule, how to add tax, is scattered over three places, so every change means hunting down every copy, and missing one makes the program inconsistent. Put it in a function, def with_tax(amount): return amount * 1.07, and the rule lives in exactly one place: every call such as with_tax(gift) picks up the fix automatically. The function name also explains far more than a bare 1.07.
Core concept: def, call, parameters and return
You define a function with def function_name(parameters): and indent its body. When Python reaches the def line it only creates a function object and binds it to the name; the body does not run yet. The body runs only when you call the function with parentheses, function_name(). Python reads a file from top to bottom, so calling a function before its def line raises NameError.
Parameters are the variable names in the def line (a and b in def add(a, b)); arguments are the values you send when calling (5 and 3 in add(5, 3)). By default, arguments are matched to parameters by position. If you pass them as keyword arguments in name=value form, as in add(b=3, a=5), the order no longer matters. Sending the wrong number of arguments gives an error such as TypeError: add() missing 1 required positional argument: 'b'.
return value stops the function immediately and sends the value back to where it was called, so you can store it, as in result = add(5, 3), or feed it into another call, as in add(add(1, 2), 10). print() only shows text on the screen and gives nothing back to the caller. A function without a return statement, or with a bare return, automatically returns None. Writing return a, b with a comma returns a tuple, which you can unpack with low, high = min_max(nums).
Give a parameter a default value, as in def greet(name, title="Mr."), and callers may leave that argument out. Parameters with defaults must come after those without, or Python reports a SyntaxError. Variables created inside a function are local: they disappear when the function finishes and cannot be seen from outside.
- The call sends arguments
- They bind to parameter names
- The body runs with locals
- return hands a value back
- No return means None
print talks to the human; return talks to the rest of the program.
General pattern
def function_name(required, optional=default_value):
# body: indented, runs only when called
result = do_something(required, optional)
return result
value = function_name(argument)
value = function_name(argument, other_argument)
value = function_name(optional=other_argument, required=argument)In the def line, parameters without defaults come first and those with defaults follow. The body hands its result back with return. The three call forms use the default, override it by position, and pass everything by name with keyword arguments.
Example: greet, add, defaults and two return values
Five functions each show one shape: no parameters, one parameter that only prints, a returned value, a default value, and two returned values. The final line shows what happens when you print the result of a function that only prints.
def greet():
print("Hello, World!")
def greet_person(name):
print(f"Hello, {name}!")
def add(a, b):
return a + b
def greet_with_title(name, title="Mr."):
return f"Hello, {title} {name}"
def min_max(numbers):
return min(numbers), max(numbers)
greet()
greet_person("Kyaw Kyaw")
result = add(5, 3)
print(f"5 + 3 = {result}")
print(add(add(1, 2), 10))
print(greet_with_title("Aung"))
print(greet_with_title("Mya", "Dr."))
print(greet_with_title(title="Daw", name="Hla"))
low, high = min_max([7, 2, 9, 4])
print(low, high)
print(greet_person("Ma Ma"))Code breakdown
- Lines 9-10
return a + badd() returns its result instead of printing it, so it can be stored in result, and in add(add(1, 2), 10) the inner call's 3 feeds straight into the outer call.
- Line 13
def greet_with_title(name, title="Mr."):title has a default, so greet_with_title("Aung") uses Mr., while passing "Dr." replaces it. name is required on every call.
- Line 30
print(greet_with_title(title="Daw", name="Hla"))Keyword arguments bind by name, so writing title first still produces the correct "Hello, Daw Hla".
- Lines 17-18, 32
low, high = min_max([7, 2, 9, 4])return min(numbers), max(numbers) returns the tuple (2, 9), and this line unpacks it into two variables.
- Line 35
print(greet_person("Ma Ma"))greet_person() runs first and prints "Hello, Ma Ma!". It has no return, so it gives back None, and the outer print shows that None.
Hello, World!
Hello, Kyaw Kyaw!
5 + 3 = 8
13
Hello, Mr. Aung
Hello, Dr. Mya
Hello, Daw Hla
2 9
Hello, Ma Ma!
None
- Bind 5 to a and 3 to b
- The body computes a + b = 8
- return sends 8 to the caller
- result is 8; a and b vanish
Local variables and a function's boundary
Variables assigned inside a function exist only for that call and disappear when it finishes. A variable with the same name outside is not affected: the price inside the function and the price outside are separate. That is why a function that wants to hand a result to the outside uses return rather than changing a global variable. In the code below, the outer price stays 100, and the only way the inner value gets out is through return.
price = 100
def with_tax(amount):
price = amount * 1.07 # a new local variable, not the outer one
return round(price, 2)
print(with_tax(50)) # 53.5
print(price) # 100: the outer price was never touchedIn real projects
Where this shows up in real projects
Real projects break code into small, well-named functions such as calculate_total(), format_price() and is_valid_email(). When each function does one job, its name tells you what it does, and a test can give it an input and check the output. Functions that return values can be reused from a web page, a command-line tool or an API, whereas a function that prints is only useful in a terminal.
Default parameters matter in API design, and Python's built-ins use them everywhere: sorted(items) covers the common case, and you add reverse=True as a keyword argument only when you need it; print() has defaults for its sep and end parameters as well. Giving your own functions sensible defaults for the most common values, and letting callers pass rarer options as keyword arguments, keeps calling code short and readable.
Common mistakes
Common mistakes
1. Printing where you meant to return
With def area(w, h): print(w * h), the line total = area(3, 4) + 1 fails with TypeError: unsupported operand type(s) for +: 'NoneType' and 'int', because area returns None. If the result will be used again, write return w * h.
2. Forgetting the parentheses
Writing greet only refers to the function object; it does not run it. print(greet) shows something like <function greet at 0x...>. To run the function, always write greet().
3. Putting a default parameter first
def greet(title="Mr.", name): raises SyntaxError: parameter without a default follows parameter with a default. List the parameters without defaults first.
4. Expecting code after return to run
return ends the function at once, so a print("done") written after return result never runs. Put logging and clean-up before the return.
Best practices
Best practices
- Name functions with a verb in snake_case that says what they do, such as calculate_total.
- Give each function one job, and return its result rather than printing it.
- The moment you feel like copy-pasting a block, it is time to turn it into a function.
Mini challenge
Mini challenge: temperature helpers
Write three functions for a week of Celsius temperature readings and combine them into a short report.
- c_to_f(celsius) returns Fahrenheit (F = C × 9 / 5 + 32)
- describe(celsius, hot_limit=30) returns "hot" at or above hot_limit, "cool" at 15 or below, otherwise "mild"
- summary(readings) returns the minimum, maximum and average rounded to one decimal
- No print inside the functions; override hot_limit once with a keyword argument
def c_to_f(celsius):
# TODO: return the Fahrenheit value
pass
def describe(celsius, hot_limit=30):
# TODO: return "hot", "cool" or "mild"
pass
def summary(readings):
# TODO: return low, high and the rounded average
pass
week = [24, 31, 28, 14, 33]
# TODO: unpack summary(week) into three variables and print them
# TODO: print the hottest day in F with its description
# TODO: describe the coldest day, then 28 with hot_limit=27Expected: low 14, high 33, average 26.0 33 C is 91.4 F and feels hot 14 C feels cool 28 C with hot_limit=27: hot
Show hint
Return three values with commas, return low, high, avg, and unpack them with low, high, avg = summary(week). For the average, wrap sum(readings) / len(readings) in round(..., 1).
Show solution
def c_to_f(celsius):
return celsius * 9 / 5 + 32
def describe(celsius, hot_limit=30):
if celsius >= hot_limit:
return "hot"
if celsius <= 15:
return "cool"
return "mild"
def summary(readings):
average = sum(readings) / len(readings)
return min(readings), max(readings), round(average, 1)
week = [24, 31, 28, 14, 33]
low, high, avg = summary(week)
print(f"low {low}, high {high}, average {avg}")
print(f"{high} C is {c_to_f(high)} F and feels {describe(high)}")
print(f"{low} C feels {describe(low)}")
print("28 C with hot_limit=27:", describe(28, hot_limit=27))Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- def only defines a function; the body runs when you call it with parentheses, name().
- Parameters are the names in def; arguments are the values sent, by position or by keyword.
- return sends a value back and ends the function; without it you get None.
- Parameters with defaults go after the parameters without them.
The Python Tutorial — Python Software Foundation