首页 > 技术文章 > 流程控制

mayu-huangdi 2021-11-04 16:46 原文

流程控制

控制程序执行顺序流程的方式有3种:顺序结构、分支结构、循环结构。绝大部分编写的程序都是顺序结构。

img

分支结构

分支结构就是根据条件判断的真伪去执行不同分支的子代码。满足条件的子代码块需要缩进(4个空格),条件判断的数据都会转化为布尔类型,0、None、空字符串、空字典、空列表、空集合都会被转化为False。

if 条件1:  # 条件1为True就执行code1
	code1
elif 条件2:  # 条件2为True就执行code2
	code2
elif 条件3:  # 条件3为True就执行code3
    code3
else:  # 上述条件都不成立,执行code4
	code4
graph TD; a[input输入] --> b[条件判断] b --> |条件1| d[code1] b --> |条件1| e[code2] b --> |条件1| f[code3] b --> |else| g[code4]

循环结构

循环结构就是重复执行某段的代码。

while循环语法

while为条件循环,满足条件则一直执行子代码块。

while 条件:
	代码1
	代码2
 	代码3

image

while+break

# while + break
# break结束本层循环
while True:
# 1.获取用户输入的用户名和密码
	username = input('username>>>:')
	password = input('password>>>:')
	# 2.判断用户名和密码是否正确
	if username == 'jason' and password == '123':
		print('来宾三位')
		# 直接结束本层循环
		break
	else:
		print('输入错误')

image

while+continue

# continue会直接结束while循环中的本次循环不再执行continue下的所有代码,并开始进入下次循环。
conunt = 0
while True:
	if count == 3:
		print('count到3了')
		count += 1
		continue  # count = 3 时不打印'正在执行...'这句话
	print('正在执行...')
	count += 1

while+else

在while+else结构中,while循环不碰到break而结束,最后会执行else中的代码。

count = 0
while count < 7:
	print('正在执行中...')
	count += 1
else:
	print('执行完了')

练习

import random
import math

'''
2.猜年龄的游戏
普通要求
    用户可以有三次猜错的机会 如果过程中猜对了直接退出
拔高要求
    三次机会用完之后提示用户是否继续尝试 如果是则再给三次机会 如果否则直接结束
'''

# 随机年龄
age = math.ceil(random.random() * 100)
# 固定年龄
fixed_age = 25
# 猜测的次数
count = 3
# 全局标识
flag = True
while count > 0 and flag:
    input_age = input('请输入您猜测的年龄>>>')
    if int(input_age) == fixed_age:
        print('猜对了')
        break
    else:
        count -= 1
        print('猜错了,您还有%d次机会' % count)
        if count == 0:
            while flag:
                input_code = input('您是否要重新猜?需要请输入y,不需要输入n>>>')
                if input_code == 'y':
                    count = 3
                    break
                elif input_code == 'n':
                    break
                else:
                    print('请输入y或者n喔')

for循环语法

#for循环结构
for 变量 in 可迭代对象:
	pass
# example
name_list = ['xie','gala','xiaohu']
for name in name_list:
	print(name)
# 运行结果
xie
gala
xiaohu

推荐阅读