Python jumps out for loop continue and break program

Source: Internet
Author: User

Use for statement
Example 6.3 uses a for statement

The code is as follows Copy Code

#!/usr/bin/python
# Filename:for.py

For I in range (1, 5):
Print I
Else
print ' For loop are over '

Output
$ python for.py
1
2
3
4
The For loop are over

Jump out for Loop

Continue

The code is as follows Copy Code
# Encoding=utf-8

For x in range (10):
If x==5:
Continue

Print X

The above loop uses continue to jump out of this cycle, so only when the x==5 out of this cycle, and then continue next, so the print X statement only in the x==5 when the other values are executed to the

Break

The code is as follows Copy Code

# Encoding=utf-8
For x in range (10):
If x==5:
Break

Print X

The break loop used above, so the entire for loop is jumped out of the x==5, so the print X statement terminates only when it hits 4.

Other instances

# First: Ask for prime numbers between 50-100

The code is as follows Copy Code

Import Math
For I in range (50, 100 + 1):
For j in range (2, int (math.sqrt (i)) + 1):
If I% j = 0:
Break
Else
Print I

# Second: Put else's position in the same indent as if.

The code is as follows Copy Code

Import Math
For I in range (50, 100 + 1):
For j in range (2, int (math.sqrt (i)) + 1):
If I% j = 0:
Break
Else
Print I

# Third: Add a break statement after else.

  code is as follows copy code

Import Math
for I in range (1):
    to J in range (2, int (math.sqrt (i)) + 1):
   & nbsp;    if I% j = 0:
            break
        Else:
             print I
            break

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.