3.3 - Errors and Exception Handling

Ha Khanh Nguyen (hknguyen)


1. try/except


2. finally


3. Exercise

Let s be a string that contains a simple mathematical expression, e.g.,

s = '1.5 + 2.1'

s = '10.0-1.6'

s = '3.1*5.8'

s = '4.7 /7.2'

The expression will only have 2 operands and the operator will be one of the following: +, -, * and /.

Write a function that interprets the expression, then evaluates it and returns the result. If the input string s does not follow the format above, simply return a None object.


This lecture note is modified from Chapter 3 of Wes McKinney's Python for Data Analysis 2nd Ed.