【问题标题】:how to ask what something is (input) then if they get it wrong it'll ask them again (while loop) [duplicate]如何问什么是(输入)然后如果他们弄错了它会再次问他们(while循环)[重复]
【发布时间】:2015-07-04 14:55:36
【问题描述】:

我正在计算 GCSE 并开始编写新代码以获得乐趣,但我遇到了像菜鸟一样的麻烦。我正在制作一个代码,询问他们密码是什么,如果他们弄错了,它会再次询问,直到满足要求为止,我在互联网上查看过,它给了我所有我检查过的网站的倒计时。到目前为止,这是我的代码......

password = 1234
passinput = (input("what is your password? "))

我已经尝试了几种方法,例如...

while True:

while False:

但我不明白如何正确使用它们。我在课堂上学过,但很容易忘记。我希望代码继续询问用户,直到他们输入“1234”(密码)

请帮忙。

【问题讨论】:

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


    【解决方案1】:

    简单的答案是:

    while True:
        answer = input('password?')
        if answer == password:
            break
    

    对于更复杂的需求(或对选项的更好理解),请参阅Asking the user for input until they give a valid response

    【讨论】:

    • 它一直循环而不是中断。
    • @ChimpeusStyx:试试password = "1234"
    【解决方案2】:

    更简单的方法

    password = 1234
    while int(input()) != password: pass
    

    【讨论】:

    • 即使我输入密码,这段代码也会循环
    • @CimpeusStyx 不,这只会循环,直到您输入正确的密码,即此处的 1234。
    【解决方案3】:

    捷径:

    while True:
        if input("what's the password? ") == "1234":
            break
    

    甚至更短:

    while input("what's the password? ") != "1234":
        pass
    

    或者,如果您坚持使用单线:

    while input("what's the password? ") != "1234": pass
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 2022-01-24
      • 1970-01-01
      • 2017-01-30
      相关资源
      最近更新 更多