This is a simple code that uses an API to access real-time currency conversion rates. The user gives the amount and country to and from which the currency needs to be converted.
Currency conversion is a matter of simple unitary method calculation or cross multiplication when the conversion rates are known. However, since the currency values fluctuate everyday, it is convenient to use an API in which the values are updated instantly. This saves the hassle of creating a database of countries, their currency and updating their values every day with respect to a base standard currency.
In this code, we have chosen to use an API from fixer.io . The link to access the free key is mentioned in the comments in the code.
The code also requires the user to install requests module to python. Following are the steps:
Open 'Command Prompt' -> Type in 'pip3 install requests' -> It should display 'Successfully Installed requests'
OR
Open terminal for Mac (or an equivalent for your system) -> python -m pip install requests
The code has been explained in the comments within it.
import requests class Currency_Conversion_Rate: rate = {} # A dictionary to store the currency conversion rates. def __init__(self, url): response = requests.get(url) data = response.json() # Extracting only the rates from the json data self.rates = data["rates"] # Create a function to perform unitary method calculation to obtain final amount. def convert(self, from_cur, to_cur, iv): initial_val = iv # This url has a base of EUR, thus we consider 2 different cases. if from_cur != 'EUR' : final_val = (iv * self.rates[to_cur])/self.rates[from_cur] # Money has only 2 decimal places. So round to the second decimal place. final_val = round(final_val, 2) #print(iv) print('{} {} = {} {}'.format(initial_val, from_cur, final_val, to_cur)) else: fv = iv * self.rates[to_cur] print('{} {} = {} {}'.format(initial_val, from_cur, fv, to_cur)) # Driver code if __name__ == "__main__": # you can get your access key from https://fixer.io/ It is free. your_access_key = input("Your access key:") url = str.__add__('http://data.fixer.io/api/latest?access_key=', your_access_key) c = Currency_Conversion_Rate(url) from_country = input("From Country: ") to_country = input("To Country: ") iv = float(input("Amount: ")) # Call on the function created above to make the process simpler. c.convert(from_country, to_country, iv)
The output is shown in the photo.
Submitted by Vishaka Iyengar (reachvishakas)
Download packets of source code on Coders Packet
Comments