Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
currency_converter.py
#!/usr/bin/env python3
########################################################################################
#
# Prerequisites
# -------------
# Install globally
# `python3 -m pip install requests`
# Install locally via pipenv (pipenv must already be installed)
# `pipenv install requests && pipenv shell`
#
# Version
# -------
# v1.0.1
#
# License
# -------
# MIT License
# Copyright (c) 2020-present Hunter T.
#
########################################################################################
"""
Using the API (https://api.exchangeratesapi.io/latest), this script converts
one currency into another.
"""
####[ Imports ]#########################################################################
import requests
####[ Variables ]#######################################################################
RED = "\033[1;31m"
DEFCLR = "\033[0m"
request = requests.get("https://api.exchangeratesapi.io/latest").json()
base_value = 0.00
non_base_value = 0.00
####[ Functions ]#######################################################################
def check_valid_currency(currency, base_currency=False):
"""Check if the given currency exists in the json retrieved through the API,
then modifies 'request' and 'base_value'/'non_base_value' accordingly.
Parameters
----------
currency : str
Shorthanded currency name (i.e. USD).
base_currency : bool, optional
Dictates whether or not actions are being performed for the base currency.
Returns
-------
bool
True if input is valid and False if input is invalid.
"""
global request
global base_value
global non_base_value
try:
if base_currency:
if request["rates"][currency]:
request = requests.get(
"https://api.exchangeratesapi.io/latest?base={}".format(base)
).json()
base_value = request["rates"][currency]
return True
else:
if request["rates"][currency]:
non_base_value = request["rates"][currency]
return True
# Occurs if user enters an invalid currency
except KeyError:
return False
####[ Main ]############################################################################
print(
"IMPORTANT NOTES:\n1) When entering a currency, "
"enter it's short handed name (i.e. US Dollar = USD, Japanese "
"yen = JPY, etc."
)
print(
"2) All available currencies (as of 2020-12-7):\n"
" AUD = Australian dollar | BGN = Bulgarian lev\n"
" BRL = Brazilian real | CAD = Canadian dollar\n"
" CHF = Swiss franc | CNY = Chinese yuan renminbi\n"
" CZK = Czech koruna | DKK = Danish krone\n"
" GBP = Pound sterling | HKD = Hong Kong dollar\n"
" HRK = Croatian kuna | HUF = Hungarian forint\n"
" ILS = Israeli shekel | INR = Indian rupee\n"
" ISK = Icelandic krona | JPY = Japanese yen\n"
" KRW = South Korean won | MXN = Mexican peso\n"
" MYR = Malaysian ringgit | NOK = Norwegian krone\n"
" NZD = New Zealand dollar | PHP = Philippine peso\n"
" PLN = Polish zloty | RON = Romanian leu\n"
" RUB = Russian rouble | SEK = Swedish krona\n"
" SGD = Singapore dollar | THB = Thai baht\n"
" TRY = Turkish lira | USD = US dollar\n"
" ZAR = South African rand\n"
)
while True:
base = input("Enter base currency to be converted: ").upper()
if check_valid_currency(base, base_currency=True):
print("")
break
print("{}Invalid input: Please enter a valid currency{}".format(RED, DEFCLR))
while True:
non_base = input("Enter currency to convert the base currency to: ").upper()
if check_valid_currency(non_base):
print("")
break
print("{}Invalid input: Please enter a valid currency{}".format(RED, DEFCLR))
print("Note: Currency is rounded to two decimals")
while True:
try:
amount = round(float(input("Enter an amount to be converted: ")), 2)
print("")
break
except ValueError:
print(
"{}Invalid input: Only numbers are accepted as input{}".format(RED, DEFCLR)
)
print(
"Conversion Rate\n{}: {}\n{}: {}\n".format(
base, base_value, non_base, non_base_value
)
)
print(
"Note: Rounded to two decimals\nConverted currency approximate: {} {}".format(
round(amount * non_base_value, 2), non_base
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment