PY
py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Understanding a for loop
words = ["hello", "world", "spam", "eggs"]
for i in words:
print(i + "!")
'''
What you see in this sample, is that the print()statement has an indentation compared to the loop header. All lines of code that follows directly after print and with the same indentation belong to the codeblock of the loop.
A loop in general is made to repeat a piece of code in a program. In our case, in a for loop, we need to have at least a loop variable and a sequence of data.
The sequence can be a string, list, tuple, set,... but also something like a range object. Also some other python objects can be used. In our sample we use a list named "words". This list contains 4 elements, all of the same data type which is string, but this is not necessary. Lists can also be like:
lst = ['hello', 3.14, 12, 'XoX']
The loop variable here has the name 'i', but can have also any other valid name for variables.
This happens when the loop starts:
- The first element is picked from the list and stored in the loop variable 'i'.
- Then the control flow of the code will execute the next line or lines of code. In our case it's a print() statement, that uses the variable name to print out the first element of the list.
- Then the loop continues to run, and picks the second element from the list and stores it in the list variable, so that the previous value get overwritten.
- This is running as long as there are elements in the sequence, that not yet have been used.
- After the last element was used, the loop will be terminated, and the code lines following the loop will be executed.
'''
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run