I've been trying super hard to make a currency converter for the world. One of the many problems I've been facing is that my currency converter wouldn't figure out the exchange rate itself; YOU had to. But of course, I figured it out.
But my question is: I got the exchange rate for EURO, but it's a list, and I need it a float to do the calculation. How would I do that?
Here is what I've tried:
euro_exchange = float(str(tree.xpath('//div[@class="price"]/text()')))
######################################################################
euro_exchange = tree.xpath('//div[@class="price"]/text()')
float(str(euro_exchange)
################################################################
euro_exchange = float(tree.xpath('//div[@class="price"]/text()')
You get the pattern. When I tried euro_exchange = float(str(tree.xpath('//div[@class="price"]/text()')))
, it says (I'm using TkInter, BTW):
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 1562, in __call__
return self.func(*args)
File "/home/jboyadvance/Documents/Code/Python/Currency Converter/Alpha2/main.py", line 21, in usd_callback
euro_exchange = float(str(tree.xpath('//div[@class="price"]/text()')))
ValueError: could not convert string to float: "['1.1394']"
and when I tried euro_exchange = tree.xpath('//div[@class="price"]/text()')
float(str(euro_exchange)
I got the same results.
When I tried euro_exchange = float(tree.xpath('//div[@class="price"]/text()')
:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 1562, in __call__
return self.func(*args)
File "/home/jboyadvance/Documents/Code/Python/Currency Converter/Alpha2/main.py", line 21, in usd_callback
euro_exchange = float(tree.xpath('//div[@class="price"]/text()'))
TypeError: float() argument must be a string or a number, not 'list'
And here's the source code:
import tkinter as tk
from lxml import html
import requests
window = tk.Tk()
window.title("Currency Converter")
window.geometry("500x500")
window.configure(bg="#900C3F")
# window.wm_iconbitmap("penny.ico")
page = requests.get('https://www.bloomberg.com/quote/EURUSD:CUR')
tree = html.fromstring(page.content)
def usd_callback():
usd_amount = float(ent_usd.get())
euro_exchange = float(str(tree.xpath('//div[@class="price"]/text()')))
euro_amount = usd_amount / euro_exchange
lbl_euros.config(text="Euro Amount: %.2f€" % euro_amount)
lbl_usd = tk.Label(window, text="Enter the USD ($) here:", bg="#900C3F", font="#FFFFFF")
ent_usd = tk.Entry(window)
btn_usd = tk.Button(window, text="Convert", command=usd_callback, bg="#FFFFFF", font="#FFFFFF")
lbl_euros = tk.Label(window)
lbl_usd.pack()
ent_usd.pack()
btn_usd.pack()
window.mainloop()
Any help would be gladly appreciated! Thank you!!
You need to convert the first element from the return value from xpath
:
euro_exchange = tree.xpath('//div[@class="price"]/text()')
euro_exchange = float(str(euro_exchange[0]))