What is the result of the following code? x = 3 while x > 0: print(x) x -= 1

What is the result of the following code? x = 3 while x > 0: print(x) x -= 1

a) 1 2 3
b) 3 2 1
c) 3 3 3
d) Infinite loop

Answer:

b) 3 2 1

Explanation:

The while loop in the code x = 3 while x > 0: print(x) x -= 1 starts with x equal to 3 and continues looping as long as x is greater than 0. In each iteration, x is printed and then decremented by 1.

x = 3
while x > 0:
    print(x)  # Prints 3, 2, 1
    x -= 1

As a result, the loop prints 3, 2, and 1 before terminating when x becomes 0, which no longer satisfies the loop condition.

This example demonstrates how while loops operate based on a condition and continue executing until that condition is no longer met. They are particularly useful when the number of iterations is not known beforehand.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top