Editor

Currency Converter in Python

Beginner · Useful tools · about 30 minutes to build · 92 lines

Convert an amount between common currencies such as US dollars, euros and rupees, using a table of example rates.

The program

Press Run and answer its questions in the box that appears under the code.

currency_converter.py
"""A currency converter that uses a fixed table of example exchange rates."""
import math
# EXAMPLE RATES ONLY, for practice: how much of each currency 1 US dollar buys.
# Real rates change all day, so never use these for real money.
EXAMPLE_RATES_PER_USD = {
"USD": ("US dollar", 1.0),
"EUR": ("Euro", 0.86),
"GBP": ("British pound", 0.75),
"INR": ("Indian rupee", 88.0),
"JPY": ("Japanese yen", 150.0),
"AUD": ("Australian dollar", 1.53),
"CAD": ("Canadian dollar", 1.40),
"SGD": ("Singapore dollar", 1.30),
"AED": ("UAE dirham", 3.6725),
"MYR": ("Malaysian ringgit", 4.22),
}
MENU = "1) Convert 2) Show example rates 3) Quit"
# Reading input
def choose_currency(prompt):
"""Ask until the user types a currency code from the table."""
while True:
code = input(prompt).strip().upper()
if code in EXAMPLE_RATES_PER_USD:
return code
print(" Unknown code. Choose one of: " + ", ".join(EXAMPLE_RATES_PER_USD))
def read_amount():
"""Ask until the user types an amount above zero."""
while True:
try:
amount = float(input("Amount: ").replace(",", ""))
if amount > 0 and math.isfinite(amount):
return amount
except ValueError:
pass
print(" Please type an amount above zero, like 250 or 99.50.")
# Converting
def convert(amount, from_code, to_code):
"""Convert through US dollars: first to USD, then to the target currency."""
from_rate = EXAMPLE_RATES_PER_USD[from_code][1]
to_rate = EXAMPLE_RATES_PER_USD[to_code][1]
return amount / from_rate * to_rate
def show_rates():
"""Print the example rate table."""
print(f" {'Code':<6}{'Currency':<20}{'Per 1 USD':>10}")
for code, (name, rate) in EXAMPLE_RATES_PER_USD.items():
print(f" {code:<6}{name:<20}{rate:>10.4f}")
print(" These are examples for practice, not today's rates.")
def run_conversion():
"""Ask for two currencies and an amount, then print the result."""
from_code = choose_currency("From (code, like USD): ")
to_code = choose_currency("To (code, like INR): ")
amount = read_amount()
result = convert(amount, from_code, to_code)
rate = convert(1, from_code, to_code)
print(f" {amount:,.2f} {from_code} = {result:,.2f} {to_code}")
print(f" Example rate used: 1 {from_code} = {rate:,.4f} {to_code}")
def main():
"""Run the menu until the user quits."""
print("Currency converter (example rates, not live ones)")
while True:
print()
print(MENU)
choice = input("Choose 1-3: ").strip()
if choice == "1":
run_conversion()
elif choice == "2":
show_rates()
elif choice == "3":
print("Goodbye.")
break
else:
print(" Please choose 1, 2 or 3.")
if __name__ == "__main__":
main()

Open it in the full editor to save it, share it and keep building.

Sample run

What the program printed, and what was typed (in yellow).

Currency converter (example rates, not live ones)

1) Convert  2) Show example rates  3) Quit
Choose 1-3: 2
  Code  Currency             Per 1 USD
  USD   US dollar               1.0000
  EUR   Euro                    0.8600
  GBP   British pound           0.7500
  INR   Indian rupee           88.0000
  JPY   Japanese yen          150.0000
  AUD   Australian dollar       1.5300
  CAD   Canadian dollar         1.4000
  SGD   Singapore dollar        1.3000
  AED   UAE dirham              3.6725
  MYR   Malaysian ringgit       4.2200
  These are examples for practice, not today's rates.

1) Convert  2) Show example rates  3) Quit
Choose 1-3: 1
From (code, like USD): usd
To (code, like INR): inr
Amount: 250
  250.00 USD = 22,000.00 INR
  Example rate used: 1 USD = 88.0000 INR

1) Convert  2) Show example rates  3) Quit
Choose 1-3: 1
From (code, like USD): rupees
  Unknown code. Choose one of: USD, EUR, GBP, INR, JPY, AUD, CAD, SGD, AED, MYR
From (code, like USD): GBP
To (code, like INR): eur
Amount: -5
  Please type an amount above zero, like 250 or 99.50.
Amount: 100
  100.00 GBP = 114.67 EUR
  Example rate used: 1 GBP = 1.1467 EUR

1) Convert  2) Show example rates  3) Quit
Choose 1-3: 3
Goodbye.

How it is built

1. The example rate table

Every rate says how much of a currency one US dollar buys. The name and the comments mark the rates as examples for practice, because real rates change all day.

# EXAMPLE RATES ONLY, for practice: how much of each currency 1 US dollar buys.
# Real rates change all day, so never use these for real money.
EXAMPLE_RATES_PER_USD = {
    "USD": ("US dollar", 1.0),
    "EUR": ("Euro", 0.86),
    "GBP": ("British pound", 0.75),
    "INR": ("Indian rupee", 88.0),
    "JPY": ("Japanese yen", 150.0),
    "AUD": ("Australian dollar", 1.53),
    "CAD": ("Canadian dollar", 1.40),
    "SGD": ("Singapore dollar", 1.30),
    "AED": ("UAE dirham", 3.6725),
    "MYR": ("Malaysian ringgit", 4.22),
}

2. Picking a currency code

.upper() lets the user type inr or INR. code in EXAMPLE_RATES_PER_USD looks the code up among the dictionary's keys.

def choose_currency(prompt):
    """Ask until the user types a currency code from the table."""
    while True:
        code = input(prompt).strip().upper()
        if code in EXAMPLE_RATES_PER_USD:
            return code
        print("  Unknown code. Choose one of: " + ", ".join(EXAMPLE_RATES_PER_USD))

3. Converting through one currency

Dividing by the first rate turns the amount into US dollars, and multiplying by the second turns that into the target currency. With one base currency, one rate per currency covers every pair.

def convert(amount, from_code, to_code):
    """Convert through US dollars: first to USD, then to the target currency."""
    from_rate = EXAMPLE_RATES_PER_USD[from_code][1]
    to_rate = EXAMPLE_RATES_PER_USD[to_code][1]
    return amount / from_rate * to_rate

4. Showing the rates

for code, (name, rate) in ... takes each tuple apart in the loop line, and :>10.4f lines the rates up on the decimal point.

def show_rates():
    """Print the example rate table."""
    print(f"  {'Code':<6}{'Currency':<20}{'Per 1 USD':>10}")
    for code, (name, rate) in EXAMPLE_RATES_PER_USD.items():
        print(f"  {code:<6}{name:<20}{rate:>10.4f}")
    print("  These are examples for practice, not today's rates.")

5. One conversion

Converting 1 unit gives the rate that was used, which is printed under the answer so the user can check it.

def run_conversion():
    """Ask for two currencies and an amount, then print the result."""
    from_code = choose_currency("From (code, like USD): ")
    to_code = choose_currency("To (code, like INR): ")
    amount = read_amount()
    result = convert(amount, from_code, to_code)
    rate = convert(1, from_code, to_code)
    print(f"  {amount:,.2f} {from_code} = {result:,.2f} {to_code}")
    print(f"  Example rate used: 1 {from_code} = {rate:,.4f} {to_code}")

Make it bigger

  • Add a menu option to update a rate after looking up today's value.
  • Show amounts in yen with no decimal places, as yen are not split into smaller coins.
  • Load the rates from a CSV file instead of writing them in the program.
  • Keep a history of conversions and print it when the user quits.

What it practises