Introduction
Welcome to the Currency Exchange App! This app allows users to convert one currency to another by tracking real-time exchange rates. It retrieves the current exchange rates and provides an easy-to-use interface to convert any amount from one currency to another.
Objective
The objective of this Currency Exchange App is to help users easily convert currencies using Python by integrating with a reliable API for exchange rates. The app offers real-time data and provides accurate conversions for various currencies around the world.
Code: Currency Exchange App in Python
# Currency Exchange App using Python import requests def get_exchange_rate(from_currency, to_currency): """Fetches the exchange rate between two currencies.""" url = f"https://api.exchangerate-api.com/v4/latest/{from_currency}" response = requests.get(url) data = response.json() if response.status_code == 200 and "rates" in data: rates = data["rates"] if to_currency in rates: return rates[to_currency] return None def convert_currency(amount, from_currency, to_currency): """Converts the given amount from one currency to another.""" exchange_rate = get_exchange_rate(from_currency, to_currency) if exchange_rate is not None: converted_amount = amount * exchange_rate return converted_amount else: return None def main(): """Main function to take user input and display the conversion result.""" print("Welcome to the Currency Exchange App!") from_currency = input("Enter the base currency (e.g., USD, EUR, GBP): ").upper() to_currency = input("Enter the target currency (e.g., USD, EUR, GBP): ").upper() amount = float(input(f"Enter the amount in {from_currency}: ")) converted_amount = convert_currency(amount, from_currency, to_currency) if converted_amount is not None: print(f"{amount} {from_currency} is equivalent to {converted_amount:.2f} {to_currency}") else: print("Sorry, unable to fetch exchange rates. Please check your input and try again.") if __name__ == "__main__": main()
Program Explanation
Program Structure
This program is designed to convert currency using real-time exchange rates. Here’s a breakdown of the key components:
- get_exchange_rate: A function that fetches the exchange rate between two currencies by querying an external API (Exchangerate-API).
- convert_currency: A function that takes the amount and performs the conversion based on the exchange rate fetched from the API.
- main: The main function where the user interacts with the program. It asks for input (base currency, target currency, and amount), and displays the conversion result.
How to Run the Program
- Install the requests library using the command
pip install requests
if you don’t have it installed already. - Save the Python code in a file, for example, currency_converter.py.
- Run the Python program in your terminal or command prompt by typing:
python currency_converter.py
. - Follow the on-screen prompts to input the currencies and amount to be converted.