如何在Python中解决读取过多输入的问题



这是我的问题:

你在传统的"我在想什么数字?"游戏,帮助你的表亲学习他们的7时间表!编写一个游戏,让用户猜测你想的数字。(对于此游戏,数字将始终为42。(

用户被允许进行10次猜测,并犯了一个"错误!"如果他们猜测的数字不是7的倍数。用户最多可以犯一个错误,否则他们将输掉游戏。游戏结束后,你应该一直打印出来。这很有趣。

这里有一个例子:

Guess a multiple of 7: 14
Nope!
Guess a multiple of 7: 32
Mistake! That number isn't a multiple of 7.
Guess a multiple of 7: 28
Nope!
Guess a multiple of 7: 86
Another mistake. Too bad.
That was fun.

这里是另一个例子:

Guess a multiple of 7: 7
Nope!
Guess a multiple of 7: 14
Nope!
Guess a multiple of 7: 126
Nope!
Guess a multiple of 7: 133
Nope!
Guess a multiple of 7: 70
Nope!
Guess a multiple of 7: 77
Nope!
Guess a multiple of 7: 63
Nope!
Guess a multiple of 7: 35
Nope!
Guess a multiple of 7: 126
Nope!
Guess a multiple of 7: 77
Nope!
No guesses left!
That was fun.

如果用户正确输入42,您的程序应该打印出来。您赢了!而不是"不!"!,然后不再要求任何猜测。例如:

Guess a multiple of 7: 42
You won!
That was fun.

现在是我的代码:

guessCount = 0
mistakeMade = False
while True:
guess = int(input("Guess a multiple of 7: "))
if guess % 7 != 0:
if mistakeMade:
print("Another mistake. Too bad.")
break
else:
print("Mistake! That number isn't a multiple of 7.")
mistakeMade = True
else:
if guess == 42:
print("You won!")
break
else:
print("Nope!")
guessCount += 1
if guessCount == 10:
print("No guesses left!")
break

print("That was fun.")

我通过了Grok Learning的每一次检查,除了这个错误:

测试一个隐藏的案例。您提交的内容试图阅读过多输入这发生在您提交的第5行。

我花了很多时间思考它,但它仍然没有解决问题。希望得到大家的帮助。非常感谢。

当一个人犯错误时,您不会增加guessCount。试试这个

wrongGuess = 0
for _ in range(10):
guess = int(input("Guess a multiple of 7: "))
if guess % 7 != 0:
wrongGuess += 1
if wrongGuess > 1:
print("Another mistake. Too bad.")
break
else:
print("Mistake! That number isn't a multiple of 7.")
wrongGuess += 1
else:
if guess == 42:
print("You won!")
break
else:
print("Nope!")
else:
print("No guesses left!")

print("That was fun.")

注意:对于有限计数的类似问题,请尝试使用进行循环

您应该每次进行递增并检查guessCount,因此将其从if条件中删除。


[编辑]旧的不相关答案。

也许:

guess = int(input("Guess a multiple of 7: ").split()[0])

相关内容

  • 没有找到相关文章

最新更新