So, I ask an user for input. Then I assign that input to variable var to use it for the math module:
var = "pi"
print(math.var)
But then I get an attribute error. How could I solve this problem?
So, I ask an user for input. Then I assign that input to variable var to use it for the math module:
var = "pi"
print(math.var)
But then I get an attribute error. How could I solve this problem?
You get an attribute error because Python will try to access the var
attribute of the math
module, which does not exist. It will not try to evaluate var
as a variable.
Assuming that var
is the name of some member of the math
module (or some other module, or an object), you could use the getattr
builtin to get the value of that attribute.
>>> var = "pi"
>>> getattr(math, var)
3.141592653589793
You could use getattr()
for this. Here we're constantly asking user for math
's attribute until he provide existing one.
import math
inp = input('Enter math attribute: ')
while not getattr(math, inp, None):
inp = input('Please enter valid attribute: ')
print(getattr(math, inp))
Output:
python3 get_math.py
Enter math attribute: adc
Please enter valid attribute: pi
3.141592653589793
Check work fine:
import math
var = 'pi'
print(math.__getattribute__(var))
Output:
3.141592653589793