Lesson 16 of 30
In progress
Functions: give a job a name
Define your own functions, pass values in, return results, and turn copied blocks into one place you can fix once.
Three copies of the same five lines is not three features; it is one bug waiting to be fixed in two of the three places. A function gives that block a name, so the program says what it does instead of repeating how.
What you will learn
- Define and call a function with
def. - Pass values in as parameters and get a result back with
return. - Write docstrings and keep functions small enough to name honestly.
Defining and calling
A function definition starts with def, a name, brackets and a colon. The indented body runs only when you call the function.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
greet()
greet()
Press Run to see the output.
Defining a function does not run it. Nothing prints until the call on the last lines. That separation is the point: you describe the job once, then use it as often as you like.
Names follow the same rules as variables, and the convention is a verb phrase in snake_case: calculate_total, load_settings, is_valid_email. A good name makes the call site read like a sentence, which is why greet() needs no comment.
Parameters make it reusable
A function with no parameters always does exactly the same thing. Parameters let the caller supply the specifics.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
greet("Ana")
greet("Ravi")
Press Run to see the output.
name is a parameter in the definition; "Ana" is an argument at the call. Inside the function, name behaves like a normal local variable. The function does not know or care where the value came from, which is what makes it reusable.
Functions can take several parameters, and the order matters:
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
describe("Ana", 88)
Press Run to see the output.
describe(88, "Ana") is syntactically valid and logically wrong, and Python will not warn you because both values exist. Lesson 17 covers keyword arguments, which make call sites self-explanatory.
Return a value, do not just print it
Printing shows a value to a human. Returning hands a value back to the program. Most functions should return, so the caller decides what to do with the result.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
result = average([10, 20, 30])
print(round(result, 1))
print(average([4, 8]) + 1)
Press Run to see the output.
Because average returns a number, you can round it, add to it, or store it. A function that only prints cannot be reused in a calculation, and it becomes hard to test.
return also ends the function immediately. Code after it in the same branch never runs, which is how guard clauses inside functions work.
Docstrings explain the contract
The first statement in a function can be a string literal. Python keeps it as __doc__ and tools show it as help.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print(average.__doc__)
print(average([2, 4, 6]))
Press Run to see the output.
A docstring should say what the function promises, not how it works line by line. Mention the input shape and any precondition, such as "non-empty". If the body needs a play-by-play comment, the function is probably doing too much.
Small functions with honest names
A useful rule: if you cannot name a function without "and" in the name, split it. load_and_clean_and_save is three functions wearing a coat. Small functions are easier to test, easier to reuse and easier to read at the call site.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
def greet(name):
return f"Welcome, {clean_name(name)}"
print(greet(" mei "))
Press Run to see the output.
greet does not know how cleaning works, only that clean_name provides it. When the cleaning rule changes, one function changes.
Calling a function before its definition raises NameError, because the def statement has not run yet. Put definitions above the code that calls them, or wrap the calls in a main() function and call that at the bottom. The second habit is what the if __name__ == "__main__": pattern formalises in lesson 19.
This code repeats itself. Extract the repeated part into a function, then call it twice with different values.
name = "Ana"
print("=" * 20)
print(f"Report for {name}")
print("=" * 20)
Show solution
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
banner("Ana")
banner("Ravi")
Press Run to see the output.
The function takes the only thing that changes, name, and keeps the formatting in one place. Changing the width later means editing one line.
Recap
defnames a block of work; the body runs only when called.- Parameters carry values in, and
returnhands a result back to the caller. - Docstrings state the contract, and small functions with verb names stay readable.
Next, you will get precise about parameters: defaults, keyword arguments, and the mutable-default bug that surprises almost everyone once.
What is the difference between print and return?
Can a function call another function?
Progress is saved in this browser only. No account, no email.