# divide defdivide(a, b): if b == 0: raise ValueError("Cannot divide by zero.") return a / b
1、在 test.py中使用mymath模块
1 2 3 4 5 6 7 8 9 10 11 12
import mymath
print("Addition of 5 and 3:", mymath.add(5, 3)) print("Subtraction of 5 and 3:", mymath.subtract(5, 3)) print("Multiplication of 5 and 3:", mymath.multiply(5, 3)) print("Division of 5 and 3:", mymath.divide(5, 3))
# 输出 Addition of 5and3: 8 Subtraction of 5and3: 2 Multiplication of 5and3: 15 Division of 5and3: 1.6666666666666667
2、使用别名:
1 2 3 4 5 6
import mymath as my
print("Addition of 5 and 3:", my.add(5, 3)) print("Subtraction of 5 and 3:", my.subtract(5, 3)) print("Multiplication of 5 and 3:", my.multiply(5, 3)) print("Division of 5 and 3:", my.divide(5, 3))
3、导入具体的函数:
1 2 3 4 5 6
from mymath import add, divide
print("Addition of 5 and 3:", add(5, 3)) print("Subtraction of 5 and 3:", subtract(5, 3)) print("Multiplication of 5 and 3:",multiply(5, 3)) print("Division of 5 and 3:", divide(5, 3))
另外由于我们只导入了add和divide函数,所以在执行substract时会报错:NameError: name 'subtract' is not defined
4、使用*导入全部
1 2 3 4 5 6
from mymath import *
print("Addition of 5 and 3:", add(5, 3)) print("Subtraction of 5 and 3:", subtract(5, 3)) print("Multiplication of 5 and 3:",multiply(5, 3)) print("Division of 5 and 3:", divide(5, 3))