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 trialSteven Wheeler
2,330 PointsFeedback on my solution? Very different from the video!
def game():
import random
compGuess = random.randint(1,11)
numberOfGuesses = 0;
MAX_GUESSES = 5
def losingMessage():
print("Sorry, you have run out of guesses! My number was: {}\n".format(compGuess))
print("Play again? (y/n)")
userChoice = input(">>> ")
if userChoice.lower() == "y":
game()
else:
print("Better luck next time!")
exit()
def winningMessage():
print("Congratulations! You were correct, {} was my number. It took you {} guesses".format(compGuess, numberOfGuesses))
print("Play again? (y/n)")
userChoice = input(">>> ")
if userChoice.lower() == "y":
game()
else:
print("See you next time!")
exit()
while True:
userGuess = input("Enter a number between 1 and 10 >>> ")
if (int(userGuess) == compGuess):
winningMessage()
print("Sorry, that isn't my number. Try again!")
numberOfGuesses += 1
print("You have used {} out of {} guesses".format(numberOfGuesses, MAX_GUESSES))
if (numberOfGuesses == MAX_GUESSES) :
losingMessage()
game()
It works perfectly, except I wouldn't mind adding in a way of ensuring the input is between 1-10. I think there was probably a better solution of looping the script (when the user wants to play again) without putting it all in a function (game()). Also, maybe I could have used "break"? But I'm pretty bad when it comes to thinking about while loops etc.
Also... is random.randint(1,11) correct for getting a range of 1-10?
2 Answers
Ricky Catron
13,023 PointsFirst: Imports should be outside of any functions.
Second: Functions should not usually be nested in other functions. Maybe make a class?
Third: Since winning or losing could be represented as booleans maybe you could incorperate that into your while loop? Example:
``python while hasNotLost and hasNotWon: #do thing
You have done a great job and seem to know a lot of python! I would recommend focusing on how and why things work for a little bit then restructure this to learn more. Maintain a program is almost as important as building it. Keep up the good work!
Goodluck!
--Ricky
Kenneth Love
Treehouse Guest Teacherrandint(1, 11)
will give you a number between 1 and 11, inclusive (so 11 can be given).
If you want to check that their guess is between 1 and 10, do it :) if not int(guess) in range(1, 11):