← Back to Python Chapter 4: Functions
0% Complete

Functions: Reusable Code Blocks

A function is a named block of code that performs a specific task. Instead of writing the same code over and over, you write it once in a function and call it whenever you need it.

Why Use Functions?

  • Reusability: Write once, use many times
  • Organization: Break complex problems into smaller pieces
  • Readability: Give meaningful names to code blocks
  • Maintainability: Fix bugs in one place

Defining a Function

Use the def keyword, followed by the function name, parentheses, and a colon:

first_function.py Python
# Define a function def greet(): print("Hello, wizard!") print("Welcome to Python.") # Call the function greet() greet() # Call it again!
Hello, wizard! Welcome to Python. Hello, wizard! Welcome to Python.

Key Concept: Definition vs. Call

Defining a function (def greet():) creates the function but doesn't run it.
Calling a function (greet()) actually executes the code inside.
You must define a function BEFORE you call it!

Function Naming Rules

Same as variables: lowercase, underscores between words, descriptive names:

naming.py Python
# Good function names def calculate_total(): pass def send_email(): pass def validate_user_input(): pass # Bad function names # def X(): # Not descriptive # def DoThis(): # Use lowercase # def my func(): # No spaces allowed

Lab Exercise 1: Your First Function

Beginner

Instructions

Create and call your own function! Functions help you organize and reuse code.

Your Task

Define a function called introduce that prints "My name is [Your Name]" and "I am learning Python!". Then call the function.

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: Function Basics Complete!

You can define and call functions. Now let's make them flexible with parameters!

Parameters: Making Functions Flexible

Parameters are variables that receive values when a function is called. They make functions flexible - you can pass different data each time!

Adding Parameters

Define parameters inside the parentheses:

parameters.py Python
# Function with one parameter def greet(name): print(f"Hello, {name}!") # Call with different arguments greet("Alice") greet("Bob") greet("Charlie")
Hello, Alice! Hello, Bob! Hello, Charlie!

Parameter vs. Argument

Parameter: The variable in the function definition (name in def greet(name))
Argument: The actual value passed when calling ("Alice" in greet("Alice"))
Think: Parameters are placeholders, arguments are the real values.

Multiple Parameters

Functions can have multiple parameters, separated by commas:

multiple_params.py Python
def create_profile(name, age, city): print(f"Name: {name}") print(f"Age: {age}") print(f"City: {city}") print("---") create_profile("Alice", 25, "New York") create_profile("Bob", 30, "London")
Name: Alice Age: 25 City: New York --- Name: Bob Age: 30 City: London ---

Order Matters!

When calling a function, arguments are matched to parameters by position. create_profile("Alice", 25, "NYC") maps Alice→name, 25→age, NYC→city. Wrong order = wrong results!

Lab Exercise 2: Using Parameters

Beginner

Instructions

Create a function that takes parameters and uses them to customize output.

Your Task

Create a function calculate_area that takes length and width parameters and prints the area of a rectangle. Test it with different values.

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: Parameters Mastered!

You can pass data into functions. Now let's learn how to get data back out!

Return Values: Getting Results Back

So far, our functions have printed output. But often we want functions to calculate something and give us the result back. That's what return does!

The return Statement

return_basics.py Python
def add(a, b): return a + b # Capture the returned value result = add(5, 3) print(f"5 + 3 = {result}") # Use directly in expressions print(f"10 + 7 = {add(10, 7)}") # Chain function calls total = add(add(1, 2), add(3, 4)) print(f"(1+2) + (3+4) = {total}")
5 + 3 = 8 10 + 7 = 17 (1+2) + (3+4) = 10

print() vs return

print(): Displays text on screen. The value is lost - you can't use it further.
return: Sends a value BACK to the caller. You can store it, use it in calculations, pass it to other functions.
Rule of thumb: Use return for calculations, print() for displaying to users.

Returning Multiple Values

Python functions can return multiple values as a tuple:

multiple_returns.py Python
def get_min_max(numbers): return min(numbers), max(numbers) # Unpack the returned values data = [4, 2, 9, 1, 7] minimum, maximum = get_min_max(data) print(f"Min: {minimum}, Max: {maximum}")
Min: 1, Max: 9

Early Returns

return immediately exits the function. This is useful for handling special cases:

early_return.py Python
def divide(a, b): if b == 0: return "Error: Cannot divide by zero" return a / b print(divide(10, 2)) print(divide(10, 0))
5.0 Error: Cannot divide by zero

Lab Exercise 3: Working with Returns

Intermediate

Instructions

Create functions that return values instead of just printing them.

Your Task

Create a function calculate_grade that takes a score and returns the letter grade: A (90+), B (80-89), C (70-79), D (60-69), F (below 60). Test it with scores 95, 82, and 55.

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: Return Values Complete!

You can get data back from functions. Let's explore advanced parameter techniques!

Advanced Parameters: Defaults & Keywords

Python offers powerful ways to make function calls more flexible and readable.

Default Parameter Values

Set default values for parameters - they're used if no argument is provided:

defaults.py Python
def greet(name, greeting="Hello"): print(f"{greeting}, {name}!") # Use default greeting greet("Alice") # Override the default greet("Bob", "Hi") greet("Charlie", "Welcome")
Hello, Alice! Hi, Bob! Welcome, Charlie!

Default Parameter Order

Parameters with defaults must come AFTER parameters without defaults.
def greet(greeting="Hi", name): ← This causes an error!
def greet(name, greeting="Hi"): ← This is correct!

Keyword Arguments

When calling a function, you can specify arguments by name:

keyword_args.py Python
def create_user(name, age, role="user"): print(f"{name} ({age}) - {role}") # Positional arguments (order matters) create_user("Alice", 25) # Keyword arguments (order doesn't matter!) create_user(age=30, name="Bob", role="admin") # Mix: positional first, then keyword create_user("Charlie", role="moderator", age=28)
Alice (25) - user Bob (30) - admin Charlie (28) - moderator

When to Use Keyword Arguments

Use keyword arguments when:
• Function has many parameters (improves readability)
• You want to skip optional parameters
• The parameter meaning isn't obvious from the value
Example: create_user("Bob", 30) vs create_user(name="Bob", age=30)

Practical Example

practical.py Python
def format_price(price, currency="$", decimals=2): return f"{currency}{price:.{decimals}f}" print(format_price(19.99)) # Use all defaults print(format_price(19.99, "€")) # Change currency print(format_price(19.99, decimals=0)) # No decimals print(format_price(19.99, "£", 1)) # Both
$19.99 €19.99 $20 £20.0

Lab Exercise 4: Default Parameters

Intermediate

Instructions

Create a function with default parameters to make it flexible.

Your Task

Create a function power that calculates base raised to exponent. Make exponent default to 2 (square). Test with power(5), power(2, 3), and power(10, exponent=4).

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: Advanced Parameters Complete!

You know defaults and keywords. One more important topic - scope!

Scope: Where Variables Live

Scope determines where a variable can be accessed. Variables created inside a function have local scope - they only exist inside that function.

Local vs Global Scope

scope.py Python
# Global variable (outside any function) message = "Hello from outside!" def my_function(): # Local variable (inside function) local_msg = "Hello from inside!" print(local_msg) # Works! print(message) # Can READ global my_function() print(message) # Works - global # print(local_msg) # ERROR! Not accessible here
Hello from inside! Hello from outside! Hello from outside!

Scope Rules

Local variables: Created inside a function, only accessible inside that function.
Global variables: Created outside functions, accessible everywhere (for reading).
Parameters: Act like local variables - only exist inside the function.

Modifying Global Variables

To modify a global variable inside a function, use the global keyword:

global_keyword.py Python
counter = 0 def increment(): global counter # Declare we want the global one counter += 1 print(f"Before: {counter}") increment() increment() increment() print(f"After: {counter}")
Before: 0 After: 3

Avoid Global Variables

While global exists, using it is generally bad practice. It makes code harder to understand and debug. Better approach: pass data through parameters and return values!

Better Design: No Globals Needed

better_design.py Python
# Bad: Using global # total = 0 # def add_to_total(n): # global total # total += n # Good: Using parameters and returns def add_to_total(current_total, n): return current_total + n total = 0 total = add_to_total(total, 5) total = add_to_total(total, 3) print(f"Total: {total}")
Total: 8

Lab Exercise 5: Understanding Scope

Intermediate

Instructions

Practice working with local and global variables to understand scope.

Your Task

Predict what this code will print, then run it to verify. The code demonstrates local vs global scope:

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: Scope Understood!

You understand where variables live. Time for the summary!

Chapter 4 Summary

Congratulations! You've mastered functions - one of the most important concepts in programming. Let's recap:

What You Learned

  • Function Basics: Define with def, call with function_name()
  • Parameters: Accept input data to make functions flexible
  • Return Values: Send results back to the caller with return
  • Default Parameters: Provide fallback values for optional arguments
  • Keyword Arguments: Call functions with named parameters for clarity
  • Scope: Local vs global variables, why globals should be avoided

Key Takeaways

def keyword

Creates a reusable block of code with a name.

Parameters

Variables that receive values when the function is called.

return

Sends a value back. Different from print() which just displays.

Scope

Local variables stay inside functions. Avoid globals!

Function Template

template.py Python
def function_name(required_param, optional_param="default"): """Docstring: Describe what the function does.""" # Function body result = # ... do something ... return result # Call the function output = function_name("value")

Chapter 4 Complete!

Functions are the building blocks of organized code. Ready to prove your skills?

Take the Chapter 4 Practical Exam