While Loop

When the supplied condition is no longer true, the while loop in Python stops repeating the group of statements or lines of code that it was running.

While loop syntax is straightforward and similar to that of a for loop. When writing code, the phrase “while” must be used, followed by a condition enclosed in parenthesis, and a colon. Either true or false could apply to the condition. The loop will continue to run until the condition is satisfied. The program will run indefinitely until we stop it forcibly if we employ a condition in our while loop that never becomes false. Therefore, this type of syntax error is referred to as a logical or human error.

You can use the Ctrl+C key combination on your computer to break an infinite loop.

Syntax for while loop

while codition_is_true:

    Code inside the loop body

For vs. While:

Until the iteration through a generator function, set, list, tuple, etc., is finished, a “for” statement loop is in effect. When using a while loop, the statement simply repeats itself until the condition we have given turns out to be false. While loops are typically used in situations where we are unsure of the number of iterations and for loops in those situations when we are comfortable with the number of iterations. Considering that the loop’s sole basis is the current state of its condition.

With the aid of an example, let’s better understand what a while loop is and why we use it in situations where the number of iterations is not specified or we have no idea how many iterations will occur. Let’s say we developed an application for an ATM where a user can only withdraw up to 5000 rupees at a time. Now, the while loop’s condition would be to iterate unless the input is inside the range of 1 and 5000. So long as the user doesn’t enter a number between 1 and 5000, the condition will be true, and the loop will repeat until the user enters the incorrect value.

If we pass true or 1 as a condition, the While loop will continue to execute indefinitely. True as a whole can likewise be substituted with the number 1. As a result, the programme will run indefinitely because the condition will never become false. But because they are unable to complete their execution, these programmes never produce anything.

Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.