Python_ Loop expression

Source: Internet
Author: User
Tags terminates

One, while loop

As long as the conditions are met, you can always perform the action. This cycle is called the Dead loop, once triggered, as long as the conditions meet, on the wireless loop.

This condition is actually a Boolean value of-->true, False. If you want to make a decision to end the loop irregularly, you can set the variable to a Boolean value (True), and when you want to end it, reset the Boolean value (False) to end the loop.

Circulation in the daily use, but also need to cooperate with several expression methods, respectively: Break, continue, end, else, in the following article will be explained in detail.

While loop structure:
 while Condition:    action    

Printing is printed as long as NUM is less than or equal to 10:

num = 1 while num <=:    print(num    )= num + 1

Print even numbers only:

num = 1 while num <=:    if num% 2 = = 0:                #  $ operation for fetch remainder        print  (num)    = num + 1

Print only odd numbers:

num = 1 while num <=:    print(num    )= num + 2

Use of break:

Terminates the loop and terminates immediately when the loop encounters a break.

Prints an integer from 1 to 10, terminating the loop when num==4.

num = 1 while num <=:    print(num)    = num + 1    if num ==4:          Break
Usage of continue:

Jump out of the secondary loop, and then the loop continues without being affected.

This loop first is added once 1 and then to determine the printing, so the first time to print out is ' 2 ', when ' num=4 ', continue skip or end the cycle, do not perform continue results, so do not print ' 4 ', when the last cycle of ' num = 10 ', And the first time, is the first add 1, and then to determine the printing, so there will be ' 11 '.

num = 1 while num <=:    = num + 1    if num = = 4:        Continu E    print(num)

Python_ Loop expression

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.