Currency Exchange Rate Checker in Python
Currency Exchange Rate Checker: Develop a program that fetches and displays the latest currency exchange rates.
Input values:
User selects the currencies to compare or the base currency for which exchange rates are fetched.
Output value:
Latest currency exchange rates displayed for the selected currencies or against the base currency.
Example:
Input values: 1. Base currency: USD - User selects USD as the base currency. Output value: Latest exchange rates against USD: - EUR: 0.88 - GBP: 0.76 - JPY: 109.42 - AUD: 1.31 - CAD: 1.27 Input values: 2. Compare currencies: EUR, GBP - User selects EUR and GBP to compare exchange rates. Output value: Latest exchange rates for EUR and GBP: - EUR to USD: 1.14 - GBP to USD: 1.31 Input values: 3. Compare currencies: EUR, JPY - User selects EUR and JPY to compare exchange rates. Output value: Latest exchange rates for EUR and JPY: - EUR to USD: 1.14 - JPY to USD: 0.0091
Solution: Using requests and a Public API
Code:
# Solution 1: Using 'requests' library to fetch data from a public API
import requests # Import the requests library to handle HTTP requests
def get_exchange_rate(base_currency, symbols):
"""
Fetches exchange rates for the specified base currency against selected currencies.
Args:
base_currency (str): The currency code to use as the base.
symbols (list): List of currency codes to compare against the base currency.
Returns:
dict: A dictionary with currency codes as keys and exchange rates as values.
"""
url = f"https://api.exchangerate-api.com/v4/latest/{base_currency}" # API URL with the base currency
# Send GET request to the API and get JSON response
response = requests.get(url)
data = response.json() # Parse the JSON data
# Filter and return only the relevant currency symbols
rates = {currency: data["rates"][currency] for currency in symbols if currency in data["rates"]}
return rates
# User input for the base currency and currencies to compare
base_currency = "USD"
compare_currencies = ["EUR", "GBP", "JPY"]
# Fetch and display exchange rates
exchange_rates = get_exchange_rate(base_currency, compare_currencies)
print(f"Latest exchange rates for {base_currency}:")
for currency, rate in exchange_rates.items():
print(f"- {currency}: {rate}")
Output:
Latest exchange rates for USD: - EUR: 0.916 - GBP: 0.766 - JPY: 149.68
Explanation:
- Uses the requests library to send an HTTP GET request to a free public API.
- Extracts and displays exchange rates for the given currencies using the base currency.
- Error handling is simpler since data is directly retrieved from JSON.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics