【发布时间】:2015-01-18 20:20:06
【问题描述】:
我是整个编码方面的新手……所以就这样吧。 只是想写一个简单的猜数字游戏,还要做输入验证。所以只接受整数作为输入。我已经想出了如何清除字母字符,所以我可以将数字转换为整数。输入浮点数时遇到问题。我无法将浮点数转换为整数。任何帮助表示赞赏。正如我所说,我在这个编码的第 3 天,所以试着理解我的小知识。提前致谢。
这是我的主程序中的函数。
def validateInput():
while True:
global userGuess
userGuess = input("Please enter a number from 1 to 100. ")
if userGuess.isalpha() == False:
userGuess = int(userGuess)
print(type(userGuess), "at 'isalpha() == False'")
break
elif userGuess.isalpha() == True:
print("Please enter whole numbers only, no words.")
print(type(userGuess), "at 'isalpha() == True'")
return userGuess
如果我使用 4.3(或任何浮点数)作为输入,则会出现以下错误。
Traceback (most recent call last):
File "C:\\*******.py\line 58, in <module>
validateInput()
File "C:\\*******.py\line 28, in validateInput
userGuess = int(userGuess)
ValueError: invalid literal for int() with base 10: '4.3'
【问题讨论】:
-
您可以尝试使用 try-except 链接您的转化。如果您的 int() 转换产生 ValueError 异常,您可以尝试使用 float() 转换输入,然后将浮点值舍入或截断为整数。
-
一些旁注:你几乎不想检查
if spam == False:,只是if not spam:。在elif中,您无需重新检查与if测试相反的结果——您已经知道isalpha为真,因为您知道它不是假的。所以,只需使用else:。如果你从这个函数返回userGuess,你几乎肯定不需要它是global。最后,您不需要break只需点击return;你可以直接在if块中return userGuess。
标签: python python-3.x data-conversion floating-point-conversion