+ 1

Using "while" loops

Why does the print command get listed before the loop command? For example: print(i) i += 1 It seems like "print" should be last, since Python executes line by line. Can someone help me with the logic on this one?

14th May 2019, 5:08 AM
Nicolle Hall
Nicolle Hall - avatar
5 Respostas
+ 5
If you want the initial value of i to be printed, the print needs to come before the increment.
14th May 2019, 5:09 AM
Sonic
Sonic - avatar
+ 5
You didn't provide the full code. Am I assuming that your code is: #code.py i=0 while True: print(i) i+=1
14th May 2019, 5:11 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 1
Oh, that makes sense! Thanks, Sonic!
14th May 2019, 5:11 AM
Nicolle Hall
Nicolle Hall - avatar
+ 1
It's actually from one of the lessons. The full code is: i=1 while i<=5: print(i) i = i + 1
14th May 2019, 5:19 AM
Nicolle Hall
Nicolle Hall - avatar
+ 1
The loop runs while i <= 5. So i has to be incremented at some point in the loop, otherwise it will run forever.
14th May 2019, 6:20 AM
HonFu
HonFu - avatar