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'))
因为如果条件为true,则在每个if语句中返回,因此两个代码只有一个匹配项
对于第一个程序:将按顺序计算每个if语句,如果满足条件,
return
代码将在该块返回,其余代码将不执行。在您的情况下,它将在第6行返回,其余代码将不会执行。如果不满足任何条件,则不返回任何内容对于第二个程序:如果满足一个条件,它的行为与第一个程序类似。如果不满足任何条件,则返回默认值
False
我认为您的主要问题是您在,第一个也会起作用
chocolate
检查行中将ochre
拼写错误为orhre
,然后使用chocolate/ochre
测试第一个,使用blue/ochre
测试第二个。如果您使用^{修复这个小问题,即使使用
chocolate
,您的第一段代码也会得到一个非None
结果您的第二个示例也无法返回
None
,因为其中一个if/elif
语句将启动,或者else
语句将启动。第一个示例中的等价项是函数末尾的无条件return False
例1.
此语句与代码实际执行的操作不匹配
print(is_stylish('chocolate', 'ochre'))
无法返回False
,您的False
的olny组合为:所以这些条件都不满足,函数没有任何其他的
return
,所以它返回none例2.
这是正确的,在你的情况下,它进入
elif pants_colour == 'blue' and shirt_colour == 'ochre'
并返回True差异:除了您已经提到的以外,两个示例之间的主要区别在于,在示例2中,您有
else: return False
条件,它将覆盖所有其他情况,因此如果else
之前的任何条件都不满足,那么您的函数将返回False,而不是none在第一个示例中,如果没有满足任何条件,它将只遍历所有条件,不会命中任何条件,并且将返回none
相关问题 更多 >
编程相关推荐