w3resource

Python Project Currency Converter - Solutions and Explanations

Currency Converter:

Build a program that converts currency from one denomination to another.

Input values:
User provides an amount in one currency and selects the target currency for conversion.

Output value:
Converted the amount to the target currency.

Example:

Input values:
Enter the amount in USD: 50
Select target currency (1 for EUR, 2 for GBP, 3 for JPY): 2
Output value:
Converted amount in GBP: £37.50

Here are two different solutions for a "Currency Converter" program in Python. The program will allow users to input an amount in one currency (e.g., USD) and select a target currency for conversion (e.g., EUR, GBP, JPY). The program will then output the converted amount based on predefined exchange rates.

Solution 1: Basic Approach Using Conditional Statements

Code:

# Solution 1: Basic Approach Using Conditional Statements

# Define exchange rates for target currencies (these rates are hypothetical)
USD_TO_EUR = 0.85  # 1 USD = 0.85 EUR
USD_TO_GBP = 0.75  # 1 USD = 0.75 GBP
USD_TO_JPY = 110.0 # 1 USD = 110.0 JPY

# Function to perform currency conversion
def convert_currency(amount, target_currency):
    """Convert USD to the specified target currency."""
    if target_currency == '1':
        converted_amount = amount * USD_TO_EUR
        print(f"Converted amount in EUR: €{converted_amount:.2f}")
    elif target_currency == '2':
        converted_amount = amount * USD_TO_GBP
        print(f"Converted amount in GBP: £{converted_amount:.2f}")
    elif target_currency == '3':
        converted_amount = amount * USD_TO_JPY
        print(f"Converted amount in JPY: ¥{converted_amount:.2f}")
    else:
        print("Invalid currency selection. Please choose 1, 2, or 3.")

# Get user input for the amount in USD
amount_in_usd = float(input("Enter the amount in USD: "))

# Get user input for the target currency
print("Select target currency (1 for EUR, 2 for GBP, 3 for JPY): ")
target_currency = input("Enter the number corresponding to the target currency: ")

# Perform the conversion
convert_currency(amount_in_usd, target_currency)

Output:

Enter the amount in USD: 1000
Select target currency (1 for EUR, 2 for GBP, 3 for JPY): 
Enter the number corresponding to the target currency: 3
Converted amount in JPY: ¥110000.00
Enter the amount in USD: 1000
Select target currency (1 for EUR, 2 for GBP, 3 for JPY): 
Enter the number corresponding to the target currency: 1
Converted amount in EUR: €850.00

Explanation:

  • Uses a simple function 'convert_currency()' to perform currency conversion based on predefined exchange rates.
  • The user inputs an amount in USD and selects the target currency by entering a number corresponding to EUR, GBP, or JPY.
  • The program uses conditional statements ('if-elif-else') to check the user's selection and perform the appropriate conversion.
  • This approach is straightforward and works well for a small number of currencies, but it may become harder to maintain if more currencies or features are added.

Solution 2: Using a Class to Encapsulate Conversion Logic

Code:

# Solution 2: Using a Class to Encapsulate Conversion Logic
class CurrencyConverter:
    """Class to handle currency conversion"""
    def __init__(self):
        # Define exchange rates for target currencies (these rates are hypothetical)
        self.exchange_rates = {
            'EUR': 0.85,  # 1 USD = 0.85 EUR
            'GBP': 0.75,  # 1 USD = 0.75 GBP
            'JPY': 110.0  # 1 USD = 110.0 JPY
        }
    def convert(self, amount, target_currency):
        """Convert USD to the specified target currency."""
        # Check if the target currency is valid
        if target_currency in self.exchange_rates:
            converted_amount = amount * self.exchange_rates[target_currency]
            symbol = '€' if target_currency == 'EUR' else '£' if target_currency == 'GBP' else '¥'
            print(f"Converted amount in {target_currency}: {symbol}{converted_amount:.2f}")
        else:
            print("Invalid currency selection.")
    def get_user_input(self):
        """Get user input for amount and target currency, and perform conversion."""
        # Get user input for the amount in USD
        amount_in_usd = float(input("Enter the amount in USD: "))
        # Display the options for target currency
        print("Select target currency (EUR, GBP, JPY): ")
        target_currency = input("Enter the currency code (e.g., EUR, GBP, JPY): ").upper()
        # Perform the conversion
        self.convert(amount_in_usd, target_currency)
# Create an instance of the CurrencyConverter class
converter = CurrencyConverter()
# Start the conversion process by getting user input
converter.get_user_input()

Output:

 Enter the amount in USD: 1000
Select target currency (EUR, GBP, JPY): 
Enter the currency code (e.g., EUR, GBP, JPY): GBP
Converted amount in GBP: £750.00
Enter the amount in USD: 1000
Select target currency (EUR, GBP, JPY): 
Enter the currency code (e.g., EUR, GBP, JPY): JPY
Converted amount in JPY: ¥110000.00

Explanation:

  • Defines a 'CurrencyConverter' class to handle the conversion logic, making the code more modular and maintainable.
  • The class stores exchange rates in a dictionary ('self.exchange_rates') for easier management and scalability.
  • The 'convert()' method performs the conversion and checks for valid target currencies.
  • The 'get_user_input()' method handles user input and directs the flow of the program, making it easier to modify or extend the input and output processes.
  • This approach provides better structure, modularity, and scalability for adding more currencies or features.


Become a Patron!

Follow us on Facebook and Twitter for latest update.