Now we're going to use Python to get exchange rate from a website.
We're going to use a website called Fixer.io which is a really easy to use exchange rate API.
In your editor open
app.py which is the file where you'll write your code.
You can execute your program by using
python3 app.py, though there will be prompts when to test your code.
The editor saves automatically every few seconds.
Firstly, you need to import the urllib module for Python which lets us, as the name suggests, interact with websites. You can import the module with
import urllib.request (click to copy code).
Next we can get the website by doing this:
Insert a URL from the Fixer.io page where it says
YOUR URL HERE.
Now, surround the line to get the website with
) to show it to the console.
We can now try out our code with
python3 app.py (you can also click this).
The output doesn't look very useful does it? We can fix that by parsing the data with the JSON module because the data the website responds with is in JSON format. Import it with
Now surround the inside of the
) which will make the data into something which is easier to manipulate.
That line is now getting a little messy so space it out a bit and you should have something like this:
import urllib.request import json data = urllib.request.urlopen("http://api.fixer.io/latest?base=GBP").read() data = json.loads(data) print(data)
Now we can index the data variable to get the exchange rate for GB Pounds to US Dollars by putting
on the end of the data variable and then doing the same with
USD. Try it out and you should get something like this when you run it
1.2459 (as of 30/3/17).
- Ask the user for a value in pounds and convert it to dollars.
- Ask the user for a value and the currency and convert it to dollars.
- Ask the user for a value and the currency and convert it to anther currency the user has inputted.