For Loop Python
For Loop Python
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works more like an iterator method as found in
other object-orientated programming languages.
With the for loop, we can execute a set of statements, once for each item in a list, tuple, set etc.
Rules:
All argument must be integers i.e., whole numbers only. You cannot pass a string or float number or any
other type in a start, stop and step argument of a range().
All three arguments can be positive or negative.
The step value must not be zero. If a step is zero python raises a ValueError exception.
To loop through a set of code a specified number of times, we can use the range() function, Output:
The range() function returns a sequence of numbers, starting from 0 by default, and increments 0
by 1 (by default), and ends at a specified number. 1
Example 2
Using the range() function: 3
for x in range(6): 4
print(x) 5
Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by
adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6): Output:
Example 2
Using the start parameter: 3
for x in range(2, 6): 4
print(x) 5
The range() function defaults to increment the sequence by 1, however it is possible to specify the increment
value by adding a third parameter: range(2, 30, 3):
Example Output:
Increment the sequence with 3 (default is 1): 2
for x in range(2, 30, 3): 5
print(x) 8
11
Else in For Loop 14
The else keyword in a for loop specifies a block 17
of code to be executed when the loop is 20
finished: 23
26
Example 29
Print all numbers from 0 to 5, and print a
Output:
message when the loop has ended:
0
for x in range(6):
1
print(x)
2
else:
3
print("Finally finished!")
4
5
Note: The else block will NOT be executed if
Finally finished!
the loop is stopped by a break statement.
Example Output:
Break the loop when x is 3, and see what happens with the else block: 0
for x in range(6): 1
if x == 3: break 2
print(x)
else:
print("Finally finished!")
#If the loop breaks, the else block is not executed.
# having an empty for loop like this, would raise an error without the pass statement