While loop query


Joined
Aug 8, 2022
Messages
1
Reaction score
0
HI there, i need some help understanding this piece of code below, the output is -1 0 1 2 3. I don't understand why is 3 printed. Help would be greatly appreciated, thanks.

n = range(4)
for num in n:
print(num - 1, end = " ")
else:
print(num)
 
Ad

Advertisements

Joined
May 11, 2022
Messages
60
Reaction score
5
that is strange behavior. i didn't know you could have an else to a for loop.
and the num variable should only be applicable to the for loop, not the else
and why 3 and not 4? i have no idea
 
Ad

Advertisements

Joined
Aug 11, 2022
Messages
12
Reaction score
0
The first statement gives n the range 0,1,2,3 (4 numbers beginning with 0, not 0 to 4)

The else statement is executed when the loop is finished. The last iteration of the loop is when n=3. The loop returns the 2. When the loop is exited and the else statement is executed, n is still 3, and that is what the last statement prints.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top