# 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) > 25 or int(guess) < 0:
guess = raw_input("Please enter a VALID guess: ")
else:
# my attempt at making the game loop
while tries < 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) > 25 or int(guess) < 0:
while int(guess) > 25 or int(guess) < 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.

• Looks nice, but if you enter a letter, it errors, saying it can't convert it to a number. – FreezePhoenix Jan 27 '19 at 2:13
• Yeah that was what I figured, was just doing it for learning purposes. I'm not super far into Python 2 so it may not be too late to start on Python 3 and then continue learning and getting better! Thanks for checking it out though! – Dewayne Redding Jan 27 '19 at 2:26
• There isn't that much different with Python 3, (I think the only thing affected in your program is that print is a function and not a statement, and raw_input is now input). As Python 2 is now depreciated, I would definitely move up to it right now. – Baldrickk Feb 7 '19 at 16:34

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')
• 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 < 0 or guess > 25, you can do if not 0 <= guess <= 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.

1. Generate a secret number
2. Collect a guess from the user
3. 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:
else:
if LOW <= guess <= 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.')
• I appreciate you checking this out! Thanks and I'll start looking into it! – Dewayne Redding Jan 27 '19 at 1:09

So what I did here is I took your suggestions and read up on why you were doing what you were. Seems I haven't learned Try and Except yet but I'm reading up on it. I'm very thankful for your help. I modified some things to make it work for me and very much learned from what you set up. Thanks again! Here's what I have as of now.

# guess the number game
from random import randint

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 for the game
LO, HI = 0, 25
MAX_TRIES = 10

def main():
# generate random number each game

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

print "You Win!"
break
if MAX_TRIES == 10:
print "Too many tries. You Lose!"

# function to determine if input was an int
def get_guess():
while True:
try:
guess = int(raw_input("Please enter a number (0-25): "))
except ValueError:
print "Please enter a number: "
else:
if LO <= guess <= HI:
return guess
print "Please enter a number between %s and %s" % (LO, HI)

main()
• You haven't tried running this, have you? MAX_TRIES never changes, so your test as to whether you lose will always trigger. If you get the answer, you will win, and then instantly lose too. I would use a local variable like so: tries_remaining = MAX_TRIES while get_guess() != answer and tries_remaining > 0: __tries_remaining -= 1 if tries_remaining > 0: __print "You Win!" else: __print "Too many tries. You lose!" (substitute underscores for spaces at the beginning of lines, comments are not suited for answers) – Baldrickk Feb 7 '19 at 16:55
• The above fixes the issue with the duplicate result. Simply put, it moves all of the logic for the answer message out of the loop, ensuring that you can only get one message. It also uses a while loop, which is more in keeping with tracking conditions, instead of a for which is usually used for iterating through an entire set or a fixed number of iterations – Baldrickk Feb 7 '19 at 16:57