WORKING WITH LOOPS IN PYTHON
Python supports for loops, while loops, and range() statements. The following subsections illustrate how you can use each of these constructs.
Python for Loops
Python supports the for loop whose syntax is slightly different from other languages (such as JavaScript and Java). The following code block shows you how to use a for loop to iterate through the elements in a list:
>>> x = ['a', 'b', 'c']
>>> for w in x:
... print(w)
...
a
b
c
The preceding code snippet prints three letters on three separate lines. You can force the output to be displayed on the same line (which will “wrap” if you specify a large enough number of characters) by appending a comma (“,”) in the print() statement, as shown here:
>>> x = ['a', 'b', 'c']
>>> for w in x:
... print(w, end=' ')
...
a b c
You can use this type of code when you want to display...