3.1条件表达式
关系运算符
可以在python中连续使用
>>> print(1<2<3)
True
>>> print(1<2>3)
False
>>> print(1<3>2)
True
3.2选择结构
3.2.1单分支结构
if 表达式:
语句块
eg:求三个数的最大值
![](https://i-blog.csdnimg.cn/blog_migrate/dcc61610773e7c1bac8ca0373919bdd4.png)
3.2.2双分支结构
语法:
if 表达式 :
语句块1
else:
语句块2
eg:网吧
![](https://i-blog.csdnimg.cn/blog_migrate/2c580a5a0a1df3079fdb644726c61f16.png)
eg:判断奇偶数
![](https://i-blog.csdnimg.cn/blog_migrate/8a79eeb27f30238cb36d4dc7278f4913.png)
3.2.3三目运算符
针对 if else
语法:
表达式1 if 条件 else 表达式2
eg:
x=int (input("data:"))
print('该数为偶数') if x%2==0 | else print('该数为奇数')
3.2.4 多分支结构
if 表达式1:
语句块1
elif 表达式2:
语句块2
elif 表达式3:
语句块3
.
else:
语句块n
eg:
score=int(input('输入学生成绩:'))
if score>100|score<0:
print('输入成绩不符合要求')
elif score>=90:
print("优")
elif score>=80:
print("良")
elif score>=70:
print("中")
elif score>=60:
print("及格")
else:
print("不及格")
![](https://i-blog.csdnimg.cn/blog_migrate/6bf414f99b203252ccf5345ad4e68293.png)
查询当前时间
>>> import time
>>> time.localtime()
time.struct_time(tm_year=2023, tm_mon=3, tm_mday=22, tm_hour=23, tm_min=6, tm_sec=58, tm_wday=2, tm_yday=81, tm_isdst=0)
另一种嵌套选择结构
if 表达式1:
语句块1
if 表达式2:
语句块2
else:
语句块3
else:
if 表达式4:
语句块4
求今年过了多少天
import time
date=time.localtime()
year,month,day=date[:3]
day_month=[31,28,31,30,31,30,31,31,30,31,30,31]
if(year%4==0 and year%100!=0)or year%400==0:
day_month[1]=29
if month==1:
print(day)
else:
print(sum(day_momth[:month-1])+day)
3.3循环结构
3.3.1 while循环
while 条件表达式:
循环体
![](https://i-blog.csdnimg.cn/blog_migrate/fa570e6b19a560edc7760f5f60a2e029.png)
![](https://i-blog.csdnimg.cn/blog_migrate/ee3c4c0aff6d3e43d0bec2e4a8d4ac6b.png)
3.3.2 for循环
for 变量 in 可迭代对象:
循环体
![](https://i-blog.csdnimg.cn/blog_migrate/cf1b8ece271501ee464c7520afbc8c45.png)
![](https://i-blog.csdnimg.cn/blog_migrate/5af7adf964fe2efcedad31dccd18fa27.png)
![](https://i-blog.csdnimg.cn/blog_migrate/c112c7ee3e5971631bdb3fac0bc13e90.png)
![](https://i-blog.csdnimg.cn/blog_migrate/386a8b3a27f2490e5065c6477830a218.png)
![](https://i-blog.csdnimg.cn/blog_migrate/f05c416fca3a4c1c7a2115e0432f84ed.png)
求前100和
![](https://i-blog.csdnimg.cn/blog_migrate/dc216d90e5a58c7760c2d90b8679f58f.png)
![](https://i-blog.csdnimg.cn/blog_migrate/e591d3be3f96c0a25ee5fa60b9b6265e.png)