Loop (while, for), loop whilefor
Repeated code writing is the most shameful behavior of programmers. So how can we avoid repeated code writing and allow the program to repeat a piece of code multiple times? Loop statements can be used in a bid ......
While Loop
# While syntax structure while condition: execute code .....
# Write a small program that is printed from 0 to 100, each cycle is performed, + 1 + count = 0 while count <= 100: # only count <= 100, execute the following code print ("% s loop" % count) count + = 1 # count + 1 each time it is executed, otherwise it will become an endless loop, if count is not added with 1, count is always 0 # execution result: 0th cycles, 1st loops, 2nd loops, 3rd loops, 4th loops .................................... 100th cycles
# Do another exercise and print the even numbers of 0-100 num = 0 while num <=: if num % 2 = 0: print ("% s" % num, end = "") num + = 1 print ("") print ("----- loop is ended -----") # execution result 0 2 4 6 8 10 12 14 16 18 22 24 26 28 30 32 34 36 38 40 42 44 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 88 88 90 92 94 98 100 ----- loop is ended -----
Let's take a look at the effect of continue ......
# Print 1-10, 5th skipped do not print count = 0 while count <= 10: count + = 1 if count = 5: continue # When count = 5, end this loop without printing loop 5 print ("loop", count) print ("---- end ------") # execution result loop 1 loop 2 loop 3 loop 4 loop 6 loop 7 loop 8 loop 9 loop 10 ---- end ------