在这种情况下,if语句和elif语句之间有什么区别?

2024-09-28 19:26:54 发布

您现在位置:Python中文网/ 问答频道 /正文

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'))

Tags: orand程序falsetruereturnifis
3条回答

因为如果条件为true,则在每个if语句中返回,因此两个代码只有一个匹配项

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

对于第二个程序:如果满足一个条件,它的行为与第一个程序类似。如果不满足任何条件,则返回默认值False

我认为您的主要问题是您在chocolate检查行中将ochre拼写错误为orhre,然后使用chocolate/ochre测试第一个,使用blue/ochre测试第二个。如果您使用^{,第一个也会起作用

修复这个小问题,即使使用chocolate,您的第一段代码也会得到一个非None结果

您的第二个示例也无法返回None,因为其中一个if/elif语句将启动,或者else语句将启动。第一个示例中的等价项是函数末尾的无条件return False

例1.

For the first program: each if statement will be evaluated and if the condition is met, then the block should be executed; if that is the case then the result should be False.

此语句与代码实际执行的操作不匹配

print(is_stylish('chocolate', 'ochre'))无法返回False,您的False的olny组合为:

pants_colour == 'chocolate' and shirt_colour == 'orhre'  # !note: 'orhre' is not 'ochre'
pants_colour == 'chocolate' and shirt_colour == 'black'

所以这些条件都不满足,函数没有任何其他的return,所以它返回none

例2.

For the second program: if the preceding condition is met then the following statements would be skipped and lead to the result.

这是正确的,在你的情况下,它进入 elif pants_colour == 'blue' and shirt_colour == 'ochre'并返回True

差异:除了您已经提到的以外,两个示例之间的主要区别在于,在示例2中,您有else: return False条件,它将覆盖所有其他情况,因此如果else之前的任何条件都不满足,那么您的函数将返回False,而不是none

在第一个示例中,如果没有满足任何条件,它将只遍历所有条件,不会命中任何条件,并且将返回none

相关问题 更多 >