Python While Loops

  • Read
  • Discuss

A while loop in Python allows you to repeatedly execute a block of code as long as a given condition is true. The syntax for a while loop is as follows:

while condition:
    # code to be executed

For example, let’s say you want to print the numbers from 1 to 10. You can use a while loop for that:

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

Examples

Here are a few examples of while loops in Python:

The following while loop will print the numbers 0 through 9:

count = 0
while count < 10:
    print(count)
    count += 1

The following will be the output.

0
1
2
3
4
5
6
7
8
9

The following while loop will repeatedly ask the user to enter a number, and it will only exit when the user enters the number 4:

while True:
    user_input = int(input("Enter a number: "))
    if user_input == 4:
        break

The following while loop will repeatedly check if a number is a prime, and it will exit when the number is greater than 100:

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

number = 2
while number <= 100:
    if is_prime(number):
        print(number)
    number += 1

The following will be the output.

2
3
5
.
.
.
97

Note: It will be more efficient to use the for loop for the prime numbers between 2 to 100 as 100 will not change.

Here’s another example of a while loop that takes user input and keeps prompting the user until they enter the correct password:

password = "password123"
user_input = ""
while user_input != password:
    user_input = input("Enter your password: ")
    if user_input != password:
        print("Incorrect password, try again.")
print("Access granted.")

The following will be the output:

Enter your password: ahmed
Access granted.

In this example, the variable user_input is initialized to an empty string. The while loop will continue to execute as long as the value of user_input is not equal to the correct password. Inside the loop, the program prompts the user for their password; if the input is incorrect, it will print a message telling the user to try again.

It’s essential to be careful when using it. At the same time, loops, mainly if the condition for the loop is based on user input or other unpredictable factors, because if the condition never becomes false, the loop will run forever and cause your program to get stuck in an infinite loop. To prevent this, you can use the break statement to exit the loop.

Additionally, you can use the continue statement inside the loop to skip specific iterations of the loop. This can be useful if you have a particular condition that you want to check before each iteration of the loop, and if the condition is not met, you want to skip that iteration and move on to the next one.

You can also nest multiple while loops, creating more complex programs that can make decisions based on multiple conditions.

You can also use a while loop with if-else or try-except statements to make the program more robust and adaptable.

While loops are an essential control structure in Python, and when used correctly, they can help you solve problems more efficiently and elegantly.

Leave a Reply

Leave a Reply

Scroll to Top