Let's Create a Simple Currency Converter in Python

Let's Create a Simple Currency Converter in Python

ยท

3 min read

Introduction

Today, we're gonna make a really simple currency converter in Python. We'll be using the RatesAPI for getting the latest currency conversion rates. ๐Ÿ˜€

Prerequisites

The only prerequisites for this project are the JSON module and the request module for Python. If you don't already have these modules, you can install them using pip. Just type the following commands in the command prompt/terminal

pip install
pip install requests

A Short Intro on Requests and JSON

Requests is a really powerful library in Python. It is used to send requests to a web server and get the response back. It is usually used to interact with APIs or get the source code of a web page.

JSON stands for JavaScript Object Notation (I know it's a Python tutorial ๐Ÿ˜…). JSON is a way to transport data in a light-weight, easy-to-read and logical manner. JSON is also similar to Python's dictionary.

To learn more about JSON, run the code snippet given below in your Python interpreter. The output will be in JSON format.

import requests
import json

rates = json.loads(requests.get("https://api.ratesapi.io/api/latest?base=INR").text)

print(rates)

The Final Code

#Importing the libraries

import requests
import json

#Basic UI

print("Welcome to Currency Converter!!!")
print("powered by RatesAPI (ratesapi.io)")

print("\nCurrent Currency Rates in INR\n")

#Calling the API for getting the currenct currency rates
rates = json.loads(requests.get("https://api.ratesapi.io/api/latest?base=INR").text).get("rates")

#Printing the rates
for i in rates:
    print(i,"   ",rates[i])

print("")

#Some more UI
print("Choose an option:\n")
print("1. Convert Currency")
print("2. Exit")

choice = int(input())

if choice==1:
    base_currency = input("Enter the currency code you want to convet from: ")
    to_currency = input("Enter the currency code you want to convert to: ")
    amount = int(input("Enter the amount to convert: "))

    #Some calculation to convert the amount to desired currecny and printing it
    conversion_rates = json.loads(requests.get("https://api.ratesapi.io/api/latest?base="+base_currency).text)
    print(amount,base_currency,"is equal to",(conversion_rates.get("rates").get(to_currency))*amount,to_currency)

elif choice==2:
    quit()

else:
    print("Please try again with a valid choice!")

Conclusion

That was it for this post! If you followed till here then you have a working currency converter in Python. ๐Ÿ˜Š

If you liked this post, then following my blog would be fabulous! I will be posting more articles like this in the future related to several new topics. Stay tuned!

Thanks to Karolina Grabowska from Pexels for the Cover Image