python - Python 学习 - if、elif 和 else 语句 - 某些条件为真但没有被执行(打印),为什么?
问题描述
问题:当第 2 条 elif 语句为真时,程序不执行第 2 条 elif 语句……为什么?
例如,
输入:输入 ppl#1=100,ppl#2=31,ppl#3=30,它不会打印出语句(参见第 2 条 elif 语句)
预期输出:最老的是:100,最年轻的是:30' ## 此行来自第二个 elif 语句
ppl1=int(input('\r\n person #1: pls enter your age: '))
ppl2=int(input('\r\n person #2: pls enter your age: '))
ppl3=int(input('\r\n person #3: pls enter your age: '))
if (ppl3 > ppl1) and (ppl3 > ppl2):
if (ppl1 > ppl2):
print(f'\r\n the oldest is:{ppl3} and the youngest is: {ppl2}')
elif ppl1 > ppl3 and ppl1> ppl2:
if(ppl3 > ppl2):
print(f'\r\n the oldest is:{ppl1} and the youngest is: {ppl2}')
elif (ppl1 > ppl3) and (ppl1 > ppl2):
if ppl2 > ppl3:
print(f'\r\n the oldest is: {ppl1} and the youngest is: {ppl3}')
elif ppl3 > ppl1 and ppl3 > ppl2:
if(ppl2 > ppl1):
print(f'\r\n the oldest is: {ppl3} and the youngest is: {ppl1}')
elif ppl2 > ppl1 and ppl2 > ppl3:
if(ppl3 > ppl1):
print(f'\r\n the oldest is: {ppl2} and the youngest is: {ppl1}')
elif ppl2 > ppl1 and ppl2 > ppl3:
if ppl1 > ppl3:
print(f'\r\n the oldest is: {ppl2} and the youngest is: {ppl3}')
else:
print(f'\r\n The three people may be with the same age')
解决方案
问题是由嵌套if
块带来的:
elif ppl1 > ppl3 and ppl1> ppl2:
if(ppl3 > ppl2): # nested if block
print(f'\r\n the oldest is:{ppl1} and the youngest is: {ppl2}')
嵌套的 if 块不受“父”块的 elif/else 语句的影响。这基本上意味着一旦你进入这里:
elif ppl1 > ppl3 and ppl1> ppl2:
无论内部代码做什么,都不再考虑其他 elif/else 语句。
解决您的问题的方法是避免嵌套 if 块,而是使用and
语句链接条件:
elif ppl1 > ppl3 and ppl1 > ppl2 and ppl3 > ppl2:
print(f'\r\n the oldest is: {ppl1} and the youngest is: {ppl2}')
或者您可以在内部 if 块中添加 else:
elif ppl1 > ppl3 and ppl1 > ppl2:
if ppl3 > ppl2:
print(f'\r\n the oldest is: {ppl1} and the youngest is: {ppl2}')
else:
print(...)
(对所有块做同样的事情)
推荐阅读
- html - 如何在容器中居中 div 元素
- oracle-apex - 在按需 ajax 进程 (PL/SQL) 中向会话提交页面项目值
- javascript - 调用另一个函数时如何禁用函数?
- css - 隐藏特定 wordpress 类别中所有帖子的 CSS 按钮
- php - 使用 symfony 中的参数执行 sql 请求时出现语法错误?
- google-bigquery - 将旧版 SQL 转换为标准 SQL - 增强型电子商务
- python-3.x - 如何使用帧单元制作 TIME 字幕(.srt、.smi 等)
- c# - 无法从另一个脚本实例化预制件
- facebook-graph-api - 获取我自己的 Instagram 帖子所需的 Graph API 权限
- python - 扩展“特定”的 defaultdict(str,...)?