Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics (2015) Number Game App Number Game Takeaways

How can I get the computer to vary the number it is guessing?

I am trying the extra credit assignment and I managed to make the script to work for the purpose of the assignment:

import random

mynum = int(input("Enter Your number, but only make it between 1 and 10"))

comnum = random.randint(1,10)

comguess = []

while len(comguess) < 5: if comnum == mynum: print ("i figured it out") elif comnum > mynum or comnum < mynum : print ("Ok i cannot figure it out, I guessed {}.".format(comnum)) comguess.append(comnum)

My concern here is that the computer keeps guessing the same number.. How do I get the computer to move towards the right answer? Do I have to write two for loops? one with += and the other with -= ??

Can someone also please tell me as to why the computer does not intuitively just randomize it's choice despite already using the random module?

Thanks! :)

1 Answer

Hi, try putting comnum inside the while loop.

import random

mynum = int(input("Enter Your number, but only make it between 1 and 10"))

comguess = []

while len(comguess) < 5:
    # put comnum inside the while loop so that it creates a new random number each iteration
    comnum = random.randint(1,10)
    if comnum == mynum:
        print ("i figured it out")
        # added break here incase the number is guessed before the list is > 5
        break
    elif comnum > mynum or comnum < mynum:
        print ("Ok i cannot figure it out, I guessed {}.".format(comnum))
        comguess.append(comnum)