Introduction
In today’s globalized world, converting currencies has become a necessary task. Whether you’re traveling abroad, making international purchases, or analyzing financial data, the need to convert amounts between different currencies is common. In this guide, we will explore a simple Python program to convert amounts from one currency to another using real-time exchange rates.
Objective
The primary objective of this program is to create a currency converter tool that accepts an amount in one currency and converts it into another currency based on real-time exchange rates. Users will be able to select the currency they are converting from, the currency they want to convert to, and the amount to convert. The program will fetch the latest exchange rates and perform the conversion automatically.
Python Code: Currency Converter
import requests
def get_exchange_rate(from_currency, to_currency):
# Define the API endpoint for fetching exchange rates
url = f"https://api.exchangerate-api.com/v4/latest/{from_currency}"
# Request data from the API
response = requests.get(url)
if response.status_code != 200:
print("Error: Unable to fetch exchange rates.")
return None
data = response.json()
if to_currency in data['rates']:
return data['rates'][to_currency]
else:
print(f"Error: Unable to find the exchange rate for {to_currency}.")
return None
def convert_currency(amount, from_currency, to_currency):
rate = get_exchange_rate(from_currency, to_currency)
if rate:
converted_amount = amount * rate
return converted_amount
return None
def main():
print("Welcome to the Currency Converter!")
# Get user input for conversion details
from_currency = input("Enter the currency you are converting from (e.g., USD, EUR): ").upper()
to_currency = input("Enter the currency you are converting to (e.g., USD, EUR): ").upper()
amount = float(input("Enter the amount you want to convert: "))
# Convert the currency
converted_amount = convert_currency(amount, from_currency, to_currency)
if converted_amount is not None:
print(f"{amount} {from_currency} is equal to {converted_amount:.2f} {to_currency}.")
else:
print("Conversion could not be completed.")
if __name__ == "__main__":
main()
Explanation of the Program Structure
The program is structured as follows:
- get_exchange_rate: This function fetches the exchange rate between two currencies from a third-party API (ExchangeRate-API). It takes two parameters: the source currency (from_currency) and the target currency (to_currency). If the exchange rate is found, it returns the rate; otherwise, it prints an error message.
- convert_currency: This function calls the
get_exchange_rate
function to get the exchange rate and multiplies it with the given amount to return the converted value. - main: This is the entry point of the program. It prompts the user for input, such as the amount, the source currency, and the target currency. It then calls the
convert_currency
function to perform the conversion and prints the result to the console.
How to Run the Program
- Make sure you have Python installed on your system (preferably Python 3.x).
- Install the required Python library (requests) to handle HTTP requests. You can do this by running the following command in your terminal or command prompt:
pip install requests
- Save the Python script (the code above) in a file, for example,
currency_converter.py
. - Open a terminal or command prompt, navigate to the folder containing the script, and run the following command:
python currency_converter.py
- The program will prompt you for the currency details (source currency, target currency, and amount), and it will display the converted amount based on the latest exchange rates.