ShareYourGroupShareYourGroupPython

Lesson 15 of 21 · about 7 minutes with the exercises

Functions

A function is a named block of code that does one job. You have used functions since lesson one: print, len, input, sorted. Now you will write your own. Functions let you write a piece of logic once and use it many times, and they break a long program into parts small enough to understand.

Defining and calling

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

greet()
greet()

Output

Namaste!
Welcome to the class.
Namaste!
Welcome to the class.

def is short for define. After it comes the name, round brackets and a colon. The indented lines are the body. Defining a function does not run it. The body runs only when you call the function by writing its name with brackets. Here it is called twice, so the two lines print twice.

A function must be defined above the line that calls it, because Python reads from the top.

Parameters: giving a function information

A function becomes useful when it can work on different values. Name the values it needs inside the brackets.

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

greet("Asha")
greet("Ravi")

Output

Namaste, Asha
Namaste, Ravi

name is a parameter: a variable that exists inside the function. The value you pass in the call, such as "Asha", is the argument. A function can take several parameters, separated by commas. The arguments are matched to them in order.

def area(length, width):
    print("Area:", length * width)

area(12, 10)
area(5, 4)

Output

Area: 120
Area: 20

Returning a result

The area function above prints its answer. That is fine for the screen, but the rest of the program cannot use the number. To hand a result back to the caller, use return.

def area(length, width):
    return length * width

room = area(12, 10)
hall = area(20, 15)
print(room)
print("Both rooms:", room + hall)
print("Paint needed:", area(12, 10) / 100, "litres")

Output

120
Both rooms: 420
Paint needed: 1.2 litres

A call to a function that returns a value can be used anywhere a value can: stored in a variable, used in a sum, passed to another function.

Print or return?

This is the question that confuses most beginners.

A function without a return hands back the special value None.

def add_print(a, b):
    print(a + b)

def add_return(a, b):
    return a + b

x = add_print(2, 3)
y = add_return(2, 3)
print(x)
print(y)

Output

5
None
5

As a rule, functions that work something out should return it. Leave printing to the main part of the program. Then the same function can serve a screen, a file or a test.

return ends the function

When Python reaches a return, it leaves the function at once. Lines after it do not run. You can use this to deal with special cases first.

def grade(marks):
    if marks >= 90:
        return "A"
    if marks >= 75:
        return "B"
    if marks >= 33:
        return "C"
    return "Fail"

print(grade(95), grade(80), grade(20))

Output

A B Fail

No elif is needed here, because each return already ends the function.

Returning more than one value

Separate the values with commas. Python packs them into a tuple, and the caller can unpack them.

def min_max(numbers):
    return min(numbers), max(numbers)

low, high = min_max([31, 29, 35, 33])
print(low, high)

Output

29 35

Functions that answer yes or no

A function that returns True or False reads well in an if. By habit their names start with is_ or has_.

def is_even(n):
    return n % 2 == 0

for n in [3, 8, 10]:
    if is_even(n):
        print(n, "is even")

Output

8 is even
10 is even

One function calling another

def percent(marks, total):
    return marks / total * 100

def report(name, marks, total):
    p = percent(marks, total)
    return f"{name}: {p:.1f}%"

print(report("Asha", 432, 500))

Output

Asha: 86.4%

Small functions that each do one thing, joined together, are easier to test and fix than one long one.

Docstrings

A string in triple quotation marks on the first line of the body describes the function. It is called a docstring. The built-in help shows it.

def simple_interest(principal, rate, years):
    """Return simple interest. Rate is in percent per year."""
    return principal * rate * years / 100

print(simple_interest(10000, 7, 2))

Output

1400.0

Common mistakes

Try it yourself

Exercise 1. Write a function square(n) that returns the square of a number. Print the squares of 4 and 11.

Show one answer
def square(n):
    return n * n

print(square(4), square(11))

Output

16 121

Exercise 2. Write a function to_fahrenheit(c) that returns a Celsius temperature in Fahrenheit. Test it with 0 and 100.

Show one answer
def to_fahrenheit(c):
    return c * 9 / 5 + 32

print(to_fahrenheit(0), to_fahrenheit(100))

Output

32.0 212.0

Exercise 3. Write a function count_vowels(text) that returns how many vowels are in a string. Test it with "Programming in Python".

Show one answer
def count_vowels(text):
    count = 0
    for ch in text.lower():
        if ch in "aeiou":
            count += 1
    return count

print(count_vowels("Programming in Python"))

Output

5

Examples on this page were run with Python 3.14 on 12 November 2026. The output shown is the real output.

This is an independent learning site. It is not connected with or approved by the Python Software Foundation. "Python" is a trademark of the Python Software Foundation and is used here only to name the language.