Article directory
1. Abnormal
Opening a non-existent file will raise an exception
FileNotFoundError: [Errno 2] No such file or directory: 'D:/file that does not exist.txt'
f=open(file="D:/不存在的文件.txt",mode="r", encoding='utf-8')
print(f.read())
(1) Exception capture
You can use exception capture to make the program execute normally
try:
f=open(file="D:/不存在的文件.txt",mode="r", encoding='utf-8')
except:
print("文件不存在") # 输出:文件不存在
Catch all exceptions
Method 1
try:
1/0 # 可替换为其他异常
except:
print("捕获到了异常") # 捕获到了异常
law two
try:
1/0 # 可替换为其他异常
except Exception as x:
print(x) # division by zero
print("捕获到了异常") # 捕获到了异常
(2) Catch specified exceptions
There are many types of exceptions, such as FileNotFoundError, NameError, ValueError, ZeroDivisionError
print(x) # NameError: name 'x' is not defined
a="str"
i=int(a) # ValueError: invalid literal for int() with base 10: 'str'
print(1/0) # ZeroDivisionError: division by zero
So it can be caught according to the exception type
try:
print(x)
except NameError as y: # 定义任意变量y用于接收错误信息
print(y) # name 'x' is not defined
print("这是NameError异常") # 这是NameError异常
(3) Multiple except clauses
A try statement may contain multiple except clauses to handle different specific exceptions.
If an exception occurs during the execution of the try clause, the rest of the try clause will be ignored, that is, at most one branch will be executed.
If the exception type matches the name after except, then the corresponding except clause will be executed.
The following program will just output: This is NameError
try:
print(x) # NameError: name 'x' is not defined(非输出)
a = "str"
i = int(a) # ValueError: invalid literal for int() with base 10: 'str'(非输出)
print(1 / 0) # ZeroDivisionError: division by zero(非输出)
except NameError as n:
print("This is NameError")
except ValueError as v:
print("This is ValueError")
except ZeroDivisionError as z:
print("This is ZeroDivisionError")
(4) raise throws an exception
You can use raise to continue throwing an exception after outputting the specified statement
If raise is added to the exception that is not the first exception thrown, no exception will be thrown
Throw the specified exception
x=5
if x>3:
raise Exception("引发了异常,x比3大了")
(5) Handle multiple exceptions at the same time
An except clause can handle multiple exceptions at the same time, and these exceptions will be placed in a parenthesis to become a tuple. In the try statement, if there is an exception that satisfies the tuple, the except statement will be executed.
try:
print(1 / 0)
except (NameError,ValueError,ZeroDivisionError) as nvz:
print(nvz) # division by zero
print("NameError/ValueError/ZeroDivisionError") # NameError/ValueError/ZeroDivisionError
(6) try/except...else
else must be placed after all except clauses
try:
print(1/0)
except:
print("引发了异常")
else:
print("继续执行")
# 输出: 引发了异常
try:
print(1/5)
except:
print("引发了异常")
else:
print("继续执行")
"""
0.2
继续执行
"""
(7) The try-finally statement
executes finally regardless of whether an exception occurs
(8) Transitivity of exceptions
f2 is called in the main function, and f2 calls f1. An exception is thrown in f1, return to f2, and then return to the main function, we can handle the exception (except) in the main function, which is the transitivity of the exception
def f1():
print("this is f1")
num=1/0
print("f1 end")
def f2():
print("this is f2")
f1()
print("f2 end")
def main():
try:
f2()
except Exception as e:
print(e)
main() # 调用
"""
this is f2
this is f1
division by zero
"""
2. error
Errors generally refer to syntax errors/parsing errors
The following is an error in the if statement without a colon. The parser points out the line in error and marks an arrow at the location of the first error found.
x=6
if x>5
print(1)
3. Module
(1) Import the entire time module, including all methods in it
import time
time.sleep(5) # 程序暂停5秒
from time import *
sleep(5) # 程序暂停5秒
(2) Only import the sleep method of time
from time import sleep
sleep(5) # 程序暂停5秒
(3) Alias
import time as t
t.sleep(5) # 程序暂停5秒
from time import sleep as t2
t2(5) # 程序暂停5秒
(4) Custom module
① The following is an addition function and call
def add(a,b):
print(a+b)
add(2,3) # 5
You can change it to a module
and create a new module file
write function code
Import the module in the main function, you can use
②When multiple functions with the same name are called, the latter will overwrite the former
Call the subtraction operation of module46, output: -1
③When importing a module, the module content will be executed by default
Output: 1
④If you do not want to execute part of the content of the module when importing the module
It will output when it is run directly in the module ,
but it will not output anything when it is imported.
Principle: When running in the module, the current module is regarded as the main function (name=main), and if the judgment is true, the print statement will be executed. When imported (equivalent to calling), the name becomes module45.py (instead of main), if the judgment is not true, the statement of print will not be executed
⑤Control import * through __all__
All content in module45.py can be called through from module45 import *
But in module45.py, the access to * can be restricted through the list, that is, the accessible range of * can be redefined
[Example]
module45.py
__all__ = ["f1"] # 只允许调用f1,f2访问不到
def f1():
print(1)
def f2():
print(2)
print(3)
if __name__ == "__main__":
print(4)
main.py
from module45 import *
f1()
f2()
(when running main) output:
3
1
First output 3, when the import is imported,
the if statement will be executed to judge that it is not true, and it will not output 4.
When f1 is called, the content of the all declaration can be called normally.
When the output 1 is called, f2 will have the following exception
4. Package
A package is similar to a folder and can contain multiple py files
(select Python package/Python Package)
(1) The import of the package
has an addition operation in the package
Import: import package name. module name
call: package name. module name. method name
(2) Use from to import and call
Import: from package import module
call: module.method
from nihao import module
module.add(2,3) # 5
(3) Specify function import Import
: from package. module import method
call: method
from nihao.module import add
add(2,3) # 5
(4) Use all control *
(The init file is created by default to identify that this folder is a package)
Use all restrictions in init *
Here only allowed to import the module module in the package
* Import all modules in the package by default
output:
(5) Third-party packages
[Installation method 1]
Take the installation of numpy package as an example
command prompt input
pip install numpy
If the download speed is too slow, try the following methods
If there is no installation prompt for the guide package, the installation is considered successful
[Installation method 2]
Install in the settings of PyCharm
If the installation speed is slow, try the following methods
[Combined training]
[untie]
str_util.py
def str_reverse(s):
return s[::-1]
def substr(s,x,y):
return s[x:y]
file_util.py
def print_file_info(file_name):
f=None
try:
f=open(file_name,"r",encoding="UTF-8")
except Exception as e:
print(f"文件不存在,异常原因为:{
e}")
else:
print(f.read())
finally:
if f:
f.close() # 如果不要求使用finally,可以将close放到else中
def append_to_file(file_name,data):
f=open(file_name,"a",encoding="UTF-8")
f.write(data)
f.close() # close带有flush功能
main.py (arbitrary test data)
from my_utils import str_util
from my_utils import file_util
print(str_util.str_reverse("hello"))
print(str_util.substr("hello",0,3))
file_util.print_file_info("D:/ceshi.txt")
file_util.append_to_file("D:/ceshi.txt","hehe")