else 语句

else 语句示例

else 语句一定要跟在 if 语句的后面才是有效的,它的意义是否定前面 if 的条件,例如下面的示例程序,else 否定前面的if score >= 60条件,得到的结论就是等价于if score<60

示例程序:分数 score 大于等于 60 时,会输出 pass,否则输出 fail。

score = int(input())
if score >= 60:
    print(score, 'pass')
else:
    print(score, 'fail')

else 语句一般形式

if {condition}:
    {statement1}
    {statement2}
    ……
else:
    {statement3}
    {statement4}
    ……

27

选择结构
score = int(input())
if score >= 60:
    print('pass')
else:
    print('fail')

如果输入60,程序会输出

如果输入50,程序会输出

[0/2]

28,29

选择结构

以下程序语法正确的是?

[0/1]
选择结构
score = int(input())
if score >= 90:
    print('excellent',end=' ')
if score >= 60:
    print('pass',end=' ')
else:
    print('fail')

如果输入90,程序会输出

如果输入50,程序会输出

[0/2]

嵌套 if-else

有些复杂的条件,我们需要在 if-else 中再嵌套一组 if-else 才能实现。嵌套的实现主要依靠缩进的规范和统一。

score = int(input())
if score >= 60:
    if score >= 90:
        print(score, 'excellent')
    else:
        print(score, 'pass')
else:
    print(score, 'fail')

30

选择结构
score = int(input())
if score >= 60:
    if score >= 90:
        print('excellent')
    else:
        print('pass')
else:
    if score >= 0:
        print('fail')
    else:
        print('error')

如果输入90,程序会输出

如果输入80,程序会输出

如果输入50,程序会输出

如果输入-10,程序会输出

[0/4]
上一章
if语句
下一章
elif语句