Return values

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — Introduction to the return Statement

So far, we've seen functions that perform actions (like printing), but functions can also give back a value to the code that called them. This is done using the return keyword.

Think of a function like a calculator: you give it numbers (parameters), it does calculations, and then it returns the result to you.

def calculate_power(base_power, level): total_power = base_power + (level * 2) return total_power # When we call this function, it returns a value codemon_power = calculate_power(50, 10) print("Codémon power:", codemon_power)

In this example: 1. The function calculates the total power 2. return sends that value back to where the function was called 3. We store the returned value in the codemon_power variable 4. We can then use that value however we want

Function Execution Stops at return

When Python encounters a return statement, it immediately exits the function. Any code written after return will not be executed!

Exercise 2 — What Happens After return?

What will this function return when called with check_type('fire')?

def check_type(codemon_type): if codemon_type == 'water': return 'Strong against fire' return 'Not water type' print('This line will never execute')
Options
• 'Not water type'
• 'Strong against fire'
• 'This line will never execute'
• The function will cause an error

Hint : The function checks the condition, and since the type is 'fire' (not 'water'), it skips the first return and executes the second return statement.

Exercise 3 — Using Return Values

Once a function returns a value, you can use it in several ways:

Method 1: Store in a variable

def get_codemon_level(): return 25 level = get_codemon_level() print("Level stored:", level)

Method 2: Use directly in an expression

def get_codemon_level(): return 25 next_level = get_codemon_level() + 1 print("Next level:", next_level)

Method 3: Use directly in a condition

def get_codemon_level(): return 25 if get_codemon_level() > 20: print("Strong Codémon!")

You can even use the return value of one function as an argument for another function!

def get_base_power(): return 50 def calculate_damage(power): return power * 2 total_damage = calculate_damage(get_base_power()) print("Total damage:", total_damage)

Exercise 4 — Complete the Return Statement

Complete the function so it returns the result of adding the Codémon's base power and bonus power.

Hint : Think about which keyword sends a value back from a function, and what value you want to send back.

Exercise 5 — Return vs Print

A very common confusion for beginners: return and print() are NOT the same thing!

- print() displays something on the screen for humans to see - return sends a value back to the code for the program to use

Function with print() - displays but returns nothing:

def greet_with_print(name): print(f"Hello {name}!") # This function returns None by default result = greet_with_print("Aquachu") print("Result stored in variable:", result) # Will show None

Function with return - sends back a value:

def greet_with_return(name): return f"Hello {name}!" result = greet_with_return("Pyrochu") print("Result stored in variable:", result) # Will show the greeting

When to Use Which?

Use return when you want the function to give back a value that your program will use later. Use print() only when you want to display information to the user.

Exercise 6 — Return or Print?

Which function correctly returns a value that can be used in a calculation?

Options
• def get_power(): return 100
• def get_power(): print(100)
• def get_power(): power = 100
• def get_power(): 100

Hint : Think about which statement actually sends a value back from the function so it can be stored or used in calculations.

Exercise 7 — Introduction to None

In Python, if a function doesn't have a return statement, or has a return without a value, it automatically returns a special value called None.

None is Python's way of representing "nothing" or "no value". It's like an empty box.

Case 1: Function with no return statement

def display_codemon(name): print(f"Codémon: {name}") result = display_codemon("Aquachu") print("Result:", result) # None

Case 2: Function with empty return

def check_status(): print("Checking...") return result = check_status() print("Result:", result) # None

Case 3: Function that returns a value

def get_level(): return 25 result = get_level() print("Result:", result) # 25

Three ways a function returns None: 1. No return statement at all 2. return with no value after it 3. return None explicitly (rarely used)

Is None Bad?

No! None is perfectly valid. Functions that perform actions (like printing or modifying data) often don't need to return anything, so None is appropriate. Just be aware that if you try to use None in calculations, you might get errors.

Exercise 8 — Match Functions with Their Return Values

Match each function with what it returns when called:

Items to match
• def func1(): return 42
• def func2(): print(42)
• def func3(): x = 42 return
• def func4(): return 'Aquachu'
Definitions
• Returns the number 42
• Returns None
• Returns None
• Returns the string 'Aquachu'

Exercise 9 — Using Return Values in Expressions

Complete the code to calculate the total power by using the return value of get_base_power() in an expression.

Hint : Remember: to use a function's return value, you need to call the function with parentheses ().

Exercise 10 — Working with None

What will happen when this code runs?

def get_power(): print("Getting power...") result = get_power() final_power = result * 2 print(final_power)
Options
• It will cause an error because you can't multiply None by 2
• It will print None
• It will print 2
• It will print 0

Hint : Think about what value get_power() returns, and whether that value can be used in mathematical operations.

Exercise 11 — Complete the Codémon Function

Complete this function that checks if a Codémon is strong enough. It should return True if the level is 20 or higher, and False otherwise.

Hint : Think about what values you want to send back based on the condition, and use the return keyword to send them back.

Exercise 12 — Functions Can Return Any Data Type

So far, we've seen functions return numbers and strings. But here's the cool part: functions can return any data type in Python - lists, dictionaries, booleans, and even other functions!

Returning a List:

def get_codemon_moves(): moves = ["Water Blast", "Bubble Shield", "Tidal Wave"] return moves # Use the returned list aquachu_moves = get_codemon_moves() print("Aquachu's moves:") for move in aquachu_moves: print("-", move)

Returning a Dictionary:

def get_codemon_stats(name, level): stats = { "name": name, "level": level, "hp": level * 10, "attack": level * 5 } return stats # Use the returned dictionary pyrochu = get_codemon_stats("Pyrochu", 15) print(f"Name: {pyrochu['name']}") print(f"Level: {pyrochu['level']}") print(f"HP: {pyrochu['hp']}") print(f"Attack: {pyrochu['attack']}")

This flexibility makes functions incredibly powerful! You can create functions that organize and return complex data structures, making your code more modular and reusable.

Exercise 13 — Codémon Battle Calculator

Create a damage calculator using functions with parameters and return values! Your tasks: 1. Define a function calculate_attack(power, level) that: - Returns: power + (level * 2) 2. Define a function calculate_bonus(level) that: - Returns 50 if level is greater than 15 - Returns 0 otherwise 3. Call both functions with power = 50 and level = 20, add the results together, and print the total damage

Starter code
# 1. Define calculate_attack(power, level) # 2. Define calculate_bonus(level) # 3. Call both functions and calculate total damage
Back to the course