5
Lesson 5: Functions and Modular Programming
Creating reusable code blocks
Learning Objectives
By the end of this lesson, students will:
- Define and call custom functions
- Use parameters and return values effectively
- Understand variable scope (local vs global)
- Apply modular programming principles
Skills Developed:
- Code organization and reusability
- Problem decomposition
- Software engineering fundamentals
Lesson Content
1 Function Basics (20 minutes)
Why Functions?
- • Avoid repeating code (DRY - Don't Repeat Yourself)
- • Break complex problems into smaller pieces
- • Make code easier to read and maintain
- • Enable code reuse across projects
# Function definition
def greet_robot():
print("🤖 Hello from the robot!")
print("Ready for commands!")
# Function call
greet_robot() # This runs the function
greet_robot() # Can call multiple times
# Function with calculation
def calculate_battery_life():
voltage = 12.5
current = 2.1
power = voltage * current
print(f"Power consumption: {power} watts")
calculate_battery_life()
Instructor Notes:
Compare functions to recipes - they're instructions you can follow multiple times. Show how robot actions could be functions: move_forward(), turn_left(), check_sensors().
2 Parameters and Arguments (20 minutes)
Making Functions Flexible:
- • Parameters are variables in function definition
- • Arguments are actual values passed when calling
- • Functions can have multiple parameters
- • Default values make parameters optional
# Function with parameters
def move_robot(direction, steps):
print(f"Moving {direction} for {steps} steps")
for i in range(steps):
print(f"Step {i+1}: Moving {direction}")
# Function calls with arguments
move_robot("forward", 3)
move_robot("left", 2)
move_robot("backward", 1)
# Function with default parameter
def check_sensor(sensor_type="distance"):
print(f"Checking {sensor_type} sensor...")
if sensor_type == "distance":
print("Distance: 25 cm")
elif sensor_type == "temperature":
print("Temperature: 22°C")
check_sensor() # Uses default
check_sensor("temperature") # Override default
3 Return Values (15 minutes)
Functions That Give Back:
- • return statement sends value back to caller
- • Functions can return any data type
- • Can return multiple values as tuple
- • Functions without return give back None
# Function that returns a value
def calculate_distance(speed, time):
distance = speed * time
return distance
# Using the returned value
robot_distance = calculate_distance(5, 10)
print(f"Robot traveled: {robot_distance} meters")
# Function returning multiple values
def get_sensor_readings():
temperature = 23.5
humidity = 65
pressure = 1013
return temperature, humidity, pressure
temp, hum, press = get_sensor_readings()
print(f"Temp: {temp}°C, Humidity: {hum}%")
4 Variable Scope (10 minutes)
Local vs Global Variables:
Local Variables:
- • Created inside functions
- • Only accessible within that function
- • Destroyed when function ends
Global Variables:
- • Created outside functions
- • Accessible everywhere
- • Use sparingly for better code
# Global variable
robot_name = "AutoBot"
def introduce_robot():
# Local variable
greeting = "Hello, I am"
print(f"{greeting} {robot_name}")
def set_robot_mode():
mode = "autonomous" # Local variable
print(f"Mode set to: {mode}")
introduce_robot()
set_robot_mode()
# print(greeting) # Error! greeting is local
Hands-On Activity (25 minutes)
Project: Robot Control Library
Students will create a library of functions to control different aspects of a robot.
Requirements:
- • Create at least 5 different robot control functions
- • Include functions with parameters and return values
- • Use default parameters in at least one function
- • Create a main program that uses all functions
- • Include proper documentation (comments)
- • Demonstrate understanding of variable scope
🤖🛠️ How to Code This Project (Choose Your Platform):
📱 Pythonista 3:
- Open Pythonista 3
- Tap "+" → "Empty Script"
- Name it "robot_library.py"
- Type the code below
- Tap ▶️ to run
- Test all functions
Tip: Test functions with different parameters
🤖 Pydroid 3:
- Open Pydroid 3
- Tap "+" → "Python file"
- Name it "robot_library.py"
- Type the code below
- Tap ▶️ yellow play button
- Test all functions
Tip: Watch global variables change
💻 PC/Mac:
- Open IDLE or editor
- Create new file
- Save as "robot_library.py"
- Type the code below
- Press F5 to run
- Test all functions
Tip: Use functions interactively in shell
# Robot Control Library
# Global robot status
robot_battery = 100
robot_position = [0, 0]
def move_forward(steps=1):
global robot_battery, robot_position
if robot_battery < 10:
return "Low battery! Cannot move."
robot_position[1] += steps
robot_battery -= steps * 2
print(f"Moved forward {steps} steps")
def turn_robot(direction):
valid_directions = ["left", "right"]
if direction in valid_directions:
print(f"Turned {direction}")
else:
return "Invalid direction"
def check_battery():
return robot_battery
def get_position():
x, y = robot_position
print(f"New position: ({x}, {y})")
def scan_area(range_meters=10):
objects_found = ["tree", "rock", "path"]
print(f"Scanning {range_meters}m range: {objects_found} objects")
# Main program
print("🤖 Robot Control System Active")
move_forward(3)
turn_robot("right")
get_position()
print(f"Battery: {check_battery()}%")
scan_area(15)
print(scan_area(15))
Assessment & Homework
Quick Check (In Class):
- • Can student define and call functions?
- • Do they understand parameters vs arguments?
- • Are they using return values correctly?
- • Do they grasp variable scope concepts?
Homework Assignment:
Smart Device Controller
Create a modular program that controls various smart devices (lights, thermostat, security system). Each device should have its own functions with appropriate parameters and return values. Include error handling and status reporting.