By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,820 Members | 1,051 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,820 IT Pros & Developers. It's quick & easy.

Python shows an error when it needs to exit the program

P: 1
I wrote this program:

Expand|Select|Wrap|Line Numbers
  1. try:
  2.    x=int(raw_input("Please enter a number: "))
  3. except:
  4.    print 'Please enter a numeric number.'
  5.    import sys
  6.    sys.exit()
and after it prints "Please enter a numeric number." it shows this problem with the exit command line:
Traceback (most recent call last):
File "C:\Users\Dor\Desktop\Python.py", line 6, in <module>
sys.exit()
SystemExit
Is it supposed to do that? How can I fix it?
Oct 4 '12 #1
Share this Question
Share on Google+
1 Reply

bvdet
Expert Mod 2.5K+
P: 2,851
If you input a character or series of characters that cannot be converted to an integer, a ValueError exception will be raised and control will be passed to the except block. A matter of style - you should make all your imports at the top of the file. See Style Guide For Python Code. You should qualify the except block instead of catching all possible errors. Most of the time a return statement is appropriate if encapsulated in a function or a simple pass would work. Are you sure you need a call to sys.exit()?.

I may do something like:
Expand|Select|Wrap|Line Numbers
  1. import sys #if needed
  2.  
  3. def get_num():
  4.     while True:
  5.         x = raw_input("Please enter a number: ")
  6.         try:
  7.             return int(x)
  8.         except ValueError, e:
  9.            print 'You entered an invalid number. Try again.'
  10.  
  11. print get_num()
Oct 4 '12 #2

Post your reply

Sign in to post your reply or Sign up for a free account.