Currency exchanger in Python

Description

This project is a Python-based currency converter that uses live exchange rate data from the Frankfurter API. The program retrieves the latest available currency rates, displays the supported currency codes, and allows the user to choose an input currency, an output currency, and the amount to convert. It includes simple validation to ensure that only existing currencies and positive amounts are accepted, making the interaction clear and reliable. With its straightforward structure and use of real API data, this project is an excellent introduction to HTTP requests, JSON data handling, user input validation, and basic financial calculations in Python. It can be used as a foundation for travel tools, budgeting applications, finance dashboards, exchange-rate utilities, or other API-powered software projects.

CODE:

currency_exchanger.py
#-- https://nemiatools.com --#

import requests  # Import HTTP library

url = "https://api.frankfurter.app/latest"  # Set API URL

# Get available currencies
response = requests.get(url)  # Send GET request
response.raise_for_status()  # Check request status
all_currencies = response.json()["rates"]  # Get currency rates
all_currencies["EUR"] = 1.0  # Add EUR base currency

print("Currency Names:", ", ".join(sorted(all_currencies)), "\n")  # Print currencies

while True:  # Repeat program
    while True:  # Ask input currency
        currency_in = input("Enter current currency: ").upper()  # Read input currency
        if currency_in in all_currencies:  # Check currency exists
            break  # Exit loop
        print("Currency not found. Try again.\n")  # Show error

    while True:  # Ask output currency
        currency_out = input("Enter final currency: ").upper()  # Read output currency
        if currency_out in all_currencies:  # Check currency exists
            break  # Exit loop
        print("Currency not found. Try again.\n")  # Show error

    while True:  # Ask amount
        amount_in = float(
            input(f"Enter amount to exchange in {currency_in}: ")
        )  # Read amount
        if amount_in > 0:  # Check positive amount
            break  # Exit loop
        print("Invalid amount.\n")  # Show error

    data = requests.get(url, params={"from": currency_in}).json()  # Get exchange data
    amount_out = data["rates"][currency_out] * amount_in  # Convert amount

    print(f"Final amount: {amount_out:.2f} {currency_out}\n")  # Print result

How it works:

The program starts with import requests, which imports the Requests library. This library is used to send HTTP requests, allowing the program to communicate with an online service and receive updated currency data.

The API address is stored in url = "https://api.frankfurter.app/latest". This makes the code cleaner, because the same URL can be reused whenever the program needs to request exchange rate information.

The line response = requests.get(url) sends a GET request to the API. In simple words, requests.get() asks the server to send back data from that URL. The result is saved inside response. Then, response.raise_for_status() checks if the request worked correctly. If there is an error, the program stops instead of continuing with missing or invalid data.

The instruction all_currencies = response.json()["rates"] converts the API response from JSON into Python data and selects the "rates" section, where the exchange rates are stored. The line all_currencies["EUR"] = 1.0 manually adds EUR because the API uses EUR as the default base currency, so it is not included in its own rates list. Since 1 EUR is equal to 1 EUR, its value is set to 1.0.

The program displays the available currencies with print("Currency Names:", ", ".join(sorted(all_currencies)), "\n"). Here, sorted(all_currencies) puts the currency codes in alphabetical order, while ", ".join(...) combines them into a single readable line.

The main converter runs inside while True:, which keeps the program active so the user can make multiple conversions. The inputs currency_in = input("Enter current currency: ").upper() and currency_out = input("Enter final currency: ").upper() read the selected currencies and convert them to uppercase, so inputs like usd or Usd still work correctly.

The conditions if currency_in in all_currencies: and if currency_out in all_currencies: check that the entered currencies really exist in the API data. If a currency is not found, the program shows an error message and asks again.

The amount is read with amount_in = float(input(f"Enter amount to exchange in {currency_in}: ")). The float() function converts the user input into a decimal number, while the f"..." string inserts the selected currency directly into the message. The condition if amount_in > 0: makes sure that only positive amounts are accepted.

The line data = requests.get(url, params={"from": currency_in}).json() sends another request to the API, this time using params={"from": currency_in}. This tells the API which currency should be used as the base currency. The .json() part converts the response into Python data immediately.

The conversion is calculated with amount_out = data["rates"][currency_out] * amount_in, which multiplies the selected exchange rate by the amount entered by the user. Finally, print(f"Final amount: {amount_out:.2f} {currency_out}\n") prints the result. The format .2f simply means two decimal places.

This project is a good introduction to APIs, HTTP requests, JSON data, input validation, loops, and basic currency conversion in Python.

ONLINE GBD project runner:

LINK: https://onlinegdb.com/x27VF4Dla