Home Tutorials Python Tutorial While Loop
While Loop

While Loop


Definition: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The loop continues to run as long as the condition remains True.

Why: While loops are essential when you don't know in advance how many times a block of code needs to run, but you do know the condition that should stop it (e.g., waiting for a specific user input or reaching a mathematical threshold).

Syntax

while condition:
    # code to execute
    # update condition

Example

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

Explanation

  • Initial Variable: We start with i = 1.
  • Condition: The loop checks if i <= 5. Since 1 is less than 5, the code inside runs.
  • Execution: The current value of i is printed.
  • Update: i += 1 increases the value of i. If we didn't do this, the loop would run forever (an infinite loop).
  • Termination: Once i becomes 6, the condition 6 <= 5 becomes False, and the loop stops.

Key Notes

  • Indentation: Just like if statements, the code inside the while loop must be indented.
  • Infinite Loops: Always ensure the condition will eventually become False. If the loop never stops, it can crash your program.
  • Breaking a Loop: You can use the break statement to stop a loop immediately, even if the condition is still true.
Example

🏋️ Test Yourself With Exercises

Take our quiz on While Loop to test your knowledge.

Exercise »