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:

  1. Get the value of range(1, 10) which is a list of numbers from 1 to 10
  2. For each value in that list:
    1. Set the count variable to the current item in the list
    2. Run the code:
      1. Print the value of the count variable
    3. Go to the next item
  3. Print "Blast off!"
There was meant to be an ad here. Support us by turning off your ad blocker or donating.