-3

When the input is letter instead of number, Python gives error (ValueError: invalid literal for int() with base 10: '')

print('I am thinking of a number between 1 and 20')
import random
secretNumber = random.randint(1, 20)
for guessesTaken in range(1, 7):
    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
if guess == secretNumber:
    print('Good job! You guessed my number in ' + str(guessesTaken) + 'guesses!')
else:
    print('Nope. The number I was thinking of was ' + str(secretNumber))
Roland Deschain
  • 2,211
  • 19
  • 50
Yasin
  • 3
  • 3
  • Well you are casting the input() to an int without any error checking. Surround `guess= int(input())` in a try/catch block or sanitize ur input in a while loop. – plum 0 Jul 13 '20 at 17:44
  • 2
    That's what's supposed to happen. No letters are valid in a base 10 integer, just "0" through "9". See the standard tutorial on [Errors and Exceptions](https://docs.python.org/3/tutorial/errors.html#errors-and-exceptions). – tdelaney Jul 13 '20 at 17:48
  • or this? [Asking the user for input until they give a valid response](https://stackoverflow.com/q/23294658/2745495) – Gino Mempin Jul 14 '20 at 05:08

1 Answers1

0

You can use a while loop to keep asking for input if it not a number like this.

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

for guessesTaken in range(1, 7):
    while (True):
        print('Take a guess.')
        guess = input()
        if (guess.isnumeric()):
            guess = int(guess)
            break
        else:
            print("Please enter a number")

    if guess < secretNumber:
        print('Your guess is too low.')
    elif guess > secretNumber:
        print('Your guess is too high.')
    else:
        break

if guess == secretNumber:
    print('Good job! You guessed my number in ' + str(guessesTaken) + 'guesses!')
else:
    print('Nope. The number I was thinking of was ' + str(secretNumber))

Thank you

Dinesh
  • 812
  • 4
  • 14