Functions

INPUT · Slides

Ask for the answer back

01 / 07

You want the answer, not the display

Every function so far has printed something and stopped there. It appears on screen, but you cannot use the answer afterwards.

Suppose you have a function that works out a price with tax on it, and you want to add those up. You need the function to bring the value home.

def double(number):    print(number * 2)double(5)

Result

10

02 / 07

return hands it back

Write return inside a function and whatever follows it comes back to where you called from.

The value that comes back behaves as if you had written it there yourself. print(double(5)) is the same thing as writing print(10).

def double(number):    return number * 2print(double(5))

Result

10

03 / 07

Put what came back into a variable

The value that came back can be kept in a variable. Once you have caught it, it is just a number.

Then you can use it as often as you like. This is the decisive difference from print.

def double(number):    return number * 2answer = double(5)print(answer)print(answer + 3)

Result

10
13

04 / 07

It can go straight into an expression

You can skip the variable and write the call inside an expression.

Think of the call being replaced by the value that comes back. double(5) + double(10) is 10 + 20. You can also hand the answer of one function straight to another.

def double(number):    return number * 2print(double(5) + double(10))print(double(double(3)))

Result

30
12

05 / 07

No return means None comes back

So what comes back from a function with no return? None does.

None is the "nothing here" value from Chapter 1. A function always returns something — leave out return and that something is None. That is the rule in Python.

def double(number):    print(number * 2)answer = double(5)print(answer)

Result

10
None

06 / 07

Reaching return ends the function

return has a second job. The function stops there. Lines written below it never run.

That lets you split with if and return partway through. You get away without an else because nothing carries on once you have returned.

def judge(score):    if score >= 60:        return "pass"    return "fail"print(judge(80))print(judge(40))

Result

pass
fail

07 / 07

It does not have to be a number

Numbers are not the limit. Text, True and False, lists, dictionaries — all of them can come back.

A function is a box: put values in, get a value out. Once you see them that way, you can write programs as parts that fit together.

But now comes the place people trip hardest in this chapter: the difference between print and return. The whole of the next lesson is given over to it.

def passed(score):    return score >= 60print(passed(80))print(passed(40))

Result

True
False