Functions: reusable steps
A function is a named recipe you can use again and again. Learn def, parameters and return, and why returning beats printing.
In 60 seconds
Functions: reusable steps
A function is a named recipe you can use again and again. Learn def, parameters and return, and why returning beats printing.
Making a function
def greet(name):
message = f"Namaste, {name}!"
return message
print(greet("Meena"))
print(greet("Karan"))defmeans "define a function".greetis its name. Choose a name that says what it does.nameinside the brackets is a parameter: a variable that gets its value when the function is used.- The indented lines are the body: the steps.
returnhands the answer back to whoever used the function.
greet("Meena") calls greet with the value "Meena", which is called an argument.Several parameters, and default values
def percentage(marks, out_of=100):
return marks / out_of * 100
print(percentage(45)) # out_of uses its default, 100: 45.0
print(percentage(18, 25)) # 18 out of 25: 72.0
print(percentage(out_of=50, marks=40)) # you can name the argumentsout_of=100 is a default value. If you do not pass it, Python uses 100.return or print?
print() shows a value on the screen, and then it is gone. return gives the value back, so the rest of your program can use it: store it, add it, compare it.def add_gst_print(amount):
print(amount * 1.18)
def add_gst_return(amount):
return amount * 1.18
a = add_gst_print(100) # shows 118.0 on screen...
print("a is", a) # ...but a is None: nothing came back
b = add_gst_return(100)
print("b is", b) # b is 118.0, ready to use
print("Two items:", b * 2)return gives back a special value, None, which means "nothing". If you see None where you expected an answer, look for a missing return.Why functions help
- 1
Write once
Put the steps for one job in one place. - 2
Use many times
Call it for every student, every bill, every match. - 3
Fix once
Found a bug? Fix it in the function and every use is fixed. - 4
Read easily
bill_total(cart, prices)tells you what happens without reading every line.
Variables inside a function stay inside
greet, message cannot be used outside the function. This keeps functions tidy: they talk to the outside world through their parameters and their return value.Writing a function step by step
- Say in one sentence what it takes in and what it gives back.
- Write a few examples with the right answers, including edge cases.
- Write the body.
- Call it with your examples and compare the answers.
- Prints the answer but does not return it
- Uses a variable from outside instead of a parameter
- One huge function that does five jobs
- Returns the answer so other code can use it
- Gets everything it needs through parameters
- Small functions that each do one job well
def square(n): that returns n * n. Call it with 7 and print the answer. Then print square(3) + square(4). Did you get 25? 🎉Watch and read more
Lab
Two small functions for an auto-rickshaw ride: the fare, and each friend's share.
The problem
Write two functions that follow these (made-up) rules exactly:
auto_fare(km)returns the fare in rupees. The first 2 km cost a flat 30 rupees in total. Every km after that costs 15 rupees. So 1 km costs 30, 2 km cost 30, 3 km cost 45, and 5 km cost 75. Part-kilometres count too: 2.5 km costs 37.5.split_bill(total, people=2)returns how much each person pays, rounded up to a whole rupee, so the driver is never short. For examplesplit_bill(100, 3)is 34, andsplit_bill(90)is 45. Tip:math.ceil()rounds up.
Both functions must return their answer, not just print it. Run the starter first: can you spot why it shows None?
Practice lab
Edit the code and run it. Python runs in your browser — nothing is sent to our server.
No output. Add print(...) to see values.
You are done when
Hard questions
Try to answer before you reveal. If you can answer these, you understood the lesson.
Q1Why did the starter print <code>Fare for 5 km: None</code> even though it also printed 30?Reveal
auto_fare printed 30 inside the function, but it had no return, so the call gave back None. That None was stored in fare and printed. Printing shows a value; only return gives it to the caller.
Q2Why round <em>up</em> in split_bill instead of using round()?Reveal
With round(100 / 3) each person pays 33, and three people give only 99, one rupee short. Rounding up (34 each, 102 in total) makes sure the full fare is always covered. Choosing the right rounding is a real design decision in billing code.
Questions people ask
What is the difference between a parameter and an argument?
The parameter is the name in the def line, like name. The argument is the actual value you pass when calling, like "Meena". People often mix up the words, and that is fine.
Can a function return more than one value?
Yes. return total, count gives back both, and you can catch them with t, c = my_function(). Python packs them into a tuple, which is like a list you cannot change.
Does the code after return run?
No. return ends the function straight away. Any lines after it in the same block are skipped.
Where should I put my functions?
Define them near the top, before the lines that call them. Python must have read the def before you use the function.
Lesson test
5 questions. Get 3 right (60%) to pass and complete this lesson.