-2

I have a function in which I want to print the value of these math data, how can I make that work?

import math

string = str(input('pi,tau or e'))

print(math.string)

I want it to also work when I randomly input sqrt(3) or something like that, so if statements would be a lot of work if it is possible to do it otherwise. I get the following error:

Traceback (most recent call last):
  File "C:/Users/danny/Documents/TU Delft/Introduction to programming/assignment3_1.py", line 41, in <module>
    print(math.string)
AttributeError: module 'math' has no attribute 'string'
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

3 Answers3

1

Use the built-in function getattr:

import math

string = str(input('pi,tau or e'))

print(getattr(math, string))

From the documentation:

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

Community
  • 1
  • 1
Maximouse
  • 4,170
  • 1
  • 14
  • 28
  • Recommend `print(eval('math.'+string))` instead, to also cover `sqrt(3)` as asked. – Wim Lavrijsen Nov 21 '19 at 08:36
  • @WimLavrijsen `eval` is not safe. The user might type `e,__import__("some_module").do_something()` and Python would execute the function. Abstract syntax trees are better: https://docs.python.org/3/library/ast.html – Maximouse Nov 21 '19 at 09:02
0

What is happening is that Python thinks that math.string is a function in the math module. According to docs.python.org, there is a function in the math module, and to get this to work, you want to do something like the following code:


import math
string = input("pi, tau or e")
if string == "pi":
  print(math.pi)
elif string == "tau":
  print(math.tau)
elif string == "e":
  print(math.e)
else:
  #String here for if a user inputs an answer that isn't pi, tau or e.

This takes the input, check if it's pi, tau or e and then prints pi, tau or e. Another thing, algebra doesn't work when dealing with strings. Python will not expect the function to be algebra, so it will look for 'string' and fail. I'm not sure where you got this idea from though. You can, however, define pi, tau or e.


pi=math.pi
tau=math.tau
e=math.e

import math

string = input('pi,tau or e')
if string == "pi":
  print(pi)
elif string == "tau":
  print(tau)
elif string == "e":
  print(e)
else:
  #string here for fail.

OnlyTrueJames
  • 47
  • 1
  • 8
0
import math

your_input = input('Enter pi, tau or e:\n')

if your_input == "e":
    print(math.e)

elif your_input == "pi":
    print(math.pi)

elif your_input == "tau":
    print(math.tau)

else:
    print("You entered ", your_input)
k2a
  • 71
  • 1
  • 6