python基础之流程控制
一,if判断
语法
if 条件1: 代码1 代码2 代码3 elif 条件2: 代码1 代码2 代码3 elif 条件3: 代码1 代码2 代码3 ... else: 代码1 代码2 代码3
代码示例:
score = input('请输入您的成绩:') # score="18" score=int(score) if score >= 90: print('优秀') elif score >= 80: print('良好') elif score >= 70: print('普通') else: print('很差,小垃圾') print('=====>')
if的嵌套
age = 17 is_beautiful = True star = '水平座' if 16 < age < 20 and is_beautiful and star == '水平座': print('开始表白。。。。。') is_successful = True if is_successful: print('两个从此过上没羞没臊的生活。。。') else: print('阿姨好,我逗你玩呢,深藏功与名') print('其他代码.............')
二,while循环
2.1 基本格式
''' print(1) while 条件: 代码1 代码2 代码3 print(3) '''
2.2 死循环与效率问题
count=0 while count < 5: # 5 < 5 print(count) # 0,1,2,3,4 while True: name=input('your name >>>> ') print(name) 纯计算无io的死讯会导致致命的效率问题 while True: 1+1 while 1: print('xxxx')
2.3 退出循环的三种方式
还有一种退出方式在函数中利用return来终止。
# 方式一:将条件改为False,等到下次循环判断条件时才会生效 tag=True while tag: inp_name=input('请输入您的账号:') inp_pwd=input('请输入您的密码:') if inp_name == username and inp_pwd == password: print('登录成功') tag = False # 之后的代码还会运行,下次循环判断条件时才生效 else: print('账号名或密码错误') # 方式二:break,只要运行到break就会立刻终止本层循环 while True: inp_name=input('请输入您的账号:') inp_pwd=input('请输入您的密码:') if inp_name == username and inp_pwd == password: print('登录成功') break # 立刻终止本层循环 else: print('账号名或密码错误')
2.4 while + continue
# 强调:在continue之后添加同级代码毫无意义,因为永远无法运行 count=0 while count < 6: if count == 4: count+=1 continue # count+=1 # 错误 print(count) count+=1
2.5 while + else 针对的是break
else中的代码是在while正常执行完的情况下才执行,当被break打断的后,是不会执行的。
count=0 while count < 6: if count == 4: count+=1 continue print(count) count+=1 else: print('else包含的代码会在while循环结束后,并且while循环是在没有被break打断的情况下正常结束的,才不会运行') count=0 while count < 6: if count == 4: break print(count) count+=1 else: print('======>')
三,for循环
3.1 语法
for 变量名 in 可迭代对象: # 此时只需知道可迭代对象可以是字符串\列表\字典,我们之后会专门讲解可迭代对象 代码一 代码二 ... #例1 for item in ['a','b','c']: print(item) # 运行结果 a b c # 参照例1来介绍for循环的运行步骤 # 步骤1:从列表['a','b','c']中读出第一个值赋值给item(item=‘a’),然后执行循环体代码 # 步骤2:从列表['a','b','c']中读出第二个值赋值给item(item=‘b’),然后执行循环体代码 # 步骤3: 重复以上过程直到列表中的值读尽
# for+break: 同while循环一样 # for+else:同while循环一样 username='egon' password='123' for i in range(3): inp_name = input('请输入您的账号:') inp_pwd = input('请输入您的密码:') if inp_name == username and inp_pwd == password: print('登录成功') break else: print('输错账号密码次数过多')
补充:终止for循环只有break一种方案 在函数中还可以用return来终止。
3.2 for + continue
for i in range(6): # 0 1 2 3 4 5 if i == 4: continue print(i)

浙公网安备 33010602011771号