How to Write and Use Python While Loops

Written by Coursera • Updated on

By the end of this tutorial you will be able to efficiently use Python while loops and emulate do while loops.

[Featured Image] A programmer examines code while on a video call with other members of his coding team.

Materials Required: Latest version of Python (Python 3), an integrated development environment (IDE) of your choice (or terminal), stable internet connection

Prerequisites/helpful expertise: Basic knowledge of Python and programming concepts

While loops are control flow tools. Like for loops, they are used to iterate over a block of code. Unlike for loops, they will repeat that block of code for an unknown number of times until a specific condition is met. You’ll use while loops when you’re not sure how many times you need your code to repeat. You’ll use do while loops when you need it to repeat at least once.

TermDefinition
While loopUsed to iterate over code when the condition is true. This loop type is typically used when the number of times you’ll need to repeat is unknown.
For loopAn iterating function used to execute statements repeatedly.
Control flowControl flow or program flow, is the order of execution in a program’s code.
Control statementsIn Python, continue, break, and pass are control statements that change the order of a program’s execution.
Loop statementsLoop statements execute code repeatedly as determined by the user.
IterateIn programming, iteration is the repetition of a code or a process over and over until a specific condition is met.
IndentationIndentation is the space at the beginning of each line of code. In Python, indentation indicates a new line of code. In other programming languages, it is used only for readability.
Boolean expressionA boolean expression is a logical statement. They are either True or False.
ifif is a common conditional statement. It dictates whether a statement should be executed or not by checking for a given condition. If the condition is true, the if block of code will be executed.
elseThe else statement contains the block of code that will execute if the condition from the if statement is false or resolves to zero.
breakThe break command terminates the loop that contains it and redirects the program flow to the following statement.

How to use while loop in Python

While loops continuously execute code for as long as the given condition or, boolean expression, is true. They are most useful when you don’t know how many times you’ll need the code to execute. For example, you may want to run a piece of code as long as a given number is between 1 and 5. In that case, the loop will run while the number remains between 1 and 5. When the user chooses a 6 or any other number that isn’t between 1-5, the control flow will exit the while loop body.

How while loop works in python

First, the Python interpreter checks the test expression or, while condition. If the test expression evaluates to true, the body of the while loop will be entered. This process repeats until the test expression evaluates to false.

-tutorial draft- python while loop

Try it yourself

PYTHON
1
2
3
4
5
numbers = [2, 4, 6, 8, 10]
total = 0
for num in numbers:
    total += num
print("The total is:", total)

What will the interpreter display at the end of the fourth loop?

After the fourth loop, the interpreter will print The total is:8.

How to write a while loop in Python

Remember that indentation is crucial in Python. Indentation tells Python where the loop body starts and ends. The while loop begins with indentation and ends at the first unindented line. First, let’s examine the syntax and structure of a Python while loop:

PYTHON
1
2
while count < 5:    # condition to check if the loop should continue
    print(count)    # body of the loop, will execute as long as the condition is true

A note on non-zero values

Python will interpret all non-zero values as true while none and 0 are false.

Now, let’s look at an example:

Screenshot 2023-02-22 at 9.55.51 AM

In this example, the loop will print out the even numbers from 0 to 8, because we start at 0 and add 2 to the number for each iteration. Once num reaches 10, the condition num < 10 is no longer true, and the loop terminates.

Tip

Be careful not to create an infinite loop. If the condition never resolves to a false value, infinite iteration occurs.

How to end a while loop in Python

As mentioned above, the first unindented line of code marks the end of a while loop. However, you may need to end a loop early or terminate the current loop iteration. In that case, you can use one of three loop control statements:

1. Break

The break keyword is used to exit a loop early. It terminates the loop that contains it and redirects the program flow to the following statement.

Example: Screenshot 2023-02-22 at 10.49.42 AM

In this example, we're using a while loop to print the numbers from 1 to 10. However, we're also using an if statement to check if the loop has reached the halfway point, which is when i is equal to 5. If we've reached the halfway point, we print a message to the console saying "We've reached the halfway point, stopping loop." and then immediately exit the loop using the break statement.

Learn more: How to Use Python Break: In For Loops, While Loops, and If Statements

2. Continue

continue is a Python keyword that you can use to end a for loop’s current iteration. The control flow will continue on to the next iteration. The continue statement is useful when you want to skip over certain iterations of a loop based on some condition, without exiting the loop entirely.

Example: Screenshot 2023-02-22 at 10.56.02 AM

In this example, the while loop iterates over the numbers 1 through 10. The if statement checks whether the current value of i is even. If it is, the continue statement is executed, causing the loop to skip the current iteration and move on to the next one without executing the rest of the loop body. If i is odd, the print statement is executed, outputting the value of i.

3. Pass

The pass statement in Python intentionally does nothing. It can be used as a placeholder for future code or when a statement is required by syntax but you don’t want anything to happen. In a while loop, you can use it to ignore a certain condition during an iteration.

Example: Screenshot 2023-02-22 at 10.59.54 AM

In this example, the while loop iterates over the numbers 1 through 5. The if statement checks whether the current value of i is equal to 3. The pass statement indicates that there is no specific action to be taken when i is equal to 3, but the program should continue executing the rest of the loop body.

Try it yourself

Write a program that repeatedly prompts the user to enter a number between 1 and 10, until the user enters a valid number. For each invalid input, the program should print an error message and prompt the user to try again. If the user enters a valid number, the program should print a message indicating that the number is valid and exit the loop.

Use a continue statement to skip over any input that is not a valid number between 1 and 10.


Here's one possible solution to the exercise:

PYTHON
1
2
3
4
5
6
7
8
9
10
11
while True:
  num_str = input("Enter a number between 1 and 10: ")
  if not num_str.isdigit():
      print("Error: input must be a number.")
      continue
  num = int(num_str)
  if num < 1 or num > 10:
      print("Error: number must be between 1 and 10.")
      continue
  print("You entered a valid number:", num)
  break

In this example, a for loop iterates through each character in the string string from beginning to end. For each character, it concatenates that character to the beginning of the variable reversed_string. By the end of the loop, reversed_string will contain the original string in reverse order.

Need help?

How do you end a nested while loop? If the while loop is nested, make sure to place a break statement in the outer loop. Otherwise, only the inner loop is exited.

Does Python have do while loops?

A do while loop is a variant of the while loop that checks the condition at the end of the loop rather than the beginning. Even if the condition is never true, the statements inside the loop body will be executed at least once. do while loops are useful when you need your code to run at least once. Python does not have a built-in do while loop like other programming languages. However, you can modify a regular Python while loop to accomplish the same functionality.

How to emulate do while loop in Python

A Python while loop only runs when the condition is met. Since it checks that condition at the beginning, it may never run at all. To modify a while loop into a do while loop, add true after the keyword while so that the condition is always true to begin with. Then, you can add if statements to check the inside condition and break statements to control the flow of the loop based on your terms.

Here’s an example:

Screenshot 2023-02-22 at 11.25.26 AM

This loop will print the numbers 1 to 5, which is equivalent to the behavior of a do while loop that iterates from 1 to 5. We use a break statement to exit the loop once we have printed all the numbers, since the while condition is always True and would otherwise result in an infinite loop.

Key takeaways

  • while loops continuously execute code for as long as the given condition is true.
  • There is no do while loop in Python, but you can modify a while loop to achieve the same functionality.
  • There are three control statements you can use to break out of a while loop in Python: break, continue, and pass.
  • Indentation tells Python which statements are inside or outside of the loop.

Resources

Keep improving your Python skills with Coursera.

You can practice working with while loops with a Guided Project like Concepts in Python: Loops, Functions, and Returns. Or, take the next step in mastering the Python language and earn a certificate from the University of Michigan in Python 3 Programming.


Written by Coursera • Updated on

This content has been made available for informational purposes only. Learners are advised to conduct additional research to ensure that courses and other credentials pursued meet their personal, professional, and financial goals.

Learn without limits