5. for loop
The next type of loop in Python is the for loop. Unlike in most languages, for requires some __iterable__ object like a Set or List to work.
The output:
The output looks very familiar, but the program code looks different. The first line uses the range function. The range function uses two arguments like this range(start,finish). start is the first number that is produced. finish is one larger than the last number. Note that this program could have been done in a shorter way:
Here are some examples to show what happens with the range function:
Remark: for the current version of Python, we need to pass the range function to list() to actually print a list. For instance, we need to use list(range(1,10)) to get [1, 2, 3, 4, 5, 6, 7, 8, 9].
Another way to use the range() function in a for loop is to supply only one argument:
The above code acts exactly the same as:
with 0 implied as the starting point. The output is
"For Loops" by en.wikibooks.org is licensed under CC BY-SA 4.0