Search code examples
pythonif-statementwhile-loopand-operator

Python while loop number guessing game with limited guesses


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

Solution

  • What about something like this?

    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
    

    It's very similar to your program, but has a couple break statements in there. This tells Python to immediately stop execution of that loop and go to the next block of code (nothing in this case). In this way you don't have to wait for the program to evaluate the conditions you specify for your while loop before starting the next loop. If this helped solve your problem, it'd be great of you to click the checkmark by my post