Python For Loops
Python For Loops
Dark mode
Dark code
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP BOOTSTRAP HOW TO W3.CSS C C++ C# REACT R JQUERY DJANGO
Python HOME
Python Intro
Python Get Started
Try it Yourself »
The for loop does not require an indexing variable to set beforehand.
for x in "banana":
print(x)
Try it Yourself »
Example
Exit the loop when x is "banana":
Try it Yourself »
Example
Exit the loop when x is "banana", but this time the break comes before the print:
ADVERTISEMENT
Try it Yourself »
ADVERTISEMENT
Example
Do not print banana:
Try it Yourself »
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)
Try it Yourself »
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):
Example
Using the start parameter:
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):
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!")
Try it Yourself »
Note: The else block will NOT be executed if the loop is stopped by a break statement.
Example
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
Try it Yourself »
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)
Try it Yourself »
Example
Try it Yourself »
Exercise:
Loop through the items in the fruits list.
Submit Answer »
ADVERTISEMENT
ADVERTISEMENT
FORUM | ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we
cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.