|
| 1 | +# Simple Python program for a currency converter |
| 2 | + |
| 3 | +import requests |
| 4 | + |
| 5 | +class CurrencyConverter: |
| 6 | + def __init__(self): |
| 7 | + self.exchange_rates = {} |
| 8 | + |
| 9 | + def fetch_exchange_rates(self): |
| 10 | + # Fetch real-time exchange rates from a currency API (e.g., exchangerate-api.com) |
| 11 | + api_key = "your_api_key" # Replace with your API key |
| 12 | + base_url = f"https://open.er-api.com/v6/latest/{api_key}" |
| 13 | + |
| 14 | + try: |
| 15 | + response = requests.get(base_url) |
| 16 | + response.raise_for_status() |
| 17 | + |
| 18 | + data = response.json() |
| 19 | + self.exchange_rates = data.get("rates", {}) |
| 20 | + except requests.exceptions.RequestException as e: |
| 21 | + print(f"Error fetching exchange rates: {e}") |
| 22 | + |
| 23 | + def convert_currency(self, amount, source_currency, target_currency): |
| 24 | + source_rate = self.exchange_rates.get(source_currency, 1.0) |
| 25 | + target_rate = self.exchange_rates.get(target_currency, 1.0) |
| 26 | + |
| 27 | + converted_amount = amount / source_rate * target_rate |
| 28 | + return round(converted_amount, 2) |
| 29 | + |
| 30 | +def main(): |
| 31 | + print("Welcome to Currency Converter!") |
| 32 | + |
| 33 | + converter = CurrencyConverter() |
| 34 | + |
| 35 | + # Fetch real-time exchange rates |
| 36 | + converter.fetch_exchange_rates() |
| 37 | + |
| 38 | + # Perform currency conversion |
| 39 | + amount = float(input("Enter the amount: ")) |
| 40 | + source_currency = input("Enter the source currency code (e.g., USD): ").upper() |
| 41 | + target_currency = input("Enter the target currency code (e.g., EUR): ").upper() |
| 42 | + |
| 43 | + converted_amount = converter.convert_currency(amount, source_currency, target_currency) |
| 44 | + |
| 45 | + print(f"\nConverting {amount} {source_currency} to {target_currency}...") |
| 46 | + print(f"Result: {converted_amount} {target_currency}") |
| 47 | + |
| 48 | +if __name__ == "__main__": |
| 49 | + main() |
0 commit comments