-1

For instance in this program I have used try and except to attempt to validate it, but it doesn't work; any ideas? I want to make sure the input is not a string.

userGuess = int(input("%s %s %s = ?\n" % (num1, op, num2)))
try:
    validation = int(userGuess)
except ValueError:
    print("You have not entered a number!")
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

0

Now it should work

You were getting the exception before the try, as you were already trying to convert hte input into an int.

userGuess = input("%s %s %s = ?\n" % (num1, op, num2))
try:
    validation = int(userGuess)
except ValueError:
    print("You have not entered a number!")

But the common practice is more like this:

try:
    userGuess = int(input('%s %s %s = ?\n' % (num1, op, num2)))
except ValueError:
    raise Exception('You have not entered a number!')
DevLounge
  • 8,313
  • 3
  • 31
  • 44
  • 2
    I don't understand your common practice example. There's no need to import `Exception`, and since `input` returns a string, I'm not sure what could trigger the `ValueError`. – DSM Nov 06 '14 at 17:19
  • Let me try again. Your `from exceptions import Exception` line doesn't do anything. Your original code lacked the `int`, and so there was no way it could raise an exception, which is what I was puzzled by. And it's pretty likely that the OP is using Python 3 because that's how the OP tagged the question. – DSM Nov 06 '14 at 17:30
  • I wasn't the one who downvoted you, and it's certainly not correct that `from exceptions import Exception` is common practice. – DSM Nov 06 '14 at 17:42
  • I will try one more time: `Exception` is *automatically imported*. Start up a new interpreter, and type `Exception`. You don't get a `NameError`. *There is no need to import Exception*. – DSM Nov 06 '14 at 19:09
  • you can skip the 'raise exception' with a print and it works – DaSweatyGooch Nov 08 '14 at 18:28
  • Of course it works, BUT the program would still continue and try to use the userGuess variable somewhere after, and it would create some exceptions. For a basic cli program, fine, but never for a real software. Exception must be always caught or raised. – DevLounge Nov 08 '14 at 18:29
  • okay obviously I'm new to python so thanks for informing me – DaSweatyGooch Nov 13 '14 at 06:06