Write currency converter in Python, use free API
- User
Write currency converter in Python, use free API
- Assistant
Sure! Below is a Python script for a currency converter that uses a free API from exchangerate.host. This script allows you to convert an amount from one currency to another using real-time exchange rates.
pythonimport requests def currency_converter(): try: # Prompt the user for input amount = float(input("Enter the amount to be converted: ")) from_currency = input("Enter the currency code you are converting from (e.g., USD): ").upper() to_currency = input("Enter the currency code you are converting to (e.g., EUR): ").upper() # Construct the API URL url = f"https://api.exchangerate.host/convert?from={from_currency}&to={to_currency}&amount={amount}" # Make a GET request to the API response = requests.get(url) data = response.json() # Check if the request was successful and extract the result if response.status_code == 200 and data.get('result') is not None: result = data['result'] print(f"\n{amount} {from_currency} = {result} {to_currency}") else: print("\nError in conversion. Please check the currency codes and try again.") except ValueError: print("\nInvalid input. Please enter numeric values for the amount.") except requests.exceptions.RequestException as e: print(f"\nError fetching data from the API: {e}") if __name__ == "__main__": currency_converter()How the Script Works:
-
Imports:
- The script imports the
requestslibrary to handle HTTP requests to the currency exchange API.
- The script imports the
-