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 trialArshad Hasan
Courses Plus Student 2,841 PointsI tried solving this way. Is my code easily readable or should I make any changes? Need your feedback.
import random
random_number = random.randint(1, 10)
number_of_guesses = 0
def guessingGame(guess):
if guess == random_number:
return ["You won! You guessed the number {} in {} tries.".format(random_number, number_of_guesses), True]
return ["Wrong! Try again.", False]
while number_of_guesses < 5:
number_of_guesses += 1
guess = input("Guess a number between 1 and 10: ")
try:
guess = int(guess)
result_list = guessingGame(guess)
print(result_list[0])
if result_list[1] == True:
break
except:
print("That's not a whole number. Retry.")
3 Answers
man odell
1,905 PointsGJ
Sara Chicazul
7,475 PointsI found your code easy to read! The one suggestion I have is to include a "game over" message if the player fails to guess the number in five tries. Your current code will just print "Wrong, try again!" and then not accept another guess.
Arshad Hasan
Courses Plus Student 2,841 PointsAlright. I'll do that. Thanks for giving a feedback on this, Sara.
Anish Walawalkar
8,534 PointsHey Arshad. Your code looks great and very readable. I would suggest running your app in a while True loop so that the user can keep playing the game until he wants to exit. Use can use a specific user input as a keyword to exit the while loop. For example "Quit", "Stop", "Exit"
Arshad Hasan
Courses Plus Student 2,841 PointsAnish, the problem stated limiting the number of chances to five, otherwise, I believe I could have used implemented that using ifs and elifs.
Thanks for the feedback!
Anish Walawalkar
8,534 PointsYes. I just mean't if that even if the user fails or succeeds to get the answer, a new instance of the game begins until the user explicitly states that he/she wants to leave the game :)
Arshad Hasan
Courses Plus Student 2,841 PointsOh! Nice.
Arshad Hasan
Courses Plus Student 2,841 PointsArshad Hasan
Courses Plus Student 2,841 PointsDidn't get you, ?