首页 > 解决方案 > 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')

标签: python

解决方案


问题是由嵌套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(...)

(对所有块做同样的事情)


推荐阅读