Python from zeroBeginnerLesson 1045 min read

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.

Lesson in motion

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.

1/5
In simple words
Think of a pressure cooker recipe your family uses every week. Nobody rewrites it each time; they just say "make the usual dal". A function is the same: you write the steps once, give them a name, and then just use the name.

Making a function

Python: your own functionpython
def greet(name):
    message = f"Namaste, {name}!"
    return message

print(greet("Meena"))
print(greet("Karan"))
  • def means "define a function".
  • greet is its name. Choose a name that says what it does.
  • name inside the brackets is a parameter: a variable that gets its value when the function is used.
  • The indented lines are the body: the steps.
  • return hands the answer back to whoever used the function.
Using a function is called calling it. greet("Meena") calls greet with the value "Meena", which is called an argument.

Several parameters, and default values

Python: marks as a percentagepython
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 arguments
out_of=100 is a default value. If you do not pass it, Python uses 100.

return or print?

This is the most important idea in this lesson. 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.
Python: print is not returnpython
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)
Note
The 18% above is only an example number for the maths. Real GST rates depend on the item and can change, so check the current rate if you ever need a real bill.
A function with no 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. 1

    Write once

    Put the steps for one job in one place.
  2. 2

    Use many times

    Call it for every student, every bill, every match.
  3. 3

    Fix once

    Found a bug? Fix it in the function and every use is fixed.
  4. 4

    Read easily

    bill_total(cart, prices) tells you what happens without reading every line.

Variables inside a function stay inside

A variable made inside a function exists only while the function runs. In 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

  1. Say in one sentence what it takes in and what it gives back.
  2. Write a few examples with the right answers, including edge cases.
  3. Write the body.
  4. Call it with your examples and compare the answers.
Hard to use
  • Prints the answer but does not return it
  • Uses a variable from outside instead of a parameter
  • One huge function that does five jobs
Easy to use
  • Returns the answer so other code can use it
  • Gets everything it needs through parameters
  • Small functions that each do one job well
Try this. Write 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.

~15 min

The problem

Write two functions that follow these (made-up) rules exactly:

  1. 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.
  2. split_bill(total, people=2) returns how much each person pays, rounded up to a whole rupee, so the driver is never short. For example split_bill(100, 3) is 34, and split_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.

Output

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.

Please sign in to continue.

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.

Sign in to take the test and save your progress