Loop (while, for), loop whilefor

Source: Internet
Author: User

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 ------

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.