ProgrammingModerateTCS NQT · Accenture

What is printed?

What is printed?
def is_prime(n):
    if n < 2:
        return False
    i = 2
    while i * i <= n:
        if n % i == 0:
            break
        i += 1
    else:
        return True
    return False
print([n for n in range(2, 20) if is_prime(n)])
  1. A. [2, 3, 5, 7, 9, 11, 13, 15, 17, 19]
  2. B. [3, 5, 7, 11, 13, 17, 19]
  3. C. [2, 3, 5, 7, 11, 13, 17, 19]
  4. D. [2, 3, 5, 7, 11, 13, 17]

Correct answer: C. [2, 3, 5, 7, 11, 13, 17, 19]

The while-else clause runs only when the loop ends without a break, so the function returns True only when no divisor was found. For n = 2 and 3 the loop never starts, and the else branch still runs.

More Python Programming questions

Exams that ask this topic