联系代码
''' if-else语句 if-elif-else语句 格式: if 表达式1: 语句1 elif 表达式2: 语句2 elif 表达式3: 语句3 ....... elif 表达式n: 语句n else: 语句n+1 # else可有可无 ''' age = int(input()) if age < 0: print("1") elif age > 0 and age <= 3: print("2") elif age > 3 and age <= 5: print("3") else: print("4") #改进 if age < 0: print("1") elif age <= 3: print("2") elif age <= 5: print("3") else: print("4") #elif else if 每个el都是对上面表达式的否定 #死循环: 表达式永远为真的循环 #while 1: # print("111") ''' while 表达式: 语句1 else: 语句2 当while 位False时 执行else ''' a = 1 while a <= 3: print("ben is a good man") a += 1 else: print("very good") #for 语句 #格式: for 变量名 in 集合: # 语句 for i in [1,2,3,4,5]: print(i) #range()函数 列表生成器 a = range(10) print(a) for x in range(10): print(x) #生成1 到 10 每次步长增加2 for y in range(1,10,2): print(y) #enumerate 同时遍历下标和值 for m,index in enumerate([1,2,3,4,5]): print(m,index) #求和 sum = 0 for n in range(1,10): sum += n print(sum)
执行结果
D:\pycharm\python\venv\Scripts\python.exe D:/pycharm/python/010条件控制语句.py
3
2
2
ben is a good man
ben is a good man
ben is a good man
very good
1
2
3
4
5
range(0, 10)
0
1
2
3
4
5
6
7
8
9
1
3
5
7
9
0 1
1 2
2 3
3 4
4 5
45
Process finished with exit code 0