Self updating Currency Converter Program in Python for CLI
Posted on September 28, 2014
Recently I find myself traveling quite a bit internationally. I needed a program to quickly convert my money into the currency of the country I happen to visit at the moment. I took advantage of this need to practice my coding skills in Python. In this post I explain how I did it.
I’m always refining the code. You can find the most updated version on this program on Github.
###Business requirements/user stories
As I user I need to be able to put in any amount I desire and see the resulted converted output on screen
As a user I need a program for CLI in which converts any amount to a destination currency of my choice (i.e.: US Dollars to Euros)
Needs to convert a source currency to a destination currency
Needs to have a menu to pick what conversion rate to use
The output needs to be formatted (i.e: $3,235.50)
The conversion rate used should not be more the 24 hours old
###How the program works
The user gets prompted to chose from a menu of possible conversions as shown in Fig. 1
After the user has chosen which currency to convert the prompt asks for the amount to convert as shown in Fig.2
When the user hits return the calculated amount converted in the desired currency is shown along with the conversion rate as shown in Fig.3
conv_rates.txt. is the text database in which I store all the currency conversion rate, line by line comma delimited:
create_exchange_dict(). In this function read the conv_rates.txt and create the Exchange Rate Dictionary:
grab_web_rates(). This is the heart of the program. The function goes online, grabs the exchange rates from a live website and saved them into conv_rates.txt. To do this I use the Python libraries urllib2 and re. In this instance I only grab the first 23 lines to avoid copying the whole website.
get_result(choice, amount). Based on the amount and the exchange rate chosen by the user this function returns the desired amount in the new currency based on the exchange rate in the database. Returns an error if the rate is not found.
format_currency(value). Just a simple function that formats the amount with a comma every thousands and only two decimals after the point.
checkChoice(choice). Error handling function that checks that the user enter a number. This is needed in the menu section.
main(). This is the main function that shows the menu and call all the above functions when the user has made a selection. It’s the first function being executed when the program is launched