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