Guess-the-number game by a Python beginner For some background I'm pretty much a beginner and attempting to learn Python currently. So I decided after a few days of lessons I'd look for some beginner projects to test my knowledge. A website suggested I do a 'Guess the Number' game and basically suggested I follow this guideline.


Random function
Variables
Integers
Input/Output
Print
While loops
If/Else statements


In short I read the documentation on random and decided to give it a shot. Now for the actual question. Is this a good way of doing this or can I simplify it?

I've pretty much been working at this for longer than I would like to admit (approximately 90 minutes), because I'd get stumped and then rewrite what I was thinking.

# guess the number game
import random

print "Welcome to guess the number!"
print "You have 10 tries to guess the correct number!"
print "The range of numbers will be from 0-25"

# variables to store winning number, user guess and number of tries
number = random.randint(0, 25)
guess = raw_input("Please enter a number (0-25): ")
tries = 0

# check to see if the user guessed the right number
if int(guess) == number:
    print "Congratulations you\'ve won!"

# noticed that you could input invalid numbers and it counted as a guess so this is how i solved that
while int(guess) &gt; 25 or int(guess) &lt; 0:
    guess = raw_input("Please enter a VALID guess: ")
else:
    # my attempt at making the game loop
    while tries &lt; 10 and int(guess) != number:
        guess = raw_input("Please guess again: ")
        tries = tries + 1
        # i noticed if i guessed the right answer out of the loop it would just exit so i duplicated here to prevent it
        if int(guess) == number:
            print "Congratulations you\'ve won!"
        # implemented the lose mechanic
        elif tries == 10:
            print "You've Lost!"
        # same with the correct answer issue i had so i put it in the loop as well
        elif int(guess) &gt; 25 or int(guess) &lt; 0:
            while int(guess) &gt; 25 or int(guess) &lt; 0:
                guess = raw_input("Please enter a VALID guess: ")
                # this is here because I didn't want to take tries away for invalid guesses
                tries = tries


So the game for me works as expected. You can win, lose, guess invalid numbers (I haven't tried letters but I won't get into that yet). Just not sure if this is the most efficient I can get. But if it's good enough for a beginner, I'll take it.
This is a good first stab at a guess the number game.

Here's a few things:


You should be learning/using Python 3 instead of Python 2. So far the only difference for you will be raw_input becomes input and print "foo" becomes print("foo").
The line tries = tries doesn't do anything meaningful. You don't need it
You should put all of this inside a function called main and then at the bottom you run it with this (tests if this script is being run standalone):




if __name__ == '__main__':
    main()



You do int(guess) a lot. This is something that can fail (if someone types abc for example). You should do it once and check for failure.




try:
    guess = int(guess)
except ValueError:``
    print('Guess must be between 0 and 25')
    # ask for another guess



It's a good idea to comment. That's a fantastic habit to get into. However, you run the risk of over-commenting. And that is more distracting than having too few. As a rule, don't explain what, explain why. More concretely, "check to see if a user guessed the right number" is obvious from the if guess == secret_number:. Finding a balance is a skill, but if you work on it and read good quality open source code, you'll pick it up.
When you do your range check, you can do it in a much more pythonic way. Instead of checking guess &lt; 0 or guess &gt; 25, you can do if not 0 &lt;= guess &lt;= 25
tries = tries + 1 can be tries += 1
You don't need to escape ' inside a " (so "Congratulations you\'ve won!" can be "Congratulations you've won!")


The overarching issue you have though is most of your logic is duplicated in several different places. This becomes a problem if you want to, say, change the number range from 0-25 to 0-50. You'd need to change that in 6 places. What happens if you miss one? Then your game will break in weird ways.

What's the solution? Look to pull out duplicate logic like this into smaller, manageable chunks. In this case, it's helpful to identify the steps of your game.


Generate a secret number
Collect a guess from the user
If the user guessed the secret or more than 10 attempts have been made, end, else go back to 2


One easy thing you can pull out is "collect a guess from the user." You can do this in a function that gets the number, converts it to an int (handling the exception), and checking it is within range.

LOW, HIGH = 0, 25

def get_guess():
    while True:
        try:
            guess = int(input(f'Guess a number between {LOW}-{HIGH}: '))
        except ValueError:
            print('Please enter a number')
        else:
            if LOW &lt;= guess &lt;= HIGH:
                return guess

            print(f'Number must be between {LOW} and {HIGH}')


Now you can use get_guess() when you need to guess the guess from the user without having to add any extra control structures (like wrapping everything in a while) or duplicate any logic.

Now, when using get_guess() you can concern yourself with fewer facets of the game. Namely, checking the number of attempts and if the guess was correct:

from random import randint

MAX_ATTEMPTS = 10

def main():
    secret = randint(LOW, HIGH)

    for _ in range(MAX_ATTEMPTS):
        guess = get_guess()

        if guess == secret:
            print('You win!')
            break
    else:
        print('Too many attempts; you lose.')