如何修复“ValueError:无法将字符串转换为浮点数:'East'”(Python)

当用户输入“East”时,我希望输出为 -1 而不是“East”


East = -1


Xdirectioninput = float(input("Is the player South or East: "))

Xdirectioninput = (Xdirectioninput)


print (Xdirectioninput)


拉莫斯之舞
浏览 279回答 2
2回答

qq_遁去的一_1

这仅适用于 Python 2。它之所以有效,是因为在 Python 2 中,用户输入的响应内容input()被评估为 Python 表达式。但是在 Python 3 中你不能这样做。一种方法是设置一个带有方向的字典:directions = {"East": -1.0, "South": -2.0}Xdirectioninput = directions[input("Is the player South or East: ")]

哈士奇WWW

我认为条件语句将是一个很好的解决方案。您可以编写如下代码:Xdirectioninput = input("Is the player South or East: ")if Xdirectioninput == 'East':    Xdirection = -1print(Xdirection)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python