forked from tiyd-python-2015-01/currency-converter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcurrency_converter.py
29 lines (24 loc) · 1.05 KB
/
currency_converter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from decimal import Decimal
rates = [("USD", "EUR", 0.74), ("EUR", "JPY", 145.949)]
cents = Decimal("0.01")
def convert(rates, value, from_code, to_code):
"""Take a monetary value in one currency and return a value in another
currency"""
if from_code == to_code:
return str(value) + " " + to_code
else:
returned_list = [(origin, destination, rate)
for (origin, destination, rate)
in rates if from_code == origin]
returned_tuple = returned_list[0]
returned_rate = returned_tuple[2]
new_value = returned_rate * value
return str(new_value) + " " + to_code
def convert_reverse(rates, value, from_code, to_code):
returned_list = [(destination, origin, rate)
for (destination, origin, rate)
in rates if to_code == destination]
returned_tuple = returned_list[0]
returned_rate = returned_tuple[2]
new_value = Decimal(value / returned_rate).quantize(cents)
return str(new_value) + " " + to_code