• python-循环while


    while

    只要…条件成立,就一直做…。

      for 循环会在可迭代的序列被穷尽的时候停止,while 则是在条件不成立的时候停止,因此 while 的作用概括成一句话就是:只要…条件成立,就一直做…。

    死循环例子:
    while 1< 3:
    print('1 is smaller than 3 ')
    解决死循环的方法
    方法一:在程序中制造某种可以使循环停下来的条件
    count = 0
    while True:
    print('Repeat this line!')
    count = count + 1
    if count == 5:
    break
    方法二:
    让 while 循环停下来的另外一种方法是:改变使循环成立的条件
    给登录函数增加一个新功能:输入密码错误超过3次就禁止再次输入密码。
    password_list = ['*#*#','12345']

    def account_login():
    tries = 3
    while tries > 0:
    password = input('Password:')
    password_correct = password == password_list[-1]
    password_reset = password == password_list[0]

    if password_correct:
    print('Login success!')
    elif password_reset:
    new_password = input('Enter a new password:')
    password_list.append(new_password)
    print('Password has changed successfully!')
    account_login()
    else:
    print('Wrong password or invalid input!')
    tries = tries - 1
    print(tries, 'times left')
    else:
    print('Your account has been suspended')
    account_login()
    第4~5行:增加了while循环,如果tries>0 这个条件成立,那么便可输入密码,从而执行辨别密码是否正确的逻辑判断:
    第20~21行:当密码输入错误时,可尝试的次数tries减少1:
    第23~24行:while循环的条件不成立时,就意味着尝试次数用光,通告用户账户被锁。
    
    
  • 相关阅读:
    Debian 8(jessie)下设置系统启动直接进入命令行,无GUI
    Unity 查找物体对象
    Unity的生命周期函数
    Unity脚本实现添加子物体
    Unity工程中 .Meta 文件
    Unity 中简单的第三人称摄像机跟随
    github删除自己的库--Deleting a repository
    TypeScript函数
    Egret引擎学习笔记
    Egret引擎list内单个渲染对象代码编写
  • 原文地址:https://www.cnblogs.com/goodright/p/5893741.html
Copyright © 2020-2023  润新知