1

I am new to Python, so this is probably a dumb question to many here, but in the following code, how would I go about adding an exception, so that should someone enter say a word for instance, that would handle the invalid input and continue to ask, 'Take a guess.'?

import random
secretNumber = random.randint(1, 100)
print('I am thinking of a number between 1 and 100.')

for guessesTaken in range(1, 11):
    print('Take a guess.')
    guess = int(input())

    if guess < secretNumber:
        print('Your guess is too low.')
    elif guess > secretNumber:
        print('Your guess is too high.')
    else:
        break   # This condition is the correct guess!

if guess == secretNumber:
    print('Good job! You guessed mu number in ' + str(guessesTaken) + ' guesses!')
else:
    print('Nope. The number I was thinking of was ' + str(secretNumber))
3
  • fix your indentation Commented Oct 21, 2016 at 19:28
  • Sorry, the formatting did not take? Maybe someone will understand what I am trying to accomplish. I realize this is purely amateur, but I am really trying to learn by doing small stuff. Commented Oct 21, 2016 at 19:29
  • I think this post in exception handling might be helpful too: exception in input in python Commented Jul 15, 2019 at 13:02

1 Answer 1

4

I believe what you are trying to do can be accomplished with the input as follows:

guess = None
while guess is None:
    try: 
        print('Take a guess.')
        guess = int(input())
    except ValueError:
        pass
Sign up to request clarification or add additional context in comments.

2 Comments

Is this the typical error thrown for wrong inputs?
For built-in methods the ValueError will be thrown when the type matches, but the value is not correct. For this particular example the int method expects a string, gets the string, but the string cannot be converted. If you supply say an object of a custom class to the same method, you will get TypeError. More on base exception classes: docs.python.org/3/library/exceptions.html#base-classes

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.