Appendix B — Practice Problem Solutions — Chapter 6
Solution Section 6.9.1
try:
= float("abc")
value except ValueError:
print("Not a valid number")
Solution Section 6.9.2
= {"A": 1, "C": 2, "G": 0, "T": 4}
counts = sum(counts.values())
total
try:
= counts["N"] / total
n_ratio except KeyError:
print("N is not present in the counts dictionary")
= None n_ratio
Solution Section 6.9.3
try:
5, 0)
silly_divide(except ZeroDivisionError:
print("you can't divide by zero!")
except Exception as error:
print(f"a mysterious error occurred: {error=}")
Solution Section 6.9.4
def fold_change(expression_1, expression_2)
try:
return expression_1 / expression_2
except ZeroDivisionError:
print("expression_2 was zero!")
return None
Solution Section 6.9.5
class SequenceLengthError(Exception):
pass
= 50
MIN_LENGTH = 150
MAX_LENGTH
def validate_sequence_length(sequence):
= len(sequence)
sequence_length
if sequence_length < MIN_LENGTH:
raise SequenceLengthError(f"sequence length {sequence_length} was too short!")
if sequence_length > MAX_LENGTH:
raise SequenceLengthError(f"sequence length {sequence_length} was too long!")
return None
Solution Section 6.9.6
def run_simulation(max_turns):
if max_turns < 1:
raise ValueError(f"Expected at least 1 iteration, but got {max_turns=}")
if max_turns > 1000:
raise ValueError(f"Expected at most 1000 iterations, but got {max_turns=}")
# Simulation code would follow
pass