By the end of this tutorial you will be able to efficiently use Python while loops and emulate do while loops.
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.
Term | Definition |
---|---|
While loop | Used 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 loop | An iterating function used to execute statements repeatedly. |
Control flow | Control flow or program flow, is the order of execution in a program’s code. |
Control statements | In Python, continue, break, and pass are control statements that change the order of a program’s execution. |
Loop statements | Loop statements execute code repeatedly as determined by the user. |
Iterate | In programming, iteration is the repetition of a code or a process over and over until a specific condition is met. |
Indentation | Indentation 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 expression | A boolean expression is a logical statement. They are either True or False . |
if | if 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. |
else | The else statement contains the block of code that will execute if the condition from the if statement is false or resolves to zero. |
break | The break command terminates the loop that contains it and redirects the program flow to the following statement. |
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.
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
.
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
.
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:
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
true
while none
and 0
are false
.
Now, let’s look at an example:
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
false
value, infinite iteration occurs.
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:
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:
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
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:
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
.
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:
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.
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:
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?
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.
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.
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:
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.
while
loops continuously execute code for as long as the given condition is true.do while
loop in Python, but you can modify a while
loop to achieve the same functionality.break
, continue
, and pass
.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.
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.