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
Iván Higuera-Mendieta
764 PointsPick a number challenge
Hi to all,
I have been trying a different approach from the solution proposed by Kenneth, but I am having troubles with the loop. When I try to run the code, the second guess does not work; the error appears to be something with the loop.
First I called "random" and define the functions:
import random
number_guesses = []
def show_inst():
print ("Guess a number between 1 and 10")
def high_guess():
print ("{} Is not the right number ".format(guess))
print ("Muy alto!")
def low_guess():
print ("{} Is not the right number ".format(guess))
print ("Muy bajo!")
def right_guess():
print ("Great! {} is the right number".format(guess))
def number_guess(int):
number_guesses.append(int)
print("You have tried {} times".format(len(number_guesses)))
def random_num(int):
random = random.randint(1, int)
return random
Then, I start the loop:
show_inst()
while True:
guess = int(input())
random_num(guess)
if guess == random:
right_guess()
break
elif guess < random:
low_guess()
number_guess(guess)
continue
elif guess > random:
high_guess()
number_guess(guess)
continue
I know that Kenneth's solution is more elegant, but I want my solution to work, it would be a push :)
Thanks in advance
2 Answers
mrben
8,068 PointsNearly there! A couple of things need fixing...
When you call this...
random_num(guess)
... you need to store the return value in a variable so you can use it in the if statements. You're referencing a random variable in the if statements (e.g. if guess == random:) so that would be the obvious choice. However, this would mean overwriting the module you import with import random so future calls to the random function would fail.
I suggest changing random_num() to:
def random_num(int):
return random.randint(1, int)
Then when you call it, store the result in a variable that is not called "random" and use that variable name in your if statements.
Iván Higuera-Mendieta
764 PointsThank you very much!