Name

for

Examples
for i in range(40):
    line(30, i, 80, i)
for i in range(0, 80, 5):
    line(30, i, 80, i)
for i in range(40, 80, 5):
    line(30, i, 80, i)
# Nested for() loops can be used to
# generate two-dimensional patterns
for i in range(30, 80, 5):
    for j in range(0, 80, 5):
        point(i, j)
nums = [5, 4, 3, 2, 1]
for i in nums:
    print(i)
Description Controls a sequence of repetitions. In Python, a for loop requires a list function to iterate over. The range() function provides such a list, and accepts arguments in three ways:
range(10) # Creates the list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(5, 10) # Creates the list [5, 6, 7, 8, 9]
range(5, 10, 2) # Creates the list [5, 7, 9]

In the first example above, the for structure is executed 40 times. The for structure loops until it reaches the last element of the list created by range(40): 39.

A second type of for structure makes it easier to iterate over each element of a list. The last example above shows how it works. First, define a variable name. This variable name will be assigned to each element of the list in turn as the for moves through the entire list. Then specify the list to iterate over after in, in this case nums.
Syntax
for var in iterable:
    statements

for var in iterable:
    statements
Parameters
varvariable to be assigned to each element of the iterable
iterableiterable object to loop over
statementscollection of statements executed each time through the loop
Related while

Updated on Mon Sep 21 15:53:25 2020.

If you see any errors or have comments, please let us know.