In
previous example we’ve been using the raw_input and int method/function. The
raw_input function is used for user input from the keyboard and int function is
used to transform the user input which is always in str (string) into int type
of value. So in all these examples we
had to type numbers if we had typed the string the function int wouldn’t work.
The Python interpreter would give us a ValueError. Here’s an example:
>>>value = raw_input(‘Please enter a number: ‘) Please enter a number: thing >>>x = int(value) Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: 'thing '
In order
to avoid ValueError we’ll implement the
try and except commands.
>>>value = raw_input(‘Please enter a number: ‘) >>>try: … x = int(value) … y = x + 5 … print y …except: … print “Please enter a number:” ...
Python
starts by executing the sequence of statements in the try block. If all goes
well, it skips the except block and proceeds. If an exception occurs in the try
block in our case we’ve written string instead of integer, then Python jumps
out of the try block and executes the sequence of statements in the except
block.
In
general, catching an exception gives you a chance to fix the problem, or try
again, or at least end the program gracefully.
Nema komentara:
Objavi komentar