我有一个函数要在其中打印这些数学数据的值,我该如何使其工作?
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'
当我随机输入sqrt(3)或类似的内容时,我希望它也能工作,因此,如果可以的话,if语句会做很多工作。 我收到以下错误:
mysql> select 'abc123' + 0;
+--------------+
| 'abc123' + 0 |
+--------------+
| 0 |
+--------------+
mysql> select '123abc' + 0;
+--------------+
| '123abc' + 0 |
+--------------+
| 123 |
+--------------+
答案 0 :(得分:1)
使用内置功能getattr
:
import math
string = str(input('pi,tau or e'))
print(getattr(math, string))
从文档中:
getattr(object, name[, default])
返回
object
的命名属性的值。name
必须是字符串。如果字符串是对象属性之一的名称,则结果是该属性的值。例如,getattr(x, 'foobar')
等效于x.foobar
。如果指定的属性不存在,则返回default
(如果提供),否则引发AttributeError
。
答案 1 :(得分:0)
正在发生的事情是Python认为math.string是math模块中的一个函数。根据docs.python.org的说法,math模块中有一个函数,要使其正常工作,您需要执行以下代码:
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.
这将接受输入,检查它是pi,tau还是e,然后打印pi,tau或e。 另一件事,在处理字符串时,代数不起作用。 Python不会期望该函数为代数,因此它将查找“字符串”并失败。我不确定您是从哪里得到这个想法的。但是,您可以定义pi,tau或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.
答案 2 :(得分: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)