Python 尝试并排除(类型错误)
我想做的是在我的程序中创建一个菜单式的开始,让用户选择是验证代码还是生成代码。代码如下所示:Python 尝试并排除(类型错误),python,try-catch,typeerror,except,Python,Try Catch,Typeerror,Except,我想做的是在我的程序中创建一个菜单式的开始,让用户选择是验证代码还是生成代码。代码如下所示: choice = input("enter v for validate, or enter g for generate").lower() try: choice == "v" and "g" except TypeError: print("Not a valid choice! Try again") restartCode() *#pre-defined funct
choice = input("enter v for validate, or enter g for generate").lower()
try:
choice == "v" and "g"
except TypeError:
print("Not a valid choice! Try again")
restartCode() *#pre-defined function, d/w about this*
prompt = "Enter v for validate, or g for generate >"
choice = input(prompt).strip().lower()[:1] # take at most 1 character
while choice not in ("v", "g"):
print("Not a valid choice! Try again.")
choice = input(prompt).strip().lower()[:1]
因此,我希望我的程序输出print语句,并在用户输入除“v”或“g”以外的其他字符(不包括输入这些字符的大写版本)时执行定义的功能。
我的try和except函数有问题,但每当用户输入这两个字符以外的其他字符时,代码就结束了。try
choice = input("enter v for validate, or enter g for generate").lower()
if (choice == "v") or (choice == "g"):
#do something
else :
print("Not a valid choice! Try again")
restartCode() #pre-defined function, d/w about this*
但是,如果您真的想坚持使用try/except,您可以存储所需的输入,并与它们进行比较。该错误将是KeyError而不是TypeError
choice = input("enter v for validate, or enter g for generate").lower()
valid_choices = {'v':1, 'g':1}
try:
valid_choices[choice]
#do something
except:
KeyError
print("Not a valid choice! Try again")
restartCode() #pre-defined function, d/w about this
您对
try/except
的作用感到困惑<代码>尝试/例外在可能出现错误时使用。不会引发任何错误,因为程序中的所有内容都是有效的。只有当代码中存在执行错误时,才会引发错误。错误不仅仅是在需要时提出的
但是,如果用户没有输入有效的选项,则希望显示错误。您需要使用if/else
逻辑,然后自己打印错误。作为旁注,choice==“v”和“g”
行不测试choice是否等于'v'
或'g'
。它测试选项i是否等于v,以及字符串'g'
是否为“truthy”。你敬重的话
如果变量=值且为真
我很确定那不是你想要的。下面是我将如何重新编写您的代码
if choice.lower() in {"v", "g"}: # if choice is 'v' or 'g'
# do stuff
else: # otherwise
print("Not a valid choice! Try again") # print a custom error message.
问题不在于您的
try
和except
,而在于您正在使用try
和except
。try
块中的代码不会给您错误,因此将永远不会触发除外。您希望使用if
语句
此外,您的条件仅检查choice==“v”
,因为它的计算结果为(choice==“v”)和“g”
,并且“g”
是长度不为0的字符串,所以总是“truthy”(在布尔上下文中为true)。任何和
True都是不变的,因此只有第一个测试有任何意义。执行此测试的最佳方法是使用
中的
最后,您可以并且应该使用while
循环重复提示,直到用户输入有效条目
总而言之,你想要这样的东西:
choice = input("enter v for validate, or enter g for generate").lower()
try:
choice == "v" and "g"
except TypeError:
print("Not a valid choice! Try again")
restartCode() *#pre-defined function, d/w about this*
prompt = "Enter v for validate, or g for generate >"
choice = input(prompt).strip().lower()[:1] # take at most 1 character
while choice not in ("v", "g"):
print("Not a valid choice! Try again.")
choice = input(prompt).strip().lower()[:1]
如果您考虑如何泛化代码以再次使用它(正如您可能在脚本的其余部分中所做的那样),那么这样做很简单,也很有用。首先,您可以将input
内容分解成一个单独的函数,因为它被调用了两次:
def input1char(prompt):
return input(prompt + " >").strip().lower()[:1]
然后将while循环分解为它自己的函数:
def validinput(prompt, options):
letters = tuple(options)
choice = input1char(prompt)
while choice not in options:
print("'%s' is not a valid choice! Try again." % choice)
choice = input1char(prompt)
return choice
然后你就写:
choice = validinput("Enter v for validate, or g for generate", "vg")
使用if-else
语句不会引发异常,因此永远不会执行except子句。使用@letsc建议的if-else
类型逻辑。if-choice=='v'或choice=='g':
在“vg”中的选择是一个陷阱。尝试打印(““vg”中的“)
:-)@好吧,啊!谢谢你接过来;)有时我会为了自己的利益而变得聪明。就在上周,我被这件事缠住了。:-)非常感谢。我试图使用一个try-and-except语句,然后使用while循环来表示“while-choice==v”等等,但这很简单,但也很有效。