顺序分支循环结构

发布时间 2023-06-12 23:08:28作者: 半糖+奶茶

一、流程控制理论

  #控制实物执行的流程

  执行流程分类:顺序结构、分支结构、循环结构

 

二、必知必会

在python中使用缩进就是表示从属关系

(如果一行代码是冒号结尾,下一行自动缩进,为了美观通常缩进四个空格,冒号相当于拥有子代码)

具有相同缩进量的代码彼此之间是顺序结构,无从属关系,平起平坐

if 18>19:
    print('嘿嘿嘿')
elseprint('哈哈哈')

三、分支结构

1.单if分支

  #如果一个女孩年龄大于38,叫阿姨好

age = 48(先定义一个女孩年纪)

if age > 38:     #分支

    print('阿姨好')

2.if 和 else分支  (执行的子代码可以有多行,这里仅仅展示了一行)

如果一个女孩年龄大于38,叫阿姨好,否则叫小姐姐

age = 48(先定义一个女孩年纪)

if age > 38:     #分支

    print('阿姨好')

else:(分支)

    print('小姐姐')

3.if 与 elif 与 else分支  (elif用于两个分支以上使用)

如果用户是jason打印CEO,如果是tony打印理发师,如果是kevin打印安保,其他打印普通员工

username = input('username>>>:')

if username == 'jason':

    print('ceo')

elif username == 'tony':

    print('理发师')

elif username == 'kevin':

    print('安保')

else:

    prine = '普通员工'

4.if 的嵌套

#如果女孩年纪大于38说  不好意思 认错人了   否则上去要微信

如果要成功  则去吃饭  看电影  天黑了 睡觉,如果没有成功说打扰了

age = 22
is_success = ture

if age <38:
    print('我观察你很久了,想加你个联系方式')
    if is_success:
        print('吃饭 看电影、天黑了、睡觉觉')
    elseprint('打扰了')
elseprint('不好意思 认错人了')

 练习:

成绩大于90为优秀,成绩大于60小于等于90为良好,成绩小于60为挂科

score = input('score>>>:')
if score > '90':
    print('优秀')
elif score > '60':
    print('良好')
else:
    print('挂科')

注意:由于input里面是字符串,所有当我们写score > 90时,这个90也必须是字符串,否则报错

四、循环结构

while 条件:

    条件成立后执行循环体的代码

 

1.无限循环

while True:
    username = input('username>>>:')
    password = input("password>>>:")
    if username == 'jason' and password == "123":
        print("登录成功")
    else:
        print('用户名或密码错误')

while True(但是这个程序不管成功还是失败都会无限循环)

2.满足条件,不再循环

方法一:

num = 1
while num < 5:
    username = input('username>>>:')
    password = input("password>>>:")
    if username == 'jason' and password == "123":
        print("登录成功")
    else:
        print('用户名或密码错误')
        num +=1

使用num来控制次数,以上代码用户连续输4次就结束,但是登录成功依然还是有循环问题存在

方法二:

while True:
    username = input('username>>>:')
    password = input("password>>>:")
    if username == 'jason' and password == "123":
        print("登录成功")
        break
    else:
        print('用户名或密码错误')

使用break来打破循环,以上登录成功后就不会循环,但是失败可以一直输入

注意:break只能结束所在那一层的循环

3.循环到中间去掉一个,再继续进行后续循环

首先打印1-10的数字

count = 1
while count < 11:
    print(count)
    count += 1

 

现在要求打印1-10,但是4不打印

count = 1
while
count < 11: if count == 4: count += 1 continue #不进行本次循环,直接跳到下一次循环(使用不是很多) print(count) count += 1

五、将代码进行分布执行(方便我们找bug)