Closed lcabrini closed 9 years ago
This is also having the same problem oo.
But I have pushed the script
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.
Try the following in the python interactive interpreter:
As you can see it does not work, and you get an error message as follows:
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.
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
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).