1
\$\begingroup\$

I'm making a random number guessing game in Python. Any suggestions? I'm going to add a restart button to it.

import random

#imports the random module to generate random numbers


#defines the guess_number function, which creates the random int
def guess_number():
  #generates number
  random_number = random.randint(1, 100)
  #sets maximum amount of guesses
  max_guesses = 20
  #sets current guesses
  num_guesses = 0

  #creates while loop
  while True:
    guess = int(input("Enter your guess (1-100): "))
    num_guesses += 1

    if guess == random_number:
      print("Congratulations! You guessed the number in", num_guesses,
            "guesses.")
      # display messages based on the number of guesses
      if num_guesses <= 2:
        print("Wow! You're good at this!")
      elif num_guesses <= 5:
        print("Good job!")
      elif num_guesses <= 10:
        print("Stay determined!")
      elif num_guesses <= 15:
        print("You musn't give up!")
      elif num_guesses <= 20:
        print("Get better at the game man")
      user_input = input(
          "Do you want to save your score to a text file? (y/n): ")
      #asks the player whether or not they want to save their score to a text file

      if user_input == "y":
        with open("RandomNumbersGameScores.txt", "a") as file:
          #if the player says yes then create a text file to save their score
          file.write(f"Score: {num_guesses} guesses\n")
          print("Have a nice day!")
      elif user_input == "n":
        print("Okay, have a nice day!")
        #if they don't want to save it then say goodbye
      else:
        print("Please enter a valid input (y/n).")
      break  # if they try anything wierd then tell them to enter y/n

    if num_guesses >= max_guesses:
      print("Sorry, you ran out of guesses. The number was", random_number)
      #if they run out of guesses then tell them the number
      break
    elif guess < random_number:
      print("Try again. Your guess is too low.")
    else:
      print("Try again. Your guess is too high.")


#calls guess_number function to start game
guess_number()
\$\endgroup\$

3 Answers 3

3
\$\begingroup\$

If you type in anything other than 'y' or 'n' to the question, the program will terminate, instead of asking again.

You should also allow 'Y' and 'N' as inputs. You can achieve this like so:

user_input = input("<question>").lower()

You could also allow 'yes' or 'no' as valid inputs.

I would further recommend writing the loop with a condition, instead of breaking out. A good condition would be

while num_guesses < max_guesses and guess != random_number:

Then handle the cases num_guesses >= max_guesses and guess == random_number after the loop.

\$\endgroup\$
2
\$\begingroup\$

Generally, the code is easy to read and understand. You chose meaningful names for variables and functions. It also runs well with expected inputs.

You should consider using more than 2 spaces for indentation to make it easier to read. I prefer 4 single spaces for each indent level.

Many of your comments do not convey any useful information. For example:

  #creates while loop
  while True:

It is obvious you are creating a while loop. A more meaningful comment would describe what the loop does:

# Keep asking the user to guess a number until the right guess
# or user runs out of guesses

You could add header comments at the top of the file which explain the purpose of the code.

# Give user 20 chances to guess a number between 1 and 100.

Instead of using the hard-coded 20 in the line below, use the variable max_guesses. Change:

  elif num_guesses <= 20:

to:

  elif num_guesses <= max_guesses:

If the user gets it right on the first try, we see:

Congratulations! You guessed the number in 1 guesses.

You could add some intelligence to print guess instead of guesses.

It would be nice to print out the progress on every guess:

You have 20 guesses left.  Enter your guess (1-100):

When the user wants to write the result to a file, you could print an information message showing the file name:

Do you want to save your score to a text file? (y/n): y
Wrote to file RandomNumbersGameScores.txt
Have a nice day!

It would be nice to remember all the previous guesses and notify the user if a guess was repeated. Then don't count the repeat guess as a guess.

I tried an invalid numeric guess (-3), but the code treated it as a valid guess. It would be nice to print a unique notice and treat it as a repeated guess as above.

I tried an invalid non-numeric guess (a), and the code exited with an error. It would be nice to show a message and continue instead of exiting.

A couple of words are misspelled: musn't and wierd

\$\endgroup\$
2
\$\begingroup\$

This review adds points to the other review. I agree that the code is well formatted and easy to read. Much easier to read then my first try at this some 38 years ago, but Python is generally easier to read than MSX BASIC.


It's best to split up the single method into multiple methods. For instance you could have a method for:

  • asking the values (including correctness check)
  • printing out the result
  • printing out the final text
  • storing the score

Variables such as the maximum value to guess (currently a literal not a variable) and max_guesses should be parameters of the guess_number method. The integers can be integrated into the strings (such as "Enter your guess (1-100)" where required.

In general we try to have as few as possible literals in our code, especially for number values (sometimes called "magic numbers" if it unclear what they are used for).


I'd always put comments before the lines of code, not after them.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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