条件判断
基本语法:
if 条件:执行代码
当if 后面的条件 成立的时候,才会执行 下面的代码。
if 3>2:print('hi')
执行结果
hi
if 3<2:print("hello")
3<2 不成立,下面的语句将不再执行。
if … else…
当if条件不成立的时候,就执行else中的语句。
if 3<2:print('a')else:print('b')
3<2 不成立,就会执行 else 语句中的代码。
输出
b
if … elif … esle
elif 可以是多个分支条件。
| score | 输出 | |
|---|---|---|
| 0-59 | 不及格 | |
| 60-80 | 良 | |
| 81-100 | 优 | |
| 不在0-100 | 输入数据有误 |
score = 80if score<60 and score>0:print('不及格')elif score>=60 and score<=80:print("良")elif score<=100 and score>80:print("优")else:print("输入数据有误")
elif 可以添加多个分支条件。
- 打印金字塔。

# 打印 5 层 需要循环5次for i in range(1,6):# 空格的数量blank = (5-i)*" "# 星星的数量star =(i*2-1) * "*"print(blank+star)
- 打印倒立的金子塔

for i in range(1,6):blank = (i-1)*" "star = (2*(6-i)-1)*"*"print(blank+star)
- 给定如下数据,请使用代码进行排序,排序按照长度从大到小进行排序。
```python data = [“helloworld”,”hi”,”tom”,”china”,”lily”]data = ["helloworld","hi","tom","china","lily"]
data.sort(key=lambda d:len(d),reverse=True) # len 根据长度进行排序, print(data) ```
