Python while 循环猜数游戏,猜数有限

Python while loop number guessing game with limited guesses

对于 class 作业,我正在尝试制作一个数字猜谜游戏,用户可以在其中决定答案和猜测次数,然后在有限的回合数内猜出数字。我应该使用带有 and 运算符的 while 循环,而不能使用 break。然而,我的问题是我不确定如何格式化程序,以便在达到最大转数时程序不打印提示(higher/lower),而只是告诉你你已经 lost/what 答案是。 如果我选择最大猜测次数为 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!")

像这样的事情怎么样?

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 循环指定的条件,然后再开始下一个循环。如果这有助于解决您的问题,请点击我的 post

旁边的复选标记。