Loops
A loop is a control structure that can execute a statement or group of statements repeatedly. Python has three types of loops: while
loops, for
loops, and nested loops.
While Loops
A while
loop will repeatedly execute a code block as long as a condition evaluates to True
.
The condition of a while
loop is always checked first before the block of code runs. If the condition is not met initially, then the code block will never run.
while condition:
# Code inside
This loop will only run 1 time:
hungry = Truewhile hungry:print("Time to eat!")hungry = False
This loop will run 5 times:
i = 1while i < 6:print(i)i = i + 1
For Loop
A for
loop can be used to iterate over and perform an action one time for each element in a list.
Proper for loop syntax assigns a temporary value, the current item of the list, to a variable on each successive iteration:
for <temporary value> in <a list>:
for
loop bodies must be indented to avoid an IndentationError
.
dog_breeds = ["boxer", "bulldog", "shiba inu"]# Print each breed:for breed in dog_breeds:print(breed)
Nested Loops
Loops can be nested inside other loops. Nested loops can be used to access items of lists which are inside other lists. The item selected from the outer loop can be used as the list for the inner loop to iterate over.
groups = [["Jobs", "Gates"], ["Newton", "Euclid"], ["Einstein", "Feynman"]]# This outer loop will iterate over each list in the groups listfor group in groups:# This inner loop will go through each name in each listfor name in group:print(name)
Break Keyword
In a loop, the break
keyword escapes the loop, regardless of the iteration number. Once break executes, the program will continue to execute after the loop.
numbers = [0, 254, 2, -1, 3]for num in numbers:if (num < 0):print("Negative number detected!")breakprint(num)
In this example, the output would be:
02542Negative number detected!
Continue Keyword
The continue
keyword is used inside a loop to skip the remaining code inside the loop code block and begin the next loop iteration.
big_number_list = [1, 2, -1, 4, -5, 5, 2, -9]# Print only positive numbers:for i in big_number_list:if i < 0:continueprint(i)
Pass Keyword
The pass
keyword is used as a placeholder statement to allow empty loops, functions or classes to be included in an executable code block without throwing an error. This is common when structuring future implementations.
# Nested loop with a placeholder for incomplete logicfor i in range(3):for j in range(3):if i == j:# Placeholder for future implementationspasselse:print(f"i: {i}, j:{j}")
Video Walkthrough
In this video, you will learn how to use the for and while loops in a Python script.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly90 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours