
Build A Simple Python Currency Converter
In this article, we’ll walk through the creation of a simple Python currency converter.
The user will be prompted to enter their initial currency, their target currency, and the amount they’d like to convert.
From here, we’ll make a web request to a currency conversion API to retrieve the required information. We’ll then present it back to the user via the CLI (command line interface).
This is a short tutorial that’s most suitable for Python beginners.
And with that said, let’s begin.
Our Python currency conversion code in full
Before we step through the script in detail, here it is in its entirety:
import requests
initial_currency = input("Enter the initial currency: ")
target_currency = input("Enter the target currency: ")
while True:
try:
amount = float(input("Enter the amount: "))
except:
print("The amount must be a numeric value!")
continue
if not amount > 0:
print("The amount must be greater than 0")
continue
else:
break
url = "https://api.apilayer.com/fixer/convert?to=" + target_currency + "&from=" + initial_currency + "&amount=" + str(amount)
payload = {}
headers= {
"apikey": "YOUR API KEY"
}
response = requests.request("GET", url, headers = headers, data = payload)
status_code = response.status_code
if status_code != 200:
print("Uh oh, there was a problem. Please try again later")
quit()
result = response.json()
print("Conversion result: " + str(result["result"]))
As you can see, it’s fairly succinct, and this makes it an ideal Python project for beginners to take a look at (and perhaps expand upon, afterwards).
There’s a lot of scope with this type of project, and many new and useful features that can be added on. For now, though, let’s keep it as simple as possible.
Running the Python currency converter
You can copy/paste this script to a file ie. currency-converter.py
and then execute it via the command line with something like:
python3 currency-converter.py
If you’re not using Python 3, you’ll need to tweak that accordingly.
Now, let’s step through the code in detail to see what’s going on.
Importing the required libraries
We only need one Python library here, requests
.
import requests
This is a HTTP library that, unsurprisingly, helps us to fire off web requests! We’ll be using this when communicating with our currency conversion API of choice. More on that later.
Prompting for user input
Firstly, we must prompt the user for their inputs. We need to know what information to feed to the API in the next few steps.
The information we need to gather from the user is:
- The initial currency
- The target currency
- The amount to convert
Once we have this information, we can proceed with fetching the required data from the API and presenting the resultant data back to the user.
We can prompt for the user information like so:
initial_currency = input("Enter the initial currency: ")
target_currency = input("Enter the target currency: ")
Validating the user input
Since we need our user inputs to be in a specific format, we must do some basic validation before we pass the inputs to the API. Typically, the API would handle incorrect inputs, too. But if possible, it’s better to confirm this beforehand to save on a wasted network request.
The steps we are following to receive and then validate user info are as follows:
- Prompt the user for information
- Is it in the correct format?
- Yes? Okay, continue
- No? Show them the prompt again along with a message to tell them what went wrong
- Repeat until the valid inputs have all been supplied
In terms of presenting the input prompt back to the user on incorrect entry, we can use the while
loop as displayed.
while True:
try:
amount = float(input("Enter the amount: "))
except:
print("The amount must be a numeric value!")
continue
if not amount > 0:
print("The amount must be greater than 0")
continue
else:
break
As you can see, we have a while True
condition here that loops indefinitely.
On correct input, though, we break
the loop and hence continue on with the rest of the script.
This is a convenient way of re-presenting the prompts back to the user each time, until correct (or valid) input has been received in each case.
Using the currency conversion API
Now we have valid user inputs, we can move forward with interacting with the API.
Let’s briefly cover the role of the API (application programming interface) firstly though, for the sake of completeness.
In short, an API provides us with the means to interface with another system (in this case, this system is provided via fixer.io).
As we are converting currency in this beginner Python app, we’ll clearly need to rely on some external service or resource to handle this for us. Likewise if we were building a weather app, a cryptocurrency tracker or a route-planning app, for example.
Interacting with this service can be achieved through the use of an API that the supplier provides — usually a REST API for us to make requests to.
Preparation for interacting with the API
In this example, as stated, we are going to be using fixer.io’s currency conversion API.
Typically, to access APIs such as this one – you’ll need an API key.
It’s simply a case of signing up via the website and then retrieving your API key (which you can do here) — this key will then be included in our requests later on.
The API key essentially grants you access to the given resource, and it provides a means for the service to track and identify the requests made via this account.
Making the API request
We imported Python’s requests
library earlier on, we’ve accepted user inputs, and we’re all configured in terms of using the fixer.io API (ie. we have an API key). Now lets look at making our request!
To make a web request using Python’s requests
library, you can simply use the request
method — supplying the necessary parameters as required:
url = "https://api.apilayer.com/fixer/convert?to=" + target_currency + "&from=" + initial_currency + "&amount=" + str(amount)
payload = {}
headers= {
"apikey": "YOUR API KEY"
}
response = requests.request("GET", url, headers = headers, data = payload)
As you can see, we’re passing in some headers
containing our API key as well as the target URL (or endpoint).
Since this is a GET
request, the necessary parameters have been provided directly, appended to the endpoint URL. So it’s simply a case of concatenating the user input variables into the URL string, as shown.
We’re using the convert
endpoint in particular within this Python app, so it’s necessary for us to provide the from
, to
and amount
parameters, as per the API documentation. These pieces of information have all been provided already by the user; so this forms all we need to actually make our request!
Returning the response to the user
Hopefully the request was successful, in which case we’d expect a 200 status code to be returned.
Given this, it’s simply a matter of formatting the returned currency conversion data in the structure we want to output to the user.
We’ll keep it nice and simple here, and just print the converted amount embedded in some user-friendly text, like so:
status_code = response.status_code
if status_code != 200:
print("Uh oh, there was a problem. Please try again later")
quit()
result = response.json()
print("Conversion result: " + str(result["result"]))
And with that, the Python script is complete!
You can convert monetary amounts quickly and easily via this tool and the Python command line interface!
Improving the script
As stated, this is a beginner Python project and as such – it’s a very bare-bones example.
There are of course some improvements you can make to this simple Python currency converter, however, and some extra features and functionalities that can be included:
- Also validate currency (
to
andfrom
) inputs (see the Supported Symbols endpoint documentation) - Convert to more than one currency
- Gracefully handle errors that occur as a result of the API request (see the Potential Errors documentation)
- Have an option to show historical data for each conversion (see the Historical Rates endpoint documentation)
There’s really a lot more than can be added and improved here.
If you’re looking for more ideas on top of those, remember to check out the documentation. You’ll no doubt think of more useful features by browsing through the list of available endpoints in this API.
Where to from here for more beginner Python articles?
For more beginner Python projects like this one, feel free to check out our 10 Python Project Ideas For Beginners article.
Here, we’ve listed 10 ideal projects for Python beginners to sink their teeth into.
The projects are all fairly basic, with few moving parts. This makes them ideal for Python beginners to tackle, and they should provide a good opportunity to pick up and build upon the fundamentals when programming with Python.