Intermediate Project: Build a Real-Time Currency Converter CLI

3D visualization of a command line interface converting Dollar and Euro coins, representing a Python Currency Converter project.

We’re going to build a Command Line Interface (CLI) tool that can convert any amount of money between two currencies using live rates. This project will be a Python-based currency converter application.

We will use the free Frankfurter API (https://api.frankfurter.app). Our Python tool will leverage this API for accurate currency conversion.

Step 1: The API Function

Let’s write a function that gets the current rate between two currencies using our Python currency converter.

import requests

def get_rate(from_currency, to_currency):
    url = f"https://api.frankfurter.app/latest?from={from_currency}&to={to_currency}"
    response = requests.get(url)
    data = response.json()
    
    # The API returns something like: {'rates': {'EUR': 0.95}}
    rate = data['rates'][to_currency]
    return rate

Step 2: The Main Logic

Now we need to ask the user for input and use our function to perform the currency conversion in our Python tool.

def main():
    print("=== Python Currency Converter ===")
    amount = float(input("Enter amount: "))
    from_curr = input("From Currency (e.g., USD): ").upper()
    to_curr = input("To Currency (e.g., EUR): ").upper()

    try:
        rate = get_rate(from_curr, to_curr)
        converted_amount = amount * rate
        
        print(f"\n{amount} {from_curr} is equal to:")
        print(f"{converted_amount:.2f} {to_curr}")
        
    except Exception as e:
        print(f"Error: Could not find rate. Make sure currency codes are correct. ({e})")

if __name__ == "__main__":
    main()

Run it and try converting 100 USD to EUR using the converter!

Similar Posts

Leave a Reply