Python Arena
Step 4 of 6

Returning a value

Some functions give something back. input gives back the text the user typed, len gives back a length and int gives back a number. Python replaces the call with that value, which you can store in a variable or use in a calculation:

count = len("hello") + 1

The value a function gives back is its return value. Your own functions give one back with the return statement:

def double(number):
    return number * 2


result = double(21)
print(result)
print(double(5) + 1)
Output
42
11

double prints nothing itself. It works out number * 2 and returns it, and the code that called it decides what to do with it: the first call stores it in result, the second adds 1 to it.

return ends the function

A return ends the function right away, even in the middle of a loop or an if. That makes it easy to return different values in different cases:

def sign(number):
    if number > 0:
        return "positive"
    if number < 0:
        return "negative"
    return "zero"


print(sign(15))
print(sign(-3))
print(sign(0))
Output
positive
negative
zero

For 15 the first return runs and the function is over: the lines below it never run for that call. Only when neither condition is true does Python reach the last line. One call runs exactly one return.

A function can return anything: a number, a string, True or False. Here the function reads a number, so the code that uses it stays short:

def ask_number(prompt):
    return int(input(prompt))


width = ask_number("Width: ")
height = ask_number("Height: ")
print("Area:", width * height)
Input
4
5
Output
Width: 4
Height: 5
Area: 20

A return without a value

A plain return, with no value after it, just ends the function. It's handy in a function that prints, to stop early when there's nothing sensible to do:

def print_ratio(a, b):
    if b == 0:
        print("Can't divide by zero")
        return
    print(a / b)


print_ratio(7, 2)
print_ratio(7, 0)
Output
3.5
Can't divide by zero

In a function task, the checks call your function and show what it returns the way the interpreter does: 42 for a number, 'positive' with quotes for a string.

Your task

Challenge 1 of 3

Fill in the blank so that area(width, height) returns the area of a rectangle. For example, area(3, 4) returns 12.

Challenge 2

A museum's ticket is free for children under 7, costs 8 euros from 7 to 17 years, 12 euros from 18 to 64 years and 6 euros from 65 years on. Write the function ticket_price(age), which returns the price as a whole number. For example, ticket_price(5) returns 0 and ticket_price(30) returns 12.

Challenge 3

Write the function initials(first_name, last_name), which returns a person's initials in capital letters, each followed by a dot. For example, initials("ada", "Lovelace") returns 'A.L.'.