Prince-linux / python-learning

for learning Python
MIT License
1 stars 0 forks source link

Dealing with exceptions #7

Closed lcabrini closed 9 years ago

lcabrini commented 9 years ago

Try the following in the python interactive interpreter:

>>> a = int("gnu")

As you can see it does not work, and you get an error message as follows:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'gnu'

This is actually called an exception and the exception is of type ValueError, as you can see above. We can actually "handle" exception is python with a try-except structure. Try the following program.

s = input("Enter an integer: ")
try:
    a = int(s)
    print("Thank you for giving me %d" % (a))
except ValueError:
    print("That is not a valid integer: %s" % (s))

Pay close attention to the indentation in this case, because indentation is significant in python. Run the program and try entering first an integer, then something that cannot be converted. Notice that you do not get the normal error messages, but rather our own message.

Now you can upgrade the add program to convert the numbers to integers and ensure that they are valid. Instead of crashing the program if the input is not valid, print a friendly messaage and exit. To exit you need to use the sys.exit() function. This is in a module called sys and to use it you need to call

import sys

before you make the call to sys.exit(). Normally the import statements are placed at the top of the source file (but under the she-bang line).

Prince-linux commented 9 years ago

This is also having the same problem oo.

Prince-linux commented 9 years ago

But I have pushed the script

lcabrini commented 9 years ago

Please refer to comment on #6

You may want to be more specific in your prompts to make sure the user is aware that it is integers that you want, but specifically stating "Enter the first integer: " instead of number.

The other option would be to use float() to convert to floating point numbers instead. But this exercise at this time is meant to use ints.