4
\$\begingroup\$

I am new to learning code, and would love some feedback on how this little game could be improved and/or tidied up.

import random

num = random.randint(1, 100)

def user_guess():
    guess = input("Guess a number between 1 and 100: ")
    print("Your guess is", guess)
    guess = int(guess)

    while guess != num:
        if guess < num:
            guess = input("Your guess was too low: guess again!")
            print("Your guess is", guess)
            guess = int(guess)
        if guess > num:
            guess = input("Your guess was too high: guess again!")
            print("Your guess is", guess)
            guess = int(guess)
        if guess == num:
            print("Correct! Well done!")
            again = input("Would you like to play again? (Y or N): ")
            if again == "y":
                user_guess()
            break
\$\endgroup\$
3
  • \$\begingroup\$ I assume that below this somewhere is something like if __name__ == '__main__': user_guess()? \$\endgroup\$ – scnerd May 31 '18 at 21:27
  • \$\begingroup\$ I'm not sure what that code means but the code I posted is the whole thing. I will endeavour to understand! :) \$\endgroup\$ – sim Jun 1 '18 at 12:43
  • \$\begingroup\$ Doing some searching but can't get my head around it :/ \$\endgroup\$ – sim Jun 1 '18 at 13:12
2
\$\begingroup\$

You follow a lot of standard practices well, so the code is actually quite easy to read, but there are some ways to consolidate a bit that'll make it even simpler.

You while loop while the guess is incorrect, but you also break when the answer is correct, nullifying the need for the condition. This also has the unintended side effect that, if their answer is correct in their first guess, you never enter the loop, and therefore never congratulate the user for winning. Change this into while True: or, much better, provide some maximum number of guessed then do for _ in range(max_num_guesses):

You repeat the input/print/int call many times, but this could just be the first part of the loop instead. It alters the formatting very slightly, but makes for much more readable/maintainable code.

global variables aren't usually a good idea in the long run; consider making num a parameter instead, then call randint wherever it is you call this function.

Some last minor tweaks I would suggest: move the "guess again?" logic to outside this function--recursion isn't the most intuitive solution in this case, and could get you into trouble (recursion limits, memory "leaks", etc.); use elif when chaining mutually-exclusive if statements; convert user input to lower case when checking if they input y, especially since your input message explicitly tells them that 'Y' is a valid, expected input.

The final code looks something like the following:

def user_guess(num, max_num_guesses=10):
    for _ in range(max_num_guesses):
        guess = int(input("Guess a number between 1 and 100: "))
        print("Your guess was {}".format(guess))

        if guess < num:
            print("Your guess was too low: guess again!")
        elif guess > num:
            print("Your guess was too high: guess again!")
        elif guess == num:
            print("Correct! Well done!")
            return

    print("Sorry, you ran out of guesses.")


if __name__ == '__main__':
    while True:
        user_guess(random.randint(1, 100))

        again = input("Would you like to play again? (Y or N): ")
        if again.lower() != "y":
            print("Ok, goodbye")
            break
\$\endgroup\$
3
  • \$\begingroup\$ Thank you for such excellent feedback! My first post here. This is more than I could've hope for! I really appreciate it :) \$\endgroup\$ – sim May 31 '18 at 21:53
  • \$\begingroup\$ I can't get my head around the "if name == 'main':" What is it doing here? Thanks! \$\endgroup\$ – sim Jun 1 '18 at 15:10
  • 1
    \$\begingroup\$ @sim See the excellent answer to that question here \$\endgroup\$ – scnerd Jun 1 '18 at 20:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.