Methods of Python Process Control statements

Source: Internet
Author: User
Tags case statement
People often say that life is a continuous choice of the process: some people have no choice, there is only one way to go; some people better, you can choose one; some people with good ability or good family can have more choices, and some people in the confusion of life will be in the same circles, can't find the direction. For those who believe in God, it is as if God had set the course for us in advance, as well as the many tribulations that God and the Immortals have in place in advance of the journey of the Scriptures. Programming languages can simulate all aspects of human life, and programmers are like gods and immortals. The execution of special keywords in a programming language, which consists of process control statements.
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, is the execution of a row of rows, do not need special instructions. The main point here is the branching and looping statements.
One, 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). The spoke statements provided in Python are: if. Else statement that does not provide a switch: Case statement. If.. The Else statement has several forms:
Single branch:
If judging condition:
code block
If the code block for a single branch statement has only one statement, you can write the if statement and code on the same line:
If judging condition: one sentence code
Instance: Determine if the specified UID is root user

UID = 0if UID = = 0:  print ("root")


You can also write this:

UID = 0if UID = = 0:print ("root")


Output Result: Root
Dual Branch:
If judging condition:
code block
Else
code block
Example: Print user identity based on user ID

UID = 100if UID = = 0:  print ("root") Else:  print ("Common user")


Output Result: Common user
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.8level = Int (score) if level >=:  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 (' Le Vel E ')


Output Result: Level B
Description
When the expression in the "judging condition" above can be an arbitrary expression, it can be any type of data object instance. As long as the true value test for the final return result of the condition is true, it means that the corresponding code block is executed, otherwise the condition is not established and the next condition needs to be judged.
Second, the circular statement
Loop statements are used when we need to execute a code statement or block of code multiple times. The looping statements provided in Python are: while loops and for loops. 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.
1. While loop
Basic form
The basic form of a while loop statement 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: cyclic printing of numbers 0-9

Count = 0while Count <= 9:  print (count, end= ")  count + = 1


Output results: 0 1 2 3 4 5 6 7 8 9
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.
While.. Else
Statement form:
While judging condition:
code block
Else
code block
The code block in else will execute if the while loop is executed normally, and if the while loop is broken, the code block in else will not execute.
Instance 1:while loop Normal execution ends (the statement in else will be executed)

Count = 0while count <=9:  print (count, end= ")  count + = 1else:  print (' End ')


Execution results are: 0 1 2 3 4 5 6 7 8 9 End
Instance 2:while the loop is interrupted (the statement in else is not executed)

Count = 0while count <=9:  print (count, end= ")  if Count = = 5:    break  count + = 1else:  print (' End ')


Output results: 0 1 2 3 4 5
2. For loop
A For loop is typically used to traverse a sequence (such as list, tuple, range, str), a collection (such as set), and a mapping object (such as Dict).
Basic form
Basic format for the For loop:
For temp variable in iterate object:
code block
Example: traversing an element in a 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
For...else
With while: Else basically consistent, no longer repeat.
3. Circular 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.
Circular Control Statement Description
Break terminates the entire loop
Contine skip this cycle and perform the Next loop
Pass Pass statement is an empty statement, just to maintain the integrity of the program structure, 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 the loop control statement

For I in range:  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 with 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
4. Loop nesting
Loop nesting refers to embedding another loop inside a loop body.
Example 1: Printing a 99 multiplication table through a while loop

j = 1while 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, ten):  for I in range (1, j+1):    print ('%d*%d=%d '% (i, J, i*j), end= ' \ t ')    i + = 1  print ( )  J + = 1


Output Result:
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81

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.