For-Loops
Do it again!¶
Let’s simulate multiple days.
Instead of repeating all the code, we can use a loop.
We could use a while
loop again, but there is a better way, since we know in advance how many iterations our simulation should run for.
To use the for
loop, we need to be able to count out the days, so let’s start with a small example first.
The built-inNote: This is best done in the REPL
range(…)
-function can be very practical here.
It generates a sequence of numbers.
These numbers are one after the other used as the value for current_turn
.
When all numbers have been used as values, the loop stops.
Common Pitfall
When given a value to stop at, the range(…)
-function does not include that last stopping value.
In our example the generated numbers thus would be 0…19, excluding the 20.
Fine-tuning¶
But wait, we usually count days starting from 1 and want to end with 20
Much better. Now we have all the pieces we need to run the simulation for multile days.
for current_day in range(1, 21):
print("Start of day", current_day)
(current_population, current_food) = simulate_day(current_population, current_food)
current_food = current_food + food_per_day
Now this is getting exciting. We have the necessary puzzle pieces to also input the amount of days we want to run the simulation for.
It is a good idea to introduce a constant for the starting day so there is no confusion what we talk about.
Especially since we know that programmers often start counting at 0
instead of 1
.
from constants import START_DAY
… # Prepare the other imports and simulation starting values
simulation_duration = input_positive_integer("simulation duration (in days)")
# Prepare for the first day
# Variables to carry information over from one day to the other
current_population = starting_population
current_food = food_per_day
for current_day in range(START_DAY, START_DAY + simulation_duration):
… # do the calculation and printing for one day
Don’t forget to apply the proper indentation inside the loop!
Key Points
- A
for
-loop repeats for each value in a given bunch of data. - The
range(…)
-function can be very useful to generate number sequences- If not specified otherwise, it counts from 0 up to but excluding the stop value.
Code Checkpoint
This is the code that we have so far:
- 📁
alien_growth_model