0

好的,所以我试图基本上阻止某人在该字段中输入字符串值:

#User selection
print("Which program would you like to run?")
print("(Type '9' if you wish to exit the menu)")
selection = int(input())
print()

#Security statement followed by case statement
while selection <= 0 or selection >= 10:
    try:
        print("That is an invalid selection, please input a proper selection.")
        print("Which program would you like to run?")
        selection = int(input())
        print()
    except ValueError:
        print("Cmon man")

简单明了,它没有运行。我尝试重新组织所有内容,但没有找到合适的解决方案。已经环顾了将近一个小时。对这个问题没有帮助。有善良的灵魂吗?

顺便说一句,忽略case语句部分,这甚至还没有写出来。

PS 只是继续获得通常的“字符串不是数字 durr”响应

(“ValueError:int() 的无效文字,基数为 10:'为什么'”)

PPS 问题已被指出。我显然愚蠢地忘记了大声笑...感谢您的帮助。

4

1 回答 1

0

try...except没有涵盖最初的用户输入,因此ValueError实际上并没有被捕获。如果您输入int定义的边界外 (0 >= x >= 10) 作为第一个输入,那么您可以看到这些try...except块正在工作。

您需要重构代码,以便第一个输入请求位于您的 try 块和循环中,或者将现有输入请求包装在另一个try...except.

此外,作为旁注,input()可以采用一个字符串参数,该参数将作为提示显示给用户。

selection = int(input("Which program would you like to run? "))
于 2014-04-28T04:04:04.360 回答