将变量prize
设置为None
的原因是什么?
def which_prize2(points):
prize = None
if points <= 50:
prize = "a wooden rabbit"
elif 151 <= points <= 180:
prize = "a wafer-thin mint"
elif points >= 181:
prize = "a penguin"
if prize:
return "Congratulations! You have won " + prize + "!"
else:
return "Oh dear, no prize this time."
答案 0 :(得分:3)
如果变量NameError
不存在,则会引发prize
例外
变量奖金是设置为None
还是""
(空字符串)还是0
并不重要,因为所有这些值在Python中都是假的。
在此特定示例中,奖金设置为None
,因为在if / else签入时它将退出。
即使这个if / elif块不创建变量奖品,也会在此块之前创建变量奖品:
if points <= 50:
prize = "a wooden rabbit"
elif 151 <= points <= 180:
prize = "a wafer-thin mint"
elif points >= 181:
prize = "a penguin"