Guess-the-number game by a Python beginner












4












$begingroup$


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.










share|improve this question











$endgroup$








  • 1




    $begingroup$
    Looks nice, but if you enter a letter, it errors, saying it can't convert it to a number.
    $endgroup$
    – FreezePhoenix
    Jan 27 at 2:13










  • $begingroup$
    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!
    $endgroup$
    – Dewayne Redding
    Jan 27 at 2:26










  • $begingroup$
    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.
    $endgroup$
    – Baldrickk
    Feb 7 at 16:34


















4












$begingroup$


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.










share|improve this question











$endgroup$








  • 1




    $begingroup$
    Looks nice, but if you enter a letter, it errors, saying it can't convert it to a number.
    $endgroup$
    – FreezePhoenix
    Jan 27 at 2:13










  • $begingroup$
    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!
    $endgroup$
    – Dewayne Redding
    Jan 27 at 2:26










  • $begingroup$
    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.
    $endgroup$
    – Baldrickk
    Feb 7 at 16:34
















4












4








4


1



$begingroup$


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.










share|improve this question











$endgroup$




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.







python beginner python-2.x number-guessing-game






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 26 at 23:42









200_success

130k17155419




130k17155419










asked Jan 26 at 23:22









Dewayne ReddingDewayne Redding

233




233








  • 1




    $begingroup$
    Looks nice, but if you enter a letter, it errors, saying it can't convert it to a number.
    $endgroup$
    – FreezePhoenix
    Jan 27 at 2:13










  • $begingroup$
    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!
    $endgroup$
    – Dewayne Redding
    Jan 27 at 2:26










  • $begingroup$
    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.
    $endgroup$
    – Baldrickk
    Feb 7 at 16:34
















  • 1




    $begingroup$
    Looks nice, but if you enter a letter, it errors, saying it can't convert it to a number.
    $endgroup$
    – FreezePhoenix
    Jan 27 at 2:13










  • $begingroup$
    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!
    $endgroup$
    – Dewayne Redding
    Jan 27 at 2:26










  • $begingroup$
    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.
    $endgroup$
    – Baldrickk
    Feb 7 at 16:34










1




1




$begingroup$
Looks nice, but if you enter a letter, it errors, saying it can't convert it to a number.
$endgroup$
– FreezePhoenix
Jan 27 at 2:13




$begingroup$
Looks nice, but if you enter a letter, it errors, saying it can't convert it to a number.
$endgroup$
– FreezePhoenix
Jan 27 at 2:13












$begingroup$
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!
$endgroup$
– Dewayne Redding
Jan 27 at 2:26




$begingroup$
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!
$endgroup$
– Dewayne Redding
Jan 27 at 2:26












$begingroup$
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.
$endgroup$
– Baldrickk
Feb 7 at 16:34






$begingroup$
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.
$endgroup$
– Baldrickk
Feb 7 at 16:34












2 Answers
2






active

oldest

votes


















4












$begingroup$

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 < 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:
print('Please enter a number')
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.')





share|improve this answer









$endgroup$













  • $begingroup$
    I appreciate you checking this out! Thanks and I'll start looking into it!
    $endgroup$
    – Dewayne Redding
    Jan 27 at 1:09



















0












$begingroup$

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
answer = randint(LO, HI)

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

if guess == answer:
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()





share|improve this answer









$endgroup$













  • $begingroup$
    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)
    $endgroup$
    – Baldrickk
    Feb 7 at 16:55












  • $begingroup$
    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
    $endgroup$
    – Baldrickk
    Feb 7 at 16:57











Your Answer





StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");

StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212292%2fguess-the-number-game-by-a-python-beginner%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









4












$begingroup$

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 < 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:
print('Please enter a number')
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.')





share|improve this answer









$endgroup$













  • $begingroup$
    I appreciate you checking this out! Thanks and I'll start looking into it!
    $endgroup$
    – Dewayne Redding
    Jan 27 at 1:09
















4












$begingroup$

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 < 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:
print('Please enter a number')
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.')





share|improve this answer









$endgroup$













  • $begingroup$
    I appreciate you checking this out! Thanks and I'll start looking into it!
    $endgroup$
    – Dewayne Redding
    Jan 27 at 1:09














4












4








4





$begingroup$

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 < 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:
print('Please enter a number')
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.')





share|improve this answer









$endgroup$



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 < 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:
print('Please enter a number')
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.')






share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 27 at 0:04









Bailey ParkerBailey Parker

2,0641014




2,0641014












  • $begingroup$
    I appreciate you checking this out! Thanks and I'll start looking into it!
    $endgroup$
    – Dewayne Redding
    Jan 27 at 1:09


















  • $begingroup$
    I appreciate you checking this out! Thanks and I'll start looking into it!
    $endgroup$
    – Dewayne Redding
    Jan 27 at 1:09
















$begingroup$
I appreciate you checking this out! Thanks and I'll start looking into it!
$endgroup$
– Dewayne Redding
Jan 27 at 1:09




$begingroup$
I appreciate you checking this out! Thanks and I'll start looking into it!
$endgroup$
– Dewayne Redding
Jan 27 at 1:09













0












$begingroup$

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
answer = randint(LO, HI)

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

if guess == answer:
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()





share|improve this answer









$endgroup$













  • $begingroup$
    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)
    $endgroup$
    – Baldrickk
    Feb 7 at 16:55












  • $begingroup$
    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
    $endgroup$
    – Baldrickk
    Feb 7 at 16:57
















0












$begingroup$

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
answer = randint(LO, HI)

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

if guess == answer:
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()





share|improve this answer









$endgroup$













  • $begingroup$
    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)
    $endgroup$
    – Baldrickk
    Feb 7 at 16:55












  • $begingroup$
    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
    $endgroup$
    – Baldrickk
    Feb 7 at 16:57














0












0








0





$begingroup$

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
answer = randint(LO, HI)

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

if guess == answer:
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()





share|improve this answer









$endgroup$



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
answer = randint(LO, HI)

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

if guess == answer:
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()






share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 27 at 2:25









Dewayne ReddingDewayne Redding

233




233












  • $begingroup$
    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)
    $endgroup$
    – Baldrickk
    Feb 7 at 16:55












  • $begingroup$
    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
    $endgroup$
    – Baldrickk
    Feb 7 at 16:57


















  • $begingroup$
    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)
    $endgroup$
    – Baldrickk
    Feb 7 at 16:55












  • $begingroup$
    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
    $endgroup$
    – Baldrickk
    Feb 7 at 16:57
















$begingroup$
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)
$endgroup$
– Baldrickk
Feb 7 at 16:55






$begingroup$
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)
$endgroup$
– Baldrickk
Feb 7 at 16:55














$begingroup$
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
$endgroup$
– Baldrickk
Feb 7 at 16:57




$begingroup$
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
$endgroup$
– Baldrickk
Feb 7 at 16:57


















draft saved

draft discarded




















































Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212292%2fguess-the-number-game-by-a-python-beginner%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

MongoDB - Not Authorized To Execute Command

How to fix TextFormField cause rebuild widget in Flutter

Npm cannot find a required file even through it is in the searched directory