Master Python while Loops: Essential Components to Avoid Infinite Loops

Table of Contents

The while loop in Python is a fundamental control flow statement used to repeatedly execute a block of code as long as a specific condition remains true.

When Should You Use a While Loop?

Use a while loop when:

  • You are not aware of the number of times a loop runs.
  • You need to wait for a condition to become true or false.
  • You want more control over the stopping condition.
				
					while condition:
        # code to execute
				
			
Flowchart illustrating the Python while loop's execution flow and conditional checks.
Figure 1: A step-by-step flowchart of how Python's while loop evaluates its condition and executes its code block.
  •  The loop checks the condition.
  •  If the condition is True, it runs the code inside.
  •  Once the condition becomes False, the loop stops.

 

Write a Python program to print Hello World times five using while loop.

				
					count = 1
while count <= 5:
    print("Hello World")
    # Update: Increment the counter by 1
    count += 1
    
# output
#     Hello World
#     Hello World
#     Hello World
#     Hello World
#     Hello World
				
			

Analysis:

  1. Initial State: Value is 1 and the condition check is True. Print the value.
  2. 1st Loop: Value increments to 2 and the condition check is True. Print the value.
  3. 2nd Loop: Value increments to 3 and the condition check is True. Print the value.
  4. 3rd Loop: Value increments to 4 and the condition check is True. Print the value.
  5. 4th Loop: Value increments to 5 and the condition check is True. Print the value.
  6. 5th Loop: Value increments to 6 and the condition check is False. Stop Loop (Termination).

 

Write a Python program to print numbers from one to five using a while loop.

				
					i = 1
while i <= 5:
    print(i)
    i += 1
    
# output
#     1
#     2
#     3
#     4
#     5
				
			

Analysis:

  1. Initial State: i starts at 1.
  2. Loop 1: i=1 Condition is True. Printed Output: 1. i becomes 2.
  3. Loop 2: i=2. Condition is True. Printed Output: 2. i becomes 3.
  4. Loop 3: i=3. Condition is True. Printed Output: 3. i becomes 4.
  5. Loop 4: i=4. Condition is True. Printed Output: 4. i becomes 5.
  6. Loop 5: i=5. Condition is True. Printed Output: 5. i becomes 6.
  7. Loop 6 (Termination): i=6. Condition is False. Loop stops.

 

Write a Python program to calculate the numbers entered by the users. The program must continually accept positive numbers from the users until the user enters 0, at which point the final total should be displayed.

				
					total = 0
num = int(input("Enter a number (or 0 to stop): "))

while num != 0:
    total += num
    num = int(input("Enter another number (0 to stop): "))

print("Total sum:", total)

# output

#       Enter a number (or 0 to stop): 10
#       Enter another number (or 0 to stop): 5
#       Enter another number (or 0 to stop): 2
#       Enter another number (or 0 to stop): 3
#       Enter another number (or 0 to stop): 0
#       Total sum: 20
				
			

Analysis:

1.     Initialisation: The program sets total=0.First Input: The user enters 10.

  • The condition (10 != 0) is true.

2.    Loop 1:

  • total becomes 0+10=10.
  • The program asks for the next number 0and the user enters 5.

3.   Loop 2:

  • The condition is True.
  • total becomes 10+5=15.
  • The program asks for the next number and the user enters 2.

4.    Loop 3:

  • The condition is True.
  • total becomes 15+2=17.
  • The program asks for the next number and the user enters 3.

5.     Loop 4:

  • The condition is True.
  • total becomes 17+3=20.
  • The program asks for the next number and the user enters 0 (the stop signal).

6.      Termination: The while condition (0 != 0) is False. The loop ends

7.      Final Output: The program prints the final accumulated total.

 

Write a Python program for a password authentication system.

				
					password = "python123"

attempt = input("Enter password: ")

while attempt != password:
    print("Wrong password. Try again.")
    attempt = input("Enter password: ")
    
# output

#    Enter password: python
#    Wrong password. Try again.
#    Enter password: python123
#    Access granted
				
			

Infinite Loops

If you forget to update the variable inside the loop, it can run forever.

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

				
			

This code never ends because i is never incremented — a classic infinite loop!

 

Break Statement

The break statement is used to immediately exit the current loop (either while or for). As soon as Python encounters break, the loop terminates completely, and the program moves to the first line of code after the loop.

				
					i = 1
while i <= 10:
    if i == 6:
        break
    print(i)
    i += 1

# output

#       1
#       2
#       3
#       4
#       5
				
			

Analysis:

1. Initialization: The variable i is set to 1.

2.   Loop 1 (i=1):

  • Conditional check  1 <= 10 is True
  • Break Check: 1 == 6 is False.
  • Action: Print 1
  • Increment: i is incremented to 2.

3.    Loop 2 (i=2):

  • Condition Check: 2 <= 10 is True.
  • Break Check: 2 == 6 is False.
  • Action: Print 2.
  • Increment: i becomes 3.

4. Loop 3 (i=3):

  • Condition Check: 3 <= 10 is True.
  • Break Check: 3 == 6 is False.
  • Action: Print 3.
  • Increment: i becomes 4.

5.    Loop 4 (i=4):

  • Condition Check: 4 <= 10 is True.
  • Break Check: 4 == 6 is False.
  • Action: Print 4.
  • Increment: i becomes 5.

6.      Loop 5 (i=5):

  • Condition Check: 5 <= 10 is True.
  • Break Check: 5 == 6 is False.
  • Action: Print 5.
  • Increment: i becomes 6.

7.        Loop 6 (i=6):

  • Condition Check: 6 <= 10 is True.
  • Break Check: 6 == 6 i True.
  • Action: The break statement is executed and the loop is terminated immediately.

 

Continue Statement

				
					i = 0
while i < 5:
    i += 1
    if i == 3:
        continue
    print(i)
    
# output

#       1
#       2
#       4
#       5

				
			

Analysis:

1.    Initialisation: The variable i is set to 0.

2.    Loop 1 (Check: 0 < 5 is True):

  • Increment: i becomes 1.
  • Continue Check: 1 == 3 is False.
  • Action: Print 1.

3.    Loop 2 (Check: 1 < 5 is True):

  • Increment: i becomes 2.
  • Continue Check: 2 == 3 is False.
  • Action: Print 2.

4.     Loop 3 (Check: 2 < 5 is True):

  • Increment: i becomes 3.
  • Continue Check: 3 == 3 is True.
  • Action: continue is executed. The print(i) statement is skipped.

5.      Loop 4 (Check: 3 < 5 is True):

  • Increment: i becomes 4.
  • Continue Check: 4 == 3 is False.
  • Action: Print 4.

6.      Loop 5 (Check: 4 < 5 is True):

  • Increment: i becomes 5.
  • Continue Check: 5 == 3 is False.
  • Action: Print 5.
  • Termination Check (i=5): 5 < 5 is False. The loop stops.

 

FAQ (Frequently Asked Questions)

 

1. What is the difference between a for loop and a while loop in Python?   

 A for loop runs a fixed number of times usually over a sequence (like a list or range).
A while loop on the other hand runs until a condition becomes false, making it ideal when you don’t know the number of iterations in advance.

 

2. Can a while loop run forever in Python?

Yes — if the condition never becomes false, the while loop will run indefinitely.
This is called an infinite loop. You can stop it manually by pressing Ctrl + C in your terminal or by including a break statement in your code.

 

3. What happens if the while loop condition is initially false?

If the initial condition is false the loop body will not execute even once.
In that case, Python simply skips the loop and continues with the next line of code.

 

4. How do you exit a while loop early in Python?

You can exit a loop early using the break statement.
It immediately stops the loop, regardless of the condition’s truth value.

 

5. What is the syntax of a while loop in Python?

while condition:
# code block to execute