表达式math.sqrt()是否必要?

5 python math

我今天刚开始玩python; 我完全不知道自己在做什么.下面是我编写的用于显示素数的小程序,它看起来工作得很好而且非常快:

import math
N = input('List primes up to: ')
N = int(N)
for i in range(3,N,2):
    for d in range(2,int(math.sqrt(i))):
        if i%d==0:
            break
else :
    print(str(i))
Run Code Online (Sandbox Code Playgroud)

sqrt()除非我保留在math.sqrt()零件和零件中,否则该功能不起作用import math.此外,当我在shell中键入内容时,它只有在我使用math.sqrt()而不是sqrt().

所以......对于简单的事情来说,长篇大论的问题是:#include <math.h>我可以使用某种类型的-esque行,对于shell和程序文件(尽管每行可能有不同的行)所以我可以避免math.每次都输入' '部分我想用数学模块中的函数吗?(这是一个模块,对吗?)(因为我发誓我已经阅读过帽子使用的程序sqrt()而不是math.sqrt().但也许不是.)

Ósc*_*pez 4

好吧,你可以像这样直接导入一个函数:

from math import sqrt
# elsewhere
sqrt(n)
Run Code Online (Sandbox Code Playgroud)

您甚至可以从模块导入所有内容:

from math import *
Run Code Online (Sandbox Code Playgroud)

这样您就不必使用模块前缀并说math.sqrt. 但是,建议您这样做,以避免两个模块定义同名函数时可能发生的名称冲突(这种情况在实践中经常发生)。简而言之,这是首选方式:

import math
# elsewhere
math.sqrt(n)
Run Code Online (Sandbox Code Playgroud)