day05-控制流程之if/while/for

控制流程之if判断

if 其实就是根据条件来做出不同的反应,如果这样就这样干,如果那样就那样干

1. 如果:成绩 > 90,那么:优秀(if...)

score = 91
if score > 90:
    print('优秀')

2. 如果:成绩>90,那么:优秀,否则:良好(if...else...)

score = 89
if score > 90:
    print("优秀")
else:
    print("良好")

3. 如果:成绩>90,那么:优秀;如果:成绩<60,那么:不及格,否则:良好(if...elif...else)

score = int(input("enter score>>>"))
if score > 90:
    print("优秀")
elif score < 60:
    print("不及格")
else:
    print("良好")

4. 如果:成绩>90,那么:优秀;如果:成绩<60,那么:不及格,否则:良好(if嵌套)

score = int(input("enter score>>>"))
if score > 60:
    if score < 90:
        print("良好")
    else:
        print("优秀")
else:
    print("不及格")

控制流程之while循环

循环就是一个重复的过程,while循环又称为条件循环,当条件满足时进入循环体,不满足时退出。

while 条件:    
    # 循环体
    # 如果条件为真,那么循环体则执行,执行完毕后再次循环,重新判断条件。。。
    # 如果条件为假,那么循环体不执行,循环终止

1. 打印100以内的整数(while...)

count = 1
while count < 101:
    print(count,end=',')
    count += 1

2. 打印100以内(除50之外)的整数(while...continue)

count = 1
while count < 101:
    if count == 50:
        count += 1
        continue        # continue跳出本次循环,直接进入下一次循环
    print(count, end=',')
    count += 1

3. 猜年龄,直到猜中后跳出循环(while...break)

real_name = 23
while 1:
    enter_name = int(input("请猜下我的年龄:"))
    if enter_name == real_name:
        print("恭喜你,猜对了")
        break						# break跳出整个循环
    elif enter_name > real_name:
        print("猜大了,再猜小点")
    else:
        print("猜小了,再猜大点")

4. 当while循环没有被break掉的时候,会执行else下面的代码(while...else)

n = 1
while n < 3:
    print(n)
    n += 1
else:
    print('else会在while没有被break时才会执行else中的代码')

控制流程之for循环

for循环的循环次数受限于容器类型的长度,而while循环的循环次数需要自己控制

for i in 列表or字典:
	i就是列表中的每一个元素

**1. 打印列表中的值(for...) **

game_list =['chaoji','CF','xiaoxiaole','lianliankan','tank']
for i in game_list:
    print(i)

2. 打印列表元素'CF'前的所有元素(for...break)

game_list =['chaoji','CF','xiaoxiaole','lianliankan','tank']
for i in game_list:
    if i == 'CF':
        break		# break跳出整个循环
    print(i)

3. 打印列表中除'CF'之外的元素(for...continue)

game_list =['chaoji','CF','xiaoxiaole','lianliankan','tank']
for i in game_list:
    if i == 'CF':
        continue		# continue跳出本次循环,直接进入下一次循环
    print(i)

4. for循环没有被break的时候,执行else里的代码(for...else)

game_list =['chaoji','CF','xiaoxiaole','lianliankan','tank']
for i in game_list:
    print(i)
else:
    print("for循环没有被break的时候,执行else里的代码")

5. for循环嵌套

'''打印九九乘法表'''
for i in range(1, 10):
    for j in range(1, i+1):
        print(f"{i}*{j}={i*j}", end='	')
    print('
', end='')
1*1=1	
2*1=2	2*2=4	
3*1=3	3*2=6	3*3=9	
4*1=4	4*2=8	4*3=12	4*4=16	
5*1=5	5*2=10	5*3=15	5*4=20	5*5=25	
6*1=6	6*2=12	6*3=18	6*4=24	6*5=30	6*6=36	
7*1=7	7*2=14	7*3=21	7*4=28	7*5=35	7*6=42	7*7=49	
8*1=8	8*2=16	8*3=24	8*4=32	8*5=40	8*6=48	8*7=56	8*8=64	
9*1=9	9*2=18	9*3=27	9*4=36	9*5=45	9*6=54	9*7=63	9*8=72	9*9=81
原文地址:https://www.cnblogs.com/863652104kai/p/10907918.html