When programming in Python or other programming languages, loops are very important to understand in order to create dynamic programs that can do many different things. Loops are a programming construct that repeats a section of code a set number of times until the desired result is achieved. Much of the power of programming is having the ability to automate repetitive tasks, and loops are the tool to get that job done. In this tutorial, we’ll look at while and for loops in Python, and several examples of how each work.
Introducing while
Loops
There are times when you need to do something more than once in your program. In other words, we need a loop, and the most simple looping mechanism in Python is the while loop. A while loop runs as long as a certain condition is True
. The while loops syntax looks like this:
while test_expression: Body of while
A simple program that counts to 3 is a great first example of the while statement.
count = 1
while count <= 3:
print(count)
count += 1
1 2 3
The first step is to assign the value of 1 to the count
variable. Next, we check to see if the value stored in count
is less than or equal to the number 3. If that expression evaluates to True
, then the value in count
is printed. The next step is to add 1 to the count
variable, which completes one iteration. The process then starts again and continues until count
is no longer less than or equal to 3.
The while loop consists of the following.
- The while keyword
- An expression that evaluates to True or False, also known as the condition
- A colon : character
- The body, or clause, of the while loop which is indented
Avoid Infinite Loops
The highlighted line is super important in a while loop. It is used to increment the value of the count
variable.
count = 1
while count <= 3:
print(count)
count += 1
If you never add 1 to the count
variable, then the expression in this loop will always evaluate to True
. That means this program will simply print out the number 1 forever. So a while loop with counter helps prevent this. If you do happen to write an infinite while loop, a keyboardinterrupt can stop it. This is done by using the CTRL-C key combination. You might need a way to manually end the while loop.
Control An Infinite Loop With break
You can break out of a while loop with the break keyword. This is used when you want a semi-infinite loop. In other words, you want to keep looping until something specific happens, but you’re not sure when that might happen. What is a good example of this? How about a program that lets you type in a word, and the program will print the string in reverse. The program will continue in an infinite loop until you type the ‘q’ character to quit, which will break the loop. This is an example of using if statements inside a while loop.
while True:
word = input('Enter a string and I will print it backwards(type q to quit): ')
if word == 'q':
break
print(word[::-1])
Enter a string and I will print it backwards(type q to quit): Python nohtyP Enter a string and I will print it backwards(type q to quit): Wow it works! !skrow ti woW Enter a string and I will print it backwards(type q to quit): q Process finished with exit code 0
This program reads the user’s typing from the keyboard using the input() function, and then prints that string in reverse. As long as the user does not type a single ‘q’ character, then the program continues to run. If they do type just the letter ‘q’, then that break statement runs and the infinite loop stops.
while True:
word = input('Enter a string and I will print it backwards(type q to quit): ')
if word == 'q':
break
print(word[::-1])
Skip Ahead With continue
You can use the continue keyword to return to the start of a loop based on the result of a conditional test. When a program reaches a continue statement, the program jumps right back to the start of the loop and reevaluates the condition of the loop. For example, consider a loop that counts from 1 to 10 but prints only the even numbers:
num = 0
while num <= 10:
num += 1
if num % 2 != 0:
continue
print(num)
2 4 6 8 10
Using else
With break
If you have a program that uses a break statement in a while loop, but the break statement is never called, control passes to an optional else construct. You use this approach in a while loop that checks for something and breaks as soon as it’s found. The else runs if the while loop completes but nothing was found. This little program checks for words that are 4 characters in length. If it does not find a 4 character word, the else clause runs.
words = ['cat', 'rat', 'bat']
i = 0
while i < len(words):
word = words[i]
if len(word) == 4:
print(f'{word} has 4 characters')
break
i += 1
else:
print('No words have 4 characters')
No words have 4 characters
We can change the words list to include a 4 character word to see how the program reacts.
words = ['cat', 'rat', 'bat', 'brat']
i = 0
while i < len(words):
word = words[i]
if len(word) == 4:
print(f'{word} has 4 characters')
break
i += 1
else:
print('No words have 4 characters')
brat has 4 characters
Multiple Conditions In A while
Loop
A while statement can have multiple conditions. Here is an example of using multiple conditions in a while loop. As soon as any of the conditions become false, iteration stops.
color, number, count = 'red', 7, 0
while color == 'red' and number == 7 and count < 3:
if count == 0:
print('color is ', color)
elif count == 1:
print(number, ' is the number')
else:
print('while statement multiple conditions example')
count += 1
color is red 7 is the number while statement multiple conditions example
Nested while
Loop in Python
You can have a while
loop inside of another while
loop to create what is known as a nested while loop.
outer = 1
inner = 5
print('Outer|Inner')
while outer <= 4:
while inner <= 8:
print(outer, '---|---', inner)
inner += 1
outer += 1
Outer|Inner 1 ---|--- 5 2 ---|--- 6 3 ---|--- 7 4 ---|--- 8
while
Loop User Input
The pattern of repeatedly getting user input from a user of your program can be accomplished by using the input() function inside of a while loop that makes use of the boolean True in the while condition. Let’s see how that works.
number = 3
while True:
what_number = input('What number is it? [type q to quit]: ')
if what_number == 'q':
print('Thanks for guessing!')
break
if int(what_number) == number:
print('You got it!')
break
What number is it? [type q to quit]: 1 What number is it? [type q to quit]: 2 What number is it? [type q to quit]: 3 You got it!
Iterate With for
Loop
Iterators in Python are great since they allow you to loop over data structures even if you don’t know how big they are. It is also possible to iterate over data that is created on the fly. This ensures the computer doesn’t run out of memory when working with very large data sets. This leads us to the for loop in Python. We learned about the while loop which loops over and over while its condition is True
. When you want to run a block of code a certain number of times, you can use the for loop in combination with the Python range() function. There are two types of loops in Python. We already saw the while loop, now we can look at the for loop. We use a for loop to iterate over a sequence. A sequence is something like a list, tuple, string, or any iterable object. When looping over a sequence, this is known as traversing. The for loop syntax is as follows:
for val in sequence: Body of for
for loop through list
trees = ['Pine', 'Maple', 'Cedar']
for tree in trees:
print(tree)
Pine Maple Cedar
Lists such as trees are one of Python’s iterable objects. Strings, tuples, dictionaries, sets, and some other elements are also iterable objects. When we iterate over a list or tuple, we access one item at a time. With String iteration, you are accessing one character at a time.
Here is another exercise where we loop over some questions in a for loop.
questions = ['Whats up?', 'How are you?', 'What time is it?']
for question in questions:
print(question)
Whats up? How are you? What time is it?
for loop through tuple
boats = ('Row', 'Motor', 'Sail')
for boat in boats:
print(boat + ' Boat')
Row Boat Motor Boat Sail Boat
for loop through string
for letter in 'Winnipesaukee':
print(letter)
W i n n i p e s a u k e e
for loop through dictionary
When iterating over a dictionary, you have a few different options. You can iterate over just the keys, just the values, or both the keys and values. To access the values of a dictionary in a for loop, you need to use the .values() method. To access both the keys and values of a dictionary using a for loop, you can use the .items() method.
for loop through dictionary keys
forecast = {'Mon': 'Rainy', 'Tues': 'Partly Cloudy', 'Wed': 'Sunny', 'Thu': 'Windy', 'Fri': 'Warm', 'Sat': 'Hot',
'Sun': 'Clear'}
for day in forecast:
print(day)
Mon Tues Wed Thu Fri Sat Sun
for loop through dictionary values
forecast = {'Mon': 'Rainy', 'Tues': 'Partly Cloudy', 'Wed': 'Sunny', 'Thu': 'Windy', 'Fri': 'Warm', 'Sat': 'Hot',
'Sun': 'Clear'}
for weather in forecast.values():
print(weather)
Rainy Partly Cloudy Sunny Windy Warm Hot Clear
for loop through dictionary keys and values
forecast = {'Mon': 'Rainy', 'Tues': 'Partly Cloudy', 'Wed': 'Sunny', 'Thu': 'Windy', 'Fri': 'Warm', 'Sat': 'Hot',
'Sun': 'Clear'}
for day, weather in forecast.items():
print(day + ' will be ' + weather)
Mon will be Rainy Tues will be Partly Cloudy Wed will be Sunny Thu will be Windy Fri will be Warm Sat will be Hot Sun will be Clear
for loop with counter
By using the range() function with a for loop, you get access to an index that can be used to access each item of a list.
str_nums = ['one', 'two', 'three', 'four', 'five']
for counter in range(5):
print(counter, str_nums[counter])
0 one 1 two 2 three 3 four 4 five
A more common and pythonic way to approach this is by using the enumerate() function. By using the enumerate() function, you gain access to multiple variables in the python for loop. This example uses two loop variables, counter
and val
.
for loop with counter using enumerate
str_nums = ['one', 'two', 'three', 'four', 'five']
for counter, val in enumerate(str_nums):
print(counter, val)
0 one 1 two 2 three 3 four 4 five
break
and continue
statements With for
Loops
You can use break
and continue
statements inside for
loops just like we did with the while
loop. The continue statement will skip to the next value of the for loop’s counter, as if the program execution had reached the end of the loop and returned to the start. The break and continue statements work only inside while and for loops. If you try to use these statements elsewhere, Python will throw an error.
for letter in 'Programming':
if letter == 'a':
print('Found "r", Breaking Out Of Loop Now')
break
print('Current Letter :', letter)
Current Letter : P Current Letter : r Current Letter : o Current Letter : g Current Letter : r Found "r", Breaking Out Of Loop Now
In this example below, when the num variable is equal to 7 during the iteration, the continue statement is used to skip the rest of the loop.
for num in range(10):
if num == 7:
print('Seven is not so lucky')
continue
print(num)
0 1 2 3 4 5 6 Seven is not so lucky 8 9
Check break
Use With else
In for
Loop
Just like the while
loop, for
has an optional else
clause that you can use to check if the for loop completed normally. If a break
was not called, the else statement is run. This can be useful when you want to check that the previous for loop ran to completion, instead of being stopped early with a break. The for loop in the following example prints each letter of the string ‘Programming’ while looking for the letter ‘Z’. Since it is never found, the break statement is never hit and the else clause is run.
for letter in 'Programming':
if letter == 'Z':
print('Found "Z", Breaking Out Of Loop Now')
break
print('Current Letter :', letter)
else:
print('Did Not Find "Z"')
Current Letter : P Current Letter : r Current Letter : o Current Letter : g Current Letter : r Current Letter : a Current Letter : m Current Letter : m Current Letter : i Current Letter : n Current Letter : g Did Not Find "Z"
Using The range()
Function With for
Loops
The range() function returns a stream of numbers within a given range. The nice thing about the range() function is that you can create large ranges without using a lot of memory. There is no need to first declare a large data structure like a list or tuple. You can use a for loop with the range() function when you want to execute a block of code a certain number of times.
Nested for
Loop in Python
The syntax for a nested for loop in Python is as follows:
for [first iterating variable] in [outer loop]: # Outer loop [do something] # Optional for [second iterating variable] in [nested loop]: # Nested loop [do something]
A nested loop works like so:
- The program first runs the outer loop, executing its first iteration.
- This first iteration triggers the inner nested loop, which runs to completion.
- The program returns back to the top of the outer loop to complete the second iteration.
- The nested loop then runs again to completion.
- The program returns back to the top of the outer loop until the sequence is complete or a break statement stops the process.
Here are a few exercises of a nested for loop in Python.
nums = [1, 2, 3]
letters = ['xx', 'yy', 'zz']
for number in nums:
print(number)
for letter in letters:
print(letter)
1 xx yy zz 2 xx yy zz 3 xx yy zz
columns = [1, 2, 3]
rows = [1, 2, 3, 4]
for column in columns:
if column == 1:
print(' |', end='')
print('column', column, '|', end='')
if column == 3:
print()
for row in rows:
print('row', row, f'| r{row}, c1 | r{row}, c2 | r{row}, c3 |')
|column 1 |column 2 |column 3 | row 1 | r1, c1 | r1, c2 | r1, c3 | row 2 | r2, c1 | r2, c2 | r2, c3 | row 3 | r3, c1 | r3, c2 | r3, c3 | row 4 | r4, c1 | r4, c2 | r4, c3 |
Looping Backwards
There are many ways to loop backward using both a while and for loops. Let’s look at a few examples of looping backward in Python using the while and for loops.
while loop backwards
countdown = ['Blastoff!', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
start = 10
while start >= 0:
print(countdown[start])
start -= 1
10 9 8 7 6 5 4 3 2 1 Blastoff!
for loop backwards
To loop backward when using a for loop, you make use of the range() function while specifying the start, stop, and step parameters. The step is the third parameter, and when using -1 as the argument, this tells Python to count or loop backwards.
countdown = ['Blastoff!', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
for i in range(10, -1, -1):
print(countdown[i])
10 9 8 7 6 5 4 3 2 1 Blastoff!
Loop Over Several Iterables At Once!
Now that we know a good bit about loops in Python using while and for, you might want to use your superpowers to loop over more than one thing at a time. This is possible using the built-in Python zip() function. If you have two lists, for example, you can loop over both at the same time accessing each index for each list simultaneously – or in parallel.
letters = ['a', 'b', 'c']
numbers = [0, 1, 2]
for letter, number in zip(letters, numbers):
print(f'Letter: {letter}')
print(f'Number: {number}')
print('------------------')
Letter: a Number: 0 ------------------ Letter: b Number: 1 ------------------ Letter: c Number: 2 ------------------
Learn More About Python Loops
- Python Loops – A powerful concept in programming (techvidvan)
- Python while Loop (linuxize)
- Emulate do-while loop in Python (coderwall)
- How to use For and While Loops in Python (pythonforbeginners)
- Think Like A Computer Scientist With Python for Loop (runestone)
- How to loop with indexes in Python (treyhunner)
- Python For Loop Range With Examples (pythonforloops)
- Loop with an automatic counter via enumerate() (pythontips)
- Looping over multiple iterables using Python zip() (pythonprogramming)
Python While And For Loops Summary
It is also possible to do a for loop in one line with what is known as comprehensions. Check them out if you are interested. This tutorial covered a lot of ground concerning looping in Python using while and for. We saw how to loop based on a condition such as True, use an else clause with a loop, studied several examples of loops, used the not operator with a loop, handled user input in combination with the while loop, accessed the index in for loops, made use of the range() function with for loops, and controlled loop execution with the break and continue statements. Now go get loopy!