The do while Python loop executes a block of code repeatedly while a boolean condition remains true. The Python syntax for while loops is while[condition]. A “do while” loop is called a while loop in Python.
Most programming languages include a useful feature to help you automate repetitive tasks. This feature is referred to as loops.
For example, say you want to write a program that prints out individually the names of every student in a list. You may want to use a loop to print out each name rather than separate print() statements.
In this tutorial, we are going to break down the do while loop (which is officially called a while loop) in Python. A while loop can be used to repeat a certain block of code based on the result of a boolean condition. The code in the while block will be run as long as the statement in the while loop is True.
We’ll also run through a couple of examples of how to use a do while loop in Python.
For Loop Refresher
Loops are useful in a vast number of different situations when you’re programming. As a result, Python has two built-in functions that allow you to create loops: for and while.
Here’s an example of a Python for loop in action that iterates through a range of values:
for i in range(0, 3): print(i)
We use a Python range() statement to create a list of values over which our while loop can iterate. Our code returns:
81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.
The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.
0 1 2
The for loop sets i as the iterator, which keeps track of how many times the loop has been executed. The loop runs three times, or once for each item in the range of 1 and 3.
Do While Python
Python do while loops run a block of code while a statement evaluates to true. The loop stops running when a statement evaluates to false. A condition evaluates to False at some point otherwise your loop will execute forever.
Here’s the syntax for creating a while loop in Python:
while [our condition is True]: [run code]
We use the “while” keyword to denote our while loop.
Our loop will continue to run until the condition being evaluated is equal to false. In many programming languages, this is called a do while loop, but in Python we simply refer to it as a while loop.
Once our condition evaluates to False, the loop is terminated. A loop that does not have a condition that evaluates to False is called an infinite loop. This type of loop is called an infinite loop because it does not run for a specified number of times. The loop keeps going.
Each time the while loop runs, our code checks the condition in the loop. If the condition is met, the loop is run.
- Career Karma matches you with top tech bootcamps
- Get exclusive scholarships and prep courses
This is slightly different to a “do while” loop with which you may be familiar in other programming languages. A “do while” loop executes a loop and then evaluates a condition. “do while” loops do not exist in Python so we’ll focus on regular while loops.
Let’s use an example to illustrate how a while loop works in Python.
Python Do While Example
We are going to create a program that asks a user to guess the magic number. Our program should continue to run until the user guesses correctly.
If the user guesses the number incorrectly, the loop will keep going, and if the user guesses the correct number, the loop will stop.
Write a Basic While Loop
Here’s the code for our example while loop program that runs whlile a condition is True:
user_guess = 0 magic_number = 5 while user_guess != magic_number: print('What is the magic number?') user_guess = int(input()) print('You have correctly guessed the magic number!')
On the first two lines of our code, we declare two Python variables. The user_guess variable will be used to store the number our user inputs into the program. The magic_number variable stores the number the user is attempting to guess.
On the next line, we declare our while loop. This loop checks if the variable user_guess is not equal to magic_number, and if these values are not the same, the loop will run. In other words, if our user has not guessed the correct magic number, the while loop will execute. The code inside our while loop is called the body of the loop.
We print the statement “What is the magic number?” We then use the Python input() function to request a guess from the user.
Our program will check to see if the while condition is still True when the user presses the enter key. When the condition becomes False, our loop stops executing.
Testing the Program
Here’s what happens if we guess the wrong number:
What is the magic number? 1 What is the magic number? 2 What is the magic number? 3 What is the magic number?
If we guess the wrong number, the program executes the while loop again. Our loop keep running until we enter the right number. At this point, our loop body will stop running and our program will move on.
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
Here’s what happens if we guess the correct number:
What is the magic number? 5 You have correctly guessed the magic number!
After we guessed the correct number, user_guess was equal to magic_number and so our while loop stopped running. Then, our program printed out the message stating that we had correctly guessed the magic number.
Remember that when you’re working with input(), you may need to convert the values that you are receiving from a user. In our case, we had to use int(input()) because we were gathering numbers from a user. If we wanted our values to be strings, though, we would not have to convert our values.
Improving the Do While Python Loop Example
Now that we know the basics of while loops in Python, we can start to explore more advanced loops. We are going to create another guessing game. But, this time we are going to include a few additional features to make it more functional for users.
The specifications for our program are as follows:
- The magic number must be automatically generated.
- The user should only get three attempts to guess the magic number.
- If the user guesses the correct number, they should receive a message.
Let’s build our program!
Writing the Program
Firstly, we are going to import the random module using import, which allows us to generate random numbers. Then, we are going to create a variable that stores a randomly-generated number. We can do so using this code:
import random magic_number = random.randint(1,20)
In our code below, we are going to define a while loop, like we did above, which receives our user’s guess. But in this example, we are going to use while to check how many times a user has guessed the number. If that number is more than 4, the loop will not run. Here’s our code:
import random magic_number = random.randint(1,20) attempts = 0 while attempts < 5: print("Guess a number between 1 and 20:") guess = int(input()) attempts = attempts + 1 if guess == magic_number: break print("You have guessed the magic number!")
Our while loop checks if a user has attempted to guess the loop fewer than four times. If the user has used up fewer than four guesses, the code within our loop will run. Then, the message “Guess a number between 1 and 20:” will be printed to the console. The user will be prompted to guess a number.
We increase the number of attempts a user has had by 1. This allows us to keep track of how many guesses a user has had.
We then check to see if the user’s guess is equal to the magic_number that our program generated earlier. If guess is equal to magic_number, our while loop will stop because we have used a break statement.
You can learn more about the break keyword in our Python break statement guide.
Once our break statement is executed, our loop will stop. The statement “You have guessed the magic number!” will be printed to the console.
Testing the Program
Let’s test our code to see if it works. When we guess a number incorrectly, our loop runs again like this:
Guess a number between 1 and 20: 1 Guess a number between 1 and 20: 2 Guess a number between 1 and 20: 3
But when we guess the number correctly, our program returns the following:
Guess a number between 1 and 20: 5 You have guessed the magic number!
Python while loops (which are often called do while loops in other languages) execute a block of code while a statement evaluates to true. The syntax for a while loop is: while [your condition]. A while loop should eventually evaluate to false otherwise it will not stop.
For example, you may want to use a while loop to check if a user’s password is correct on a login form.
Are you up for a challenge? Write a while loop that prints out every value in this list to the console:
names = ["Mark", "Luke", "Mary", "Louise"]
Then, write a while loop that prints out each name in the console whose length is over four characters. You may want to use the Python len() statement to help you out.
The final output should be:
Now you’re ready to start writing while loops like a pro in Python!
For advice on top Python learning resources, courses, and books, check out our How to Learn Python guide.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.