zoukankan      html  css  js  c++  java
  • 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循环的条件不成立时,就意味着尝试次数用光,通告用户账户被锁。
    
    
  • 相关阅读:
    python读写excel利器:xlwings 从入门到精通
    认识--类 ( Class ) 面向对象技术
    python 平均值/MAX/MIN值 计算从入门到精通
    python读写word文档 -- python-docx从入门到精通
    【模板】KMP算法
    【模板】主席树
    C语言第一次博客作业
    C语言--第0次作业
    Chapter5:语句
    Chapter4:表达式
  • 原文地址:https://www.cnblogs.com/goodright/p/5893741.html
Copyright © 2011-2022 走看看