Skip to content
Advertisement

In a Python guessing game, how do you stop the lower/upper limit from changing after it’s already changed?

I’m a beginner so please forgive me if this is a dumb question. I wrote this guessing game (using a tutorial) where the user selects an upper bound and then a random number is chosen as the “secret number.”

When the user makes a guess and it’s lower/higher than the secret number, the lower/upper limit changes to give the user a hint. For example, the secret number is 50. The user types in 30. The lower limit changes from 0 to 30.

In the next attempt, if the user types a number below 30, the lower limit goes back down. For example, in the second attempt, user writes 20. In the third attempt, the lower limit is now 20.

I can’t figure out how to stop that from happening. Instead of the lower limit changing, I want the program to tell the user that they can’t go lower/higher than the number they guessed in the previous attempt.

Here’s the code:

import random
while True:
    flag=True
    while flag:
            num = input("Choose an upper bound: ")
            if num.isdigit():
                print("Let's play!")
                num=int(num)
                flag=False
            else:
                print("Invalid input. Try again: ")
    secret_number = random.randint(1, num)
    no_tries=0
    max_tries=3
    lower_limit=0
    upper_limit=num ```

    while no_tries<max_tries:
        guess = int(input(f"Please type a number between {lower_limit} and {upper_limit} "))
        no_tries=no_tries+1
        if guess==secret_number:
            print("You won!")
            break
        elif guess<secret_number:
            print(f"You've guessed wrong.")
            lower_limit=guess
        elif guess>secret_number:
            print(f"You've guessed wrong.")
            upper_limit=guess
    else:
        print("You have used all three tries. You lose!")
    user_input=input("Would you like to play again? Y/N: ").upper()
    if user_input=="N":
        print("Game over")
        break





Advertisement

Answer

Check if lower_limit is less than guess / upper_limit is more than guess before assigning.

if guess == secret_number:
    print("You won!")
    break
elif guess < secret_number:
    if lower_limit < guess:
        print("You've guessed wrong.")
        lower_limit = guess
    else:
        print(f"You can't go lower than {lower_limit}!")
elif guess > secret_number:
    if upper_limit > guess:
        print("You've guessed wrong.")
        upper_limit = guess
    else:
        print(f"You can't go higher than {upper_limit}!")
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement