Python conditional loop

Source: Internet
Author: User

If statement:

If

Elif

Else

Half the representation of the IF statement in Python:

1 ifp_1:2     Print('is 1')3 elifp_2:4     Print('is 2')5 Else:6     Print('is 3')

If the condition satisfies p_1 will output is 1, if the condition does not meet p_1 satisfies p_2 will output is 2, if the above two conditions are not satisfied will be executed the third result is 3, so if the key statement is: if elif else.

Attention:

    • Each condition is followed by a colon:, which represents the block of statements to be executed after the condition is next satisfied.
    • A statement block that uses indentation to divide a statement block and the same indent number.
    • There are no switch-case statements in Python.

Example: guessing numbers

1 #!/usr/bin/env python2 #_*_ coding:utf-8 _*_3 __author__='Zhangkai'4 5Age = 5#variable sets the age value6  whileTrue:#Loops7age = Int (input ('Please guess the age of the dog:'))#int is the input converted into a numeric type8     ifAge < 5:9         Print('The age you entered is too small! ')Ten     elifAge >5: One         Print('The age you entered is too big! ') A     Else: -         Print('Congratulations, you guessed it! ') -Exit ()#Exit System

Execution Result:

/library/frameworks/python.framework/versions/3.5/bin/python3.5/users/zhangkai/pycharmprojects/oldboy12_3.5/ day01/test.py Please guess the age of the dog:1 The age you entered is too small! Please guess the age of the dog:2 The age you entered is too small! Please guess the age of the dog:6 The age you entered is too big! Please guess the age of the dog:5 #猜对了之后退出Congratulations, you guessed it! Process finished with exit code 0

Cycle

The looping statements in Python have for and while.

Control structure diagram of the Python loop statement:

While loop

The general form of a while statement in Python:

 while Judging Condition:    statements

Also note the colon and indent, in addition, there is no do in Python: While loop

Example: Using the while loop to find 1-100 and:

# !/usr/bin/env python # _*_ coding:utf-8 _*_ __author__ ' Zhangkai '  # variable sum == 1 while counter <=N:    + = counter     +=1print("sumof 1-100:")

Operation Result:

/library/frameworks/python.framework/versions/3.5/bin/python3.5/users/zhangkai/pycharmprojects/oldboy12_3.5/ day01/test.py1-100:5050Process finished with exit code 0

For statement

A python for loop can traverse any sequence of items, such as a list or a string.

The general format for the For loop is as follows:

 for  in < sequence >:    < declarations >else:    < declaration >

Examples of Python loop loops:

1>>> a = ["C","C + +","Perl","Python"]2>>> forIinchA:3...Print(i)4 ... 5 C6C++7 Perl8 Python9>>>

The break statement is used to jump out of the current loop body:

1 #!/usr/bin/env python2 #_*_ coding:utf-8 _*_3 __author__='Zhangkai'4A = ["C","C + +","Perl","Python"]5  forIinchA:6     ifi = ='C':7         Print('the list contains C')8          Break   #jump out of this cycle9     Print('nice work.')Ten Else: One     Print('there is no C in the list') A Print('hehe')

After the execution of the script, the first loop to determine whether the condition C is not in the list, and then go down to see the break immediately jumped out of the loop and then went to the "hehe", the results are as follows:

/library/frameworks/python.framework/versions/3.5/bin/python3.5/users/zhangkai/pycharmprojects/oldboy12_3.5/ day01/test.py list contains C hehe process finished with exit code 0

Range () function

If you need to traverse a list of numbers, you can use the built-in function range (). He will generate a series:

 for  in range (5): ...   Print (i) ... 01234

You can also specify values for range ranges:

 for  in range (5,9): ...   Print  5678

You can also use range to specify a number to start with and specify a different increment (even negative; sometimes called a step).

 for  in range (0,10,3): ...   Print (i) ... 0369

You can also traverse the index of a sequence by combining the range () and Len () functions:

1>>> a = ['Mary','had','a','Little','Lamb']2>>> forIinchRange (len (a)):3...Print(i,a[1])4 ... 5 0 had61had72had83had94hadTen>>> forIinchRange (len (a)): One...Print(I,a[i]) A ...  - 0 Mary -1had the2a -3Little -4 Lamb

Create a list with the range () function:

>>> List (range (51, 2, 3, 4)

Brea and continue statements and else sub-statements in loops

The break statement can jump out of a for and while loop body. If you terminate from a for or while loop, any corresponding loop else blocks will not execute.

The continue statement is used to tell Python to skip the remaining statements in the current loop block and proceed to the next round of loops.

A looping statement can have an ELSE clause, which is executed when the exhaustion list (in a For loop) or the condition becomes false (in a while loop), but not when the loop is terminated by a break. The following is an example of a loop that searches for prime numbers:

1 #!/usr/bin/env python2 #_*_ coding:utf-8 _*_3 __author__='Zhangkai'4  forNinchRange (2,10):5      forXinchRange (2, N):6         ifn% x = =0:7             Print(N,'equals'X'*', n//x)8              Break9     Else: #循环没有找到的数字Ten         Print(N,'Is a prime number') One #Results A/library/frameworks/python.framework/versions/3.5/bin/python3.5/users/zhangkai/pycharmprojects/oldboy12_3.5/ day01/test.py -2 isa prime number -3 isa prime number the4 Equals 2 * 2 -5 isa prime number -6 equals 2 * 3 -7 isa prime number +8 equals 2 * 4 -9 equals 3 * 3 +  AProcess finished with exit code 0

Pass Statement

The pass statement does nothing. It only requires a statement in syntax but is used when the program does not require any action. For example:

 while True:      ... Pass #如果回车还会一直在等待状态

The smallest class:

class haha:      ... Pass

Python conditional loop

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.