gpt4 book ai didi

python - 简单的Python Q : idk what produces None when this code's executed

转载 作者:行者123 更新时间:2023-12-01 02:59:54 25 4
gpt4 key购买 nike

我只是通过阅读一本书来学习Python,下面的代码用于显示try和 except命令。这些是有道理的,但我的问题是关于输出。执行时,sp​​am(0)产生错误后,在下一行显示None,然后是42。None从哪里来?

def spam(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print('Error')

print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))

最佳答案

在 Python 中,没有 return 语句的函数将返回 None。因此异常被捕获并且函数返回,然后执行下一行。

如果 except block 再次引发异常,则该函数不会返回,而是会抛出异常。

关于python - 简单的Python Q : idk what produces None when this code's executed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43927017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com