arrow
arrow
arrow
Which of the following will not run the loop statement an infinite number of times in Python?
Question

Which of the following will not run the loop statement an infinite number of times in Python?

A.

while 21 % 2:
  print("ALWAYS")

B.

while 21 // 2:
  print("ALWAYS")

C.

while True:
  print("ALWAYS")

D.

while 1 % 1:
  print("ALWAYS")

Correct option is D


The loop in option (d), while 1 % 1:, will not run an infinite number of times.
Here's why:
· 1 % 1 evaluates to 0 because the remainder when dividing 1 by 1 is 0.
· In Python, any value that evaluates to 0 is considered False in a Boolean context.
· Since 0 is False, the loop will not execute, and the print("ALWAYS") statement will not be run.
Important Key Points:
1. while loop: The condition in a while loop is checked before each iteration. If the condition evaluates to True, the loop runs; if it evaluates to False, the loop stops.
2. 1 % 1 = 0: Since the modulus operation results in 0, the condition evaluates to False, causing the loop to terminate immediately.
3. Other Loops: In the other options:
· while 21 % 2: will always return 1 (True), as 21 is an odd number.
· while 21 // 2: will return 10 (True), as the floor division of 21 by 2 is 10.
· while True: will run infinitely because True is always true.
Knowledge Booster:
· Option (a): while 21 % 2: will run infinitely because 21 % 2 results in 1 (which is evaluated as True), so the condition remains true.
· Option (b): while 21 // 2: will run infinitely because 21 // 2 results in 10 (which is evaluated as True), so the condition remains true.
· Option (c): while True: will run infinitely because True always evaluates as true.

Free Tests

Free
Must Attempt

CDP Subject Test 01

languageIcon English
  • pdpQsnIcon20 Questions
  • pdpsheetsIcon20 Marks
  • timerIcon20 Mins
languageIcon English
Free
Must Attempt

EVS Subject Test 01

languageIcon English
  • pdpQsnIcon20 Questions
  • pdpsheetsIcon20 Marks
  • timerIcon20 Mins
languageIcon English
Free
Must Attempt

CTET Paper-I PYP (07 July 2024)

languageIcon English
  • pdpQsnIcon150 Questions
  • pdpsheetsIcon150 Marks
  • timerIcon150 Mins
languageIcon English
test-prime-package

Access ‘EMRS PGT’ Mock Tests with

  • 60000+ Mocks and Previous Year Papers
  • Unlimited Re-Attempts
  • Personalised Report Card
  • 500% Refund on Final Selection
  • Largest Community
students-icon
289k+ students have already unlocked exclusive benefits with Test Prime!
Our Plans
Monthsup-arrow