Python Course: while statement

Python Course: while Statement

In Python, there are mainly two ways to create loops: the for statement and the while statement. In this course, we will learn in detail how the while statement works and how to use it. The while statement allows the block of code to be executed as long as the given condition is True.

Basic Structure of the while Statement

The basic syntax of the while statement is as follows:

while condition:
    block of code to execute
    (usually includes code that makes the condition false)

In simple terms, for the while statement, the block of code below is repeatedly executed every time the condition is true. And when the condition becomes false, the loop ends. Now let’s look at a simple example of a while statement.

Basic Example

Let’s examine how the while statement works through an example. Here, we will look at a simple example that prints the numbers from 1 to 5.

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

In this example, the initial variable i is set to 1. The while statement continues executing the loop as long as the condition i <= 5 is true. Inside the loop, it prints the value of i and adds 1 to i. Eventually, when i becomes 6, the condition evaluates to false, and the loop ends.

Infinite Loop

If the condition is always true, the while statement can enter an infinite loop. This means that the program will keep running without stopping. Infinite loops can be useful when paired with control mechanisms that appropriately end the loop.

while True:
    user_input = input("Enter 'q' to exit: ")
    if user_input == 'q':
        break

The above code runs indefinitely because of the condition True, but when the user enters ‘q’, the loop will terminate through the break statement.

Using an else Block with a while Statement

You can also attach an else block to the while statement. The else block is executed after the&nbps; while block is finished, unless the loop was terminated by a break statement.

i = 1
while i <= 5:
    print(i)
    i += 1
else:
    print("The loop has ended naturally.")

In this code, when i becomes 6, the while loop ends, and the statements in the else block are executed.

Practical Applications of the while Statement

Through examples, we will explore some useful ways to use the while statement. Each example demonstrates how the while statement can be used to solve more complex problems.

User Input Validation

You can write a program that keeps requesting input from the user until valid input is received.

while True:
    number_str = input("Please enter a number: ")
    try:
        number = int(number_str)
        break
    except ValueError:
        print("That's not a valid number. Please try again.")

In this case, the program continues to prompt for input until the user enters a number. If an invalid input is received, it shows an error message.

Reading Until End of File

You can write a program that reads a file line by line and stops when there is no more data to read.

with open('some_file.txt', 'r') as file:
    line = file.readline()
    while line:
        print(line, end='')
        line = file.readline()

This code opens a file and prints its content while reading each line sequentially. The loop ends when there are no more lines to read.

Things to Be Careful About When Using while Statements

When using the while statement, it is important to set the condition clearly to avoid getting stuck in an infinite loop. Infinite loops can often stop the program and create unintended situations. Therefore, within the loop, you should properly modify the condition or use statements like break to ensure the loop ends as intended.

Additionally, when using the while statement, if the number of iterations is not properly limited, performance issues may arise. It is important to optimize operations within the loop and avoid unnecessary tasks to minimize long processing times.

Conclusion

Now you understand how the while statement works and have learned ways to use it in various situations. The while statement is a powerful structure that executes repeatedly as long as the given condition is true, and can be used in various scenarios such as infinite loops and user input validation. I hope this course enables you to use the while statement with confidence.