You are on page 1of 15

Currency Converter in Python




Python is a very versatile programming language. Python is being used in almost each
mainstream technology and one can develop literally any application with it. Let’s see a Python
program to convert the currency of one country to that of another country. To use this service,
one must need the API key, which can be get from here. We will use fixer API to get the live
conversion rates and convert the corresponding amount.

Case 1

Modules needed:

1. requests: This module does not build in with python. To install it type the below command in
the terminal or cmd.
pip install requests
Below is the implementation:

 Python3

# Python program to convert the currency


# of one country to that of another country

# Import the modules needed


import requests

class Currency_convertor:
# empty dict to store the conversion rates
rates = {}
def __init__(self, url):
data = requests.get(url).json()

# Extracting only the rates from the json data


self.rates = data["rates"]

# function to do a simple cross multiplication between


# the amount and the conversion rates
def convert(self, from_currency, to_currency, amount):
initial_amount = amount
if from_currency != 'EUR' :
amount = amount / self.rates[from_currency]

# limiting the precision to 2 decimal places


amount = round(amount * self.rates[to_currency], 2)
print('{} {} = {} {}'.format(initial_amount, from_currency,
amount, to_currency))

# Driver code
if __name__ == "__main__":

# YOUR_ACCESS_KEY = 'GET YOUR ACCESS KEY FROM fixer.io'


url = str.__add__('http://data.fixer.io/api/latest?access_key=',
YOUR_ACCESS_KEY)
c = Currency_convertor(url)
from_country = input("From Country: ")
to_country = input("TO Country: ")
amount = int(input("Amount: "))

c.convert(from_country, to_country, amount)

Input :
From Country: USD
TO Country: INR
Amount: 1
Output :
1 USD = 70.69 INR

Case 2

Modules needed:
2.1: tkinter: It facilities Graphical User interfaces (GUIs).
pip install tkinter
2.2: forex_python: It is a Free Foreign exchange rate and currency conversion library.
pip install forex_python
Implementation:
 Python

#pip install tkinter


import tkinter as tk
from tkinter import *
import tkinter.messagebox
#GUI
root = tk.Tk()

root.title("Currency converter:GeeksForGeeks")
Tops = Frame(root, bg = '#e6e5e5', pady=2, width=1850, height=100,
relief="ridge")
Tops.grid(row=0, column=0)

headlabel = tk.Label(Tops, font=('lato black', 19, 'bold'),


text='Currency converter :GeeksForGeeks ',
bg='#e6e5e5', fg='black')
headlabel.grid(row=1, column=0, sticky=W)

variable1 = tk.StringVar(root)
variable2 = tk.StringVar(root)

variable1.set("currency")
variable2.set("currency")
#Function To For Real Time Currency Conversion

def RealTimeCurrencyConversion():
from forex_python.converter import CurrencyRates
c = CurrencyRates()

from_currency = variable1.get()
to_currency = variable2.get()

if (Amount1_field.get() == ""):
tkinter.messagebox.showinfo("Error !!", "Amount Not Entered.\n
Please a valid amount.")

elif (from_currency == "currency" or to_currency == "currency"):


tkinter.messagebox.showinfo("Error !!",
"Currency Not Selected.\n Please
select FROM and TO Currency form menu.")

else:
new_amt = c.convert(from_currency, to_currency,
float(Amount1_field.get()))
new_amount = float("{:.4f}".format(new_amt))
Amount2_field.insert(0, str(new_amount))

#clearing all the data entered by the user


def clear_all():
Amount1_field.delete(0, tk.END)
Amount2_field.delete(0, tk.END)

CurrenyCode_list = ["INR", "USD", "CAD", "CNY", "DKK", "EUR"]


root.configure(background='#e6e5e5')
root.geometry("700x400")

Label_1 = Label(root, font=('lato black', 27, 'bold'), text="", padx=2,


pady=2, bg="#e6e5e5", fg="black")
Label_1.grid(row=1, column=0, sticky=W)

label1 = tk.Label(root, font=('lato black', 15, 'bold'), text="\t


Amount : ", bg="#e6e5e5", fg="black")
label1.grid(row=2, column=0, sticky=W)

label1 = tk.Label(root, font=('lato black', 15, 'bold'), text="\t From


Currency : ", bg="#e6e5e5", fg="black")
label1.grid(row=3, column=0, sticky=W)

label1 = tk.Label(root, font=('lato black', 15, 'bold'), text="\t To


Currency : ", bg="#e6e5e5", fg="black")
label1.grid(row=4, column=0, sticky=W)

label1 = tk.Label(root, font=('lato black', 15, 'bold'), text="\t


Converted Amount : ", bg="#e6e5e5", fg="black")
label1.grid(row=8, column=0, sticky=W)

Label_1 = Label(root, font=('lato black', 7, 'bold'), text="", padx=2,


pady=2, bg="#e6e5e5", fg="black")
Label_1.grid(row=5, column=0, sticky=W)

Label_1 = Label(root, font=('lato black', 7, 'bold'), text="", padx=2,


pady=2, bg="#e6e5e5", fg="black")
Label_1.grid(row=7, column=0, sticky=W)

FromCurrency_option = tk.OptionMenu(root, variable1, *CurrenyCode_list)


ToCurrency_option = tk.OptionMenu(root, variable2, *CurrenyCode_list)

FromCurrency_option.grid(row=3, column=0, ipadx=45, sticky=E)


ToCurrency_option.grid(row=4, column=0, ipadx=45, sticky=E)

Amount1_field = tk.Entry(root)
Amount1_field.grid(row=2, column=0, ipadx=28, sticky=E)

Amount2_field = tk.Entry(root)
Amount2_field.grid(row=8, column=0, ipadx=31, sticky=E)

Label_9 = Button(root, font=('arial', 15, 'bold'), text=" Convert ",


padx=2, pady=2, bg="lightblue", fg="white",
command=RealTimeCurrencyConversion)
Label_9.grid(row=6, column=0)

Currency Converter – Python Project


with Source Code
Are you looking to build a solid career in Python? If Yes, you have to work on
projects. DataFlair is devoted to make you a successful Python Developer. After
tons of tutorials, practicals, interview questions, we are coming with a series of
projects from beginner to advanced level.

In this tutorial, we are going to build an exciting python project through which
you can convert currencies. For a user interface, we are going to use the tkinter
library

Currency Converter in Python


Prerequisites
The currency converter project in python requires you to have basic knowledge of
python programming and the pygame library.

tkinter – For User Interface (UI)



 requests – to get url
To install the tkinter and requests library, type the following code in your
terminal:

pip install tkinter

pip install requests

Download Project Code


Before proceeding ahead, please download source code of project: Currency
Converter Project Code

Steps to Build the Python Project on Currency


Converter
1. Real-time Exchange rates
2. Import required Libraries
3. CurrencyConverter Class
4. UI for CurrencyConverter
5. Main Function
1. Real-time Exchange rates
To get real-time exchange rates, we will use:
https://api.exchangerate-api.com/v4/latest/USD
Here, we can see the data in JSON format, with the following details:

Base – USD: It means we have our base currency USD. which means to convert
any currency we have to first convert it to USD then from USD, we will convert it
in whichever currency we want.
Date and time: It shows the last updated date and time.
Rates: It is the exchange rate of currencies with base currency USD.
2. Import the libraries:
For this project based on Python, we are using the tkinter and requests library. So
we need to import the library.

import requests

from tkinter import *

import tkinter as tk

from tkinter import ttk

3. Create the CurrencyConverter class:


Now we will create the CurrencyConverter class which will get the real-time
exchange rate and convert the currency and return the converted amount.

3.1. Let’s create the constructor of class.


class RealTimeCurrencyConverter():

def __init__(self,url):

self.data= requests.get(url).json()
self.currencies = self.data['rates']

requests.get(url) load the page in our python program and then .json() will
convert the page into the json file. We store it in a data variable.

3.2. Convert() method:

def convert(self, from_currency, to_currency, amount):

initial_amount = amount

#first convert it into USD if it is not in USD.

# because our base currency is USD

if from_currency != 'USD' :

amount = amount / self.currencies[from_currency]

# limiting the precision to 4 decimal places

amount = round(amount * self.currencies[to_currency], 4)

return amount

This method takes following arguments:

From_currency: currency from which you want to convert.


to _currency: currency in which you want to convert.
Amount: how much amount you want to convert.
And returns the converted amount.

Example:
url = 'https://api.exchangerate-api.com/v4/latest/USD'

converter = RealTimeCurrencyConverter(url)

print(converter.convert('INR','USD',100))

OUTPUT: 1.33
100 Indian rupees = 1.33 US dollars

4. Now let’s create a UI for the currency converter


To Create UI we will create a class CurrencyConverterUI
def __init__(self, converter):

tk.Tk.__init__(self)

self.title = 'Currency Converter'

self.currency_converter = converter

Converter: Currency Converter object which we will use to convert currencies.


Above code will create a Frame.

Let’s Create the Converter


self.geometry("500x200")

#Label

self.intro_label = Label(self, text = 'Welcome to Real Time Currency Convertor', fg = 'blue', relief = tk.RAISED,
borderwidth = 3)

self.intro_label.config(font = ('Courier',15,'bold'))

self.date_label = Label(self, text = f"1 Indian Rupee equals = {self.currency_converter.convert('INR','USD',1)} USD \n


Date : {self.currency_converter.data['date']}", relief = tk.GROOVE, borderwidth = 5)

self.intro_label.place(x = 10 , y = 5)

self.date_label.place(x = 170, y= 50)

NOTE: This Code part of __init__ method.


First, we set up the frame and add some info in it. After the execution of this part
of code, our frame looks like something.
Now let’s create the entry box for the amount and options of currency in the
frame. So That users can enter the amount and choose among currencies.

# Entry box

valid = (self.register(self.restrictNumberOnly), '%d', '%P')

# restricNumberOnly function will restrict thes user to enter invavalid number in Amount field. We will define it later in
code

self.amount_field = Entry(self,bd = 3, relief = tk.RIDGE, justify = tk.CENTER,validate='key', validatecommand=valid)

self.converted_amount_field_label = Label(self, text = '', fg = 'black', bg = 'white', relief = tk.RIDGE, justify =


tk.CENTER, width = 17, borderwidth = 3)

# dropdown

self.from_currency_variable = StringVar(self)

self.from_currency_variable.set("INR") # default value

self.to_currency_variable = StringVar(self)
self.to_currency_variable.set("USD") # default value

font = ("Courier", 12, "bold")

self.option_add('*TCombobox*Listbox.font', font)

self.from_currency_dropdown = ttk.Combobox(self,
textvariable=self.from_currency_variable,values=list(self.currency_converter.currencies.keys()), font = font, state =
'readonly', width = 12, justify = tk.CENTER)

self.to_currency_dropdown = ttk.Combobox(self,
textvariable=self.to_currency_variable,values=list(self.currency_converter.currencies.keys()), font = font, state =
'readonly', width = 12, justify = tk.CENTER)

# placing

self.from_currency_dropdown.place(x = 30, y= 120)

self.amount_field.place(x = 36, y = 150)

self.to_currency_dropdown.place(x = 340, y= 120)

#self.converted_amount_field.place(x = 346, y = 150)

self.converted_amount_field_label.place(x = 346, y = 150)

NOTE: This code is part of __init__


After the successful Execution of code till now. We will get below screen:
Now Let’s add the CONVERT button which will call the perform function.
# Convert button

self.convert_button = Button(self, text = "Convert", fg = "black", command = self.perform)

self.convert_button.config(font=('Courier', 10, 'bold'))

self.convert_button.place(x = 225, y = 135)

Command = self.perform – It means on click it will call perform().


perform() method:
The perform method will take the user input and convert the amount into the
desired currency and display it on the converted_amount entry box.

def perform(self,):

amount = float(self.amount_field.get())

from_curr = self.from_currency_variable.get()

to_curr = self.to_currency_variable.get()
converted_amount= self.currency_converter.convert(from_curr,to_curr,amount)

converted_amount = round(converted_amount, 2)

self.converted_amount_field_label.config(text = str(converted_amount))

NOTE: this function is a part of App class.


RestrictNumberOnly() method:
Now let’s create a restriction in our entry box. So that user can enter only a
number in Amount Field. We have discussed earlier that this will be done by our
RrestricNumberOnly method.
def restrictNumberOnly(self, action, string):

regex = re.compile(r"[0-9,]*?(\.)?[0-9,]*$")

result = regex.match(string)

return (string == "" or (string.count('.') <= 1 and result is not None))

NOTE: This function is a part of App class.

5. Let’s create the main function.


First, we will create the Converter. Second, Create the UI for Converter

if __name__ == '__main__':

url = 'https://api.exchangerate-api.com/v4/latest/USD'

converter = RealTimeCurrencyConverter(url)

App(converter)

mainloop()
Label_1 = Label(root, font=('lato black', 7, 'bold'), text="", padx=2,
pady=2, bg="#e6e5e5", fg="black")
Label_1.grid(row=9, column=0, sticky=W)

Label_9 = Button(root, font=('arial', 15, 'bold'), text=" Clear All ",


padx=2, pady=2, bg="lightblue", fg="white",
command=clear_all)
Label_9.grid(row=10, column=0)

root.mainloop()

Output:

You might also like