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.
START_DAY = 1
simulation_duration = input_positive_integer("simulation duration (in days)")
for current_day in range(START_DAY, START_DAY + simulation_duration):
…
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.