Python/Flow control

python flow control - while

kimble2 2024. 8. 10. 09:36
반응형

The while loop in Python is a control flow statement that repeatedly executes a block of code as long as a given condition is True. The loop stops executing once the condition becomes False. The while loop is typically used when the number of iterations is not known in advance and you want to continue looping until a certain condition is met.

Basic Structure

The basic structure of a while loop is as follows:

 

while condition:
    # Code block to execute as long as the condition is True

 

  • condition: This is the expression that is evaluated before each iteration. The loop continues to execute as long as this condition is True. Once the condition is False, the loop stops.

Examples of Using while Loops

Simple while Loop

count = 0

while count < 5:
    print(count)
    count += 1
# Output:
# 0
# 1
# 2
# 3
# 4

 

In this example, the loop continues as long as count is less than 5. The count variable increments by 1 with each iteration until the condition becomes False.

Infinite Loop

A while loop can create an infinite loop if the condition always remains True. In such cases, you can use a break statement to exit the loop.

 

while True:
    name = input("Enter your name: ")
    if name:
        print(f"Hello, {name}!")
        break  # The loop exits when the user enters a name

 

In this example, the loop repeatedly asks for the user's name until they enter a valid input. The loop exits with a break statement once a name is provided.

Using while with else

Just like for loops, a while loop can have an else block. The else block executes if the loop terminates normally, meaning without encountering a break statement.

 

count = 0

while count < 5:
    print(count)
    count += 1
else:
    print("Loop finished.")
# Output:
# 0
# 1
# 2
# 3
# 4
# Loop finished.

In this example, when count reaches 5, the loop ends, and the else block is executed.

Looping with User Input

user_input = ""

while user_input != "exit":
    user_input = input("Type 'exit' to stop: ")
    print(f"You typed: {user_input}")

 

This example repeatedly asks for user input until the user types "exit". The loop stops when "exit" is entered.

Using continue Statement

The continue statement is used to skip the current iteration and move to the next one.

 

count = 0

while count < 10:
    count += 1
    if count % 2 == 0:
        continue  # Skip the even numbers
    print(count)
# Output:
# 1
# 3
# 5
# 7
# 9

 

 

In this example, when count is an even number, the continue statement skips the print function, so only odd numbers are printed.

Nested while Loops

A while loop can be nested inside another while loop.

 

i = 1

while i <= 3:
    j = 1
    while j <= 3:
        print(f"i = {i}, j = {j}")
        j += 1
    i += 1
# Output:
# i = 1, j = 1
# i = 1, j = 2
# i = 1, j = 3
# i = 2, j = 1
# i = 2, j = 2
# i = 2, j = 3
# i = 3, j = 1
# i = 3, j = 2
# i = 3, j = 3

 

In this example, there are two variables i and j, each controlled by a nested while loop. The outer loop controls i, and the inner loop controls j, with both loops iterating through their ranges.

Applications of while Loops

  • Handling User Input: Useful for repeatedly asking for user input until a certain condition is met.
  • Game Loops: Commonly used in game programming to keep the game running until the player chooses to exit.
  • Waiting for a Condition: Can be used to keep a program or system in a waiting state until a specific condition is satisfied.

The while loop is a powerful tool in Python when you need to perform repetitive tasks without knowing in advance how many iterations will be required.

반응형

'Python > Flow control' 카테고리의 다른 글

python flow control - for loop  (0) 2024.08.03
python flow control - if statement  (0) 2024.08.03