Reputation: 73
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))
Upvotes: 1
Views: 14983
Reputation: 1185
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
Upvotes: 4