我想在Python和不知道解决这个为什么它不工作...为什么此输入为int不能正常工作?
x = int(input("Enter the value of X: "))
y = int(input("Enter the value of Y: "))
print(y)
input("...")
的问题是Y.我确切地输入不带引号如下:“2 * X” 我已经尝试了很多东西并且研究了很多东西(就像我之前所做的那样),但是我在这里难倒了。也许是因为我是这样一个基本的用户。
我想在Python和不知道解决这个为什么它不工作...为什么此输入为int不能正常工作?
x = int(input("Enter the value of X: "))
y = int(input("Enter the value of Y: "))
print(y)
input("...")
的问题是Y.我确切地输入不带引号如下:“2 * X” 我已经尝试了很多东西并且研究了很多东西(就像我之前所做的那样),但是我在这里难倒了。也许是因为我是这样一个基本的用户。
好像你正在阅读与python2书籍,但你已经安装python3。在python2中,input
等于eval(raw_input(prompt))
,这就是为什么当您输入2 * x
时,它会评估表达式的值并将其分配给y
。
在python3,input
只是获取用户输入的字符串,而不是eval
,作为一个表达式,你可能需要明确eval
,这是a bad practice和dangerous:
In [7]: x=2
In [8]: y=eval(input('input Y:'))
input Y:3*x
In [9]: y
Out[9]: 6
总而言之,使用:raw_input
在py2,input
in py3,从不在您的产品代码中使用eval
(或python中的input
)。
python3的情况如何? – GreenAsJade
python3没有'raw_input' – inspectorG4dget
@zhangxaochen:非常感谢。这就是我需要做的。 – Gavin
这是因为2 * x
不是整数。但是,当你评估它时,但这不是input
所做的。
所以,你要的是这样的:
x = int(input("Enter the value of X: "))
y = int(input("Enter the value of Y: ")) * x
然后,输入2
,当问Y
我明白了,但那对我在做的事不起作用。如何通过用户输入将表达式作为Y的值输入?例如“x-4”,“2 * x”等等。 – Gavin
@Gavin:如果你真的想输入表达式,你必须使用'eval',但这是不明智的(如果我输入命令使计算机崩溃?)。所以你可以做的是保持字典中的符号映射到函数中,然后你可以在手动解析输入之后提取各种函数。 – inspectorG4dget
@ G4adget:谢谢,这是个好主意。我发现我需要使用eval(),但为什么使用eval不好(通俗地说)? – Gavin
您不能通过表达字符串字面来int
这种方式。你可以这样做,而不是,
x = int(input("Enter the value of X: "))
y = x * 2
print(y)
input("...")
如果相反,需要在乘法中使用另一个值,你可以做,
x = int(input("Enter the value of X: "))
y = int(input("Enter the value of Y: "))
z = x * y
print(z)
input("...")
我明白了,但那对我所做的事不起作用。如何通过用户输入将表达式作为Y的值输入?如“x-4”,“2 * x”等等。 – Gavin
'int()'需要一个* literal *数字,而不是一个表达式 – mhlester
我有点困惑,我用type来检查(2 + 2),它表示int。我怎样才能输入一个表达呢? – Gavin