Python from Beginner to Master Chapter 4 (Program Control Structure)

Note: Part of the content of this chapter is mentioned in Chapters 2 and 3. The mentioned parts may not be repeated in detail here (such as single-branch judgment statements and two-branch judgment statements).

1. Logical operations

1. and (with/and)

(1) If both conditions are met at the same time, True is returned.

(2) As long as one of them is not satisfied, False will be returned.

2. or (or/or)

(1) As long as one of the two conditions is met, True is returned.

(2) If both conditions are not met, False is returned.

3. not (not/not)

(1) If the condition is met, return False.

(2) If the condition is not met, True is returned.

4. Example:

(1) Example 1:

# 练习1: 定义一个整数变量 age,编写代码判断年龄是否正确
age = 100

# 要求人的年龄在 0-120 之间
if age >= 0 and age <= 120:
    print("年龄正确")
else:
    print("年龄不正确")

# 练习2: 定义两个整数变量 python_score、c_score,编写代码判断成绩
python_score = 50
c_score = 50

# 要求只要有一门成绩 > 60 分就算合格
if python_score > 60 or c_score > 60:
    print("考试通过")
else:
    print("再接再厉!")

(2) Example 2:

# 练习: 定义一个布尔型变量 `is_employee`,编写代码判断是否是本公司员工
is_employee = True

# 如果不是提示不允许入内
if not is_employee:
    print("非公勿内")

2. Branch statement

1. Multi-branch statements

if condition 1:

        Code executed when condition 1 is met

        ……

elif condition 2:

        When condition 2 is met, the code to be executed

        ……

elif condition 3:

        When condition 3 is met, the code to be executed

        ……

else:

        When none of the above conditions are met, the code to be executed

        ……

holiday_name = "平安夜"

if holiday_name == "情人节":
    print("买玫瑰")
    print("看电影")
elif holiday_name == "平安夜":
    print("买苹果")
    print("吃大餐")
elif holiday_name == "生日":
    print("买蛋糕")
else:
    print("每天都是节日啊……")

Notice:

① Both elif and else must be used in conjunction with if and cannot be used alone.

②If, elif and else and their respective indented codes can be regarded as a complete code block.

2. Nesting of if statements

if condition 1:

        Condition 1 satisfies the executed code

        ……

    

        if condition 1 based on condition 2:

                When condition 2 is met, the code to be executed

                ……    

        

        # Processing if condition 2 is not met

        else:

                When condition 2 is not met, the code to be executed

        

        # Processing if condition 1 is not met

else:

        When condition 1 is not met, the code to be executed

        ……

①Example 1:

# 定义布尔型变量 has_ticket 表示是否有车票
has_ticket = True
# 定义整数型变量 knife_length 表示刀的长度,单位:厘米
knife_length = 20
# 首先检查是否有车票,如果有,才允许进行 安检
if has_ticket:
    print("有车票,可以开始安检...")
    # 安检时,需要检查刀的长度,判断是否超过 20 厘米
    # 如果超过 20 厘米,提示刀的长度,不允许上车
    if knife_length >= 20:
        print("不允许携带 %d 厘米长的刀上车" % knife_length)
    # 如果不超过 20 厘米,安检通过
    else:
        print("安检通过,祝您旅途愉快……")
# 如果没有车票,不允许进门
else:
    print("大哥,您要先买票啊")

②Example 2:

"""
1. 从控制台输入要出的拳 —— 石头(1)/剪刀(2)/布(3)
2. 电脑 随机 出拳 —— 先假定电脑只会出石头,完成整体代码功能
3. 比较胜负
"""
# 在Python中,要使用随机数,首先需要导入随机数的模块 —— “工具包”(建议在导入工具包时应该将导入的语句放在文件顶部)
# ● 导入模块后,可以直接在模块名称后面敲一个 . 然后按 Tab 键,会提示该模块中包含的所有函数
# ● random.randint(a, b) ,返回 [a, b] 之间的整数,包含 a 和 b
import random

# 从控制台输入要出的拳 —— 石头(1)/剪刀(2)/布(3)
print("石头(1)/剪刀(2)/布(3)")
player =int(input("请出拳:"))

# 电脑随机出拳
computer = random.randint(1,3)

# 比较胜负
# 如果条件判断的内容太长,可以在最外侧的条件增加一对大括号
# 再在每一个条件之间,使用回车,PyCharm 可以自动增加 8 个空格
if((player == 1 and computer == 2)
        or (player == 2 and computer == 3)
        or (player == 3 and computer == 1)):
    print("用户胜出!")
elif player == computer:
    print("平局")
else:
    print("电脑胜出!")

# 另一种写法
if (computer == player % 3 + 1 ):
    print("用户胜出!")
elif player == computer:
    print("平局")
else:
    print("电脑胜出!")

③The nested syntax format of if is no different from the previous one except for the indentation.

3. Loop statement - conditional loop

1. Basic use of while loop

(1) The function of a loop is to execute the specified code repeatedly.

(2) The most common application scenario of while loop is to let the executed code be executed repeatedly a specified number of times.

(3) Infinite loop: Due to the programmer's fault, he forgets to modify the judgment condition of the loop inside the loop, causing the loop to continue executing and the program cannot be terminated.

2. Counting methods in Python

(1) Natural counting method (starting from 1) - more in line with human habits

(2) Program counting method (starting from 0) - almost all programming languages ​​choose to start counting from 0 (except for special circumstances)

3. Format of conditional loop

while(<condition>):

        <Statement block 1>

        <Statement block 2>

① When the condition is True (true), execute statement block 1, and then judge the condition again. When the condition is False (false), exit the loop and execute statement block 2.

②Conditional loops are generally used like this: (the while statement and the indented part are a complete code block)

Initial condition setup - usually a counter for repeated execution

while condition (to determine whether the counter reaches the target number of times):

        What to do when the conditions are met 1

        When the conditions are met, do things 2

        What to do when the conditions are met 3

        ...(omission)...

    

        Process condition (counter + 1)

Note: After the loop ends, the value of the previously defined counter condition still exists.

③Example:

# 1. 定义重复次数计数器
i = 1

# 2. 使用 while 判断条件
while i <= 5:
    # 要重复执行的代码
    print("Hello Python")

    # 处理计数器 i
    i = i + 1

print("循环结束后的 i = %d" % i)

4. Loop calculation

(1) In program development, we usually encounter the need to use loops to repeat calculations. When encountering this need, you can:

① Define a variable above while to store the final calculation result.

②Inside the loop body, each loop uses the latest calculation results to update the previously defined variables.

(2) Example 1:

# 计算 0 ~ 100 之间所有数字的累计求和结果
# 0. 定义最终结果的变量
result = 0

# 1. 定义一个整数的变量记录循环的次数
i = 0

# 2. 开始循环
while i <= 100:
    print(i)

    # 每一次循环,都让 result 这个变量和 i 这个计数器相加
    result += i

    # 处理计数器
    i += 1

print("0~100之间的数字求和结果 = %d" % result)

(3) Example 2:

# 0. 最终结果
result = 0

# 1. 计数器
i = 0

# 2. 开始循环
while i <= 100:

    # 判断偶数
    if i % 2 == 0:
        print(i)
        result += i

    # 处理计数器
    i += 1

print("0~100之间偶数求和结果 = %d" % result)

5、break和continue

(1) break and continue are keywords specifically used in loops.

①break: When a certain condition is met, exit the loop and no longer execute subsequent repeated codes.

②continue: When a certain condition is met, subsequent repeated code will not be executed.

③break and continue are only valid for the current loop.

(2) During the loop, if you no longer want the loop to continue executing after a certain condition is met, you can use break to exit the loop.

i = 0

while i < 10:

    # break 某一条件满足时,退出循环,不再执行后续重复的代码
    # i == 3
    if i == 3:
        break

    print(i)

    i += 1

print("over")

(3) During the loop, if you do not want to execute the loop code after a certain condition is met, but do not want to exit the loop, you can use continue. (That is, in the entire loop, only certain conditions do not need to execute the loop code, while other conditions need to be executed)

i = 0

while i < 10:

    # 当 i == 7 时,不希望执行需要重复执行的代码
    if i == 7:
        # 在使用 continue 之前,同样应该修改计数器
        # 否则会出现死循环
        i += 1

        continue

    # 重复执行的代码
    print(i)

    i += 1

6. While loop nesting

(1) While nesting means - there is while inside while.

while condition 1:

        What to do when the conditions are met 1

        When the conditions are met, do things 2

        What to do when the conditions are met 3

        ...(omission)...

    

        while condition 2:

                What to do when the conditions are met 1

                When the conditions are met, do things 2

                What to do when the conditions are met 3

                ...(omission)...

    

                Processing condition 2

    

        Processing conditions 1

(2) Loop nesting drill - multiplication table:

# 定义起始行
row = 1

# 最大打印 9 行
while row <= 9:
    # 定义起始列
    col = 1

    # 最大打印 row 列
    while col <= row:

        # end = "",表示输出结束后,不换行
        # "\t" 可以在控制台输出一个制表符,协助在输出文本时对齐
        print("%d * %d = %d" % (col, row, row * col), end="\t")

        # 列数 + 1
        col += 1

    # 一行打印完成的换行
    print("")

    # 行数 + 1
    row += 1

4. Loop statement - traversal loop

1. Format of traversal loop

for <loop variable> in <traversal structure>:

        <statement block>

① The traversal loop can be understood as extracting elements one by one from the traversal structure, placing them in the loop variable, and executing a statement block once for each extracted element.

②The number of loop execution times of the for statement is determined based on the number of elements in the traversal structure.

③The traversal structure can be a string, file, range function or combined data type, etc. The more common ones are lists and tuples.

2. Iterate through each character of the string one by one

for c in "字符串":
    print(c)

3. Use the range function to specify the number of loops

range(a,b,s): Generate a sequence from a to b (excluding b) with s as the step size.

①When there is only one parameter x, range returns the sequence (0,1,…,x-1).

②When there are only two parameters x and y (x<y), range returns the sequence (x, x+1,...,y-1).

for i in range(4):
    print("第%d次循环" % (i + 1))

print("",end="\n")
for i in range(1,5):
    print("第%d次循环" % i)

4. Expansion mode of traversal loop

for <loop variable> in <traversal structure>:

        <Statement block 1>

else:

        <Statement block 2>

①After the for loop is executed normally, the program will continue to execute the contents of the else statement.

②The else statement is only executed when the normal execution of the loop is not interrupted by break, so statements to judge the execution of the loop can be placed in <Statement Block 2>.

for i in range(4):
    print("第%d次循环" % (i + 1))
else:
    print("循环正常结束")

print("",end="\n")
for i in range(1,5):
    print("第%d次循环" % i)
    if i == 3:
        break
else:
    print("循环正常结束")

5. Program exception handling

1. The concept of abnormality

(1) When the program is running, if the Python interpreter encounters an error (such as indentation error, division by 0 error), it will stop the execution of the program and prompt some error messages. This is an exception.

(2) The action of the program stopping execution and prompting an error message is usually called: raising an exception .

(3) When developing a program, it is difficult to handle all special situations in an all-round way. However, through exception capture, emergencies can be handled intensively to ensure the stability and robustness of the program.

2. Catching exceptions

(1) During program development, if you are not sure whether the execution of some code is correct, you can add try to catch exceptions.

(2) The simplest syntax format for catching exceptions:

try:

        Code to try to execute

except:

        Error handling

①The code you are trying to execute is code that is not sure whether it can be executed normally.

When an exception (error) occurs in the code you are trying to execute , execute the statement after the except reserved word , and the program will not stop running because of the error.

try:
    n = eval(input("请输入一个数字:"))
    print("输入数字的4次方值为:%d" % n ** 4)
except:
    print("输入错误!")  
    # 如果输入的不是数字,n ** 4将会出错,产生异常
    # 此时程序不会终止,而是转来执行except的语句

3. Error type capture

(1) When the program is executed, different types of exceptions may be encountered, and different responses need to be made for different types of exceptions. At this time, the error type needs to be captured.

(2) The syntax is as follows:

try:

        # Code to try to execute

        pass

except error type 1:

        # For error type 1, the corresponding code processing

        pass

except (error type 2, error type 3):

        # For error types 2 and 3, the corresponding code processing

        pass

except Exception as result:

        print("Unknown error %s" % result)

Note: When the Python interpreter throws an exception, the first word of the last line of the error message is the error type. (See the section "Understanding Errors" in Chapter 1)

try:
    num = int(input("请输入整数:"))
    result = 8 / num
    print(result)
except ValueError:
    print("请输入正确的整数")  # 输入字符串会产生ValueError
except ZeroDivisionError:
    print("除 0 错误")  # 输入数字0会产生ZeroDivisionError

4. Capture unknown errors

(1) During development, it is still difficult to predict all possible errors.

(2) If you want the program to not be terminated because the Python interpreter throws an exception regardless of any errors, you can add another except (as shown below).

except Exception as result:

        print("Unknown error %s" % result)

5. Complete syntax for exception capture

try:

        # Code to try to execute

        pass

except error type 1:

        # For error type 1, the corresponding code processing

        pass

except error type 2:

        # For error type 2, the corresponding code processing

        pass

except (error type 3, error type 4):

        # For error types 3 and 4, the corresponding code processing

        pass

except Exception as result:

        # Print error message

        print(result)

else:

        # Code that will be executed only if there is no exception

        pass

finally:

        # Code that will be executed regardless of whether there is an exception or not

        print("Code that will be executed regardless of whether there is an exception or not")

try:
    # 提示用户输入一个整数
    num = int(input("输入一个整数:"))

    # 使用 8 除以用户输入的整数并且输出
    result = 8 / num

    print(result)
except ValueError:
    print("请输入正确的整数")
except Exception as result:
    print("未知错误 %s" % result)
else:
    print("尝试成功")
finally:
    print("无论是否出现错误都会执行的代码")

print("-" * 50)

6. Exception transmission

(1) When an exception occurs during the execution of a function/method , the exception will be passed to the calling party of the function/method . If there is still no exception handling after passing it to the main program, the program will be terminated.

(2) During development, exception capture can be added to the main function, and for other functions called in the main function, as long as exceptions occur in other functions, they will be passed to the exception capture of the main function, so there is no need to add exception capture in the code. A large number of exception captures can ensure the cleanliness of the code.

(3) Example:

①Define function demo1() to prompt the user to enter an integer and return

②Define function demo2() and call demo1()

③Call demo2() in the main program

def demo1():
    return int(input("请输入一个整数:"))


def demo2():
    return demo1()

try:
    print(demo2())
except ValueError:
    print("请输入正确的整数")
except Exception as result:
    print("未知错误 %s" % result)

7. Throw an exception

(1) During development, in addition to the Python interpreter throwing exceptions when code execution errors occur, exceptions can also be actively thrown based on the unique business needs of the application (there are no code errors in the program, but errors will occur when applied in practice. At this time, you need to actively throw an exception).

(2) Python provides an Exception class. During development, if you want to throw an exception to meet specific business needs, you can create an Exception object and then use the raise keyword to throw the exception object.

(3) Example:

①Define the input_password function to prompt the user to enter a password

②If the user input length < 8, throw an exception

③If the user input length>=8, return the entered password

def input_password():

    # 1. 提示用户输入密码
    pwd = input("请输入密码:")

    # 2. 判断密码长度 >= 8,返回用户输入的密码
    if len(pwd) >= 8:
        return pwd

    # 3. 如果 < 8 主动抛出异常
    print("主动抛出异常")
    # 1> 创建异常对象 - 可以使用错误信息字符串作为参数
    ex = Exception("密码长度不够")

    # 2> 主动抛出异常
    raise ex


# 提示用户输入密码
try:
    print(input_password())
except Exception as result:
    print(result)

Guess you like

Origin blog.csdn.net/Zevalin/article/details/135433498