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
Julie Maya
14,666 PointsOpposite version of the game: Plz help me debug
So I've tried to build an app of what Kenneth mentioned in the end of the video: User input a number between 1 and 10, and let the computer guess which number it is.
Here is my code, and can be executed. But I have some bugs:
- How do I limit user input within 1 and 10?
- How do I limit computer not to guess more than 5 times?
- Seems like I didn't ask computer to adjust its answer to make a lower or higher guess. How can I do it?
Any idea, please?
# I give a number
# Ask the computer to guess
# Compare and adjust the number
import random
def game():
try:
secret_num = int(input("Please give a number between 1 and 10, for computer to guess: "))
except ValueError:
print("{} isn't a number or beyond scope".format(secret_num))
game()
else:
guesses = []
while len(guesses) < 5:
computer_guess = random.randint(1, 10)
if computer_guess > secret_num:
print("Computer guessed '{}' but my number is lower.".format(computer_guess))
continue
elif computer_guess < secret_num:
print("Computer guessed '{}' but my number is higher.".format(computer_guess))
continue
else:
print("Yeah! You got it right!")
break
guesses.append(computer_guess)
else:
print("Dear computer, you lost it! My number was {}.".format(secret_num))
play_again = input("Do you want to play again? Y/n ")
if play_again.lower() != 'n':
game()
else:
print("Bye~")
game()
1 Answer
Steven Parker
243,215 Points1. How do I limit user input within 1 and 10?
If the computer is guessing, the player should not have to input the number. Just ask the player to think of a number between 1 and 10.
2. How do I limit computer not to guess more than 5 times?
You can use a for loop:
for try in range(0,5):
Then if the loop ends before winning, the computer can admit defeat.
3. Seems like I didn't ask computer to adjust its answer to make a lower or higher guess. How can I do it?
For each guess, ask the player if the guess is correct, too high, or too low. Then, reduce the guessing range:
computer_guess = random.randint(low, high)
Start low and high at 1 and 10, and for each "too high" guess, set high to guess - 1, and for each "too low" guess, set low to guess + 1.