【问题标题】:How to add an if/else to an "except" statement in Python?如何在 Python 中的“except”语句中添加 if/else?
【发布时间】:2018-10-29 11:24:53
【问题描述】:

我想在 except 语句中添加 if/else,以检查用户的特定输入(即“退出”)。但是,except 语句绑定到值错误。运行下面的代码给了我 2 个错误:值错误和名称错误。在 except 块中未识别“user_guess”变量,因此出现名称错误。我尝试过使用抽象,即通过从异常语句块调用的函数路由数据,但是我仍然不断收到名称错误。

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

我想知道如何实现代码,以便程序向除一种情况以外的所有情况(即用户在终端中输入“退出”一词时)抛出“值错误”异常。我正在使用 Python 3.6

【问题讨论】:

  • try上方初始化user_guess
  • 每次都会检查 user_guess 是否有有效输入,直到用户用完生命(即 5 次)或用户猜到了数字。在 'try' 之上初始化它只会使 except 语句不合逻辑。不会吗?
  • 想一想,如果user_guess=int(...这一行出现错误,那么user_guess没有初始化,不存在同名的变量。然后您的 except 块尝试将“退出”与不存在的变量进行比较。
  • 把 else 下的东西移到 try 块中
  • @SweeneyTodd 你的解释很有道理。然而,将 if/else 块移动到“try”中会带来另一个问题。我将值作为“int”获取,但正在检查字符串。

标签: python if-statement exception-handling


【解决方案1】:

正如您所说,您正试图在获得输入后立即将其转换为整数。因此,您没有机会将其与“退出”进行比较。所以,相反,让我们获取输入并将其保存为字符串,将其与“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

【讨论】:

  • 这太棒了!感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-19
  • 2012-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-22
相关资源
最近更新 更多