Robotics & Artificial Intelligence

Predict the output of the following snippet:

m, n = 2, 15
for i in range(1, 5):
    m = m + 1
    n = n - 1
print("m =", m)
print("n =", n)

Python Control Flow

3 Likes

Answer

Output
m = 6
n = 11
Explanation

Let’s break down the code line by line:

1. m, n = 2, 15: This statement uses multiple assignment, where m is assigned 2 and n is assigned 15 in a single statement.

2. for i in range(1, 5):: The for loop runs for the values 1, 2, 3, 4. Therefore, the loop executes 4 times.

3. Iterations

  • First Iteration: m = 3, n = 14
  • Second Iteration: m = 4, n = 13
  • Third Iteration: m = 5, n = 12
  • Fourth Iteration: m = 6, n = 11

4. print("m =", m): Displays m = 6

5. print("n =", n): Displays n = 11

6. Therefore, the final output is:

m = 6
n = 11

Answered By

2 Likes


Related Questions