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

Python Python Basics (Retired) Pick a Number! Any Number! The Solution

My guessing game works, but I'm sure the code could be improved. Any suggestions?

My guessing game works well from what I can see, including counting and limiting guesses and asking for a specific input to start again. I've tested all I can think of and fixed little problems here and there. I'd love to know what I can do to make it "cleaner" though. Thanks!

import random

def main_game():
  print("You have 5 guesses!")
  rand_num = random.randint(1,10)
  guess_count = 5
  while True:
    guess = input("Pick a number between 1 and 10!: ")
    try:
      user_num = int(guess)
    except:
      print("That wasn't a number! Try again. You have {} guesses.".format(guess_count))
      continue
    guess_count = guess_count - 1
    if user_num == rand_num:
      print("Great job! The number was {}. You got it in {} guesses!".format(rand_num,5-guess_count))
      play_again()
    elif guess_count == 0:
      print("You ran out of guesses! The number was {}. Better luck next time!".format(rand_num))
      play_again()
    elif user_num >= rand_num:
      print("Too high! You have {} more guesses. Guess again!".format(guess_count))
      continue
    elif user_num <= rand_num:
      print("Too low! You have {} more guesses. Guess again!".format(guess_count))
      continue

def play_again():
  print("Thank you for playing! Type 'P' to play again.")
  again = input("> ")
  if again == "P":
    main_game()
  elif again != "P":
    print("Command not recognized.")
    play_again()

main_game()
play_again()

1 Answer

Sean May
Sean May
9,145 Points

That's pretty well done, I can't see any major ways you could change how the script functions...really, the only thing I can see is you could change your instances of checklist = checklist - 1 into checklist -= 1 as they do the same thing.