0

For a class assignment, I'm trying to make a number guessing game in which the user decides the answer and the number of guesses and then guesses the number within those limited number of turns. I'm supposed to use a while loop with an and operator, and can't use break. However, my issue is that I'm not sure how to format the program so that when the maximum number of turns is reached the program doesn't print hints (higher/lower), but rather only tells you you've lost/what the answer was. It doesn't work specifically if I choose to make the max number of guesses 1. Instead of just printing " You lose; the number was __", it also prints a hint as well. This is my best attempt that comes close to doing everything that this program is supposed to do. What am I doing wrong?

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!")
4

1 回答 1

1

这样的事情呢?

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在开始下一个循环之前评估您为循环指定的条件。如果这有助于解决您的问题,您最好点击我帖子的复选标记

于 2019-03-05T21:05:29.827 回答