4.流程控制
1、流程控制语句for:
1.格式一:
for 变量 in iterable:
pass
1 s = 'abcd' 2 for i in s: 3 print(i)
2.格式二:
for 变量 in iterable:
if 条件:
break(或者continue)
pass
1 s = 'abcd' 2 for i in s: 3 print(i) 4 if i == 'b': 5 break
3.格式三:
for 变量 in iterable:
pass
else:
pass
1 s = 'abcd' 2 for i in s: 3 print(i) 4 else: 5 print('打印完成!')
2、循环
方式二:
格式:
while 条件:
循环体
代码:
1 # 打印1-100偶数: 2 3 count = 0 4 while True: 5 count += 1 6 if count % 2 == 0: 7 print(count) 8 if count == 100: 9 break
1 count = 0 2 while count < 100: 3 count += 2 4 print(count)
1 # 打印1-100数字: 2 3 FLAG = True 4 NUM = 0 5 6 while FLAG: 7 print(id(NUM)) 8 NUM += 1 9 print(NUM, end=' ') 10 if NUM == 100: 11 FLAG = False 12 print('\n打印完成!')
方式二:
格式:
while 条件:
循环体
continue
循环体
规则:
结束本次循环,继续下一次循环
代码:
1 while True: 2 print(111) 3 print(222) 4 continue 5 print(333)
1 111 2 222 3 111 4 222 5 ....
1 # continue用法: 2 3 count = 0 4 while count < 5: 5 count += 1 6 if count == 3: 7 continue 8 print(count)
方式三:
格式:
while 条件:
循环体
else:
语句体
代码:
1 # 满足条件执行循环体,当不满足条件时执行else语句体 2 3 count = 0 4 while count < 5: 5 count += 1 6 print(count) 7 else: 8 print(666)
1 # 跳出循环不再执行else语句体 2 3 count = 0 4 while count < 5: 5 count += 1 6 print(count) 7 if count == 3: 8 break 9 else: 10 print(666)
3、流程控制语句(if):
1 dream = input("你长大后想做什么?") 2 3 if dream == "医生": 4 print("看病免费") 5 6 print('666')
1 age = int(input('请输入年龄:')) 2 3 if age > 18: 4 print('做你想做的事情') 5 else: 6 print('小屁孩') 7 8 print('666')
1 num = input('请输入你猜测的数字:') 2 3 if num == '6': 4 print('请你吃饭') 5 elif num == '3': 6 print('不用写作业') 7 elif num == '1': 8 print('请你大宝剑')
1 num = input('请输入你猜测的数字:') 2 3 if num == '6': 4 print('请你吃饭') 5 elif num == '3': 6 print('不用写作业') 7 elif num == '1': 8 print('请你大宝剑') 9 else: 10 print('....')
1 code = input('请输入验证码:') 2 username = input('请输入用户名:') 3 password = input('请输入密码:') 4 if code == 'qwe3': 5 if username == 'alex' and password == '123': 6 print('登陆成功') 7 else: 8 print('用户名或者密码错误') 9 else: 10 print('验证码错误')