如何在Python中添加if / else到“except”语句?

时间:2018-05-19 02:08:25

标签: python if-statement exception-handling

我想在if语句中添加一个if语句来检查用户的特定输入(即“exit”)。但是,except语句绑定到Value Error。运行以下代码给出了2个错误:值错误和名称错误。 “user_guess”变量未在except块中标识,因此名称错误。我尝试过使用抽象,即通过从except语句块调用的函数来路由数据,但是我仍然一直在获取Name Error。

while (lives>0 and not found): 

    try:
        user_guess=int(input(f"(Lives = {lives})Enter Your Guess: ").strip())

    except ValueError:
        if(user_guess == "exit"):
            break
        else:
            raise (ValueError)

    else:

        if((user_guess)>guess):
            print("Your guess is High. Try Something Lower. \n")
            lives-=1

我想知道如何实现代码,使得程序将“Value Error”异常抛到除了一种情况之外的所有情况,即当用户将单词“exit”输入到终端时。我正在使用Python 3.6

1 个答案:

答案 0 :(得分:0)

正如你所说,你试图在输入后立即将输入转换为整数。因此,您没有机会将其与“退出”进行比较。所以,相反,让我们得到并将输入保存为字符串,将其与“exit”进行比较,然后尝试将其转换为整数:

lives = 5
guess = 6
found = False
while lives > 0 and not found:
    user_guess = input(f"(Lives = {lives})Enter Your Guess: ").strip()
    if user_guess == "exit":
        break
    try:
        user_guess_int = int(user_guess)
    except ValueError:
        print("Invalid input!")
    else:
        if user_guess_int > guess:
            print("Your guess is High. Try Something Lower.")
            lives -= 1
        elif user_guess_int < guess:
            print("Your guess is Low. Try Something Higher.")
            lives -= 1
        else:
            print("Correct!")
            found = True