Python Basics (ii)--flow control statements

Source: Internet
Author: User
Tags case statement

The Process Control statements in a programming language fall into the following categories:

    • Sequential statements
    • Branch statements
    • Looping statements

Where the order statement does not need a separate keyword to control, that is, in order to follow the sequence of one line of execution , do not need special instructions.

The following are mainly descriptions of the branching and looping statements:

True and false judging criteria in Python:

Python only the final result of the Judgment statement: non- 0 , non-empty, non- None , the result is true

1 , branch statements

A conditional branching statement is a block of code that determines which branch to execute by the execution result (true/false) of one or more statements (judging conditions).

Python the branch statements provided in are: If.. else statement that does not provide a switch: Case statement.

If.. The Else statement has several forms:

1.1 Single branch:

If judging condition:

code block

If the code block of a single branch statement has only one statement, you can if The statement and code are written on the same line:

If judging condition: one sentence code

Example:

A = 1
b = 5
c = 10
if a <= b <= C:
Print(' 1 <= 5 <= ')

Output:

1 <= 5 <= 10

There is only one statement in the code block that can be rewritten as:

A = 1
b = 5
c = 10
if a <= b <= c: print(' 1 <= 5 <= ')

Output:

1 <= 5 <= 10

1.2 Dual Branch:

If judging condition:

code block

Else

code block

Example:

A = 1
b = 5
if a >= b :
Print(' A greater than B ')
Else
Print(' a less than B ')

Output Result:

A is less than B

1.3 Multi-branch:

If judgment condition 1:

Code Block 1

Elif Judgment Condition 2:

Code Block 2

...

Elif Judgment Condition N:

Code block n

Else

Default code block

Example: Print letter grades based on student scores

Score = 88.8

level = Int (score% 10)

If level >= 10:

Print (' Level A + ')

elif level = = 9:

Print (' Level A ')

elif level = = 8:

Print (' Level B ')

elif level = = 7:

Print (' Level C ')

elif level = = 6:

Print (' Level D ')

Else

Print (' Level E ')

Output Result: Level B

Note :

When the expression in the "judging condition" above can be an arbitrary expression, it can be any type of data object instance. Only if the true value of the final return result of the condition is tested to true indicates that the condition is valid and the corresponding code block is executed Otherwise the condition is not set and the next condition needs to be judged .

2 , looping statements

Loop statements are used when we need to execute a code statement or block of code multiple times.

There are 2 types of looping statements available in Python: While loop (common) and for loop (used for known loop count).

It is important to note that there is no do in Python . while loop .

In addition, there are several loop control statements that control the loop execution process: Break, continue, and pass.

2.1. while Loop

Basic form

2.1.1 While Loop statement Base statement

The basic form is as follows:

While judging condition:

code block

Executes the code of the loop body when the return value of the given judgment condition evaluates to True , otherwise exits the loop body .

Example: loop-Print the number 0-9

Count = 0

While Count <= 9:

Print (count, end= ")

Count + = 1

Output results: 0 1 2 3 4 5 6 7 8 9

2.1.2 while dead Loop

While the judgment condition of the while is always true, the code in the while loop body loops forever

While True:

Print ("This is a dead loop")

Output Result:

It's a dead loop.

It's a dead loop.

It's a dead loop.

...

You can now terminate the run with CTRL + C.

2.1.3 while. Else

Statement form:

While judging condition:

code block

Else

code block

Else the code blocks in the while the loop is executed properly when executed, if while Loop is Break interrupted, Else the code block in is not executed.

Example 1:while loop normal execution End (the statement in else will be executed)

Count = 0

While Count <=9:

Print (count, end= ")

Count + = 1

Else

Print (' End ')

Execution results are: 0 1 2 3 4 5 6 7 8 9 End

Example 2:while a loop is interrupted (the statement in else is not executed)

Count = 0

While Count <=9:

Print (count, end= ")

if Count = = 5:

Break

Count + = 1

Else

Print (' End ')

Output results: 0 1 2 3 4 5

2.2. for Loop

for loops are typically used to traverse a sequence ( such as list,tuple,range,str) , Collection ( such as set) and Mapping Objects ( e.g. dict).

Basic form

2.2.1. For loop basic format:

For temp variable in iterate object:

code block

Example: traversing an element in the Print List

names = [' Tom ', ' Peter ', ' Jerry ', ' Jack ']

For name in Names:

Print (name)

For sequences, iterations are also done through the index:

names = [' Tom ', ' Peter ', ' Jerry ', ' Jack ']

For I in range (len (names)):

Print (Names[i])

Execution Result:

Tom

Peter

Jerry

Jack

2.2.2 For...else

With while: else is basically the same, and the Else statement executes only at the end of the normal execution of the For loop, and if the For loop is popped out, the Else statement is not executed.

2.3. loop control Statements

A loop control statement can change the execution of a program in the loop body, such as breaking a loop, skipping the loop.

Loop control Statements

Description

Break

Jump out of the current layer loop and not jump out of layers at once

Contine

Skip this loop and continue with the next loop of this layer

Pass

Pass statement is an empty statement, just to maintain the integrity of the program structure, equivalent to placeholder, there is no special meaning.

Pass statements are not used only in circular statements, but also in branch statements.

Example 1: Traverse all numbers in the 0-9 range and print out the odd number in a loop control statement

For I in range (10):

If I% 2 = = 0:

Continue

Print (I, end= ")

Output results: 1 3 5 7 9

Example 2: Print the first 3 elements of a list through a loop control statement

names = [' Tom ', ' Peter ', ' Jerry ', ' Jack ', ' Lilly ']

For I in range (len (names)):

If I >=3:

Break

Print (Names[i])

Output Result:

Tom

Peter

Jerry

2.4. Looping nesting

Loop nesting refers to embedding another loop inside a loop body.

Example 1: Printing a 99 multiplication table through a while loop

j = 1

While J <= 9:

i = 1

While I <= J:

Print ('%d*%d=%d '% (i, J, i*j), end= ' \ t ')

i + = 1

Print ()

J + = 1

Example 2: Printing a 99 multiplication table with a for loop

For j in range (1, 10):

For I in range (1, j+1):

Print ('%d*%d=%d '% (i, J, i*j), end= ' \ t ')

i + = 1

Print ()

J + = 1

Note: There are no self-increment and decrement operations in Python similar to C, because objects of numeric types are immutable types in Python and cannot be changed in-place

Python Basics (ii)--flow control statements

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.