python合集(2)----------三大流程控制

1. 三大流程

在这里插入图片描述

1.1分支流程控制

**标准if语句:**
if expression:
     if_suite
**if-else语句:**
if exprssion:
     if_suite
else:
     else_suite
**if-elif-else语句**
if expression1:
     if_suite
elif expression2
     elif_suite
else:
     else_suite   
#python 中input 接受的是字符串,所以整型需要int转换为整型
age = int(input('年龄:'))
#python 特性:简介和可读性好;python的语法规范:冒号,缩进
if age > 22:
    print("男性法定结婚年龄")
else:
    print("非男性法定结婚年龄")
#转换三元运算符:简化代码
print("男性法定结婚年龄" if age>22 else "非男性法定结婚年龄" )
"""
要求: 成绩记录
1.90<=score<==100,grade=A
2.80<=score<=90,grade=B
3.score<80,grade=c
"""
score = int(input('成绩:'))
if 90<=score<=100:
    print("grade=A")
#elif:满足其余条件
elif 80<=score<=90:
    print("grade=B")
else:
    print("grade=c")

1.2循环流程控制

**第一类循环语句:while语句**:
循环原理:while 循环的 suite_to_repeat 子句会一直循环执行, 直到 expression 值为布尔假
while expression:
      suite_to_repeate
while语句语法结构:
1.计数循环:
count =0
while(count<9)
  print('the index is',count)
  count +=1
2.无限循环
while True
  cmd = input()
  if cmd:
     os.system(cmd)
**#无限循环**
try_count = 1
while True:
     print(f"user is loginning systemctl {try_count} times")
     try_count += 1
     name = input("user: ")
     passwd = input("passwd: ")
     if name == "root" and passwd == "westos":
           print(f"{name} is login")
           exit()
     else:
           print(f"{name} is not login")

Python 的 for语句更加简洁,for循环原理:
可以遍历序列成员, 可以用在 列表解析 和 生成器表达式中, 它会自动地调用迭代器的 next()
方法, 捕获 StopIteration 异常并结束循环(所有这一切都是在内部发生的).在这里插入图片描述

#for语法结构:
**range() 内建函数**
range语法:
range(start, end, step =1)返回一个包含所有 k 的列表, start <= k < end , k每次递增 step

range(3)	[0,1,2]
range(1, 5)	[1,2,3,4]
range(0, 8, 2)	[0,2,4,6]
string = 'haha'
for item in string:
     print('变量:'item)
**序列类型for循环**
for item in range(1.8):
    print('变量:'item) 
跳出循环语句:
break语句:用来终止循环语句,即循环条件没False条件或者序列还没被完全递归完,也会停止执行循环语句。
continue语句: 跳过当前循环的剩余语句,然后继续进行下一轮循环。
**break:**
count = 0
while count <= 10:
    count += 1
    print(count)
    if count == 5:
        break
    print(f"success")
**continue:**
count = 0
while count <= 10:
    count += 1
    print(count)
    if count == 5:
        continue
    print(f"success")

1.3循环语句实验

1.3.1九九乘法表

i=1 j=1   1*1
i=2 j= 1,2 1*2 2*2
i=3 j=1,2,,3     1*3 2*3 3*3
for b in range(1,10):
    for c in range(1,b+1):
        print(f"{b}*{c}={b*c}",end=' ')
    print()

1.3.2防黑客暴力破解的用户登录系统

try_count = 1  用户尝试登录次数
while try_count<=3: 用户尝试登录次数不超过3print(f"user is loginning systemctl {try_count} times")
     try_count += 1 用户尝试登录次数加1
     name = input("user: ")
     passwd = input("passwd: ")
     if name == "root" and passwd == "westos":
           print(f"{name} is login")
           exit()
     else:
           print(f"{name} is not login")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值