How To Use While Statements Python

In this tutorial, we will learn about while statements in Python, a fundamental flow control structure that is widely used in programming.

You’ll gain an understanding of the concept, and learn how to effectively use while statements to reduce code complexity and repetition. We’ll work through simple examples and a use-case scenario to reinforce the concepts.

Understanding while Statements

The while statement is a type of loop that runs as long as a specified boolean condition remains true. This allows you to execute a block of code repeatedly until a certain criterion is met. The basic syntax of a while statement is:

Here, the condition is a boolean expression that evaluates to either True or False. If the condition is True, the code block is executed. If the condition is False, the loop terminates, and the control proceeds to the next line of code after the loop.

How to Use a Simple While Loop

Let’s look at a simple example of a while loop that prints out the numbers from 1 to 5:

Output:

1
2
3
4
5

At the beginning of the loop, count is initialized to 1. The while loop checks if count is less than or equal to 5. If so, it prints the value of count and increments it by 1. The loop continues until count is greater than 5, at which point the loop stops.

How to Use a while Loop with an else Statement

You can add an else statement at the end of a while loop. This code block is executed when the condition specified in the while loop becomes false. Here is an example:

Output:

1
2
3
4
5
Loop ended.

When count becomes 6, the condition count <= 5 becomes False, so the loop terminates and the code block inside the else statement is executed. The message “Loop ended.” is displayed.

Using the break and continue Statements in while Loops

Break and continue are two control statements that you can use to alter the flow of a while loop.

  1. break: The break statement terminates the loop when a certain condition is met, and the control moves to the next line of code after the loop. For instance:

Output:

1
2
3
4
5

This example stops the loop when the count variable reaches 6, so only the values from 1 through 5 are printed.

  1. continue: The continue statement skips the rest of the current loop iteration and starts the next iteration. Consider the following example:

Output:

1
3
5
7
9
11

Here, the while loop iterates from 1 to 11, but the continue statement only allows printing of odd numbers. If the count is even, the rest of the iteration is skipped, and the loop continues with the next iteration.

Conclusion

In this tutorial, we have learned about the while statement in Python, its syntax, and how to use it with break, continue, and else statements. Practice using while loops to gain a deeper understanding of their functionality and use in real-world applications.

The complete code in this tutorial: