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 trialMahmoud Galal
553 PointsHow 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
Jeremiah Bushau
24,061 PointsHi, 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)