while loop

A while loop is used to repeat a block of code as long as a condition is True.

  • Useful when we do not know how many times the loop will run
  • The loop continues until the condition becomes False
  • It uses a condition to control execution
  • Variables inside the loop must be updated
  • If not handled properly, it can create an infinite loop

Explanation

  • First, the condition is checked
  • If True → code runs
  • Then the condition is checked again
  • This repeats until condition becomes False

Real-Life Scenario

  • Enter password until it is correct
  • Playing a game until lives become 0
  • Filling water until the tank is full

 Loop runs until the condition becomes False

Syntax

while condition:
    # code


Example 1

i = 1

while i <= 3:
    print("Hi")
    i += 1


Output

Hi
Hi
Hi


Example 2

num = 1
sum = 0

while num <= 5:
    sum += num
    num += 1

print(sum)


Output

15

 

Explanation of Example

  • Loop runs from 1 to 5
  • Adds values → 1+2+3+4+5 = 15

Why while loop is Important

  • Used when repetitions are unknown
  • Helps in real-world tasks like validation
  • Useful in games and user input programs
  • Builds logical thinking


Difference Between for Loop and while Loop

Feature for Loop while Loop
Use Fixed repetitions Condition-based
Easy Easy Medium
Risk Less Can cause infinite loop

Common Beginner Mistakes

  •  Forgetting to update variable
  • Creating infinite loop
  • Wrong condition
  • Incorrect indentation

➤ Key Points

  • while loop runs until condition becomes False
  • Depends on a True/False condition
  • Number of repetitions is not fixed
  • Needs variable update
  • Can cause infinite loop if not handled

➤ Tips

  • Use while loop when repetitions are unknown
  • Always update variable (i += 1)
  • Check condition carefully
  • Avoid infinite loops
  • Good for user input, games, validations
  • Test with small values first

Check your knowledge

Quickly verify what you've learned from this tutorial.

Question 1

What does a while loop do?

A while loop repeats code based on a condition.

Question 2

When does a while loop stop?

Loop stops when condition becomes False.

Question 3

What is the output?

i = 1

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

Loop runs for 1 and 2.

Question 4

What happens if variable is not updated?

Without update, condition stays True → infinite loop.

Question 5

What is the output?

x = 2

while x < 6:
    print(x)
    x += 2

Loop runs for 2 and 4; stops before 6.

Congratulations!

You've successfully mastered the knowledge check for "while loop."

For more questions and practice, click the link below:

Practice More Questions
Previous Topic for Loop