Building a Currency Converter in Python (with Real-Time Exchange Rates)

Currency conversion is a common utility in global applications such as travel apps, financial tools, and e-commerce systems. In this article, we’ll learn how to build a functional Currency Converter in Python using real-time exchange rates from a public API.
This script will allow users to:
Input an amount
Choose a source and target currency
Get the latest exchange rate
See the converted value instantly
We’ll use the ExchangeRate-API (free tier) or exchangerate.host which is completely free and doesn't require an API key.
Step 1: Install Required Libraries
We’ll use the built-in json module and the third-party requests library to make HTTP calls. If you don’t have requests, install it with:
pip install requests
Step 2: Import Necessary Modules
Start by importing the required modules.
import requests
The requests module is used to make HTTP requests to the currency exchange API and fetch JSON data.
Step 3: Define the Currency Conversion Function
We'll write a function that accepts the base currency, target currency, and amount to convert.
def convert_currency(base_currency, target_currency, amount):
url = f"https://api.exchangerate.host/latest?base={base_currency.upper()}&symbols={target_currency.upper()}"
try:
response = requests.get(url)
data = response.json()
if target_currency.upper() in data['rates']:
rate = data['rates'][target_currency.upper()]
converted_amount = amount * rate
return converted_amount, rate
else:
print("Currency code not found.")
return None, None
except Exception as e:
print(f"An error occurred: {e}")
return None, None
Explanation
The API returns real-time exchange rates in JSON format.
We extract the specific rate for the target currency.
Multiply the rate by the amount to get the converted value.
The function also handles possible errors, such as invalid currency codes or network issues.
Step 4: Get User Input and Perform Conversion
Let’s now build a simple interface to let the user enter the base currency, target currency, and the amount to convert.
if __name__ == "__main__":
print("Welcome to the Currency Converter")
base = input("Enter base currency (e.g., USD): ").strip()
target = input("Enter target currency (e.g., EUR): ").strip()
try:
amount = float(input("Enter amount to convert: "))
except ValueError:
print("Invalid amount.")
exit()
result, rate = convert_currency(base, target, amount)
if result is not None:
print(f"\nExchange Rate: 1 {base.upper()} = {rate:.4f} {target.upper()}")
print(f"Converted Amount: {amount} {base.upper()} = {result:.2f} {target.upper()}")
What This Does
Prompts the user to enter currencies and the amount.
Converts the amount using the
convert_currency()function.Displays the exchange rate and the result.
Sample Output
Welcome to the Currency Converter
Enter base currency (e.g., USD): usd
Enter target currency (e.g., EUR): eur
Enter amount to convert: 100
Exchange Rate: 1 USD = 0.9132 EUR
Converted Amount: 100 USD = 91.32 EUR
Why Use exchangerate.host?
It’s free and doesn’t require an API key
Simple and fast JSON responses
Offers historical rates, conversion, and time series if needed
You can also replace it with another API like ExchangeRate-API, OpenExchangeRates, or Fixer.io if you want more advanced features or authenticated requests.
Additional Features You Can Add
GUI Interface: Use
tkinterto create a desktop GUI.Dropdown Menus: Load available currency codes dynamically.
Historical Conversion: Add date selection to convert with historical rates.
Command-Line Arguments: Support script usage from the terminal with arguments.
Conclusion
You now have a working real-time currency converter in Python. This script demonstrates how to integrate external APIs with Python logic to create practical and user-friendly tools. With a bit of extension, you can turn this into a desktop app or even integrate it into a web service.




