I was making a simple calculator:
import math
number1 = input("Enter a number: ")
number2 = input("Enter a number: ")
result = math.lcm(int(number1), int(number2))
print(result)
when I got the error in the title. This works in the shell and even code as simple as
import math
math.lcm(10, 20)
gives me the error.
Well, let's take a look at the documentation for math.lcm to see why it sometimes exists and sometimes doesn't exist!
What's it says? New in version 3.9.
Looks like your code works when run with python 3.9, and doesn't work when run with python 3.8 or older.
On the other hand, math.gcd exists since version 3.5. If you need an lcm function in python 3.5, 3.6, 3.7 or 3.8, you can write it this way:
import math
def lcm(a,b):
return (a * b) // math.gcd(a,b)
So lcm is in math since 3.9, and gcd is in math since 3.5. What if your python version is even older than that?
In older versions, gcd wasn't in math, but it was in fractions. So this should work:
import fractions
def lcm(a,b):
return (a * b) // fractions.gcd(a,b)
Please let me refer you to the kind user who asked that exact question:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With