For Loop in Python
For Loop in Python
With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.
Example
Print each fruit in a fruit list:
Output:
The for loop does not require an indexing variable to set beforehand.
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
Output:
Output:
Example
Exit the loop when x is "banana", but this time the break comes before the print:
Output:
Example
Do not print banana:
Output:
C:\Users\My Name>python demo_for_continue.py
apple
cherry
The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
Example
Using the range() function:
for x in range(6):
print(x)
Output:
Example
Using the start parameter:
Output:
Example
Increment the sequence with 3 (default is 1):
Output:
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Output:
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
Print each adjective for every fruit:
for x in adj:
for y in fruits:
print(x, y)
Output: