← Project 2

Lesson 6

Functions and return values

~40 min

1. Reusing Code: Defining Functions

Functions are modular, self-contained blocks of code that perform a specific task. They prevent code duplication, enhance structure, and make debugging easier. You define a function in Python using the def keyword, followed by the function name, parentheses containing optional parameters, and a colon. Code inside the function block must be indented.

2. Parameters, Arguments, and Default Values

Parameters are the placeholders defined in the function signature. Arguments are the actual values passed to the function when calling it. Python also supports **default parameters**, which are used if no argument is passed during the function call.

# exponent has a default value of 2
def power(base, exponent=2):
    return base ** exponent

print(power(3))      # Prints: 9 (uses default exponent=2)
print(power(2, 4))   # Prints: 16 (overrides default, base=2, exponent=4)

3. Return Values vs. Printing

A common point of confusion is the difference between print() and return:

  • print() displays a value on the screen. It has no effect on the program's logic or calculations.
  • return sends a value back to the caller. It immediately terminates the function, allowing the program to store the result in a variable or use it in another function call.
def add_numbers(a, b):
    return a + b

# The return value is stored in a variable
result = add_numbers(5, 7)
print("The sum is:", result)  # Prints: The sum is: 12

4. Variable Scope: Local vs. Global

Variables created inside a function are **local** to that function. They cannot be accessed from outside. Variables defined in the main script are **global** and can be read inside functions, but cannot be modified directly unless declared with the global keyword.

x = 10  # Global variable

def test():
    y = 5  # Local variable
    print(x)  # Reading global variable is allowed!

test()
# print(y)  # This will CRASH with a NameError because y is local to test()

5. Common Beginner Mistakes

⚠️ Watch out for these mistakes:

  • Forgetting to Return: Defining a function to compute a value but forgetting to write return. By default, Python functions return None if no return is written.
  • Invalid Parameter Order: Placing default parameters before required parameters. def test(a=5, b): is invalid. It must be: def test(b, a=5):.
  • Modifying Globals directly: Attempting to modify a global variable inside a function without the global keyword will result in a local variable being created, ignoring the global one.
Interactive Practice

Mini Practice: Helper Functions

Define celsius_to_fahrenheit(c) which converts Celsius to Fahrenheit using F = C * 9/5 + 32. Also, define is_even(n) which returns True if a number is even, and False otherwise. Test both by printing results.

0% complete
Check when done
Quiz

Test Your Understanding

1. What is returned by default if a Python function has no `return` statement?

2. Which of the following function definitions has INVALID parameter order?

3. Can you access a variable defined inside a function from outside that function?

🚀 Progression

Functions are completed. Next, you'll learn how to store structured data mapping keys to values using **Dictionaries**.