🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

Python while Loop

Python While Loop

In Python, the while loop is used to repeatedly execute a block of code as long as a specified condition is true. The basic syntax of a while loop is as follows:

while condition:
    # Code to be executed while the condition is True

Here's a more detailed breakdown:

  1. The while keyword is used to start the loop.
  2. condition is an expression that is evaluated before each iteration. If the condition is True, the code block inside the loop is executed. If the condition is False, the loop is exited.
  3. The indented code block following the while statement is the body of the loop, and it is executed repeatedly as long as the condition is True.

Example:

count = 0

while count < 5:
    print(count)
    count += 1

In this example, the while loop prints the value of count and increments it by 1 in each iteration until count becomes equal to or greater than 5.

Using break and continue:

count = 0

while count < 10:
    print(count)
    count += 1
    
    if count == 5:
        break  # Exit the loop when count is 5

while count < 15:
    count += 1
    
    if count == 12:
        continue  # Skip the rest of the code and move to the next iteration when count is 12
    
    print(count)

The break statement is used to exit the loop prematurely when a certain condition is met, and the continue statement is used to skip the rest of the code in the loop for the current iteration and move to the next iteration.

Infinite Loop:

A common pattern with while loops is to create an infinite loop that continues until a specific condition is met or until the loop is explicitly terminated using a break statement.

while True:
    user_input = input("Enter 'quit' to exit: ")
    
    if user_input.lower() == 'quit':
        break
    else:
        print(f"You entered: {user_input}")

In this example, the loop continues indefinitely until the user enters 'quit', at which point the loop is exited using the break statement.

The while loop is useful when you want to repeat a block of code as long as a certain condition is true. It provides flexibility for scenarios where the number of iterations is not known beforehand. However, be cautious to avoid creating infinite loops unintentionally.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.