-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcurrency.py
More file actions
59 lines (40 loc) · 2.04 KB
/
currency.py
File metadata and controls
59 lines (40 loc) · 2.04 KB
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
import requests
API_KEY = 'fca_live_wH1VpbqQoyMGE760kddTmLVGVNchRyZI0TvZ22Co'
BASE_URL = f"https://api.freecurrencyapi.com/v1/latest?apikey={API_KEY}"
CURRENCIES = ["USD", "CAD", "EUR", "AUD", "CNY"]
def convert_currency(base):
currencies = ",".join(CURRENCIES) # Because we should give it as CSV to the url
url = f"{BASE_URL}&base_currency={base}¤cies={currencies}"
try:
response = requests.get(url) # The response is going to contain a JSON (in python we will get a disctionary back
# with key value pairs with the data that the API returned )
data = response.json() # Parsing the JSON format that we got from the API call to a dictionary
return data["data"]
except Exception as e:
print("Invalid Currency")
return None
if __name__ == '__main__':
# We enter while as true
while True:
name = input("Please enter your first name (q for quit): ")
if name.lower() == "q" :
break
if name[0] != name[0].upper():
name = name[0].upper() + name[1:] # A good alternative would be name = name.capitalize()
base = input("Please enter the base currency: ").upper() # Invalid currency check in convert_currency
amount = input("Please enter the amount you have: ") # The digit number that we enter is saved as a string "100"
try: # This will convert the number from a string to a number and check for wrong datatype
amount = float(amount)
except ValueError:
break
data = convert_currency(base)
if not data:
continue
# if the value returned from the function is false (none in this case) we will
# Continue for next while iteration (not the same as if data is None:)
del data[base]
print(f"Hello, {name}.\nYour conversion rate is:")
for ticker, value in data.items():
final = value * amount
print(f"{ticker} is: {final}")
print(f"Have a nice day {name}")