1. try/except

int('430')
## 430
int('430.12')
## Error in py_call_impl(callable, dots$args, dots$keywords): ValueError: invalid literal for int() with base 10: '430.12'
## 
## Detailed traceback: 
##   File "<string>", line 1, in <module>
# define the function
def attempt_int(s):
  try:
    return int(s)
  except:
    return s
# call the function
attempt_int('430')
## 430
attempt_int('430.12')
## '430.12'
int((1, 2))
## Error in py_call_impl(callable, dots$args, dots$keywords): TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'
## 
## Detailed traceback: 
##   File "<string>", line 1, in <module>
def attempt_int(s):
  try:
    return int(s)
  except ValueError:
    return s
attempt_int((1, 2))
attempt_int('123.12')
def attempt_int(s):
  try:
    return int(s)
  except (ValueError, TypeError):
    return s

2. finally

f = open('a path to a file', 'w')

try:
  write_to_file(f)
finally:
  f.close()
f = open(path, 'w')
 
try:
  write_to_file(f)
except:
  print('Failed')
else:
  print('Succeeded')
finally:
  f.close()

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.