Previously we looked at while loops. Loops that run for as long as some condition is true. These are great for things like guessing games where we have no idea how long it will take to find the correct answer.
Sometimes, we know exactly how many times we want to execute instructions. There is a special type of loop we can use in those situations: The for loop.
Below is some Python code for a counted loop:
for x in range(0, 5, 1):
print(x)
This loop has the following output on the console:
0
1
2
3
4
There are 3 important parts to the for loop above:
Copy the above code into a Python file and run it to see for yourself. Now, make the following changes and answer the associated questions.
Enter a positive number to count to: 8
0
1
2
3
4
5
6
7
8
6. Add in the ability for the user to set the starting number and the step value. Below is example output:
Enter the value to start at: 1
Enter the value to end at: 5
Enter the value to count by: 2
1
3
5
For loops are useful for counting things, but in Python there are other things we can iterate over. Take, for example, strings. Enter the following code into Wing101 IDE and run it:
string = raw_input("Enter some text: ")
for character in string:
print (character)
Below is some sample output:
Enter some text: Some Text
S
o
m
e
T
e
x
t
The inputted text is printed one letter at a time, including the space between words.
By enclosing a list of items in square brackets [ and ], we can print out anything we want! Copy the following code:
for value in [10, "Elephant", 3.14159]:
print (value)
If you run the above, you'll see the output is:
10
Elephant
3.14159
Each element is printed on its own!