首页 > 解决方案 > 如何修复“ValueError:无法将字符串转换为浮点数:'East'”(Python)

问题描述

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

East = -1

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

print (Xdirectioninput)

标签: python

解决方案


这仅在 Python 2 中有效。它之所以有效,是因为在 Python 2 中,用户键入的响应input()内容被评估为 Python 表达式。

但是你不能在 Python 3 中这样做。一种方法是设置一个带有方向的字典:

directions = {"East": -1.0, "South": -2.0}
Xdirectioninput = directions[input("Is the player South or East: ")]

推荐阅读