Python lesson 25

Functions That Give Things Back

Default answers, more than one result, and the meaning of None.

Print Is Not Return

A function that prints shows you something and then forgets it. A function that returns hands the value back so you can store it, add to it, or pass it on. A function with no return gives back None. Python’s word for "nothing here".

def double(n):
return n * 2 # hands it back

def show(n):
print(n * 2) # shows it, gives back None

result = double(5) # 10
nothing = show(5) # prints 10, result is None

def double(n):
    return n * 2

def show(n):
    print(n * 2)

print(double(5) + 1)
print(show(5))

What Does It Give Back?

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

answer = greet("Ada")
print(answer)

A Sensible Default

Give a parameter a default value and the caller can leave it out. It makes a function easy to use for the common case and still flexible when you need it.

def greet(name, greeting="Hello"):
return greeting + ", " + name

greet("Ada") # "Hello, Ada"
greet("Ada", "Hiya") # "Hiya, Ada"

def greet(name, greeting="Hello"):
    return greeting + ", " + name

print(greet("Ada"))
print(greet("Sam", "Hiya"))

Give It a Default

Two Answers at Once

Return several values separated by commas, and unpack them on the other side. min, max and sum are built into Python and do what their names say: the smallest, the largest, and everything added up.

def stats(numbers):
    return min(numbers), max(numbers), sum(numbers)

lowest, highest, total = stats([4, 9, 2, 7])
print("Lowest:", lowest)
print("Highest:", highest)
print("Total:", total)

A Damage Calculator

Write a function that works out damage, with a default multiplier of 1. Try calling it both ways.

def damage(base, multiplier=1):
    return base * multiplier

print("Normal hit:", damage(10))
print("Critical hit:", damage(10, 3))

Early Return

A function stops the moment it hits a return. Use that to answer a question and get out.

def find_first_big(numbers):
    for n in numbers:
        if n > 100:
            return n
    return None

print(find_first_big([5, 40, 220, 300]))
print(find_first_big([1, 2, 3]))

What you can do on CodeIt

Run the example, change one part, and use the result to check your understanding before moving to the next lesson.