Robotics & Artificial Intelligence

Predict the output of the following snippet:

for i in range(4):
    for j in range(i, -1, -1):
        print(j, end=' ')
    print()

Python Control Flow

2 Likes

Answer

Output
0 
1 0 
2 1 0 
3 2 1 0 
Explanation

The outer loop runs from 0 to 3. For each value of i, the inner loop starts from i and decreases up to 0 using the step value -1. Therefore, when i = 0, the output is 0; when i = 1, the output is 1 0; when i = 2, the output is 2 1 0; and when i = 3, the output is 3 2 1 0. The print() statement moves the output to the next line after each iteration of the outer loop.

Answered By

1 Like


Related Questions