Python While And For Loops

Python While And For Loops

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

python while loop
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.

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.

python while loop flowchart

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.

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.

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.

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:

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.

No words have 4 characters

We can change the words list to include a 4 character word to see how the program reacts.

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 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|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.

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

python 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

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.

Whats up?
How are you?
What time is it?

for loop through tuple

Row Boat
Motor Boat
Sail Boat

for loop through string

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

Mon
Tues
Wed
Thu
Fri
Sat
Sun

for loop through dictionary values

Rainy
Partly Cloudy
Sunny
Windy
Warm
Hot
Clear

for loop through dictionary keys and values

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.

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

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.

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.

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.

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.

1
xx
yy
zz
2
xx
yy
zz
3
xx
yy
zz

      |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

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.

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.

Letter: a
Number: 0
------------------
Letter: b
Number: 1
------------------
Letter: c
Number: 2
------------------

Learn More About Python Loops


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!