DIGIT_MAP = {
'zero': '0',
'one':'1',
'two':'2',
'three':'3',
'four':'4',
'five':'5',
'six':'6',
'seven':'7',
'eight':'8',
'nine': '9'
}
def convert(s):
try:
number = ''
for token in s:
number += DIGIT_MAP[token]
x = int(number)
print(f"Conversion succeeded! x = {x}")
except KeyError:
print(f"Convert failed! {token} was not found in the dictionary.")
x = -1
return x
>>> from exceptional import convert
>>> convert ('This will not work'.split())
Convert failed! This was not found in the dictionary.
-1
Try with a valid number.
>>> from exceptional import convert
>>> convert ('one two three four four'.split())
Conversion succeeded! x = 12344
12344
>>> from exceptional import convert
>>> convert(1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/aaron/PycharmProjects/exceptional/exceptional.py", line 17, in convert
for token in s:
TypeError: 'int' object is not iterable
except TypeError:
print(f"Conversion failed.")
x = -1
try it again
>>> from exceptional import convert
>>> convert(1)
Conversion failed.
-1
DIGIT_MAP = {
'zero': '0',
'one':'1',
'two':'2',
'three':'3',
'four':'4',
'five':'5', 'six':'6',
'seven':'7',
'eight':'8',
'nine': '9' }
def convert(s):
x = -1
try:
number = ''
for token in s:
number += DIGIT_MAP[token]
x = int(number)
print(f"Conversion succeeded! x = {x}")
except(KeyError, TypeError):
print("Conversion failed!)
return x
roots.py
import sys
def sqrt(x):
"""compute square roots using the method
of Heron of Alexandria
Args:
x: The number for which the square root is to be
computed.
Returns:
The square root of x
Raises:
ValueError: If x is a negative
"""
if x < 0:
raise ValueError(
"Cannot compute square root of "
f"negative number {x}.")
guess = x
i = 0
while guess * guess != x and i<20:
guess = (guess + x / guess) / 2.0
i += 1
return guess
def main():
try:
print(sqrt(9))
print(sqrt(2))
print(sqrt(-1))
except ValueError as e:
print(e, file=sys.stderr)
print("Program execution continues normally here.")
if __name__ == '__main__':
main()
python3 roots.py
3.0
1.414213562373095
Cannot compute square root of negative number -1.