Swayam Shah
Swayam Shah

Reputation: 111

Why does my exit() command not work in python?

Below is my code to calculate calories based on input, after the print statements I want to exit the code and loop infinitely until the user inputs the right values.

import sys
def main():
    while True:
        try: 
            print("Please enter Age,Weight,Heart Rate and Workout Time ")
            Age,Weight,HR,Time = map(eval,input().split(' '))
            men = ( (Age * 0.2017) - (Weight * 0.09036) + (HR * 0.6309) - 55.0969 ) * Time / 4.184
            women =  ( (Age * 0.074) - (Weight * 0.05741) + (HR * 0.4472) - 20.4022 ) * Time / 4.184
            print("Men:",men," Calories \nWomen:",women,"Calories \n")
            exit()
        except:
            print("Please enter numbers only \n \n")

if __name__ == '__main__':
    main()

The code goes to the except even if the input values are right and does not exit the code, what am I missing?

Upvotes: 0

Views: 2593

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155323

exit() (some forms; it's not actually supposed to be used in scripts, so it can be overridden to do weird things; you want sys.exit()) is implemented by raising a SystemExit exception (exiting without bubbling out would mean cleanup blocks in finally and with statements don't execute, which would be bad, so they use the exception mechanism to do the cleanup). SystemExit is special in two ways:

  1. It doesn't dump a traceback and exit with a fixed status 1 if unhandled (it just silently exits the program with the status code it was provided)
  2. It's not a child of Exception, so except Exception:, which is very broad, still won't catch it

But you used a bare except, which catches everything, including SystemExit. Don't do that.

In this specific case, the correct solution is really to just replace exit() with break, which will pop you out of the while loop and allow the program to run to completion with no need for an exception at all. And use a narrower except clause while you're at it.

Upvotes: 5

Related Questions