1- # TODO REVIEW AND ENSURE THE PURPOSE OF THIS MODULE IS TO CONVERT
2- # Python program to convert the currency
3- # of one country to that of another country
1+ from api_handler import get_exchange_data
42
5- # Import the modules needed
6- import requests
7-
8- class Currency_convertor :
9- # empty dict to store the conversion rates
10- rates = {}
11-
12- def __init__ (self , url ):
13- data = requests .get (url ).json ()
14- # Extracting only the rates from the json data
3+ class CurrencyConverter :
4+ def __init__ (self ):
5+ data = get_exchange_data ()
156 self .rates = data ["rates" ]
167
17- # function to do a simple cross multiplication between
18- # the amount and the conversion rates
19- def convert ( self , from_currency , to_currency , amount ):
20- initial_amount = amount
21- if from_currency != 'EUR' :
22- amount = amount / self . rates [ from_currency ]
8+ def convert ( self , from_currency : str , to_currency : str , amount : float ) -> float :
9+ from_currency = from_currency . upper ()
10+ to_currency = to_currency . upper ()
11+
12+ if from_currency not in self . rates or to_currency not in self . rates :
13+ raise ValueError ( "Invalid currency code." )
2314
24- # limiting the precision to 2 decimal places
25- amount = round (amount * self .rates [to_currency ], 2 )
26- print ('{} {} = {} {}' .format (initial_amount , from_currency , amount , to_currency ))
15+ # Convert amount to base (EUR), then to target
16+ amount_in_base = amount if from_currency == "EUR" else amount / self .rates [from_currency ]
17+ converted_amount = round (amount_in_base * self .rates [to_currency ], 2 )
18+ return converted_amount
2719
28- # Driver code
20+ # --- DEBUG / MANUAL TEST SECTION ---
2921if __name__ == "__main__" :
22+ print ("Running manual test for CurrencyConverter...\n " )
3023
31- YOUR_ACCESS_KEY = 'YOUR_ACCESS_KEY_HERE' # Define your access key
32- url = f'http://data.fixer.io/api/latest?access_key={ YOUR_ACCESS_KEY } ' # Use f-string for cleaner concatenation
33- c = Currency_convertor (url )
34-
35- from_country = input ("From Country (currency code): " )
36- to_country = input ("To Country (currency code): " )
37- amount = float (input ("Amount: " )) # Use float for decimal support
24+ converter = CurrencyConverter ()
25+ from_cur = "USD"
26+ to_cur = "AUD"
27+ amt = 100.0
3828
39- c .convert (from_country , to_country , amount )
29+ print (f"Converting { amt } { from_cur } to { to_cur } ..." )
30+ try :
31+ result = converter .convert (from_cur , to_cur , amt )
32+ print (f"{ amt } { from_cur } = { result } { to_cur } " )
33+ except ValueError as e :
34+ print ("Error during conversion:" , e )
0 commit comments