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 Python Basics (2015) Number Game App Number Game Takeaways

Mark Kohner
Mark Kohner
1,760 Points

Python: Number game takeaways, extra Reverse number game logic problems

I found the problem of making a 'reverse' number game interesting, and I am able to get it to mostly work but through sloppy code that is tedious to make. I imagine there is some elegant solution that I am very curious to see!

import random computer_guess = random.randint(1, 20)

now when the computer makes a random guess, and it takes input of too high or too low;

user_choice = input()

ie we choose 10

if the computer guesses 11, we input 'lower', here is where my issue comes in.

How can we format the code so that it loops through and limits the ranges of choices?

if answer.lower() == 'low':
    # answer will have to be higher
    print("I will guess higher next time.")
    second_choice = random.randint(number, 20)

if answer.lower() == 'high':
    # next answer has to be lowered
    print("I will guess lower next time.")
    second_choice = random.randint(1, number)

this gets the range lowered appropriately, but I do not see how to work this into a loop. It resets if typed repeatedly. How to narrow the range in a loop with each guess until an accurate guess is achieved?

2 Answers

Steven Parker
Steven Parker
231,275 Points

:point_right: Narrowing the range is just a matter of retaining both limits.

Based on the user's input each time through the loop, you can update either the low limit or the high limit for the next pick:

if answer.lower() == 'low':
    # answer will have to be higher
    print("I will guess higher next time.")
    lownum = computer_guess + 1

if answer.lower() == 'high':
    # next answer has to be lowered
    print("I will guess lower next time.")
    highnum = computer_guess - 1

# pick the next guess within the new range
computer_guess = random.randint(lownum, highnum)