python - 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)
解决方案
当你loop back to main
因为你故意输入了一个无效的输入,最终main()
退出而你又回来之后才调用。正是在这一点上,该功能下降到该if guess_num ...
行并且guess_num
未定义。
首先,您不应该在解决方案中使用递归,其次为了避免错误,请return
在main()
.
推荐阅读
- c++ - 我如何得到空,没有抓包?
- javascript - 如何在 reactjs 中实现 react-widgets 下拉列表
- docker - 如何使用 Docker 映像中的 COPY 指令将文件从主机复制到 Docker 容器?
- c - 无法在 vscode 中使用 makefile 调试 C
- c++ - 关于未定义符号的问题:operator<<
- debugging - 为什么 GDB 'x/w' 和 'x/g' 显示不同的值?
- sql - 如何比较 SQL Server 中单行的多列值
- javascript - 组件从其父级或直接从 Redux 存储获取数据
- datetime - SML 日期结构
- python - 在 Sympy Python 中使用 Pow() 和 For 循环的交互问题