0

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?

User
  • 29
  • 6

3 Answers3

2

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
tobias_k
  • 81,265
  • 12
  • 120
  • 179
0

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
Filip Młynarski
  • 3,534
  • 1
  • 10
  • 22
0

Check work fine:

import math

var = 'pi'

print(math.__getattribute__(var))

Output:

3.141592653589793
Dmitry Leiko
  • 3,970
  • 3
  • 25
  • 42