Convert Currencies using Python
The following are two Pythong scripts that will allow you or an end user convert currencies. To use these scripts, you'll need to install the forex-python library, which you can do by running pip install forex-python in your terminal.
The following are two Pythong scripts that will allow you or an end user convert currencies.
To use these scripts, you'll need to install the forex-python
library, which you can do by running pip install forex-python
in your terminal.
from forex_python.converter import CurrencyRates
# create an instance of the CurrencyRates class
currency_rates = CurrencyRates()
# define the base currency and the target currency
base_currency = 'USD'
target_currency = 'EUR'
# define the amount you want to convert
amount = 100
# use the convert() method to convert the currency
converted_amount = currency_rates.convert(base_currency, target_currency, amount)
# print the result
print(f'{amount} {base_currency} = {converted_amount:.2f} {target_currency}')
The second Python script will allow the end user to enter the currencies that he or she wishes to convert:
from forex_python.converter import CurrencyRates, CurrencyCodes
# create an instance of the CurrencyRates and CurrencyCodes classes
currency_rates = CurrencyRates()
currency_codes = CurrencyCodes()
# get a list of all the available currency codes
all_codes = currency_codes.get_codes()
# prompt the user for the base currency
base_currency = ''
while base_currency not in all_codes:
base_currency = input('Enter the base currency code (e.g. USD): ').upper()
# prompt the user for the target currency
target_currency = ''
while target_currency not in all_codes:
target_currency = input('Enter the target currency code (e.g. EUR): ').upper()
# prompt the user for the amount to convert
amount = float(input('Enter the amount to convert: '))
# use the convert() method to convert the currency
converted_amount = currency_rates.convert(base_currency, target_currency, amount)
# print the result
base_currency_name = currency_codes.get_currency_name(base_currency)
target_currency_name = currency_codes.get_currency_name(target_currency)
print(f'{amount:.2f} {base_currency_name} ({base_currency}) = {converted_amount:.2f} {target_currency_name} ({target_currency})')