Python While

Anatomy of a 'while' loop in Python.

while

A 'while' loop in Python is used to execute a block of code repeatedly as long as a specified condition is true.

Anatomy of a 'while' Loop:

1. Initialization: This is where you set up the initial condition(s) that the loop will evaluate. Typically, this involves initializing one or more variables.

2. Condition: The loop continues to execute as long as this condition evaluates to 'True'. If the condition becomes 'False', the loop terminates, and the program continues execution after the loop.

3. Body: This is the block of code that is executed repeatedly as long as the condition remains 'True'. It often contains the logic or operations you want to perform iteratively.

4. Update: Inside the loop, you usually change the state of variables that affect the loop condition, to eventually terminate the loop. This might involve incrementing/decrementing a counter, altering the value of a variable, or some other form of state change.

[syntax]

while condition:
    # code block to execute

[code]

PDF Copy Code
# Python: while loop
num = 1  # Initialization
while num <= 5:  # Condition
    print(num)  # Body
    num += 1  # Update
Output:
1
2
3
4
5

Use Cases:

  • You need to perform an action until a certain condition is met.
  • You don't know in advance how many iterations are required.
  • You want to repeatedly perform an operation based on user input or some changing condition.

Infinite Loops:

An infinite loop occurs when the loop condition never becomes 'False', causing the loop to run indefinitely. This often happens due to mistakes in the loop condition or missing update statements.

while True: print("This is an infinite loop!")

Note: Be cautious about infinite loops and ensure that your loop conditions will eventually become 'False' to prevent them.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.