Python,将变量设置为None

时间:2017-11-06 21:00:20

标签: python

将变量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."

1 个答案:

答案 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"