首页 > 解决方案 > 在这种情况下,if 语句和 elif 语句之间的区别?

问题描述

def is_stylish(pants_colour, shirt_colour):
    """returns a Boolean True or False to indicate whether the given combination is stylish or not"""
    if pants_colour == 'blue' and shirt_colour =='black':
        return True 
    if pants_colour == 'chocolate' and shirt_colour == 'orhre':
        return False
    if pants_colour == 'blue' and shirt_colour == 'ochre':
        return True
    if pants_colour == 'chocolate' and shirt_colour == 'black':
        return False
print(is_stylish('chocolate', 'ochre'))

上述程序的结果是无。但是,如果我将其更改为“elif 语句”,则程序运行良好。我看不出这两个程序之间的区别。

这是我对执行的基本理解。

对于第一个程序:将评估每个“if 语句”,如果满足条件,则应执行该块;如果是这样,那么结果是False

对于第二个程序:如果满足前面的条件,则将跳过以下语句并导致结果。

def is_stylish(pants_colour, shirt_colour):
    """returns a Boolean True or False to indicate whether the given combination is stylish or not"""
    if pants_colour == 'blue' and shirt_colour =='black':
        return True 
    elif pants_colour == 'chocolate' and shirt_colour == 'orhre':
        return False
    elif pants_colour == 'blue' and shirt_colour == 'ochre':
        return True
    else: 
        return False
print(is_stylish('blue', 'ochre'))

标签: python

解决方案


因为如果条件为真,您会在每个 if 语句处返回,所以您的两个代码都只有一个匹配项。

对于第一个程序:每个 if 语句将按顺序执行,如果条件满足,return代码将在该块返回,其余代码将不会执行。在您的情况下,它将在第 6 行返回,并且不会执行其余代码。如果不满足任何条件,则不返回任何内容。

对于第二个程序:如果满足某个条件,它就像第一个程序一样。如果不满足条件,则返回默认值False


推荐阅读