Chapter 7: Navigating Through Space (For and While Loops)
Hello, Explorer! By now, we’re well into our journey through the endless expanse of space. We’ve encountered aliens and responded accordingly using our knowledge of if, elif, and else statements.
In this chapter, we’ll discuss a crucial programming concept that will enable us to navigate through space more effectively: loops. Loops are used when we want to repeat a block of code multiple times.
In Python, we have two types of loops - for and while loops. Let’s get started!
The For Loop
The for loop in Python is used to iterate over a sequence (like a list, tuple, or string) or other iterable objects. Iterating over a sequence is called traversal.
Here is a basic example of a for loop:
1 for i in range(5):
2 print(i)
This code will print the numbers 0 through 4. The range(5) function generates a sequence of numbers from 0 up to (but not including) 5. The variable i takes on each value in the sequence one after another, and for each value, it executes the indented block of code (in this case, print(i)).
We can also iterate over other sequences, like lists or strings. Here’s an example with a list:
1 planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Nept\
2 une"]
3
4 for planet in planets:
5 print(planet)
In this example, planet takes on each value in the planets list, and for each planet, we print its name.
The While Loop
A while loop in Python repeatedly executes a target statement as long as a given condition is true.
Here’s a simple while loop:
1 fuel = 10
2
3 while fuel > 0:
4 print("The spacecraft is still running; fuel level is", fuel)
5 fuel = fuel - 1
6
7 print("The spacecraft has run out of fuel!")
In this code, as long as the condition fuel > 0 is true, the indented block of code will be executed. Each time the loop is executed, the fuel level decreases by 1. When the fuel level reaches 0, the condition fuel > 0 is no longer true, so the loop stops executing. After the loop, we print a message that the spacecraft has run out of fuel.
Break, Continue, and Pass
Python provides break, continue, and pass statements to fine-tune your control over the flow within loops:
-
breakallows you to exit the entire loop prematurely when a certain condition is met. -
continueallows you to skip the rest of the current iteration and move on to the next one. -
passis a placeholder statement that does nothing and is used when the syntax requires a statement, but you don’t want to execute any code.
Project: Space Navigation System
Now that we’ve got a grasp on for and while loops, let’s use them in our ongoing space mission. Your task is to develop a space navigation system.
-
Route planning with a
forloop: Create a list of waypoints that the spacecraft will pass on its journey. Then, use aforloop to iterate over this list, printing a message for each waypoint.
1 waypoints = ["Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
2
3 for waypoint in waypoints:
4 print("Navigating to", waypoint)
-
Fuel monitoring with a
whileloop: Initialize a fuel level. Then, use awhileloop to simulate the spacecraft’s journey. With each iteration of the loop, decrease the fuel level and print it out. When the fuel level reaches 0, print a warning message and break the loop.
1 fuel = 100
2
3 while fuel > 0:
4 print("Current fuel level:", fuel)
5 fuel -= 10
6
7 print("Warning: Fuel level critical!")
These are just starting points. Try to expand on these projects using your knowledge of Python. For example, you could check for specific waypoints (like Earth or Mars) and execute specific code when they are encountered, or add a fuel_replenished condition to the while loop to replenish fuel.
In our next chapter, we’ll explore how to handle and manipulate strings in Python, an essential skill for any Python programmer. We’ll learn how to communicate with other space stations and decode galactic coordinates. Safe travels, and keep on exploring!