简体   繁体   English

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

[英]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.

相关问题 如何修复 ValueError :无法将字符串转换为浮点数:在 Python 中 - how to fix ValueError :could not convert string to float: in Python 如何使用tkinter修复Python中的“ ValueError:无法将字符串转换为float:” - How to fix “ValueError: could not convert string to float:” in Python with tkinter 如何修复“ValueError:无法将字符串转换为浮点数”? - How to fix “ValueError: could not convert string to float”? 如何修复“ValueError:无法将字符串转换为浮点数” - How to fix “ValueError: could not convert string to float” 如何修复此错误:ValueError:无法将字符串转换为浮点数:'A' - How to fix this error: ValueError: could not convert string to float: 'A' ValueError:无法将字符串转换为浮点数:'F' python - ValueError: could not convert string to float: 'F' python ValueError:无法将字符串转换为float'jpg'Python - ValueError: could not convert string to float 'jpg' Python Python中的“ValueError:无法将字符串转换为float” - “ValueError: could not convert string to float” in Python ValueError:无法将字符串转换为float - python - ValueError: could not convert string to float - python Python:ValueError:无法将字符串转换为浮点型:'4623634 0' - Python: ValueError: could not convert string to float: '4623634 0'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM