Intro to Python
Share
Explore
Learn Python

Loops

This section covers:
for loops
while loops
Using break and continue
Computers are often used to automate repetitive tasks. Python has two types of loops that can be used to execute instructions repeatedly: the for loop and the while loop.
The for loop
The for loop is useful for iterating over a sequence.
Here is a simple program that prints each number in a list and then prints “Done!”
my_favorite_numbers = [2, 8, 100, -23]
for num in my_favorite_numbers:
print(num)
print('Done!')
You can also use range to iterate over a sequence of numbers. The following code will print the numbers 0 through 4.
for i in range(5):
print(i)
Here is the basic structure of a for loop. Note the indentation used to indicate the instructions that should be repeated.
for <variable> in <sequence>:
<body: code to be repeated for each element in the sequence>
<code to run after iterating through the sequence>
The body will be run once for each element in the sequence. In the body, you can refer to the current element using the name of the variable you provide between the for and the in.
The while loop
The while loop is used to repeatedly execute instructions as long as a boolean condition is met.
Here is a simple program that uses a while loop to count down from 5 and then prints “Blastoff!”
n = 5
while n > 0:
print(n)
n = n - 1
print('Blastoff!')
Here is the basic structure of a while loop. Note the indentation used to indicate the instructions that should be repeated.
while <condition>:
<body: code to be repeated while condition is true>
<code to run when the condition is no longer true>
Using break and continue
The break statement is used to exit early from a for or while loop.
Here is an example of a program that repeatedly takes the user’s input and prints it out until the user types “done”.
while True:
line = input('Type a word: ')
if line == 'done':
break
print(line)
print('Done!')
The continue statement is used to skip the rest of the loop body and jump back to the for or while statement.
Here is an example of a program that prints all the cheeses except for "Parmesan”.
cheeses = ['Cheddar', 'Edam', 'Gouda']
for cheese in cheeses:
if cheese == 'Edam':
continue
print(cheese)
Task
Status
1
Learn about for and while loops
Not Started
2
Learn about break and continue statements
Not Started
No results from filter

Next Section ➡️

Share
 
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.