Python(7)循环语句

while 循环

语法:
    while 条件表达式:
        代码块
  • 执行流程
    1. while 语句在执行时,会先对 while 后的条件表达式进行判断
    2. 如果为True那么执行代码块
    3. 如果为False则终止循环

条件表达式恒为 True 的循环语句,我们称为 死循环,它会一直运行。

例如:

while True:
    print("死循环")

循环三要素(表达式)

  1. 初始化表达式,通过初始化一个变量来实现
    • i = 0
  2. 使用我们初始化的变量当作条件表达式
    • while i < 10:
  3. 更新变量
    • i += 1
i = 0
while i < 10:
    i += 1

练习1

求 100 以内所有奇数的和

count = 0

number = 0

while count < 100:
    count += 1
    if count % 2 == 1:
        number += count

print(number)

练习2

求 100 以内所有 7 的倍数的和

count = 0

number = 0

while count < 100:
    count += 1
    if count % 7 == 0:
        number += count

print(number)

练习3

水仙花数,水仙花数是指一个 n 位数 (n >=3),它的每个位上的数字的n次幂之
和等于它本身(例如:13 + 53 + 3**3 = 153)。

求 1000 以内的所有 水仙花数

# 方法一
count = 0
while count < 1000:
    count += 1
    if count >= 100:
        # 取出数字的位数 n
        n = len(str(count))
        # 取出数的所有位上的数字
        b = count // 100
        s = count % 100 // 10
        g = count % 10
        # 进行条件判断
        if b ** n + s ** n + g ** n == count:
            print(count)

# 方法二
count = 0
while count < 1000:
    count += 1
    if count >= 100:
        count_str = str(count)
        # 取出数字的位数 n
        n = len(count_str)
        # 取出数的所有位上的数字
        b = int(count_str[0])
        s = int(count_str[1])
        g = int(count_str[2])
        # 进行条件判断
        if b ** n + s ** n + g ** n == count:
            print(count)

break、continue和pass

  • break 可以用来立即退出循环语句(包括else)

  • continue 可以跳过当次循环

  • pass 用来在判断或循环语句中占位的

  • 用户登录场景模拟

    • 接收用户输入的 usernaem和password
    • 判断是否正确
    • 给三次机会
    • 最终给出欢迎词或错误提示
# 基本功能的实现
login_sign = True

count = 0
while count < 3:
    count += 1

    username = input("username:")
    password = input("password:")

    if username == "admin" and password == "admin":
        print("登录成功")
        login_sign = True
        break
    else:
        print("密码错误")
        print(f"这是你的第{count}次机会,你还有{3 - count}次机会")
        login_sign = False

if login_sign:
    print("欢迎你的使用")
else:
    print("不好意思,你的机会用光了,请联系管理员修改密码")
    
"""
增加功能
1. 判断是用户名出错还是密码出错
2. 当是用户名出错时,不减少机会
"""
login_sign = True

count = 0
while count < 3:
    count += 1

    username = input("username:")

    if username == "admin":
        password = input("password:")
        if password == "admin":
            print("登录成功")
            login_sign = True
            break
        else:
            print("密码错误")
            print(f"这是你的第{count}次机会,你还有{3 - count}次机会")
            login_sign = False
    else:
        print("用户名输入错误")
        print(f"这是你的第{count}次机会,因为是用户名错误所以机会不减少,你还有{(3 - count) + 1}次机会")
        count -= 1

if login_sign:
    print("欢迎你的使用")
else:
    print("不好意思,你的机会用光了,请联系管理员修改密码")
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值