Code Examples Python

This first example returns the square root of a given input value. If the input value is negative or if it is a character, two traceback messages are displayed.

Listing Square root (File squareroot.py)

The exceptclause in line 14 covers ValueError, OverflowError, and TypeErrorexceptions. The else clause in line 35 is only executed when no exception is raised. The next lines show the two traceback messages that are displayed by this program: Python standard traceback message and a customized version.

C:\python> s:\python\squareroot.py
Please, enter a number: i
-----------------------------------------
This is the standard traceback message:
Traceback (innermost last):
File "s:\python\squareroot.py", line 11, in ?
n = float(raw_input("Please, enter a number: "))
ValueError: invalid literal for float(): i
-----------------------------------------
This is the customized traceback message:
Exception Type: exceptions.ValueError
Error Message: invalid literal for float(): i
File name: s:\python\squareroot.py
Error message: 11
Line: ?
Function: n = float(raw_input("Please, enter a number: "))

This example uses multiple except clauses (lines 17 and 20). It also takes advantage of the assert

command to raise a debug exception (line 15).

Listing Internet country codes (File countrycode.py)

The following screen dump shows the execution of this program. Note that the program doesn't end after an exception has been raised.

C:\>python s:\python\ countrycode.py
Enter the country name or press x to exit: Mexico
exceptions.KeyError :mexico is not in the list.
Enter the country name or press x to exit: USA
USA's country code is us
Enter the country name or press x to exit: Brazil
You cannot select this country for this action!
Enter the country name or press x to exit: Argentina
Argentina's country code is ar
Enter the country name or press x to exit: x
C:\Python>

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Python Topics