[英]How to fix "ValueError: could not convert string to float: 'East'" (Python)
When the user enters "East" I want the output to be -1 not "East"当用户输入“East”时,我希望输出为 -1 而不是“East”
East = -1
Xdirectioninput = float(input("Is the player South or East: "))
Xdirectioninput = (Xdirectioninput)
print (Xdirectioninput)
That will only work in Python 2. It works because in Python 2, what the user types in response to input()
is evaluated as a Python expression.这仅适用于 Python 2。它之所以有效,是因为在 Python 2 中,用户在响应input()
被评估为 Python 表达式。
But you can't do that in Python 3. One way to do it is to set up a dictionary with directions:但是在 Python 3 中你不能这样做。一种方法是设置一个带有方向的字典:
directions = {"East": -1.0, "South": -2.0}
Xdirectioninput = directions[input("Is the player South or East: ")]
I think conditional statement would be good solution.我认为条件语句将是一个很好的解决方案。 You could make a code as follows:您可以编写如下代码:
Xdirectioninput = input("Is the player South or East: ")
if Xdirectioninput == 'East':
Xdirection = -1
print(Xdirection)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.