0

I am brand new to programming and I'm building a guessing game for fun as a first program. I've already figured out the following:

  • How to set a specific number for them to guess between 1-50 (for example)
  • What happens when they guess outside the parameters
  • Number of guesses and attempts to "break the game"
  • Included while loops full of if statements

What I can't seem to figure out though is how to stop the user from inputting anything other than a number into the game. I want them to be able to, but I'd like to print out a personal error message then exit the while loop. (Essentially ending the game).

This is as close as I've been able to guess:

if guess == number:
    print('Hey wait! That\'s not a number!')
    print('Try again tomorrow.')
    guessed = True
    break

I get the error: "ValueError: invalid literal for int() with base 10" and I'm clueless on how to figure this out. I've been reading about isdigit and isalpha and have tried messing around with those to see what happens, but I get the same error. Maybe I'm just putting it in the wrong section of code

Any hints? :)

Thank you!

2 Answers2

1

Use try/except to handle exceptions:

try:
    guess = int(input("What's your guess? "))
except ValueError:
    print("Hey wait! That's not a number!")
    print("Try again tomorrow.")
    guessed = True
    break
# otherwise, do stuff with guess, which is now guaranteed to be an int
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • getting all sorts of error messages all over the place. Does the indentation need to be exactly how you put it? The most common being that the second half of my code is unreachable. – Terence May 14 '20 at 15:37
  • Yes, indentation is important in Python because it defines where blocks begin and end, similar to braces in other languages! The second part of your code needs to be indented at the same level as the `try` and `except` (same as the commented part in my code) to indicate that the indented block under the `except` has ended. – Samwise May 14 '20 at 15:46
  • ahh I see. Ok, thank you! I'll create a new file to test all this out =) (Almost saved over my file with a bunch of errors. haha – Terence May 14 '20 at 16:02
0

You can use a try / except to attempt the cast to an integer or floating point number and then if the cast fails catch the error. Example:

try:

   guessInt = int(guess)

except ValueError:

   print('Hey wait! That\'s not a number!')
   print('Try again tomorrow.')
   guessed = True
   break



Mike
  • 1,471
  • 12
  • 17