Learn for and while loops in python with fun text based games

Iteration is the process of doing a repetitive task. Most humans find repetitive tasks boring which makes them susceptible to human error. Computers on the other hand are masters of iteration. Feed a computer a bunch of data and program it to do something and it will happily oblige.

In python there are two ways in which you can iterate or loop over data. You can use the while or for statements to craft your loops in python. You can use loops to do cool things such as making simple guessing games, simulating coin flips, or modeling famous mathematical formulas like the harmonic series. You’ll see how to do all of this in the tutorial.

Example of a while loop in python

>>> while i < 10:
...         print(i)
...         i += 1
... 
1
2
3
4
5
6
7
8
9

As you can see the syntax for a while loop is quite different from a C-style language like C++. There's no braces but instead indentations are used to identify blocks of code. Also, with while loops you’ll typically need a variable known as a loop counter which keeps track of the number of iterations or cycles.

These variables are normally generically named such as i, j, and k since they're typically used locally. If you ascend up a loop this is known as an increment, and if you descend down a loop then this is known as a decrement. The previous example showed how to increment while the next ones shows how to decrement.

>>> while i > 0:
...         print(i)
...         i -= 1
... 
10
9
8
7
6
5
4
3
2
1

If you don’t have a way to exit a loop then you’ll have what’s known as an infinite loop. As the name indicates the code will repeat infinitely until an interrupt is generated. This is OK in some situations. For example, if you’re creating a game and want the game play to reset after each session, or if you’re doing socket programming and want to accept new connections. Below is an example of an infinite while loop (don’t run it!!!):

i = 1
while True:
    print(i)

While loops are also useful if you’re unsure about the number of iterations you’ll need to make. Below is a while loop with no counter, but a condition that dictates when to exit out the loop:

i = 0
while True:
    print('i = {}'.format(i))
    i += 1
    if i == 500:
        break

As you can see the break statement can be used within loops to exit out of it. In this case the loop starts at 0 and prints all of the numbers all of the way up until 500 before exiting. Here’s another while loop that uses both the continue and break statement:

i = 1
while True:
    print(i)
    if i % 2 == 0:
        i += 1
        continue
    elif i == 11:
        break
    i += 1

The output is 1… 11. The continue statement forces the next cycle in the iteration. There’s also the condition of i == 11 which breaks out of the loop once meet. If this condition is not included then you’ll be stuck in an infinite loop. Once you’ve mastered the basics of while loops in python you can use them to create simple text based games. Let’s look at a simple guessing game simulator as shown in the code below:

import random
random_num, count = random.randint(1, 10000), 0
while True:
    if random_num == count:
        print('The secret number is {}!'.format(count))
        print('It took {} cycles to find it.'.format(count + 1))
        break
    else:
        print('{} is not the secret number'.format(count))
        count += 1

This code snippet makes use of the random class in python so that we can generate random numbers. We’ll create a while loop that keeps looping until we find the secret number which is stored in the random_num variable. There’s a variable named count that keeps track of all of the iterations and prints the total number of cycles the loop took once random_num is discovered.

We can update the above code so that we can ask for user input to make the game more interactive. Also, we should reduce the number of possibilities to make it more feasible for the user to correctly guess the number. Below is the code snippet for the number guessing game:

import random
# random_num is the number in range 1 ... 100
# tries keep count of how many guesses player makes
tries, random_num = 0, random.randint(1, 100)
while True:
    print('Guess a number in the range of 1-100')
    your_guess = int(input())
    if your_guess > random_num:
        print('{} is greater than the random number X'.
              format(your_guess))
        tries += 1
    elif your_guess < random_num:
        print('{} is less than the random number X'.
              format(your_guess))
        tries += 1
    else:
        print('Congrats! {} is equal to the random number '
              '{}.'.format(your_guess, random_num))
        tries += 1
        print('It took you {} tries'.format(tries))
        break

Let’s create another fun text based game. Well, it’s not all that fun but it’s anther solid lesson on how to use while loops in python. We can again use the random class in conjunction with the input() function to read user input. The following program simulates the flipping of coins and asks the user to enter either heads or tails. It also computes some simple game statistics by summing the number of occurrences for heads and tails. Below is an example of the program that does this with the help of a while loop as shown below:

import random
coin = ('heads', 'tails')
heads, tails = 0, 0
games = 0
print('Hit x to exit')
while True:
    flip = random.choice(coin)
    your_choice = input('Type heads or tails')
    if your_choice == 'x' or your_choice == 'X':
        print("GAME OVER :(")
        print('Coin flipping stats:')
        print('Games played = {}'.format(games))
        print('heads = {}'.format(heads))
        print('tails = {}'.format(tails))
        break
    if your_choice == flip:
        print('Coin landed on {}. Yeah boi you win!'.
              format(flip))
        games += 1
    else:
        print("Uh oh. Coin landed on {}. Better luck next "
              "time".format(flip))
        games += 1
    if flip == 'heads':
        heads += 1
    elif flip == 'tails':
        tails += 1

The three previous scripts are more practical illustrations on when and how to use the while loop. Next, let’s explore the for loop in python.

For loop

For loops are another way in which you can do iteration in python. For loops are commonly used when you know the bounds in which you want to iterate over or if you want to iterate over a container type. Therefore, it can mimic the functionality of a foreach loop in other languages like Java. Below is an example on how to use a for loop in python to iterate over a list.

>>> nums = [2, 4, 6, 8, 10]   
>>> for x in nums: 
...         print('nums = {}'.format(x))
... 
nums = 2
nums = 4
nums = 6
nums = 8
nums = 10

Here's how to use a for loop in python to iterate over a string.

>>> for char in 'Hello':
...         print(char)
... 
H
e
l
l
o

The range() functional

You can use the range() function to generate a sequence of numbers. For example, in a C style language like Java you can iterate over a predetermined range in a for loop by doing something like the following:

jshell> for(int i = 0; i < 10; i++) {
   ...>        System.out.println(i);
   ...> }
0
1
2
3
4
5
6
7
8
9

However, this can be duplicated in python using the range() function. Below is the logical equivalent in python:

>>> for x in range(10):
...          print(x)
... 
0
1
2
3
4
5
6
7
8
9

As you can see you don’t have to create the initializer, expression, and update variable. All of this is done behind the scenes via the range() function. In python3, the range() function replaced the xrange() function which was used in python 2.X. The biggest difference between the two is that range() creates a list in memory while xrange evaluates lazily, or via a generator.

Nested loops

Loops can be nested or a loop included within another loop. An example of a nested loop in python is listed below.

for x in range(1, 5):
    for y in range(1, x + 1):
        print('x = {} y = {}'.format(x, y))
x = 1 y = 1
x = 2 y = 1
x = 2 y = 2
x = 3 y = 1
x = 3 y = 2
x = 3 y = 3
x = 4 y = 1
x = 4 y = 2
x = 4 y = 3
x = 4 y = 4

You can do some pretty nifty things with nested loops such as creating some fun patterns. Not really practical, but solid training for getting the hang of looping in python. Look at the following pattern in python:

* 
* * 
* * * 
* * * * 

Here’s one way you could go about coding it.

for x in range(1, 5):
    for y in range(1, x + 1)
        print('*', end=' ')
    print()

In a nested loop the outer loop controls the inner loop. Therefore, the inner loop will tend to increment at a faster rate than that of the outer loop. For every increment the outer loop makes the inner loop sequence is from 1… x + 1. So after first cycle the inner loop increments from 1… 2, after second 1...3, third 1...4, and fourth 1… 5.

Notice how the print statement has the end= ‘’ keyword argument that goes inside of print statements? This will make each subsequent call happen on the same line as opposed to a new one if you were to use the print() statement. What pattern do you think the following code snippet will print?

for rows in range(4):
    for columns in range(4):
        print('*', end=' ')
    print()
* * * * 
* * * * 
* * * * 
* * * * 

The outer loop increments a total of four times and then the inner loop increments a total of 16 times. How would you print the following tic tac toe pattern?

X O O 
-----
O X O 
-----
O O X 
-----
for rows in range(3):
    for cols in range(3):
        if rows == cols:
            print('X', end=' ')
        else:
            print('O', end=' ')
    print()
    print('-----')

In the above code snippet a nested loop is used to create a 3 x 3 tic tac toe board. The X symbol is printed each time rows is equal to cols. They’re initially equal when they’re both start at 0. The key is to know that the outer loop variable doesn't reset, it keeps updating it’s state each iteration and stays there. The inner loop is constantly resetting to 0 and increment to 3. Knowing this we can see a pattern every time the outer loop updates. Look at the following for more details:

1st iteration

outer loop		inner loop
0			0, 1, 2		    (matches at 0)


------------------------------------------------------------------

2nd iteration 

1			0, 1, 2		     (matches at 1)

-------------------------------------------------------------------


3rd iteration 

2			0, 1, 2 	    (matches at 2)

Below are some more for loop exercises that you can work through.

for i in range(5):
    for j in range(5):
        if j >= i:
            print('H', end=' ')
        else:
            print('T', end=' ')
    print()
H H H H H 
T H H H H 
T T H H H 
T T T H H 
T T T T H 
for i in range(5):
    for j in range(5):
        if j <= i:
            print('H', end=' ')
        else:
            print('T', end=' ')
    print()
H T T T T 
H H T T T 
H H H T T 
H H H H T 
H H H H H 
def harmonic_series(n):
    """ computes harmonic series """
    summation = 0.0
    for i in range(1, n):
        summation += 1/i
    return summation
print('harmonic series = {}'.format(harmonic_series(20)))
harmonic series = 3.547739657143682
def prime_number(n):
    "checks to see if a number is prime"""
    if n > 0:
        for i in range(2, n):
            if n % i == 0:
                print('{} is composite'.format(n))
                break
        else:
            print('{} is prime'.format(n))
    else:
        print('positive numbers only')
prime_number(2)
2 is prime
============================================================================ Want to learn how to use Python's most popular IDE Pycharm? In the free pdf guide "Getting the Hang of PyCharm" you'll learn all of the amazing features in PyCharm along with how to get started with data science. Subscribe to the Purcell Consult newsletter and get started A.S.A.P.