python - 如何修复“ValueError:无法将字符串转换为浮点数:'East'”(Python)
问题描述
当用户输入“East”时,我希望输出为 -1 而不是“East”
East = -1
Xdirectioninput = float(input("Is the player South or East: "))
Xdirectioninput = (Xdirectioninput)
print (Xdirectioninput)
解决方案
这仅在 Python 2 中有效。它之所以有效,是因为在 Python 2 中,用户键入的响应input()
内容被评估为 Python 表达式。
但是你不能在 Python 3 中这样做。一种方法是设置一个带有方向的字典:
directions = {"East": -1.0, "South": -2.0}
Xdirectioninput = directions[input("Is the player South or East: ")]
推荐阅读
- javascript - Xpath:如果存在多个子项,则选择多个父项
- java - 为什么 Tomcat 会留下很多 CLOSE_WAIT 连接?
- javascript - Visual Studio Code:使用 Firefox ESR 调试 JavaScript
- markdown - pandoc 中有没有办法在代码块顶部包含文件名?
- ssl - 使用 StackExchange.Redis 与 Redis 建立 SSL 连接
- c# - 无法使用证书存储中的客户端证书,只能通过从文件加载
- android - 如何通过意图直接编辑而不是副本将 PDF 传递给 Android 上的 Adobe Reader?
- c# - RSA - 数据不能长于模数错误
- html - CKAN资源表单html“描述”字段,我如何/在哪里可以将其他字段更改为与描述相同的大小?
- gatsby - 使用 gatsby 创建新项目的命令不起作用