python - 在这种情况下,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'))
解决方案
因为如果条件为真,您会在每个 if 语句处返回,所以您的两个代码都只有一个匹配项。
对于第一个程序:每个 if 语句将按顺序执行,如果条件满足,return
代码将在该块返回,其余代码将不会执行。在您的情况下,它将在第 6 行返回,并且不会执行其余代码。如果不满足任何条件,则不返回任何内容。
对于第二个程序:如果满足某个条件,它就像第一个程序一样。如果不满足条件,则返回默认值False
推荐阅读
- webpack - 加载 svg 图标时“未定义导出”
- python-3.x - 如何从 pipelines.py 中获取 scrapy 参数的值?
- node.js - Express 中间件忽略 next(new Error()) 并继续执行代码
- c++ - 为什么空的 unordered_map.find 没有返回 end()?
- javascript - 如何使用 React Router 根据他们的推荐人重定向用户
- mysql - 将现有的自动增量 ID 排序的代码可能是什么?
- reactjs - 如何在 React 中的 onblur 事件后检查组件是否已被单击
- java - Maven 无法使用 eclipse 解决 Jacob 依赖关系
- java - 点燃持久化集合:找不到具有紧凑页脚的对象的元数据
- json - 如何在 React.js 中从 json 给出相对本地路径?