|
| 1 | +# Importing necessary modules for currency formatting and HTTP requests |
1 | 2 | from locale import currency |
2 | 3 | import requests |
3 | 4 | import json |
4 | 5 |
|
5 | | -currency = input().lower() |
| 6 | +# Get the base currency input from the user and convert it to lowercase |
| 7 | +currency = input("Enter the base currency (e.g., USD, EUR): ").lower() |
| 8 | + |
| 9 | +# Initialize an empty cache to store exchange rates |
6 | 10 | cache = {} |
7 | 11 |
|
| 12 | +# Infinite loop to process exchange requests until the user exits |
8 | 13 | while True: |
9 | 14 |
|
10 | | - currency_exch = input().lower() |
| 15 | + # Get the target currency input from the user and convert it to lowercase |
| 16 | + currency_exch = input("Enter the currency to exchange to (leave blank to exit): ").lower() |
11 | 17 |
|
| 18 | + # If the input is blank, break out of the loop (exit condition) |
12 | 19 | if currency_exch == '': |
13 | 20 | break |
14 | 21 |
|
15 | | - amount_to_exch = int(input()) |
| 22 | + # Get the amount to exchange from the user |
| 23 | + amount_to_exch = int(input("Enter the amount to exchange: ")) |
16 | 24 |
|
| 25 | + # URL for getting exchange rates from floatrates.com |
17 | 26 | URL = f'http://www.floatrates.com/daily/{currency}.json' |
18 | 27 |
|
| 28 | + # Fetch the exchange rates in JSON format |
19 | 29 | exch = json.loads(requests.get(URL).text) |
20 | 30 |
|
| 31 | + # Update cache for USD and EUR based on the base currency |
21 | 32 | if currency == 'usd': |
| 33 | + # If base currency is USD, cache EUR rate |
22 | 34 | cache.update(eur=exch['eur']['rate']) |
23 | 35 | elif currency == 'eur': |
| 36 | + # If base currency is EUR, cache USD rate |
24 | 37 | cache.update(usd=exch['usd']['rate']) |
25 | 38 | else: |
| 39 | + # For other base currencies, cache both USD and EUR rates |
26 | 40 | cache.update(usd=exch['usd']['rate'], eur=exch['eur']['rate']) |
27 | 41 |
|
28 | 42 | print("Checking the cache...") |
| 43 | + |
| 44 | + # Check if the target currency's rate is in the cache |
29 | 45 | if currency_exch in cache: |
| 46 | + # If the rate is in the cache, calculate the exchanged amount |
30 | 47 | rate = round(amount_to_exch * cache[currency_exch], 2) |
31 | 48 | print("Oh! It is in the cache!") |
32 | 49 | print(f"You received {rate} {currency_exch.upper()}.") |
33 | 50 | else: |
34 | | - #print("Sorry, but it is not in the cache!") |
| 51 | + # If the rate is not in the cache, fetch it from the exchange rates and store it in cache |
| 52 | + print("Sorry, but it is not in the cache!") |
35 | 53 | cache[currency_exch] = exch[currency_exch]['rate'] |
36 | 54 | rate = round(amount_to_exch * cache[currency_exch], 2) |
37 | 55 | print(f"You received {rate} {currency_exch.upper()}.") |
0 commit comments