KnowledgeBoat Logo
|

Robotics & Artificial Intelligence

Predict the output of the following snippet:

k = 1
i = 2
while(i < 6):
    k = k * i
    i = i + 1
print(k)

Python Control Flow

3 Likes

Answer

Output
120
Explanation

Let’s break down the code line by line:

1. k = 1: The variable k is assigned the value 1.

2. i = 2: The variable i is assigned the value 2.

3. while(i < 6):: The while loop iterates as long as i < 6.

4. The iterations are as follows:

  • i = 2: k = 1 * 2 = 2, then i becomes 3
  • i = 3: k = 2 * 3 = 6, then i becomes 4
  • i = 4: k = 6 * 4 = 24, then i becomes 5
  • i = 5: k = 24 * 5 = 120, then i becomes 6

5. When i = 6, the condition becomes false and the loop terminates. Hence, the final value of k = 120 is printed.

Answered By

2 Likes


Related Questions