Python while loop

In this tutorial, you will learn about the while loop.

A while loop is used to repeatedly execute a block of code as long as a specified condition is True.

Note: The while loop will stop when the condition becomes False.

If the while condition is true, then the loop’s body is executed repeatedly.

If the while condition is false, then the loop’s body will not be executed.

Syntax:


while condition:
    # Code to execute repeatedly

Example 1: Basic while loop


count = 0
while count < 4:
    print(count)
    count = counter + 1  # Increment the counter

Output:

0 1 2 3

In this example, the loop continues until count is no longer less than 4.

Example 2: while loop with break

You can use the break statement to exit the loop early.


i = 0
while i < 5:
    print(i)
    if i == 3:
        break  # Exit the loop when i is 3
    i += 1

Output:

0 1 2

Example 3: while loop with else

Similar to a for loop, you can use an else clause with a while loop. The else block will run if the loop completes without encountering a break.


i = 0
while i < 3:
    print(i)
    i += 1
else:
    print("Loop finished!")

Output:

0
1
2

Example 4: Infinite loop

A while loop can become an infinite loop if the condition never becomes False.


while True:
    print("This is an infinite loop!")
    break  # Use a break to avoid an actual infinite loop

Without the break, this would print endlessly. Infinite loops are commonly used when waiting for specific conditions to occur.

Python while loop – Questions and Answers

Q 1: What is a while loop in Python?

Ans: A while loop repeatedly executes code as long as a condition is true.

Q 2: When is a while loop used?

Ans: When the number of iterations is not known in advance.

Q 3: What happens if the condition never becomes false?

Ans: It results in an infinite loop.

Q 4: Can a while loop run zero times?

Ans: Yes, if the condition is false initially.

Q 5: Which statement is commonly used to control a while loop?

Ans: The break statement is often used to stop the loop.

Python While loop – Objective Questions (MCQs)

Q1. Which keyword is used to create a while loop in Python?






Q2. What will be the output of the following code?

i = 1
while i < 4:
print(i)
i += 1;






Q3. The condition inside a while loop is checked:






Q4. What will happen if the condition in a while loop never becomes False?






Q5. Which statement can be used to terminate a while loop early?






Related Python While_loop Topics