对于一个班级作业,我正在尝试制作一个数字猜谜游戏,在该游戏中,用户确定答案和猜谜次数,然后在这些有限的回合时间内猜出该数字。我应该和and运算符一起使用while循环,并且不能使用break。但是,我的问题是我不确定如何格式化程序,以便在达到最大转数时,程序不会显示提示(增大/减小),而只会告诉您迷路了/发生了什么答案是。 如果我选择最大猜测数为1,则无法正常工作。不仅打印“您输了,这个数字是__”,它还打印了一个提示。这是我最好的尝试,几乎可以完成该程序应做的所有事情。我在做什么错了?
answer = int(input("What should the answer be? "))
guesses = int(input("How many guesses? "))
guess_count = 0
guess = int(input("Guess a number: "))
guess_count += 1
if answer < guess:
print("The number is lower than that.")
elif answer > guess:
print("The number is higher than that")
while guess != answer and guess_count < guesses:
guess = int(input("Guess a number: "))
guess_count += 1
if answer < guess:
print("The number is lower than that.")
elif answer > guess:
print("The number is higher than that")
if guess_count >= guesses and guess != answer:
print("You lose; the number was " + str(answer) + ".")
if guess == answer:
print("You win!")
答案 0 :(得分:0)
这样的事情呢?
answer = int(input("What should the answer be? "))
guesses = int(input("How many guesses? "))
guess_count = 1
guess_correct = False
while guess_correct is False:
if guess_count < guesses:
guess = int(input("Guess a number: "))
if answer < guess:
print("The number is lower than that.")
elif answer > guess:
print("The number is higher than that")
else: # answer == guess
print("You win!")
break
guess_count += 1
elif guess_count == guesses:
guess = int(input("Guess a number: "))
if guess != answer:
print("You lose; the number was " + str(answer) + ".")
if guess == answer:
print("You win!")
break
它与您的程序非常相似,但是其中有几个break
语句。这告诉Python立即停止执行该循环并转到下一个代码块(在这种情况下为空)。这样,您不必等待程序评估为while
循环指定的条件,然后再开始下一个循环。如果这有助于解决您的问题,请点击我的帖子中的复选标记