Chapter 10: Living in Space (Functions)

Welcome back, Space Explorer! As our journey continues, our day-to-day tasks in space are becoming more routine. Whether it’s checking the spacecraft’s vitals, analyzing space data, or even making space coffee, we’re repeating the same sequences of tasks daily. Just as in space exploration, when programming, you often need to perform the same operation multiple times. Fortunately, Python has an excellent tool to handle these scenarios - functions!

Understanding Functions

A function in Python is a reusable piece of code that performs a specific task. Think of it like a machine: you put something in, it does some work, and then it gives something back out. The “things” you put into a function are called arguments, and the “thing” it gives back out is called the return value.

Defining Functions

In Python, you define a function using the def keyword. Here’s the basic syntax:

1 def function_name(argument1, argument2, ..., argumentN):
2     # Code to execute
3     return result
  • function_name is the name you want to give to your function. Function names should be descriptive and follow the same naming conventions as variables.
  • argument1, argument2, ..., argumentN are the inputs to your function. A function can have any number of arguments, including zero.
  • The code to execute is the task the function performs. This code runs when you call the function.
  • result is the output of your function. The return statement determines what value your function gives back when called. If you don’t include a return statement, the function will return None.

Let’s define a simple function that greets a crew member:

1 def greet_crew_member(name):
2     message = "Hello, " + name + "! Ready for another day of space exploration?"
3     return message

To use this function, we call it by its name and pass in a crew member’s name:

1 print(greet_crew_member("Alice"))

This program will output the string “Hello, Alice! Ready for another day of space exploration?”.

Function Parameters and Arguments

In the context of functions, the terms parameter and argument are often used interchangeably, but they have slightly different meanings:

  • A parameter is a variable in a function definition. In our greet_crew_member function, name is a parameter.
  • An argument is a value you pass into a function call. When we called greet_crew_member("Alice"), “Alice” was an argument.

You can think of parameters as the placeholders for the values that will be passed into a function, while arguments are the actual values.

Return Statements

The return statement is used to exit a function and go back to the place from where it was called. This statement can include an expression which gets evaluated and its result is returned. If there is no expression in the statement or the return statement itself is not present inside a function, then the function will return None.

1 def calculate_distance(speed, time):
2     distance = speed * time
3     return distance

In the calculate_distance function, the return statement returns the calculated distance.

Local and Global Variables

In Python, a variable declared outside of a function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.

On the other hand, a variable declared inside a function is known as a local variable. This means that a local variable can be accessed only inside the function in which it is declared.

Let’s see an example:

 1 # This is a global variable
 2 planet = "Mars"
 3 
 4 def greet_from_planet(name):
 5     # This is a local variable
 6     message = "Hello, " + name + "! Greetings from " + planet + "!"
 7     return message
 8 
 9 print(greet_from_planet("Alice"))  # This can access the global variable planet
10 print(message)  # This will cause an error, because message is a local variable

The greet_from_planet function can access the global variable planet, but the last line causes an error because message is a local variable, and it can’t be accessed outside its function.

Project: Daily Routine Automation

Let’s create some functions to automate our daily tasks in space. We’ll make functions for waking up, eating meals, doing a spacecraft check, and going to bed.

 1 def wake_up():
 2     print("Wake up, Space Explorer!")
 3     print("Time to start another day of space exploration.")
 4     print()
 5 
 6 def eat_meal(meal_name):
 7     print("Time to eat", meal_name + ".")
 8     print("Yum! That was some good space", meal_name + "!")
 9     print()
10 
11 def do_spacecraft_check():
12     print("Beginning spacecraft systems check.")
13     print("...")
14     print("All systems operational!")
15     print()
16 
17 def go_to_bed():
18     print("That's enough space exploration for today.")
19     print("Time to get some rest. Good night, Space Explorer!")
20     print()
21 
22 # Let's use our functions to automate our daily routine
23 wake_up()
24 eat_meal("breakfast")
25 do_spacecraft_check()
26 eat_meal("lunch")
27 do_spacecraft_check()
28 eat_meal("dinner")
29 go_to_bed()

This program simulates a day in the life of a Space Explorer, using functions to perform each routine task.

With your newfound understanding of Python functions, you’re ready to handle repeated sequences of tasks with ease. In the next chapter, we’ll explore unknown lands by learning about Python modules and libraries. Until then, keep exploring and coding!