Python loops repeat a block of code. Python has two loop statements: the for loop, which iterates over the items of a sequence such as a list, tuple, string or range(), and the while loop, which keeps running as long as a condition is true.
Key takeaways
- Use a
forloop when you know what you are iterating over; use awhileloop when you repeat until a condition changes. range(start, stop, step)generates the numbers aforloop counts through;stopis not included.breakexits the loop immediately, whilecontinueskips to the next iteration.- A loop’s
elseblock runs only when the loop finishes without hittingbreak.
For Loop¶
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
L=[10,20,"Machine Learning",40,50]
for i in L:
print("Printing",i)
The range() Function¶
To loop through a set of code a specified number of times, we can use the range() function
L=list(range(10))
for i in L:
print(i,end=' ')
for i in range(10):
print(i,end=' ')
for i in range(1,10):
print(i,end=' ')
for i in range(1,10,1):
print(i,end=' ')
for i in range(1,10,2):
print(i,end=' ')
for i in range(5):
print("MachineLearning.org.in")
For Loop Control Statement¶
for i in range(1,10):
if i%3==0:
print(i,end=' ')
Looping Through a String¶
Even strings are iterable objects, they contain a sequence of characters:
for x in "python":
print(x)
For Loop with break Statement¶
With the break statement we can stop the loop before it has looped through all the items:
for i in range(1,10):
if i==5:
break
print(i,end=' ')
For Loop with Continue Statement¶
With the continue statement we can stop the current iteration of the loop, and continue with the next:
for i in range(1,10):
if i==5:
continue
print(i,end=' ')
Else in For Loop¶
The else keyword in a for loop specifies a block of code to be executed when the loop is finished:
for x in range(6):
print(x)
else:
print("Finally finished!")
Nested For Loop¶
A nested loop is a loop inside a loop.
The “inner loop” will be executed one time for each iteration of the “outer loop”:
adj = ["Red", "Big", "Tasty"]
fruits = ["Apple", "Watermelon", "Mango"]
for x in adj:
for y in fruits:
print(x, y)
The while Loop¶
With the while loop we can execute a set of statements as long as a condition is true.
i=1
while(i<=5):
print("MachineLearning.org.in")
i=i+1
i = 1
while i <= 10:
print(i,end=' ')
i += 1
The break Statement¶
With the break statement we can stop the loop even if the while condition is true:
i = 1
while i <= 10:
if i==4:
break
print(i)
i += 1
The continue Statement¶
With the continue statement we can stop the current iteration, and continue with the next:
i = 0
while i <= 10:
i += 1
if i==4:
continue
print(i)
The else Statement¶
With the else statement we can run a block of code once when the condition no longer is true:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Summary
This tutorial covered both Python loop types with runnable examples: iterating over lists and strings with for, counting with range(), controlling the flow with break, continue and else, nesting loops, and repeating code with while. Practise each snippet and change the values to see how the output changes.
Frequently asked questions
What is the difference between for and while loops in Python?
A for loop iterates over a sequence and stops when the items run out. A while loop repeats as long as its condition stays true, so you must update the condition inside the loop to avoid an infinite loop.
How do I stop a loop in Python?
Use the break statement to exit the loop immediately. Use continue if you only want to skip the rest of the current iteration.
Does Python have a do-while loop?
No. You can get the same behaviour with while True: and a break at the end of the loop body once your condition is met.
Related tutorials
- Python MySQL Installation
- Python MYSQL Create Database
- Python MySQL Create Table
- Python MySQL Insert Into Table
- Python decision making (if, elif, else)
- Python functions
Learn it step by step
Build a strong foundation with the free Python Foundation with Data Structures & Algorithms course and earn the Python Programming Professional Certification.
Machine Learning Tutorials, Courses and Certifications