Skip to content

Instantly share code, notes, and snippets.

@StrangeRanger
Last active December 22, 2024 23:02
Show Gist options
  • Save StrangeRanger/a8200e94a9a7f6ee4faf638b6061d656 to your computer and use it in GitHub Desktop.
Save StrangeRanger/a8200e94a9a7f6ee4faf638b6061d656 to your computer and use it in GitHub Desktop.
currency_converter.py
#!/usr/bin/env python3
#
# Using the API (https://api.exchangeratesapi.io/latest), this script converts one
# currency into another.
#
# Prerequisites:
# - requests
#
# IMPORTANT:
# This script no longer works as the API now requires an API key.
#
# Version: v1.0.3
# License: MIT License
# Copyright (c) 2020-2021 Hunter T. (StrangeRanger)
#
########################################################################################
# [ Imports and Global Variables ]######################################################
import requests
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):
"""Validates a currency code against the API data and updates relevant global
variables.
Args:
currency (str): The three-letter ISO currency code (e.g., 'USD').
base_currency (bool, optional): Specifies whether the currency is being
validated as the base currency. Defaults to False.
Returns:
bool: True if the currency is valid and exists in the API data; False otherwise.
Raises:
KeyError: If the provided currency code is invalid or does not exist in the
API's response.
"""
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 the 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
)
)
@StrangeRanger
Copy link
Author

Project Tracker

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment