Domanda

When I use the float() method in a program , I am getting an error. Can you please help me with that. I am using python 3.4.0a4.

This is the program:

import urllib.request

price = 99.99
while price > 4.74:
   page = urllib.request.urlopen("http://www.beans-r-us.biz/prices.html")
   text = page.read().decode("utf8")
   where = text.find('>$')
   start_of_price = where + 2
   end_of_price = start_of_price + 4
   price = float(text[start_of_price:end_of_price])
Print("Buy!")

and this is the error I get:

Traceback (most recent call last):
  File "F:/Python/python 8.py", line 11, in <module>
    price = float(text[start_of_price:end_of_price])
ValueError: could not convert string to float: '!DOC'
È stato utile?

Soluzione

It seems like you sliced the string of the web page at the wrong position, and the result of text[start_of_price:end_of_price] is !DOC.

This is not a valid number and can hence not be converted to a float.

Altri suggerimenti

This is the exact code given in Head first Programming. The link was broken and I got the output on correcting it. Thanks for your help..

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top