Python while loop: A beginner’s guide with examples

Python is a popular programming language that is known for its simplicity and readability. One of the fundamental building blocks of Python is the “while” loop. In this beginner’s guide, we will explore what a while loop is, how it works, and provide examples to help you understand its usage.

What is a While Loop?

A while loop is a control flow statement in Python that allows you to execute a block of code repeatedly as long as a certain condition is true. It is called a “while” loop because it continues to loop while the condition remains true. Once the condition becomes false, the loop stops and the program continues with the next statement.

Syntax: The syntax of a while loop in Python is as follows:

while condition:
    # Code to be executed

The condition is an expression that evaluates to either True or False. If the condition is True, the code inside the loop is executed. After each iteration, the condition is checked again, and if it is still True, the loop continues. If the condition becomes False, the loop is exited, and the program moves on to the next line of code.

Example 1: Counting from 1 to 10

Let’s start with a simple example to illustrate how a while loop works. We want to count from 1 to 5 and print each number on a new line.

num = 1
while num <= 10:
    print(num)
    num += 1
  • We initialize a variable num with the value 1.
  • The condition num <= 10 is checked. Since 1 is less than or equal to 10, the condition is True, and the code inside the loop is executed.
  • The current value of num (which is 1) is printed.
  • We increment num by 1 using the += operator.
  • The condition is checked again. This process continues until num becomes 11, which makes the condition False. The loop is then exited, and the program continues.

Output:

1
2
3
4
5
6
7
8
9
10

Example 2: User Input Validation

Another common use case for a while loop is input validation. Let’s say we want to ask the user to enter a positive number, and we keep asking until a valid input is provided.

number = -1
while number <= 0:
    number = int(input("Enter a positive number: "))
  • We initialize the variable number with a value of -1 (which is an invalid input).
  • The condition number <= 0 is checked. Since -1 is less than or equal to 0, the condition is True, and the code inside the loop is executed.
  • The user is prompted to enter a positive number using the input function. The input is converted to an integer using the int function.
  • The value of a number is updated with the user’s input.
  • The condition is checked again. If the input is still invalid (less than or equal to 0), the loop continues until a positive number is entered.

Use while loops with else statement

In Python, the else statement in a while loop is executed when the loop condition becomes false. It provides an additional block of code to be executed after the loop has completed its iterations.

syntax:

while condition:
    # Code to be executed inside the loop
else:
    # Code to be executed after the loop

Example:

num = 1
while num <= 10:
    print(num)
    num += 1
else:
    print("Loop completed!")

print("After the loop")

Output:

In this example, we initialize the variable num with the value 1. The condition num <= 10 is checked, and since 1 is less than or equal to 10, the code inside the loop is executed. The current value of num, which is 1, is printed.

We increment num by 1 using the += operator. The condition is checked again, and this process continues until num becomes 11, which makes the condition False. The loop is then exited, and the code inside the else block is executed, printing “Loop completed!”.

Finally, the program continues with the next line of code, which prints “After the loop”.

1
2
3
4
5
6
7
8
9
10
Loop completed!
After the loop

Infinite while Loop in Python

In this example, the condition True is always true, so the loop will continue indefinitely. Inside the loop, you can include any code that you want to be executed repeatedly.

To exit the infinite loop, you can use a break statement when a certain condition is met.

For example:

while True:
    # Code to be executed indefinitely
    # ...

    # Check for a condition to break the loop
    if condition:
        break

In the above example, the loop will continue to execute indefinitely, printing the message “This loop will run forever!” repeatedly.

To exit the infinite loop, you can use the break statement inside the loop when a specific condition is met.

For example

while True:
    user_input = input("Enter 'exit' to stop the loop: ")
    if user_input == 'exit':
        break

print("Loop has been terminated.")

In this example, the loop will keep asking the user for input until the user enters “exit.” When “exit” is entered, the loop will terminate, and the message “Loop has been terminated” will be printed.

a real-life example of the Python while loop

One real-life example of a while loop is a ticketing system at a movie theater. Let’s say you have a limited number of available seats and you want to allow customers to purchase tickets until all seats are sold out.

The while loop can be used to repeatedly prompt the user for input until either all seats are sold or the user chooses to stop.

total_seats = 100
seats_sold = 0

while seats_sold < total_seats:
    # Prompt user for ticket purchase
    user_input = input("Enter 'buy' to purchase a ticket or 'exit' to stop: ")

    if user_input == 'buy':
        # Process ticket purchase
        print("Ticket purchased!")
        seats_sold += 1
    elif user_input == 'exit':
        # Exit loop if user chooses to stop
        break
    else:
        # Invalid input, ask again
        print("Invalid input. Try again.")

print("All tickets sold out. Thank you for your purchase!")

In this example, the while loop continues until all seats are sold out (seats_sold < total_seats) or the user chooses to exit the ticketing system. The loop prompts the user for input, processes the purchase if the input is “buy,” breaks the loop if the input is “exit,” and asks again for input if the input is invalid.

Once the loop ends, a message is displayed indicating that all tickets have been sold.

Leave a Comment