Currency converter

Published

2023-08-01

Example: currency converter

We’re starting with programs that take some input, perform some simple calculations, and display some output.

Here we’ll demonstrate a currency converter. Consider how we’d like such a program to behave, assuming we need the exchange rate as a user-supplied input. What’s the information we’d need to perform the calculation?

  • The amount we’d like to convert.
  • A label for the currency we’d like to convert, for example, USD, CAD, MXN, BRL, EUR, etc.1 We’ll call this the source currency.
  • An exchange rate.
  • A label for the currency we want to receive (as above). We’ll call this the target currency.

Let’s imagine how this might work:

  1. The user is prompted for a source currency label.
  2. The user is prompted for a target currency label.
  3. The user is prompted for an amount (in the source currency).
  4. The user is prompted for an exchange rate.
  5. The program displays the result.

This raises the question: how do we express the exchange rate? One approach would be to express the rate as the ratio of the value of the source currency unit to the target currency unit. For example, as of this writing, one US dollar (USD) is equivalent to 1.3134 Canadian dollars (CAD).

Taking this approach, we’ll multiply the source currency amount by the exchange rate to get the equivalent value in the target currency. Here’s how a session might proceed:

Enter source currency label: USD
Enter target currency label: CAD
OK. We will convert USD to CAD.
Enter the amount in USD you wish to convert: 1.00
Enter the exchange rate (USD/CAD): 1.3134
1.00 USD is worth 1.31 CAD

At this point, we don’t have all the tools we’d need to validate input from the user, so for this program we’ll trust the user to be well-behaved and to enter reasonable labels and rates. (We’ll see more on input validation and exception handling soon.) With this proviso, here’s how we might start this program:

source_label = input('Enter source currency label: ')
target_label = input('Enter target currency label: ')
print(f'OK. We will convert {source_label} '
      f'to {target_label}.')

This code will prompt the user for source and target labels and then print out the conversion the user has requested. Notice that we use an f-string to interpolate the user-supplied labels.

Now we need two other bits of information: the amount we wish to convert, and the exchange rate. (Here we’ll use the \, which, when used as shown, signifies an explicit line continuation in Python. Python will automatically join the lines.)2

source_prompt = f'Enter the amount in {source_label} ' \
                f'you wish to convert: '

ex_rate_prompt = f'Enter the exchange rate ' \
                 f'({source_label}/{target_label}): '
                 
source_amount = float(input(source_prompt))
exchange_rate = float(input(ex_rate_prompt))

At this point, we have both labels source_label and target_label, the amount we wish to convert stored as source_amount, and the exchange rate stored as exchange_rate. The labels are of type str. The source amount and the exchange rate are of type float.

Giving these objects significant names (rather than x, y, z, \ldots) makes the code easy to read and understand.

Now, on to the calculation. Since we have the rate expressed as a ratio of the value of a unit of the source currency to a unit of the target currency, all we need to do is multiply.

target_amount = source_amount * exchange_rate

See how choosing good names makes things so clear? You should aim for similar clarity when naming objects and putting them to use.

The only thing left is to print the result. Again, we’ll use f-strings, but this time we’ll include format specifiers to display the results to two decimal places of precision.

print(f'{source_amount:,.2f} {source_label} is worth '
      f'{target_amount:,.2f} {target_label}')

Putting it all together we get:

"""
Currency Converter
Egbert Porcupine <egbert.porcupine@uvm.edu>
CS 1210

Prompts users for two currencies, amount to convert, 
and exchange rate, and then performs the conversion 
and displays the result.
"""

source_label = input('Enter source currency label: ')
target_label = input('Enter target currency label: ')
print(f'OK. We will convert {source_label} '
      f'to {target_label}.')

source_prompt = f'Enter the amount in {source_label} ' \
                f'you wish to convert: '

ex_rate_prompt = f'Enter the exchange rate ' \
                 f'({source_label}/{target_label}): '
                 
source_amount = float(input(source_prompt))
exchange_rate = float(input(ex_rate_prompt))
                            

target_amount = source_amount * exchange_rate

print(f'{source_amount:,.2f} {source_label} is worth '
      f'{target_amount:,.2f} {target_label}')

Notice that we don’t need any comments to explain our code. By choosing good names we’ve made comments unnecessary!

We’ll revisit this program, making improvements as we acquire more tools.

Feel free to copy, save, and run this code. There are lots of websites which provide exchange rates and perform such conversions. One such website is the Xe Currency Converter (https://www.xe.com/currencyconverter/).

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).

Footnotes

  1. For three-character ISO 4217 standard currency codes, see: https://en.wikipedia.org/wiki/ISO_4217.↩︎

  2. From the Python documentation: Two or more physical lines may be joined into logical lines using backslash characters (), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character (https://docs.python.org/3/reference/lexical_analysis.html).↩︎