0

Why does it print 5 in the output?

x = 0 while x <5: x += 1 if x==3: print("I don't like that number") continue print(x) According to while condition the loop should stop when x is equal to 5 since it's <5 not <=5 so why did it not stop, ignored the condition and stopped when x = 6

31st Oct 2022, 7:15 PM
Intermediate Depression
Intermediate Depression - avatar
7 Answers
+ 3
Depression the line that contains the while statement is part of the loop. After the last print statement the loop goes back up to the while statement to check for the next iteration. It performs the conditional check only at that line, whenever it returns to the beginning of the loop. When x=5, the loop exits and leaves x as it is, 5 (not 6).
31st Oct 2022, 7:32 PM
Brian
Brian - avatar
+ 2
Cause first it enters the loop when x=4 then it becomes 5 when the expression x+=1 comes, then prints x next time. When it goes to the loop x becomes 5 and the loops stop. It didn't ignore the condition. Remember, when x becomes 5 it directly won't break out from the loop, it will complete the rest of the statement and then come to the while loop condition. then if x becomes 5 it will break. You can change the code like this to get your desired output: https://code.sololearn.com/cv3OBRqlBi32/?ref=app maybe the code doesn't click because I'm on pc
31st Oct 2022, 8:50 PM
The future is now thanks to science
The future is now thanks to science - avatar
+ 2
Well, I don't really know the reason. I have come to this platform after a long time. Back then, the web code link was formatted like the app link, so it really didn't matter. Now I think they have made some changes between the web compiler and the app compiler so the link is also showing differently.
1st Nov 2022, 3:34 PM
The future is now thanks to science
The future is now thanks to science - avatar
+ 1
The future is now thanks to science[In a break] Thank you so much, I understand now ! Also Idk why but the link doesn't click! , thanks again!
1st Nov 2022, 7:10 AM
Intermediate Depression
Intermediate Depression - avatar
+ 1
EHM.... sorry that I am about to bug you but .....why does it matter on pc or not? So all what happened is that you removed "compiler-playground" and added "/?ref=app"??? Also I saw what you did with the code it's really impressive! It took me 60sec to actually understand what you did😅😅 (for me I just added a break if x==5)
1st Nov 2022, 2:14 PM
Intermediate Depression
Intermediate Depression - avatar
+ 1
The future is now thanks to science[In a break] Thanks for your time, i really appreciate your answers. ! Take care !
1st Nov 2022, 3:43 PM
Intermediate Depression
Intermediate Depression - avatar
0
Brian Yes " the loop exits and leaves x as it is, 5" then why did it print 5 ?? How come ? It is supposed to exit and not print it right??
31st Oct 2022, 8:20 PM
Intermediate Depression
Intermediate Depression - avatar