我正在制作一个简单的计算器:
import math
number1 = input("Enter a number: ")
number2 = input("Enter a number: ")
result = math.lcm(int(number1), int(number2))
print(result)
当我收到标题错误时。这可以在 shell 中工作,甚至代码就像这样简单
import math
math.lcm(10, 20)
给我错误。
最佳答案
好吧,让我们看一下 math.lcm
的文档,看看为什么它有时存在有时不存在!
它说什么? 3.9 版本中的新增功能。
看起来您的代码在使用 python 3.9 运行时可以工作,而在使用 python 3.8 或更早版本运行时则不起作用。
快速修复,python 3.5 到 3.8
另一方面,math.gcd
从 3.5 版本开始存在。如果你需要Python 3.5、3.6、3.7或3.8中的lcm
函数,你可以这样写:
import math
def lcm(a,b):
return (a * b) // math.gcd(a,b)
快速修复,python <3.5
因此,从 3.9 开始,lcm
属于 math
,而 gcd
从 3.5 开始属于 math
。如果你的 python 版本比这个版本更旧怎么办?
In older versions, gcd
wasn't in math
, but it was in fractions
。所以这应该有效:
import fractions
def lcm(a,b):
return (a * b) // fractions.gcd(a,b)
我使用的是哪个Python版本?
请让我向您介绍一下提出该问题的好心用户:
- StackOverflow:How do I check what version of Python is running my script?
- Using the python 3.9 interpreter in Visual Studio Code [感谢用户:Jill Cheng 提供此链接]
关于python - math.lcm() 给出错误 "Module ' math' 没有 'lcm' 成员”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64977905/