How to Code a Do-While Loop in Python?

Problem Formulation and Solution Overview

This article will show you how to code a Do-While Loop in Python.

πŸ’‘ A Do-While loop is another way to iterate through data. This loop is available in other coding languages, such as C, C++, PHP, JavaScript, Basic, and more right out of the box!

What’s unique about this loop is that it executes at least once and then checks the condition. Whereas other loops check the condition before any code executes.

In Python, a Do-While loop is not available out of the box, but a while loop can be instantiated and modified to mimic this.

Let’s see how other coding languages use a Do-While loop.

Below are two (2) examples, one using JavaScript and the other using PHP.

Both examples declare a count variable and set the value of same to seven (7).

Then a Do-While loop is instantiated, outputs the value of count to the terminal, and decreases the value of count one (1).

Next, the condition is checked (while (count > 0)). If True, another iteration occurs. This iteration repeats until the condition becomes false (when count equals 0).

JavaScript Do-While Example

let count = 7;
do {
    console.log(`${count} `)
    count--; 
} while (count > 0); 

PHP Do-While Example

$count = 7;
do {
    echo $count;
    $count--;
} while ($counter > 0);

Both examples produce the same output.

7
6
5
4
3
2
1

Let’s write our own custom Do-While loop in Python by coding a game called Spin-To-Win that mimics a Do-While loop.

This game will mimic a wheel spinning containing the numbers from 1-21 (indicating the number of wheel slices). A user will be prompted to guess where (on what number) the wheel will stop. This game continues until the user wants to quit.

Let’s get started!

The first line in the code below imports the random library. This allows us access to the random.randrange() function, used to generate random numbers.

import random

The following line creates a List of numbers from 1-21 using the range() function and passing two (2) arguments: start (1), and stop (22-1). The results save to slices.

The contents of same display below.

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]

The next line declares a Boolean value and sets it to True. The result saves to spin and determines when to continue/stop the iteration.

import random

slices = list(range(1, 22))
spin = True

The following line instantiates a while loop and passes the condition spin. As you can see, spin currently contains the Boolean value True. This lets Python know to execute this loop at least once.

while (spin):
    play_game = input('Play Spin-To-Win (y/n): ').lower()
    spin_num = random.randrange(1, len(slices))

Inside the while loop, two (2) variables are declared. These variables are determined each iteration.

  • play_num: This line prompts the user to Play Spin-To-Win and offers two (2) choices, y or n. Their selection converts to lowercase() and saves to same.
  • spin_num: This line generates a random number between the stated range. The result saves to same. For this example, the contents of spin_num is shown below.
8

The next section inside the while loop is the outer if statement. The outer if statement validates the contents of play_game.

If y (play_game), the code checks to see if guess (user input) matches spin_num (random generated number). If so, a message is sent to the terminal indicating the user won.

If y (play_game) and guess does not match spin_num, a message is sent to the terminal indicating the user lost.

    if (play_game == 'y'):
        guess = int(input('Enter Number (1-21): '))
        if (guess == spin_num):
            print(f'You won a Teddy Bear 🐻!')
        else:
            print(f'Sorry, your number {guess} does not match {spin_num}. Try Again!')

The last section is the elif statement located inside the while loop.

    elif (play_game == 'n'):
        spin = False

If the user selected n when prompted from the Play Spin-To-Win input line, the code inside this statement executes and changes the value of spin to False. This lets Python know to terminate the while loop because the condition stated earlier is no longer True (spin = False).

Let’s put this code altogether!

import random

slices = list(range(1, 22))
spin = True

while (spin):
    play_game = input('Play Spin-To-Win (y/n): ').lower()
    spin_num = random.randrange(1, len(slices))
    
    if (play_game == 'y'):
        guess = int(input('Enter Number (1-21): '))
        if (guess == spin_num):
            print(f'You won a Teddy Bear 🐻!')
        else:
            print(f'Sorry, your number {guess} does not match {spin_num}. Try Again!')
    elif (play_game == 'n'):
        spin = False

The code does not account for invalid characters. The code snippet below fixes this!

import random

slices = list(range(1, 22))
spin = True

while (spin):
    try:
        play_game = input('Play Spin-To-Win (y/n): ').lower()
        spin_num = random.randrange(1, len(slices))
        
        if (play_game == 'y'):
            guess = int(input('Enter Number (1-21): '))
            if (guess == spin_num):
                print(f'You won a Teddy Bear 🐻!')
            else:
                print(f'Sorry, your number {guess} does not match {spin_num}. Try Again!')
        elif (play_game == 'n'):
            spin = False
    except:
        print('Invalid character!')

🌟Finxter Challenge:
Modify the above code to display the appropriate warning message. Click here for details.


Programming Humor – Python

“I wrote 20 short programs in Python yesterday. It was wonderful. Perl, I’m leaving you.”xkcd