为什么不是在嵌套的“if 语句”中检查所有条件?

问题描述

score = 50

if score >= 60:
  print('elon')
  if score <= 50:
      print('please type number bigger than 0')
else:
  print('please type a number next time')

任何人都可以尝试帮助我理解为什么满足第二个条件但没有执行的机制,因为它嵌套在错误的第一个条件之后。我正在努力理解如何以及何时嵌套“事物”。为什么 ELSE 语句不嵌套?

解决方法

Python 使用缩进作为块分隔符,但如果您愿意,我们可以使用 C 风格的花括号使其显式:

score = 50

if (score >= 60) {
    print('elon')
    if (score <= 50) {
        print('please type number bigger than 0')
    }
} else {
    print('please type a number next time')
}

如果检查 score 是否大于或等于 60,这段代码做了什么,如果是,它会执行块的内容,所以 print("elon") 然后检查 score 是否小于或等于 50,如果是 print("please ...")
在这种情况下,嵌套的 if 永远不可能为真,因为要在这里制作,score 必须大于或等于 60,因此它不能小于或等于 50。

如果我减少嵌套 if 的缩进,并将其设为 elif :

if score >= 60:
    print('elon')
elif score <= 50:
    print('please type number bigger than 0')
else:
    print('please type a number next time')

这意味着:
|得分|结果| |------|-----| |score = 60|埃隆| |50