0

placement of print (i)/ learning continue

today while learning the basics of python i encountered smth... i dont understand the difference between these 2 codes and why it behaves differently code 1: i=0 while True: i+=1 if i ==2: print('lol') continue if i == 5: print('help') break print (i) the results of the above would be 1 lol 3 4 help this is opposed to the following code: code 2: i=0 while True: i+=1 print (i) if i == 2: print('lol') continue if i == 5: print ('help') break the result of code 2 would be: 1 2 lol 3 4 5 help why does this work this way?

14th Jun 2020, 10:55 AM
Andre Lum
Andre Lum - avatar
2 Antworten
+ 5
Line 1 in both codes start i at zero. Line 2 in both codes start an infinite loop. Line 3 in both codes increment i. Now we come to the reason for the difference. Line 4 in the 2nd code will display 1 through 5 as each loop happens. In the 1st code, it is at the end of the loop so does not always occur. Line 4 (1st code) or 5 (2nd code) test i for 2. If so, it displays 'lol' (5 or 6) and then continues (6 or 7) to line 2 skiping the rest of the loop. This makes it so 2 is not displayed for first code. Line 7 or 8 test i for 5. If so, it displays 'help' (8 or 9) and breaks out of the loop (9 or 10). This cause the first code to never display 5.
15th Jun 2020, 1:29 AM
John Wells
John Wells - avatar
+ 4
code 1: i=0 #1 while True: #2 i+=1 #3 if i ==2: #4 print('lol') #5 continue #6 if i == 5: #7 print('help') #8 break #9 print (i) #10 code 2: i=0 #1 while True: #2 i+=1 #3 print (i) #4 if i == 2: #5 print('lol') #6 continue #7 if i == 5: #8 print ('help') #9 break #10 Added line numbers so I can talk about it as comment at the end of each line.
15th Jun 2020, 1:15 AM
John Wells
John Wells - avatar