【问题标题】:Print statement printing infinitely打印语句打印无限
【发布时间】:2017-09-26 17:04:53
【问题描述】:
password=input("Please enter your chosen password within 8 and 24 letters: ")
while len(password)>8 and len(password)<24:
    print("this password is within the given length range")
else:
    password=input("Please enter a password within the boundaries: ")

当我运行代码并且输入的密码长度超过 8 和 24 时,它只会无限打印“此密码在给定长度范围内”。 我不擅长编码,我确定我做错了什么。

【问题讨论】:

  • while?为什么while
  • 发帖前请先了解编程的基本概念。

标签: python printing while-loop


【解决方案1】:

如果您想不断提示他们输入密码,您需要像这样在您的 while 循环中提示您并更改小于和大于符号。

password = ""
while len(password) < 8 or len(password) > 24:
    password = input("Please enter your chosen password within 8 and 24 letters: ")

【讨论】:

    【解决方案2】:

    else 仅在您使用 break 退出 while 循环后执行(与条件变为 false 时相反)。你只是想要

    password=input("Please enter your chosen password within 8 and 24 letters: ")
    while len(password) < 8 or len(password) > 24:
        password=input("Please enter a password within the boundaries: ")
    

    如果您不介意对两个输入使用相同的提示,请使用带有显式中断的无限循环:

    while True:
        password=input("Please enter your chosen password within 8 and 24 letters: ")
        if 8 <= len(password) <= 24:
            break
    

    【讨论】:

      【解决方案3】:

      您将有效密码存储在“密码”变量中。 while 循环检查“密码”是否有效,确认有效,然后继续运行。如果用户输入无效密码而不是有效密码,您希望循环继续进行。试试:

      password=input("Please enter your chosen password within 8 and 24 letters: ")
      while len(password)<8 or len(password)>24:
          password=input("Please enter a password within the boundaries: ")     
      
      print("this password is within the given length range")
      

      【讨论】:

        【解决方案4】:

        您忘记了停止循环的break 语句。而且循环语句有问题,主要是你缺少elseif部分。

        password=input("Please enter your chosen password within 8 and 24 letters: ")
        while True:                                   #will continue until break statement executes
            if len(password)>8 and len(password)<24:
                print("this password is within the given length range")
                break                                                                #Quit the loop
            else:
                password=input("Please enter a password within the boundaries: ")
        

        上述代码将一直运行,直到用户输入密码8 &lt; length &lt; 24

        【讨论】: