table of Contents
Modules and functions and exception catching
The formal and actual parameters of the function
Exception 1: ZeroDivisionError
Exception 3: KeyboardInterrupt and EOFError
Modules and functions and exception catching
Modules and functions
1. Define the module name can not be Kaito with numbers
2. Cannot duplicate the name of the default module
The module file must be executed in the same directory or the module file is valid in the lib file
Examples:
print("*"*20)
hello
print("*"*20)
Create a functional module that can be called import
Contains a function function in the module, the function returns 20 *
Create Module
"""
介绍模块的作用
里面包含的功能
作者的联系方式
"""
star = "**********"
"star变量的作用是赋了10个星号"
def p_star():
"我的作用返回20个星号"
return "*"*20
Call module
import printstar
#print(help(printstar))
#print(dir(printstar))
#print(help(printstar.p_star))
star20 = printstar.p_star()
print(printstar.star)
print(" hello")
print(star20)
Here we can also use the help () and dir () functions to view the module functions
The formal and actual parameters of the function
The function realizes the division calculation of two values
def division(a,b):
num = a / b
return num
numa = int(input("请输入被除数:"))
numb = int(input("请输入除数:"))
endnum = division(numa,numb)
print(endnum)
Actual parameters: numa, numb
Formal parameters: a, b
Exception catch
benefit:
When our program is running, some exceptions will inevitably occur, such as the user's intentional input error, which causes a function of the program to crash. We capture the exception of the program to correct or warn the user's input.
structure:
try:
Captured substatement
except (exception type 1, type 2, ...):
pass/print
Exception 1: ZeroDivisionError
In the above division program, when we output a divisor of 0, the program reports an error
How can we control it so that he does n’t report an error?
def division(a,b):
num = a / b
return num
numa = int(input("请输入被除数:"))
numb = int(input("请输入除数:"))
try:
endnum = division(numa,numb)
print(endnum)
except ZeroDivisionError:
print("除数不能为0")
Exception 2: ValueError
Also when we enter letters, the program will also report an error
def division(a,b):
num = a / b
return num
try:
numa = int(input("请输入被除数:"))
numb = int(input("请输入除数:"))
endnum = division(numa,numb)
print(endnum)
except ZeroDivisionError:
print("除数不能为0")
except ValueError:
print("请输入正常的整数")
Exception 3: KeyboardInterrupt and EOFError
We directly press CTRL + D, the program will report the following error
We directly press CTRL + C, the program will report the following error
def division(a,b):
num = a / b
return num
try:
numa = int(input("请输入被除数:"))
numb = int(input("请输入除数:"))
endnum = division(numa,numb)
print(endnum)
except ZeroDivisionError:
print("除数不能为0")
except ValueError:
print("请输入正常的整数")
except (KeyboardInterrupt,EOFError):
pass
pass directly ends