-2

I'm just attempting to put in an exception where the user inputs a non numeric value, so that the program gives an error message and quits. However, using quit() like I have, it still attempts to run the end of the code (variable not defined error), and gives me an error that the kernel has died. What is the correct way to quit out of the code with the exception?

try:
    inp=raw_input("Enter Hours Worked ")
    hours=float(inp)
    inp=raw_input("Enter Pay Rate ")
    rate=float(inp)
except:
    print "Error: Enter a numeric value"
    quit()

if hours<=40:
    pay = hours * rate
else:
    pay = (hours-40) * rate * 1.5 + (40 * rate)
print "Gross Pay: $",pay
Marcy
  • 180
  • 1
  • 12
A Barra
  • 11
  • 1
  • 2
  • Can you provide sample input and a stacktrace/obtained output? – Willem Van Onsem May 09 '17 at 17:39
  • 2
    The kernel dies because `quit` exits the interpreter... what are you *trying to have happen*? – juanpa.arrivillaga May 09 '17 at 17:40
  • The user has to input numerical values to calculate their pay. I'm trying to print an error message when they enter non integer/float values. – A Barra May 09 '17 at 17:44
  • If you just wanted to print a message, why did you use `quit`??? Again, what did you think `quit` would do? Why not just remove it? – juanpa.arrivillaga May 09 '17 at 17:47
  • Because it still trys to evaluate the code after the exception. That's what I'm trying to stop it from doing. So once the user inputs non numerical values. It just simply prints the exception rather than a traceback from the rest of the code. – A Barra May 09 '17 at 17:49
  • @juanpa.arrivillaga - OP clearly wants to exit the program completely when there is an error. The question is why that didn't work. The program works when saved as a script and run on the command line (assuming a normal python setup). This must be a `jupyter` thing. – tdelaney May 09 '17 at 17:59
  • @ChristianKönig thanks for the response, gives me 'name sys not defnined'. I may be going about this the wrong way. Thought there was an easy way to stop the program when an exception is found. – A Barra May 09 '17 at 18:19
  • 1
    @ABarra Well, you have to `import sys` before you are able to call `sys.exit()`. – Christian König May 09 '17 at 18:57

1 Answers1

1

What you're looking for is probably sys.exit(), from the sys module.

So your code would read as follows instead, provided you import sys at the start of everything:

try:
    inp=raw_input("Enter Hours Worked ")
    hours=float(inp)
    inp=raw_input("Enter Pay Rate ")
    rate=float(inp)
except:
    print "Error: Enter a numeric value"
    sys.exit() # use an exit code to signal the program was unsuccessful

if hours<=40:
    pay = hours * rate
else:
    pay = (hours-40) * rate * 1.5 + (40 * rate)
print "Gross Pay: $",pay
Graham
  • 7,431
  • 18
  • 59
  • 84
Marcy
  • 180
  • 1
  • 12