Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

User input answer and python guess a number. if it's not right, python should give another number. Is this achievable?

import random
def ans():
print("""
You'll guess a number and check if it's right:
Please choose 'N' if the answer is no.
Please choose 'Y' if the answer is yes.
""")

answer = random.randint(1,10)
ans()
while True:
    try:

        secret = int(input("->"))
        print("The number i've guessed is:")
        print("{} is right?".format(answer))

        #secret.append(guess)
        if secret > answer:
            print("Too Low")
            continue

        elif secret < answer:
            print("Too high")
            continue
        elif secret == answer:
            print("Yeah !")
            break

    except ValueError:
        print("{} is not a valid number".format(guess))

[MOD: fixed formatting -cf]

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points

If you want the secret provided by the user to persist, you can move the input statement before the while loop. Then move setting the random answer value to inside the loop, but use variables of lower_bound and upper_bound in place of the 1 and 10. Now when the guess is too low or too high, you can modify the correct bound with the previous guess and generate a new answer on the next loop iteration.

Post back if you have more questions. Good luck!!