from关键字和Python中的示例

Python from关键字

from是python中的一个关键字(区分大小写),用于从模块中导入特定部分,例如函数,类等。

from关键字的语法

    from module_name import specific_section1, specific_section1, ...

这里, specific_section(s) 是函数,类等的名称。

示例

    # 从数学模块导入阶乘
    from math import factorial

from关键字的Python示例

示例1:通过从数学模块导入阶乘来查找数字的阶乘。

# python代码演示示例
# 来自关键字

# 查找数字的阶乘 
# 通过从数学模块导入阶乘。 

# 从数学模块导入阶乘
from math import factorial

num = 4

# 打印阶乘
print("factorial of ", num, " is = ", factorial(num))

输出结果

factorial of  4  is =  24

示例2:通过从数学模块中导入两个函数阶乘和平方根来查找数字的阶乘和平方根。

# python代码演示示例
# 来自关键字

# 查找数字的阶乘和平方根 
# 通过导入两个函数factorial和sqrt 
# 来自数学模块。

# 从数学模块导入阶乘和平方根
from math import factorial, sqrt

num = 4

# 打印阶乘 & square root
print("factorial of ", num, " is = ", factorial(num))
print("square root of ", num, " is = ", sqrt(num))

输出结果

factorial of  4  is =  24
square root of  4  is =  2.0