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!

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

Is this a good solution? Improvements? I Appreciate Any Input...

Would really appreciate some feedback. Thanks

# Import functionality
import random

def game_play():

    # Set up variables
    comp_number = random.randint(1,10)
    chances = 5
    guesses = 0

    # Initial Print statements
    print("This game will generate a random number between 1 and 10")
    print("You will be given 5 chances to guess the generated number. Go!")

    # Game loop
    while chances > 0:

        play = input("Enter a number between 1 and 10, inclusive. ")


            my_guess = int(play)

            if my_guess < 1 or my_guess > 10:
                print("I'm sorry your guess must be between 1 - 10! Thanks.")

            guesses += 1
            chances -= 1

            if my_guess == comp_number:
                print("You guessed it in {} guess(es)!".format(guesses))
                print("Nope. You have {} chances left.".format(chances))

        except ValueError:
            print("Your answer MUST be a number")


2 Answers

The only thing I can tell is why have two things doing the same? guesses & chances?.. just use one..

you could just set a default guess to 5.. then count it down.. when it reaches zero.. end the game..

and also why are you setting/starting a new game if guess is < 1 or > 10.. that makes no sense.. you could either disregard it and prompt for another one or just give an error and count it as a guess.. but I would go with the first option..

finally I have heard we should use random-range.. instead of what you are using to generate a random number.. as your method has some "problem".. not quite sure what but the way it generates random numbers..

Thank you - I will take your recommendations into consideration and re-write this. I really appreciate your honest words...

  • Adam