while loops break | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

while loops break

How many numbers does this code print? i = 5 while True: print(i) i = i - 1 if i <= 2: break

22nd Mar 2018, 8:55 PM
Kaleigh Patten
Kaleigh Patten - avatar
4 Answers
+ 8
It will print: 5 4 3 so 3 numbers.
22nd Mar 2018, 9:09 PM
Farshad
Farshad - avatar
+ 7
Sorry to have to contradict you @Farshad, but the 2 doesn't print. After 3 prints, i is changed to 2. The if statement becomes true, since i is equal to 2, and we break out of the loop. Note: even when you are positive you know the answer, it is worth spending a moment to try running the code. It is easy to miss something, such as the fact there might be a compile error or a simple mistake reading of the code. I've made this mistake myself so I know from experience. @Kaleigh you should have tried running this to get your answer, instead of asking.
22nd Mar 2018, 10:32 PM
John Wells
John Wells - avatar
+ 7
@john thanks for you polite way of showing a mistake and your suggestion. Will run the code next time before answering. PS:edited the answer.
22nd Mar 2018, 10:37 PM
Farshad
Farshad - avatar
+ 7
Even though I was positive, I ran the code myself to prove it as I don't ever wish to make that mistake again. I've discovered all kinds of mistaken thoughts about how a code runs or fails over the months I've been doing this so would have incorrectly posted many times without this policy. You are also not the first I've caught. I'm glad you appreciate my attempt to be polite. The person who caught me wasn't. Their correction was extremely rude making it even worst.
22nd Mar 2018, 11:05 PM
John Wells
John Wells - avatar