python基础语法--if--elif--else条件语句

本文介绍了Python的基础语法,包括if语句、if-else语句、if-elif-else语句以及assert关键词的使用。通过示例说明了如何根据条件执行不同的代码块,以及assert关键字在进行断言时的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. if 语句

if expression:
    expr_true_suite
#例子:
if 2 > 1 and not 2 > 3:
    print('Correct Judgement!')
#输出:
Correct Judgement!

2. if - else 语句

if expression:
    expr_true_suite
else:
    expr_false_suite

Python 提供与 if 搭配使用的 else,如果 if 语句的条件表达式结果布尔值为假,那么程序将执行 else 语句后的代码。
【例子】

hi = 6
if hi > 2:
    if hi > 7:
        print('好!')
    else:
        print(hi)
else:
    print('ok')
#输出:
6

3. if - elif - else 语句

if expression1:
    expr1_true_suite
elif expression2:
    expr2_true_suite
elif expressionN:
    exprN_true_suite
else:
    expr_false_suite

elif 语句即为 else if,用来检查多个表达式是否为真,并在为真时执行特定代码块中的代码。

【例子】

temp = input('请输入成绩:')
source = int(temp)
if 100 >= source >= 90:
    print('A')
elif 90 > source >= 80:
    print('B')
elif 80 > source >= 60:
    print('C')
elif 60 > source >= 0:
    print('D')
else:
    print('输入错误!')

4. assert 关键词
assert这个关键词我们称之为“断言”,当这个关键词后边的条件为 False 时,程序自动崩溃并抛出AssertionError的异常。
【例子】
在这里插入图片描述

参考:
https://github.com/datawhalechina/team-learning-program/tree/master/Python-Language

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值