Writing your own functions
You have been calling functions since lesson one. print(), len(), sum() —
someone wrote those. Now you write your own.
Why bother
Here is a program that greets three people:
print("Hello, Ayesha! Welcome to WasiLearn.")
print("Hello, Bilal! Welcome to WasiLearn.")
print("Hello, Chen! Welcome to WasiLearn.")
Hello, Ayesha! Welcome to WasiLearn. Hello, Bilal! Welcome to WasiLearn. Hello, Chen! Welcome to WasiLearn.
The greeting is written three times. Change the wording and you must change it in three places — and one day you will change two of them.
Naming a piece of work
def greet(name):
print(f"Hello, {name}! Welcome to WasiLearn.")
greet("Ayesha")
greet("Bilal")
greet("Chen")
Hello, Ayesha! Welcome to WasiLearn. Hello, Bilal! Welcome to WasiLearn. Hello, Chen! Welcome to WasiLearn.
Same output, one copy of the greeting. Four parts to that first line:
def— "I am defining a function"greet— its name, chosen by you(name)— a parameter: a variable that gets filled in when the function is used:and an indented block — the body, exactly likeifandfor
Defining is not running
This is the first thing that confuses people:
def greet(name):
print(f"Hello, {name}!")
print("The program finished.")
The program finished.
No greeting. Defining a function only teaches Python the word greet; it does
not perform it. Nothing happens until you call it — write its name followed
by brackets:
def greet(name):
print(f"Hello, {name}!")
greet("Ayesha")
Hello, Ayesha!
If your function seems to do nothing, check that you actually called it. Missing
brackets is the usual culprit — greet on its own is the function itself, not a
request to run it.
Parameters and arguments
They are two ends of the same thing, and it is worth having the words straight:
- the parameter is the name in the definition —
name - the argument is the actual value you pass in —
"Ayesha"
A function can take several:
def introduce(name, age, city):
print(f"{name} is {age} and lives in {city}.")
introduce("Ayesha", 13, "Karachi")
introduce("Bilal", 15, "Lahore")
Ayesha is 13 and lives in Karachi. Bilal is 15 and lives in Lahore.
Order matters. Python matches them by position, not by name, and it cannot tell that you meant something sensible:
def introduce(name, age, city):
print(f"{name} is {age} and lives in {city}.")
introduce(13, "Ayesha", "Karachi")
13 is Ayesha and lives in Karachi.
No error — just nonsense. Python has no idea that an age should be a number, so this is a bug you find by reading the output, not from a message.
Give too few arguments and it does stop you:
def introduce(name, age, city):
print(f"{name} is {age} and lives in {city}.")
introduce("Ayesha", 13)
The message names the ones you missed: missing 1 required positional argument: 'city'.
A function with no parameters
Not every function needs input. The brackets stay, empty:
def show_menu():
print("1. Start")
print("2. Settings")
print("3. Quit")
show_menu()
1. Start 2. Settings 3. Quit
Functions with everything else you know
Nothing new goes on inside — loops, if, lists and dictionaries all behave
exactly as they always have:
def report(marks):
for subject, score in marks.items():
if score >= 80:
print(f"{subject}: {score} — strong")
else:
print(f"{subject}: {score}")
report({"maths": 82, "history": 68})
print("---")
report({"art": 95})
maths: 82 — strong history: 68 --- art: 95 — strong
One definition, used on different data. That is the whole point of functions, and it only gets more useful as programs grow.
Naming them
A function name should say what the function does, and by convention it is
lowercase with underscores: show_menu, report, calculate_average. A verb
is usually right, because a function is an action.
do_stuff tells the next reader nothing. You in two weeks are the next reader.
There is one thing missing from every function on this page: they all print, and none of them give an answer back that the rest of your program can use. That difference is the next lesson, and it trips up almost everyone.
Prefer learning with a teacher?
WasiLearn Academy runs small-group classes covering this material, online and in Karachi.
See the classes