Part 5: Mission Control Functions — Reusable Commands
The Adventures of Ava the Astronaut: Learning Python One Planet at a Time
Part 5: Mission Control Functions — Reusable Commands
The Adventures of Ava the Astronaut: Learning Python One Planet at a Time
A Command for Everything
After mastering loops, Ava felt like a real programmer. She could collect hundreds of crystals and dock her ship with just a few lines of code. But as her missions grew more complex, her code started getting long and messy. She often found herself writing the exact same block of code in different parts of her program.
For example, she had a standard five-line sequence for greeting a new alien species. Every time she encountered aliens, she had to copy and paste those same five lines. And if she wanted to change the greeting, she had to find and update every single copy.
“Py,” she said, “there must be a way to package these lines into a single command that I can reuse whenever I need it.”
“Excellent observation, Commander,” Py responded. “You are ready to learn about functions. A function is a named, reusable block of code that performs a specific task. Think of it as creating a new button on your control panel. You build it once, and then you can press it as many times as you like.”
Creating Your Own Commands: Defining Functions
In Python, we “define” a function using the def keyword, followed by the function’s name, parentheses, and a colon. The code inside the function is indented, just like with if statements and loops.
Let’s turn Ava’s greeting sequence into a function.
# Step 1: DEFINE the function (build the button)def greet_alien(): print("Hailing frequencies open...") print("We come in peace.") print("I am Commander Ava of the Starship Explorer.") print("What is the name of your species?") print("Hailing frequencies closed.")
# Step 2: CALL the function (press the button)print("--- Entering orbit of Planet Gleep Glorp ---")greet_alien()
print("\n--- A few hours later... ---\n")
print("--- Entering orbit of Planet Zorp ---")greet_alien()What happens?
The greeting sequence prints twice — once for each planet — but we only wrote it once! Here is the key distinction:
| Action | What It Means | Analogy |
|---|---|---|
Defining a function (def greet_alien():) | Teaching Python a new command. The code inside does NOT run yet. | Building a new button on the control panel. |
Calling a function (greet_alien()) | Executing the code inside the function. | Pressing the button. |
You can call a function as many times as you want, from anywhere in your program. This is the power of reusability!
Giving Instructions: Parameters and Arguments
Ava’s greeting is good, but it is a bit generic. What if she wants to greet each planet by name? We can make functions more flexible by allowing them to accept input. These inputs are called parameters (when defining the function) and arguments (when calling the function).
# 'planet_name' is a PARAMETER — a placeholder for future inputdef greet_planet(planet_name): print("Hailing frequencies open...") print(f"Now approaching the planet {planet_name}.") print("We come in peace!") print("Hailing frequencies closed.")
# "Gleep Glorp" and "Zorp" are ARGUMENTS — the actual values we pass ingreet_planet("Gleep Glorp")print()greet_planet("Zorp")Now the function is much more useful! Each time we call it, we pass a different planet name, and the function uses that specific name in its output. You can have multiple parameters, separated by commas.
def describe_alien(species, planet, num_eyes): print(f"Species: {species}") print(f"Origin: {planet}") print(f"Number of Eyes: {num_eyes}")
describe_alien("Zorpian", "Planet Zorp", 4)print()describe_alien("Gleepoid", "Gleep Glorp", 7)Getting an Answer Back: The return Statement
Some functions perform an action, like printing to the screen. But other functions are designed to do a calculation and give you back the result. To send a value back from a function, we use the return statement.
Ava needs a function to calculate the travel time for a journey. The function will take the distance and speed as input and return the calculated time.
def calculate_travel_time(distance, speed): if speed == 0: return "Error: Speed cannot be zero!" time = distance / speed return time # Send the result back to whoever called the function
# Call the function and store the returned result in a variabletime_to_alpha = calculate_travel_time(500, 100)print(f"Estimated travel time: {time_to_alpha} years.")
# What about a ship that isn't moving?result = calculate_travel_time(1000, 0)print(result)Output:
Estimated travel time: 5.0 years.Error: Speed cannot be zero!When the return statement is reached, the function immediately stops and sends the value back. We can then store that returned value in a variable (like time_to_alpha) and use it however we like.
Default Parameters: Pre-Set Values
Sometimes, a parameter has a common value that is used most of the time. You can set a default value for a parameter, so the caller does not have to provide it every time.
def launch_ship(destination, speed=100): print(f"Launching to {destination} at speed {speed}.")
# Call with both argumentslaunch_ship("Mars", 200)
# Call without the speed argument — it uses the default value of 100launch_ship("Jupiter")Output:
Launching to Mars at speed 200.Launching to Jupiter at speed 100.Mini-Project: “Space Calculator”
Your mission is to build a simple calculator for Ava’s spaceship using functions.
Your Task:
- Create four functions:
add(a, b),subtract(a, b),multiply(a, b), anddivide(a, b). - Each function should take two numbers as parameters.
- Each function should
returnthe result of the calculation. - In the
dividefunction, add a check: ifbis zero, return the string"Error: Cannot divide by zero!"instead of performing the division. - Call each of your functions at least once and print the results.
Example:
def add(a, b): return a + b
def subtract(a, b): return a - b
def multiply(a, b): return a * b
def divide(a, b): if b == 0: return "Error: Cannot divide by zero!" return a / b
print(f"10 + 5 = {add(10, 5)}")print(f"10 - 5 = {subtract(10, 5)}")print(f"10 * 5 = {multiply(10, 5)}")print(f"10 / 5 = {divide(10, 5)}")print(f"10 / 0 = {divide(10, 0)}")Mission Complete!
You have successfully organized your command console at Mission Control! You now know how to create your own reusable commands with def, make them flexible with parameters, get results back with return, and set convenient default values. Your programs will now be cleaner, more organized, and much more powerful.
Next, we will explore the ship’s cargo hold and learn how to manage inventories of items using Lists, Tuples, and Strings! See you in Part 6!
This is Part 5 of a 10-part series: “The Adventures of Ava the Astronaut: Learning Python One Planet at a Time.”