【问题标题】:My while loop keeps looping keeps repeating even when the user inputs the correct information即使用户输入正确的信息,我的 while 循环也会不断重复
【发布时间】:2017-11-19 00:01:21
【问题描述】:

我知道该网站有一些关于我的查询的已回答字符串,但它们没有帮助。我正在制作这个程序,管理员知道密码,当被要求输入密码时,如果密码错误,它会要求他们输入密码,直到他们正确为止。

admin_password = input("To view a user's details, enter the admin pasword: ")
while True:
    if admin_password != "AdminLogin":
        print("Incorrect password")
    else:
        break

【问题讨论】:

    标签: python python-3.x while-loop


    【解决方案1】:

    将 admin_password 移到循环内

    while True:
        admin_password = input("To view a user's details, enter the admin 
    pasword: ")
        if admin_password != "AdminLogin":
            print("Incorrect password")
        else:
            break
    

    现在您只使用一次 admin_password 并根据字符串反复检查它。

    【讨论】:

      【解决方案2】:

      你的循环看起来不错。我认为您的问题在于接受输入。您是否正在使用 Python 2 解释器运行 Python 3 代码?看到这个:input string in python 3。顺便说一句,您可以使用这段代码。对我来说很好用。

      admin_password = raw_input("To view a user's details, enter the admin pasword: ")
      
      while admin_password != "AdminLogin":
          admin_password = raw_input("To view a user's details, enter the admin pasword: ")
      
      print "Logged In"
      

      【讨论】:

      • 哦,我的错。我正在使用 Python 2.7。你是对的。 raw_input 在 Python 3 上不起作用
      猜你喜欢
      • 2020-08-28
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      • 1970-01-01
      相关资源
      最近更新 更多