Thursday , September 19 2024

How many stars (*) will the following snippet send to the console? i = 0 while i <= 5 : i += 1 if i % 2 == 0: break print("*")

Questions BankCategory: Python Essentials 1How many stars (*) will the following snippet send to the console? i = 0 while i <= 5 : i += 1 if i % 2 == 0: break print("*")
How many stars (*) will the following snippet send to the console?

i = 0
while i <= 5 :
    i += 1
    if i % 2 == 0:
      break
    print("*")
  • two
  • one
  • three
  • zero

Explanation: Let’s analyze this example:

  • the i variable is assigned the integer value of 0,
  • the while
  • the i variable is incremented by 1, and its new value is 2,
  • the operation 1 % 2 is evaluated and returns 1,
  • the 1 is compared with 0, 1 == 0, and since it is False, the if conditional is not executed,
  • A star is printed on the console,
  • the while loop now compares if 2 <= 3, and since it is True, the loop is entered,
  • the i variable is incremented by 1, and its new value is 2,
  • the operation 2 % 2 is evaluated and returns 0,
  • the 0 is compared with 0, 0 == 0, and since it is True, the if conditional is executed,
  • the break statement is executed,
  • the while loop is terminated.

More Questions: Python Essentials 1 – Module 3 Test