【问题标题】:Why does my code skip input prompts after the second one?为什么我的代码在第二个之后跳过输入提示?
【发布时间】:2020-06-17 22:17:33
【问题描述】:

我已经研究了一段时间,任何帮助都将不胜感激。

secret = "Meow"
guess = ""
limit = 1

while guess != secret and limit <= 5:
    if limit == 2:
        print("You have 4 guesses left!")
    elif limit == 3:
        print("You have 3 guesses left!")
    elif limit == 4:
        print("You have 2 guesses left!")
    elif limit == 5:
        print("You have 1 guess left!")

    if limit == 1:
        guess = input("What's the secret? OwO You have 5 guesses. ")
    elif limit <= 2:
        guess = input("What's the secret? OwO. ")

    limit += 1

print("You cheated! Or lost.")

运行时,它通常是输入尝试,并且在出现问题后,一旦它说还剩 5 次尝试并再次询问输入,但之后它会跳过输入提示,只说剩下的猜测。带有猜测的输出:

What's the secret? OwO You have 5 guesses. idk man  
You have 4 guesses left!  
What's the secret? OwO. 2nd try?  
You have 3 guesses left!  
You have 2 guesses left!  
You have 1 guess left!  
You cheated! Or lost.  

【问题讨论】:

  • 如果限制 > 2 第二个 if-elif-block 中的条件都不为真。

标签: python python-3.x


【解决方案1】:

这是对您的代码的改进

secret = "Meow"
guess = ""
limit = 1

while guess != secret and limit <= 5:

    if limit == 1:
        guess = input("What's the secret? OwO You have 5 guesses. ")
    elif limit >= 2: #here was your mistake
        print("You have {0} guess left!".format(5-limit+1))
        guess = input("What's the secret? OwO. ")

    limit += 1

print("You cheated! Or lost.")

【讨论】:

  • @Kayo 我想你想要这样的 val=5-limit+1。 print(f"你还有 {val} 个猜测!")
  • 我实际上有点搞砸了,并意识到我可以将括号中的 0 替换为 5 - limit + 1 :)
【解决方案2】:

只要改变这个:

elif limit &gt;= 2:

secret = "Meow"
guess = ""
limit = 1

while guess != secret and limit <= 5:
    if limit == 2:
        print("You have 4 guesses left!")
    elif limit == 3:
        print("You have 3 guesses left!")
    elif limit == 4:
        print("You have 2 guesses left!")
    elif limit == 5:
        print("You have 1 guess left!")

    if limit == 1:
        guess = input("What's the secret? OwO You have 5 guesses. ")
    elif limit >= 2:
        guess = input("What's the secret? OwO. ")

    limit += 1

print("You cheated! Or lost.")

【讨论】:

  • 谢谢! :) 我认为这很愚蠢,我只是找不到它
  • 好的。如果您觉得这对您有帮助,请不要忘记投票并接受您有足够声誉的答案,
猜你喜欢
  • 1970-01-01
  • 2011-08-30
  • 1970-01-01
  • 2021-10-17
  • 1970-01-01
  • 2021-11-24
  • 2020-09-08
  • 1970-01-01
相关资源
最近更新 更多