Editor

Python Program for a Currency Converter

Beginner · Basics

This program converts an amount of money from one currency to another, using exchange rates stored in a dictionary. The rates in it are sample values for practice, not live rates: real exchange rates change every day.

Program

currency_converter.py
# SAMPLE rates for practice, not live rates: rupees (INR) for one unit
rates_to_inr = {
"INR": 1.0,
"USD": 85.0,
"EUR": 98.0,
"GBP": 112.0,
"AED": 23.0,
}
amount = 250 # or: amount = float(input("Amount: "))
from_cur = "USD" # or: from_cur = input("From currency: ").upper()
to_cur = "INR" # or: to_cur = input("To currency: ").upper()
if from_cur not in rates_to_inr or to_cur not in rates_to_inr:
print("Sorry, that currency is not in the list")
else:
# Convert to rupees first, then from rupees to the target currency
in_inr = amount * rates_to_inr[from_cur]
result = in_inr / rates_to_inr[to_cur]
print("Using sample rates, not live rates")
print(f"{amount} {from_cur} = {result:.2f} {to_cur}")
print(f"{amount} {from_cur} in every currency:")
for code in rates_to_inr:
print(f" {in_inr / rates_to_inr[code]:.2f} {code}")
Output
Using sample rates, not live rates
250 USD = 21250.00 INR
250 USD in every currency:
  21250.00 INR
  250.00 USD
  216.84 EUR
  189.73 GBP
  923.91 AED

How it works

  1. Each rate in the dictionary says how many rupees one unit of that currency buys, so one rate per currency is enough for any pair.
  2. To convert, the amount is first turned into rupees by multiplying, then into the target currency by dividing by its rate.
  3. The in check stops the program from crashing with a KeyError when a currency code is not in the dictionary.
  4. :.2f rounds the result to two decimal places, the way money is written.
  5. To use real rates, look them up on the day and update the dictionary; apps that show live rates download them from an exchange rate service.

Another way to write it

A conversion table with a function

A conversion table with a function
RATES = {"USD": 85.0, "EUR": 98.0, "GBP": 112.0} # sample rupees per unit, not live
def to_rupees(amount, currency):
return amount * RATES[currency]
for currency in RATES:
for amount in [1, 10, 100]:
print(f"{amount} {currency} = Rs. {to_rupees(amount, currency):,.2f}")
Output
1 USD = Rs. 85.00
10 USD = Rs. 850.00
100 USD = Rs. 8,500.00
1 EUR = Rs. 98.00
10 EUR = Rs. 980.00
100 EUR = Rs. 9,800.00
1 GBP = Rs. 112.00
10 GBP = Rs. 1,120.00
100 GBP = Rs. 11,200.00

Putting the conversion in a function lets one loop print a whole table, and :,.2f adds commas between the thousands, as in 11,200.00.

Try it yourself

Add JPY (Japanese yen) with a sample rate of 0.57 and convert 5000 INR to JPY.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises