-
Notifications
You must be signed in to change notification settings - Fork 0
/
currency_converter.py
88 lines (65 loc) · 2.34 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
from requests import get
from pprint import PrettyPrinter
BASE_URL = "https://free.currconv.com/"
API_KEY = "29cc41bbdc271ff812d"
printer = PrettyPrinter()
def get_currencies():
endpoint = f"api/v7/currencies?apiKey={API_KEY}"
url = BASE_URL + endpoint
data = get(url).json()['results']
data = list(data.items())
data.sort()
return data
def print_currencies(currencies):
for name, currency in currencies:
name = currency['currencyName']
_id = currency['id']
symbol = currency.get("currencySymbol", "")
print(f"{_id} - {name} - {symbol}")
def exchange_rate(currency1, currency2):
endpoint = f"api/v7/convert?q={currency1}_{currency2}&compact=ultra&apiKey={API_KEY}"
url = BASE_URL + endpoint
data = get(url).json()
if len(data) == 0:
print('Invalid currencies.')
return
rate = list(data.values())[0]
print(f"{currency1} -> {currency2} = {rate}")
return rate
def convert(currency1, currency2, amount):
rate = exchange_rate(currency1, currency2)
if rate is None:
return
try:
amount = float(amount)
except:
print("Invalid amount.")
return
converted_amount = rate * amount
print(f"{amount} {currency1} is equal to {converted_amount} {currency2}")
return converted_amount
def main():
currencies = get_currencies()
print("Welcome to the currency converter!")
print("List - lists the different currencies")
print("Convert - convert from one currency to another")
print("Rate - get the exchange rate of two currencies")
print()
while True:
command = input("Enter a command (q to quit): ").lower()
if command == "q":
break
elif command == "list":
print_currencies(currencies)
elif command == "convert":
currency1 = input("Enter a base currency: ").upper()
amount = input(f"Enter an amount in {currency1}: ")
currency2 = input("Enter a currency to convert to: ").upper()
convert(currency1, currency2, amount)
elif command == "rate":
currency1 = input("Enter a base currency: ").upper()
currency2 = input("Enter a currency to convert to: ").upper()
exchange_rate(currency1, currency2)
else:
print("Unrecognized command!")
main()