Python For Loops: Example
Python For Loops: Example
A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
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:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Try it Yourself »
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
Try it Yourself »
The break Statement
With the break statement we can stop the loop before it has looped through all
the items:
Example
Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
Try it Yourself »
Example
Exit the loop when x is "banana", but this time the break comes before the
print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
Try it Yourself »
Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
Try it Yourself »
Example
Using the range() function:
for x in range(6):
print(x)
Try it Yourself »
Example
Using the start parameter:
for x in range(2, 6):
print(x)
Try it Yourself »
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
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
Try it Yourself »
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!")