"Python from small white to Daniel" the 8th chapter control statements

Source: Internet
Author: User
Tags terminates

There are three kinds of control statements in program design, namely, order, branch and Loop statement. The Python program manages the flow of the program through control statements to accomplish certain tasks. A program flow is made up of several statements, which can be a single statement or a compound statement. The control statements in Python have the following categories:

    • Branching statement: If

    • Looping statements: while and for

    • Jump statements: Break, continue, and return
Branch statements

Branching statements provide a control mechanism that allows the program to "judge the ability" to analyze problems like human brains. A branch statement is also called a conditional statement, which enables some programs to be selectively executed based on the values of certain expressions.

The branch statement in Python has only an if statement. If statement has three kinds of structure: if structure, if-else structure and elif structure three kinds.

If structure

Executes the statement group if the condition evaluates to true, otherwise executes the statement following the IF structure. The syntax structure is as follows:

if 条件 :  语句组

The example code for the If structure is as follows:

# coding=utf-8# 代码文件:chapter8/8.1.1/hello.pyimport sysscore = int(sys.argv[1]) # 获得命令行传入的参数 ①if score >= 85:    print("您真优秀!")if score < 60:    print("您需要加倍努力!")if (score >= 60) and (score < 85):    print("您的成绩还可以,仍需继续努力!")

For flexible input fractions (score) This example uses SYS.ARGV,SYS.ARGV to return a list of command-line arguments, as shown in line ① of code. SYS.ARGV[1] Returns the second element of the argument list because the first element (Sys.argv[0]) is the Python file name executed. Because of the string of elements in the argument list, you also need to use the INT function to convert the string to the int type. In addition, in order to use the SYS.ARGV command line argument list, you also need to start the file by import
SYS statement into the SYS module.

To do this, you need to open the Windows command prompt and enter the following instructions, as shown in 8-1.

python ch8.1.1.py 80

If the program needs to get the sys.argv[0] element The return value is ch8.1.1.py.

Note The program code that uses SYS.ARGV to get a list of command-line arguments is not available in Python
The shell environment runs to get a list of parameters.

If-else structure

Almost all computer languages have this structure, and the format of the structure is basically the same, the statement is as follows:

if 条件 :   语句组1 else :   

When the program executes to the IF statement, the condition is evaluated first, if the value is true, the statement group 1 is executed, then the ELSE statement and statement Group 2 are skipped, and the following statement continues. If the condition is false, the statement group 1 is ignored and the statement set 2 is executed, and then the following statement continues.

The sample code for the IF-ELSE structure is as follows:

# coding=utf-8# 代码文件:chapter8/ch8.1.2.pyimport sysscore = int(sys.argv[1])  # 获得命令行传入的参数if score >= 60:    print("及格")    if score >= 90:        print("优秀")else:print("不及格")

The sample execution procedure is referenced in section 8.1.1, which is not mentioned here.

ELIF structure

The ELIF structure is as follows:

if 条件1 :     语句组1 elif 条件2 :    语句组2elif 条件3 :    语句组3 ... elif 条件n :    语句组nelse :    语句组n+1

As you can see, the elif structure is actually a multi-layered nesting of the if-else structure, and its obvious feature is that only one group of statements is executed in multiple branches, and none of the other branches are executed, so this structure can be used in a branch with multiple judgment results.

The sample code for the ELIF structure is as follows:

# coding=utf-8# 代码文件:chapter8/ch8.1.3.pyimport sysscore = int(sys.argv[1])  # 获得命令行传入的参数if score >= 90:    grade = ‘A‘elif score >= 80:    grade = ‘B‘elif score >= 70:    grade = ‘C‘elif score >= 60:    grade = ‘D‘else:    grade = ‘F‘print("Grade = " + grade)

The sample execution procedure is referenced in section 8.1.1, which is not mentioned here.

Ternary operator substitution--conditional expression

In the previous learning of operators, there was no reference to the Java-like ternary operator [^1]. To provide similar functionality, Python provides a conditional expression with the following conditional expression syntax:
[^1]: syntax form of ternary operator: condition? Expression 1:
Expression 2, when the condition is true, expression 1 returns, otherwise expression 2 is returned.

>   表达式1 if 条件 else 表达式2

Where the condition evaluates to True, the expression 1 is returned, otherwise the expression 2 is returned.

The conditional expression example code is as follows:

# coding=utf-8# 代码文件:chapter8/ch8.1.4.pyimport sysscore = int(sys.argv[1])  # 获得命令行传入的参数result = ‘及格‘ if score >= 60 else ‘不及格‘print(result)

The sample execution procedure is referenced in section 8.1.1, which is not mentioned here.

From the example, the conditional expression is actually a if-else structure, and the normal if-else structure is not an expression, there is no return value, and the conditional expression compares the conditional judgment, and there is a return value.

Looping statements

The Loop statement enables the program code to execute repeatedly. Python supports two types of looping constructs: while and for.

While statement

The while statement is a loop structure that is judged first, in the following format:

while 循环条件 :     语句组 [else:        语句组]

While Loop has no initialization statement, the number of cycles is not known, as long as the loop condition is satisfied, the loop will always execute the loop body. The while loop can have an else statement, and the Else statement is described in detail in section 8.3.

Let's look at a simple example with the following code:

# coding=utf-8# 代码文件:chapter8/ch8.2.1.pyi = 0while i * i < 100_000:    i += 1print("i = {0}".format(i))print("i * i = {0}".format(i * i))

The output results are as follows:

i = 317i * i = 100489

The purpose of the above program code is to find the largest integer with a square number less than 100_000. There are a few points to note when using a while loop, while a while looping condition statement can only write an expression and is a Boolean expression, so if a loop variable is required in the loop body, the loop variable must be initialized before the while statement. In this example, I is assigned a value of 0, and then inside the loop body must change the value of the loop variable through the statement, otherwise a dead loop will occur.

Tips
For readability, both integers and floating-point numbers can be added with multiple 0 or underscores to improve legibility, such as 000.01563 and _360_000, and neither format affects actual values. The underscore is usually every three bits plus one.

For statement

The For statement is the most widely used and most powerful loop statement. There is no C-style for statement in the Python language, and its for statement is equivalent to the enhanced for Loop statement in Java, which is used only to traverse the sequence, including strings, lists, and tuples.

The general format for the for statement is as follows:

for 迭代变量 in 序列 :  语句组[else:        语句组]

A "sequence" means that all the types of the implementation sequence can use a for loop. An iteration variable is an element that is taken from an iteration in a sequence and then executes the loop body. The For loop can also have an else statement, and the Else statement is described in detail in section 8.3.

The sample code is as follows:

# coding=utf-8# 代码文件:chapter8/ch8.2.2.pyprint("----范围-------")for num in range(1, 10):  # 使用范围    ①    print("{0} x {0} = {1}".format(num, num * num))print("----字符串-------")#  for语句for item in ‘Hello‘:    ②    print(item)# 声明整数列表numbers = [43, 32, 53, 54, 75, 7, 10]   ③print("----整数列表-------")#  for语句for item in numbers:    ④       print("Count is : {0}".format(item))

Output Result:

----范围-------1 x 1 = 12 x 2 = 43 x 3 = 94 x 4 = 165 x 5 = 256 x 6 = 367 x 7 = 498 x 8 = 649 x 9 = 81----字符串-------Hello----整数列表-------Count is : 43Count is : 32Count is : 53Count is : 54Count is : 75Count is : 7Count is : 10

The above code, section ①, the range (1, 10) function is the Create range (range) object, and its value is 1≤range (1, 10)
\< 10, with a step of 1 and a total of 10 integers. The range is also an integer sequence, which is described in detail in section 8.4.

The code ② line is a looping string hello, and the string is also a sequence, so you can use a For loop variable.

The code ③ line is a list of integers defined, and the list is described in detail in the 9th chapter later in this article. The code ④ line is the Traverse list numbers.

Jump statement

Jump statements can change the order of execution of the program, which allows the program to jump. Python has 3 types of jump statements: Break, continue, and return. This section focuses on the use of break and continue statements. Return will be described in later chapters.

Break statement

The break statement can be used for the while and for loop structure described in the previous section, which is forced to exit the loop body and no longer executes the remaining statements in the loop body.

Here is an example of the following code:

# coding=utf-8# 代码文件:chapter8/ch8.3.1.pyfor item in range(10):    if item == 3:        # 跳出循环        break    print("Count is : {0}".format(item))

In the above program code, when the condition item
When ==3 executes the break statement, the break statement terminates the loop. The range (10) function omits the start parameter, which starts from 0 by default. The results of the program run are as follows:

Count is : 0Count is : 1Count is : 2
Continue statements

The continue statement is used to end the loop, skipping statements that have not yet been executed in the loop body, and then judging the termination condition to determine whether to continue the loop.

Here is an example of the following code:

# coding=utf-8# 代码文件:chapter8/ch8.3.2.pyfor item in range(10):    if item == 3:        continue    print("Count is : {0}".format(item))

In the above program code, when the condition item
When the ==3 executes the continue statement, the continue statement terminates the loop, the statement after the continue in the loop body is no longer executed, and then the next loop, so there is no 3 in the output. The results of the program run as follows:

Count is: 0Count is: 1Count is: 2Count is: 4Count is: 5Count is: 6Count is: 7Count is: 8Count is: 9
Else statements in while and for

When you introduce the while and for loops in the previous 8.2 sections, it is also mentioned that they all have the else statement, which differs from the else in the IF statement. The else here is code that runs at the normal end of the loop body and does not execute when the loop is interrupted, and break, return, and exception throws interrupt the loop. The Else statement in the loop is shown in flowchart 8-2.

The sample code is as follows:

# coding=utf-8# 代码文件:chapter8/ch8.3.3.pyi = 0while i * i < 10:    i += 1    # if i == 3:    #     break    print("{0} * {0} = {1}".format(i, i * i))else:    print(‘While Over!‘)print(‘-------------‘)for item in range(10):    if item == 3:        break    print("Count is : {0}".format(item))else:    print(‘For Over!‘)

The results of the operation are as follows:

1 * 1 = 12 * 2 = 43 * 3 = 94 * 4 = 16While Over!-------------Count is : 0Count is : 1Count is : 2

The break statement in the preceding code is commented in the while loop, so it goes into the else statement, so the last output while
over!. In the For loop, when the break statement executes when the condition is met, the program does not go into the Else statement and finally does not output a for
over!.

Scope of Use

In the previous learning process need to use the scope, the scope in Python type is range, representing an integer sequence, create scope object using the range () function, the range () function syntax is as follows:

range([start,] stop[, step])

The three parameters are all integer types, where start is the start value, which can be omitted, indicating starting from 0; stop is the ending value; step is the step. Note Start
≤ integer sequence takes value \< stop, step step can be negative, you can create a descending sequence.

The sample code is as follows:

# coding=utf-8# 代码文件:chapter8/ch8.3.4.pyfor item in range(1, 10, 2):        ①    print("Count is : {0}".format(item))print(‘--------------‘)for item in range(1, -10, -3):  ②    print("Count is : {0}".format(item))

The output results are as follows:

Count is : 1Count is : 3Count is : 5Count is : 7Count is : 9--------------Count is : 0Count is : -3Count is : -6Count is : -9

The above code ① line is to create a range, the step is 2, contains the elements see the output, there are 5 elements. The code ② line is to create a descending range, the step is-3, contains the elements of the output, there are 4 elements, the elements contained in the output results.

Summary of this chapter

By learning the contents of this chapter, the reader can learn about the control statements of the Python language, including the branch statement if, the Loop statement (while and for), and the jump statement (break and Continue). Finally, the scope is introduced.

Companion video

Http://edu.51cto.com/topic/1507.html

Supporting source code

Http://www.zhijieketang.com/group/8

Ebook

Https://yuedu.baidu.com/ebook/5823871e59fafab069dc5022aaea998fcc2240fc

Author Micro-blog: @tony_ dongsheng br/> Email:[email protected]

Python Reader service QQ Group: 628808216

"Python from small white to Daniel" the 8th chapter 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.