-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
8
  • Can you provide sample input and a stacktrace/obtained output? Commented May 9, 2017 at 17:39
  • 2
    The kernel dies because quit exits the interpreter... what are you trying to have happen? Commented May 9, 2017 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. Commented May 9, 2017 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? Commented May 9, 2017 at 17:47
  • 1
    @ABarra Well, you have to import sys before you are able to call sys.exit(). Commented May 9, 2017 at 18:57

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

exit() is not sys.exit()
Oops, missed the sys. there. Thanks for the heads up ;)
Thank you guys. Now gives me 'an exception has occured, use %tb to see the full traceback. But this is doing the job. Appreciate the help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.