python process control and exception

Table of contents

Boolean type

Use of Boolean type

process control 

if statement

while loop

for loop

The difference between while loop and for loop

range statement

range statement and for loop

variable scope

break和continue

abnormal

foreword

exception capture

abnormal transitivity

Boolean type

Boolean type: mainly used to represent the logic in real life.

Use of Boolean type

Syntax: variable name = Boolean type literal

Notice:

  • There are two types of bool type literals (True: True, False: False)
  • True is essentially a number, recorded as 1, and False as 0
  • The boolean type can not only be obtained by definition, but also can be obtained by comparing the contents of the comparison operator
  • The first letter of True and False in Boolean type must be capitalized
#定义变量存储布尔类型的数据
flag=True
print(f"flag变量的内容是:{flag},类型是{type(flag)}")
#flag变量的内容是:True,类型是<class 'bool'>

process control 

Preface: In the process control, according to the space (generally four spaces) to determine which process the statement belongs to.

if statement

#单分支
if 要判断的条件:
    条件成立时要做的事情

#双分支
if 条件:
    满足条件要执行的事情
else:
    不满足要执行的条件

#多分支
if 条件1:
    满足条件1要执行的语句
elif 条件2:
    满足条件2要执行的语句
else:
    条件都不满足要执行的事情

Notice:

  • Else does not need to judge the condition, it will be executed when the if condition is not met 
  • Do not forget spaces and indents
  • The judgments in multi-branch are mutually exclusive and sequential, and the order is from beginning to end. If the former is satisfied, the latter will be ignored.
height=int(input("请输入您的身高(cm):"))
vip_level=int(input("请输入您的VIP等级(1-5):"))
if height<120:
    print("身高小于120cm,可以免费")
elif vip_level>3:
    print("VIP级别大于3,可以免费")
else:
    print("不好意思,掏钱吧你")

while loop

while 条件:
    条件满足时需要做的事

Notice:

  • The condition must be bool type True to continue, False to terminate
  • Do not forget spaces and indents
  • Plan the loop termination condition, otherwise infinite loop 

Case: print i from 0 to 10 

i=0
while i<=10:
    print(f"i为{i}")
    i+=1

for loop

The difference between while loop and for loop

  • The loop condition of the while loop is custom, control the loop condition by yourself
  • The for loop is a polling mechanism that processes a batch of content one by one
for 临时变量 in 待处理数据集:
    循环满足时执行的语句

Notice:

  • Unlike the while loop, the for loop cannot define the loop condition, and can only take out the content from the processed data set for processing 
  • The statements inside the for loop are also indented with spaces
name="hello world"
for x in name:
    print(x)

Understanding: Take out the contents of the name in turn, including spaces

range statement

Preface: The data set to be processed in the for loop syntax is strictly called a sequence type; a sequence type refers to a type whose contents can be taken out one by one, including strings, lists, tuples, etc.

Syntax 1: range(num)

Meaning: Get a sequence of numbers starting from 0 and ending with num (excluding num itself)

Syntax 2: range(num1,num2)

Meaning: Get a sequence of numbers starting from num1 and ending with num2 (excluding num2 itself)

Syntax 3: range(num1,num2,step)

Meaning: Get a sequence of numbers starting from num1 and ending with num2 (excluding num2 itself). The step size between numbers is based on step (step defaults to 1 and can be negative)

range statement and for loop

#让for循环执行10次
for x in range(10):
    具体的语句

The role of the range statement: quickly lock the number of executions of the for loop by cooperating with the for loop

variable scope

for i in range(10):
    print(f"for循环内部的i:{i}")
print(f"for循环外部的i:{i}")#可以访问到

Notice:

  • Temporary variables, in terms of programming specifications, are only limited to the inside of the for loop. If the temporary variable is accessed outside the for loop, it can actually be accessed, but it is not allowed to do so in the programming specification.
  • Therefore, if you want to access the temporary variable of the for loop externally, try to define the variable before the for, so that the code will not be affected, and our program is more in line with the specification

break和continue

  • continue: interrupt this loop and go directly to the next loop
  • break: directly end the current loop

Note: In a nested loop, continue and break can only work in the loop where it is located, and cannot work on the upper loop

abnormal

Meaning: When an error is detected, the python interpreter cannot continue to execute, but some error prompts appear instead. This is the so-called exception, which is what we often call bug

foreword

  • There is no perfect program in the world. During the running of any program, there may be exceptions (bugs) that may cause the program to fail to run perfectly; To prepare and process possible bugs in advance, we call this behavior exception capture
  • We don't want the entire program to crash because of a small bug, so we need exception capture
  • The role of exception capture is to assume that an exception will occur somewhere in advance, and to prepare in advance. When an exception does occur, there are follow-up means to remedy it.

exception capture

grammar:

try:
    可能出现异常的代码
except (异常类型1,异常类型2,异常类型3) as 异常别名:
    print("异常")
else:
    没有异常需要执行的代码
finally:
    无论如何都要执行的代码

Notice:

  • If try catches an exception, the following program continues to execute
  • Except is the parent class of all exceptions. If the type after except is except, the following commands can be omitted
  • except is followed by a tuple, or only one exception type (no need to write commas and parentheses)
  • finally indicates the code to be executed regardless of whether there is an exception, such as closing the file
  • else and finally are optional
try:
    f=open("D:/test/app.txt","r",encoding="UTF-8")
except:
    print("出现异常了,文件不存在")
print("后续的代码继续执行")

abnormal transitivity

Preface: When functions are nested, when an exception occurs in function 1 and the exception is not handled, the exception will be passed to function 2. When function 2 and function 2 do not catch the exception, the main function will catch the exception , which is the transitivity of the exception

def func1():
    print("func1开始执行")
    num=1/0 #肯定有异常
    print("func1结束执行")
def func2():
    print("func2开始执行")
    func1()
    print("func2结束执行")
def main():
    func2()
main()

Note: exceptions can be passed, he will pass from the bottom function all the way up

Guess you like

Origin blog.csdn.net/m0_60027772/article/details/132116389