This Jupyter notebook is intented to be used alongside the book Python for Bioinformatics
In [ ]:
!curl https://raw.githubusercontent.com/Serulab/Py4Bio/master/samples/samples.tar.bz2 -o samples.tar.bz2
!mkdir samples
!tar xvfj samples.tar.bz2 -C samples
Listing 7.1: wotest.py: Program with no error checking
In [ ]:
with open('myfile.csv') as fh:
line = fh.readline()
value = line.split('\t')[0]
with open('other.txt',"w") as fw:
fw.write(str(int(value)*.2))
Listing 7.2: LBYL.py: Error handling LBYL version
In [ ]:
import os
iname = input("Enter input filename: ")
oname = input("Enter output filename: ")
if os.path.exists(iname):
with open(iname) as fh:
line = fh.readline()
if "\t" in line:
value = line.split('\t')[0]
if os.access(oname, os.W_OK) == 0:
with open(oname, 'w') as fw:
if value.isdigit():
fw.write(str(int(value)*.2))
else:
print("Can’t be converted to int")
else:
print("Output file is not writable")
else:
print("There is no TAB. Check the input file")
else:
print("The file doesn’t exist")
Listing 7.3: exception.py: Similar to 7.2 but with exception handling.
In [ ]:
try:
iname = input("Enter input filename: ")
oname = input("Enter output filename: ")
with open(iname) as fh:
line = fh.readline()
if '\t' in line:
value = line.split('\t')[0]
with open(oname, 'w') as fw:
fw.write(str(int(value)*.2))
except NameError:
print("There is no TAB. Check the input file")
except FileNotFoundError:
print("File not exist")
except PermissionError:
print("Can’t write to outfile.")
except ValueError:
print("The value can’t be converted to int")
else:
print("Thank you!. Everything went OK.")
Listing 7.4: nested.py: Code with nested exceptions
In [ ]:
iname = input("Enter input filename: ")
oname = input("Enter output filename: ")
try:
with open(iname) as fh:
line = fh.readline()
except FileNotFoundError:
print("File not exist")
if '\t' in line:
value = line.split('\t')[0]
try:
with open(oname, 'w') as fw:
fw.write(str(int(value)*.2))
except NameError:
print("There is no TAB. Check the input file")
except PermissionError:
print("Can’t write to outfile.")
except ValueError:
print("The value can’t be converted to int")
else:
print("Thank you!. Everything went OK.")
In [ ]:
d = {"A":"Adenine","C":"Cytosine","T":"Timine","G":"Guanine"}
try:
print(d[input("Enter letter: ")])
except:
print("No such nucleotide")
In [ ]:
d = {"A":"Adenine", "C":"Cytosine", "T":"Timine", "G":"Guanine"}
try:
print(d[input("Enter letter: ")])
except EOFError:
print("Good bye!")
except KeyError:
print("No such nucleotide")
Listing 7.5: sysexc.py: Using sys.exc_info()
In [ ]:
import sys
try:
0/0
except:
a,b,c = sys.exc_info()
print('Error name: {0}'.format(a.__name__))
print('Message: {0}'.format(b))
print('Error in line: {}'.format(c.tb_lineno))
Listing 7.6: sysexc2.py: Another use of sys.exc_info()
In [ ]:
import sys
try:
x = open('random_filename')
except:
a, b = sys.exc_info()[:2]
print('Error name: {}'.format(a.__name__))
print('Error code: {}'.format(b.args[0]))
print('Error message: {}'.format(b.args[1]))
In [ ]:
def avg(numbers):
return sum(numbers)/len(numbers)
In [ ]:
avg([])
In [ ]:
def avg(numbers):
if not numbers:
raise ValueError("Please enter at least one element")
return sum(numbers)/len(numbers)
In [ ]:
avg([])