1

I'm trying to create GUI interface where user needs to enter a value. If he enters it wrong, error message appears. Otherwise it keeps the correct answer. But what if user forgot to enter a value and just left it blank? Or pressed enter without entering anything? How do I call up error message in this case?

Just to keep it simple here is basic example without GUI:

h = int(raw_input("Enter "))

if h >= 10:
    print True
elif h < 10:
    print False
else:
    print "Error"

Idea is that if user did not enter anything, it would print

"Error". However, program just stalls and prints the following: ValueError: invalid literal for int() with base 10: ''

So how do I make python see blank space as value and print "Error" instead?

Brown Bear
  • 19,655
  • 10
  • 58
  • 76
  • Don't convert the input to `int` immediately - validate first if the user has entered anything. – zwer Apr 02 '18 at 20:21
  • Use try/except regime to test of user input can be converted to an integer: https://stackoverflow.com/questions/8075877/converting-string-to-int-using-try-except-in-python/8075959 – Terry Apr 02 '18 at 20:22

3 Answers3

1

Validate that they have entered a valid number first:

inpt = raw_input("Enter ")
while not inpt.isdigit():
    inpt = raw_input("Enter ")

inpt = int()
if h >= 10:
    print True
elif h < 10:
    print False
else:
    print "Error"
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
0

You need to handle exceptions. Try this :

try:
  h = int(raw_input("Enter "))

  if h >= 10:
    print True
  else h < 10:
    print False
except ValueError:
    print "Error"

As Zwer mentioned, the error comes from converting the user input which is a string to an int using int() which fails because the user input isn't valid. So either catch the error, or validate the user input, then convert it to int

Jean Rostan
  • 1,056
  • 1
  • 8
  • 16
0

The normal syntax for doing anything with an error is using a try: except block. You will want the code in the try block to be as small as possible so it can catch specific errors and give you feedback as to what is going on in the program.

the syntax is as follows

try:
   # your code here
except <some exception here>:
   # what happens when it fails

so the actual code would be.

try:
    h = int(raw_input("Enter "))
except ValueError:
    print "Error"

if h >= 10:
    print True
else h < 10:
    print False
Back2Basics
  • 7,406
  • 2
  • 32
  • 45