2.4 - For loops
For loops iterate over a list, and executes the code inside the loop. The for loop's syntax looks like this:
for variable in list:
# Code
We'll use a built in function called range
that returns a list from a
to b
. This code will count up from 1 to 10 then say "Blast off!"
for count in range(1, 10): # 1 to 10
print(count)
print("Blast off!")
We can visualize the code like this:
- Get the value of
range(1, 10)
which is a list of numbers from 1 to 10 - For each value in that list:
- Set the
count
variable to the current item in the list - Run the code:
- Print the value of the count variable
- Go to the next item
- Set the
- Print "Blast off!"
There was meant to be an ad here. Support us by turning off your ad blocker or donating.