如何避免空输入

无程序

我对 Python 非常陌生,我编写了这部分代码,用户必须在 3 个值选项之间进行选择。我可以检查用户插入的值是否小于零或大于最大值,但我无法检查用户是否插入任何值。

user.choose_action()
choice = input("    Choose action:")
while int(choice) < 1 or int(choice) > 3:
    print("    " + "The choice must be between 1 and 3. Retry.")
    choice = input("    Choose action:")
index = int(choice) - 1
if index == 0:
    other things

此代码在 int(choice) < 1 或 int(choice) > 3: ValueError: invalid literal for int() with base 10: ' ' 时抛出,据我所知,抛出此错误是因为我正在尝试转换空值到int。我尝试使用不同的解决方案进行修复,例如:

while int(choice) < 1 or int(choice) > 3 or choice == '' :
     rest of the code

或者

try:
    choice = input("    Choose action:")
except SyntaxError:
    y = None

或者

while int(choice) < 1 or int(choice) > 3 or choice is None :

但似乎没有任何效果!我知道这可能很愚蠢,但我现在不明白为什么!我究竟做错了什么?

库奇凯姆

更改条件的顺序:

while choice == '' or int(choice) < 1 or int(choice) > 3 :
     rest of the code

不同之处在于,由于短路,如果输入为空,则它不会尝试评估会引发错误的其他条件。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章