Skip to content

Intermediate · Functions · topic 18 of 50 · 20 min

Defining and calling functions

Explanation

A function is a named block of code that does one job. You define it with def, and you run it by calling its name with brackets. return hands a value back to the code that called it; a function without return gives back None.

Why functions?

You have already used functions that Python gives you: print(), len() and sum(). A function is a named block of code that does one job. You can also make your own. Then you write the steps once and use them again and again just by calling the name.

Think of it like this: A function is like the mixer grinder in your kitchen. You put things in (the inputs), press one button, and get chutney out (the result). You do not think about the motor inside every time. Once the grinder exists, you use it every day for many different dishes.

Defining a function

Defining a function means writing it. Start with the word def, then the function name, round brackets and a colon. The lines below it, indented by 4 spaces, are the body: the steps the function runs. Defining a function does not run it. Calling a function means running it: you write its name with brackets.

python
def greet():
    print("Namaste!")
    print("Welcome to the class.")

greet()
greet()
The body runs each time you call greet(), so the two lines are printed twice.

Inputs: parameters

python
def greet(name):
    print("Namaste,", name)

greet("Asha")
greet("Ravi")
name is a parameter: a variable that gets the value you put in the brackets when you call. The next lesson covers parameters in detail.

return: giving a value back

return ends the function and hands a value back to the code that called it. You can store that value in a variable, print it, or use it in a calculation.

python
def with_gst(price):
    return price + price * 18 / 100

bill = with_gst(200) + with_gst(100)
print(bill)
with_gst(200) gives back 236.0 and with_gst(100) gives back 118.0, so bill is 354.0.

return versus print

python
def show_total(a, b):
    print(a + b)

result = show_total(2, 3)
print(result)
show_total prints 5 but returns nothing, so result is None. None is Python's special value that means "no value".
Careful: print only shows a value on the screen; the rest of the program cannot use it. If a function should give an answer, use return. A function without return always gives back None, and code like None + 5 then crashes with a TypeError.

return also stops the function at once. Any lines after a return that runs are skipped.

python
def result(marks):
    if marks >= 40:
        return "Pass"
    return "Fail"

print(result(75))
print(result(30))
For 75 the first return runs and the function ends there. Shows Pass, then Fail.

Docstrings: explaining your function

python
def area(length, width):
    """Return the area of a rectangle in square metres."""
    return length * width

print(area(5, 4))
print(area.__doc__)
A docstring is a string in triple quotes on the first line of the body. It explains what the function does. Shows 20, then the docstring.
Tip: Name functions with a verb that says what they do: add_gst, find_topper, count_votes. Keep each function to one clear job. Small functions are easy to test and easy to reuse.

Watch the lesson

Defining and calling functions · 1/7

Functions

In this lesson you will write your own functions, named blocks of code that do one job.

Prefer a video by a teacher? Find free videos on “python functions def return tutorial for beginners” on YouTube ↗

In real life: A hostel mess bill

The hostel warden works out the mess bill for every student each month: days eaten times the daily rate, plus extras like eggs or juice. Instead of writing the same sum 200 times, she writes one function and calls it for each student. If the rate changes, she fixes one line.

python
def mess_bill(days, rate, extras=0):
    """Return a student's monthly mess bill in rupees."""
    return days * rate + extras

print("Asha:", mess_bill(30, 90))
print("Ravi:", mess_bill(26, 90, 150))
print("Meena:", mess_bill(28, 90, 60))
Shows Asha: 2700, Ravi: 2490 and Meena: 2580.

Practice (0/3 done)

Task 1 · Code · Python

Write a function square(n) that returns n multiplied by itself. Example: square(7) returns 49.

Task 2 · Code · Python

This with_gst(price) function prints the answer but does not return it, so the rest of the program cannot use it. Fix it so that it RETURNS the price plus 18% GST, rounded to 2 decimal places.

Task 3 · Code · Python

Write a function grade(marks) that returns "A" for 90 or more, "B" for 75 to 89, "C" for 40 to 74, and "F" below 40.

Quick quiz

Question 1

1.Which line correctly starts a function named hello?

Question 2

2.What does a function give back if it has no return line?

Question 3

3.def double(n): return n * 2. What is double(4) + 1?

Question 4

4.def f(): print("hi"). What does x = f() store in x?

Question 5

5.What happens to lines in a function after a return line that runs?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

← Previous: Sets: each item only once