首页 > 解决方案 > try/except 块的范围

问题描述

我知道 try/except 块没有单独的范围,而且我也知道这个问题的实际解决方案,尽管我想知道它为什么会发生。我正在为我的 sdev 类制作一个简单的猜谜游戏,虽然我可以在 try/except 块之前添加guess_num 以使其工作,但为什么我也有?

我让它循环回main,但是如果我通过程序并且没有输入数字作为输入,它最终会让我再次回到输入,但是如果我再输入一个数字,它会给我这个错误:

Traceback (most recent call last):
  File "C:\Users\Jexxy\Documents\MyRepo\Guessing_Game.py", line 35, in <module>
    main()
  File "C:\Users\Jexxy\Documents\MyRepo\Guessing_Game.py", line 31, in main
    if guess_num > 0 and guess_num < 100 and isinstance(guess_num, int):
UnboundLocalError: local variable 'guess_num' referenced before assignment
def main():
    random_num = random.randrange(1, 5)
    try:
        guess_num = int(input('''Welcome to the guessing game!
                 A Random number between 1-100 has already been generated!
                 When ready, please enter a number between 1-100 to make your guess: '''))
    except ValueError:
        try_again = input("You must enter a number! Try again? Y/N: ")
        if try_again.lower() == "y":
            main()
        else:
            exit(0)

    if guess_num > 0 and guess_num < 100 and isinstance(guess_num, int):
        print(guess_num)

标签: pythontry-except

解决方案


当你loop back to main因为你故意输入了一个无效的输入,最终main()退出而你又回来之后才调用。正是在这一点上,该功能下降到该if guess_num ...行并且guess_num未定义。

首先,您不应该在解决方案中使用递归,其次为了避免错误,请returnmain().


推荐阅读