Robotics & Artificial Intelligence
Predict the output of the following snippet:
p = 100
for i in range(1, 5):
p = p - 1
print(p, end=' ')
Python Control Flow
2 Likes
Answer
Output
99 98 97 96
Explanation
Let’s break down the code line by line:
1. p = 100: The variable p is assigned the value 100.
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 of the loop:
- First Iteration: p = 100 - 1 = 99
- Second Iteration: p = 99 - 1 = 98
- Third Iteration: p = 98 - 1 = 97
- Fourth Iteration: p = 97 - 1 = 96
4. print(p, end=' '): Displays the value of p after each iteration in the same line separated by spaces.
5. Therefore, the final output is: 99 98 97 96
Answered By
1 Like
Related Questions
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)Predict the output of the following snippet:
k = 1 i = 2 while(i < 6): k = k * i i = i + 1 print(k)Predict the output of the following snippet:
p = -99 while(p < 0): p = p + 9 print(p, end=' ')Predict the output of the following snippet:
for i in range(4): for j in range(i, -1, -1): print(j, end=' ') print()