Guess-the-number game by a Python beginner












3












$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









New contributor




Dewayne Redding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$








  • 1




    $begingroup$
    Looks nice, but if you enter a letter, it errors, saying it can't convert it to a number.
    $endgroup$
    – FreezePhoenix
    1 hour ago










  • $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
    1 hour ago
















3












$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









New contributor




Dewayne Redding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$








  • 1




    $begingroup$
    Looks nice, but if you enter a letter, it errors, saying it can't convert it to a number.
    $endgroup$
    – FreezePhoenix
    1 hour ago










  • $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
    1 hour ago














3












3








3





$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









New contributor




Dewayne Redding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$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









New contributor




Dewayne Redding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Dewayne Redding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 4 hours ago









200_success

129k15153415




129k15153415






New contributor




Dewayne Redding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 4 hours ago









Dewayne ReddingDewayne Redding

183




183




New contributor




Dewayne Redding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Dewayne Redding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Dewayne Redding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 1




    $begingroup$
    Looks nice, but if you enter a letter, it errors, saying it can't convert it to a number.
    $endgroup$
    – FreezePhoenix
    1 hour ago










  • $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
    1 hour ago














  • 1




    $begingroup$
    Looks nice, but if you enter a letter, it errors, saying it can't convert it to a number.
    $endgroup$
    – FreezePhoenix
    1 hour ago










  • $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
    1 hour ago








1




1




$begingroup$
Looks nice, but if you enter a letter, it errors, saying it can't convert it to a number.
$endgroup$
– FreezePhoenix
1 hour ago




$begingroup$
Looks nice, but if you enter a letter, it errors, saying it can't convert it to a number.
$endgroup$
– FreezePhoenix
1 hour ago












$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
1 hour ago




$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
1 hour ago










2 Answers
2






active

oldest

votes


















2












$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
    2 hours ago



















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








New contributor




Dewayne Redding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$













    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
    });


    }
    });






    Dewayne Redding is a new contributor. Be nice, and check out our Code of Conduct.










    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









    2












    $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
      2 hours ago
















    2












    $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
      2 hours ago














    2












    2








    2





    $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 3 hours ago









    Bailey ParkerBailey Parker

    1,6211013




    1,6211013












    • $begingroup$
      I appreciate you checking this out! Thanks and I'll start looking into it!
      $endgroup$
      – Dewayne Redding
      2 hours ago


















    • $begingroup$
      I appreciate you checking this out! Thanks and I'll start looking into it!
      $endgroup$
      – Dewayne Redding
      2 hours ago
















    $begingroup$
    I appreciate you checking this out! Thanks and I'll start looking into it!
    $endgroup$
    – Dewayne Redding
    2 hours ago




    $begingroup$
    I appreciate you checking this out! Thanks and I'll start looking into it!
    $endgroup$
    – Dewayne Redding
    2 hours ago













    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








    New contributor




    Dewayne Redding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






    $endgroup$


















      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








      New contributor




      Dewayne Redding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      $endgroup$
















        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








        New contributor




        Dewayne Redding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






        $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








        New contributor




        Dewayne Redding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        share|improve this answer



        share|improve this answer






        New contributor




        Dewayne Redding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        answered 1 hour ago









        Dewayne ReddingDewayne Redding

        183




        183




        New contributor




        Dewayne Redding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.





        New contributor





        Dewayne Redding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






        Dewayne Redding is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






















            Dewayne Redding is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded


















            Dewayne Redding is a new contributor. Be nice, and check out our Code of Conduct.













            Dewayne Redding is a new contributor. Be nice, and check out our Code of Conduct.












            Dewayne Redding is a new contributor. Be nice, and check out our Code of Conduct.
















            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

            Fluorita

            Hulsita

            Península de Txukotka