【问题标题】:Traceback error in pythonpython中的回溯错误
【发布时间】:2013-10-29 13:29:53
【问题描述】:

当我在程序中使用float() 方法时,我收到一个错误。你能帮我解决这个问题吗?我正在使用 python 3.4.0a4。

这是程序:

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!")

这是我得到的错误:

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'

【问题讨论】:

  • 你找错了&gt;$。如果您正在解析 HTML,请考虑改用 HTML 解析器,例如 BeautifulSoup。
  • 除非你预先定义了Print,否则你会在最后一行得到一个NameError,因为它应该是print。记住 Python 区分大小写。
  • 您的切片字符串,text[start_of_price:end_of_price] 不是数字。
  • 另外一个问题,用浮点数的钱进行计算是不明智的,它们不能全部被计算完全准确地存储,因此可能会出现舍入错误。相反,您应该使用整数或 Decimal 模块来保存便士的数量。

标签: python runtime-error traceback


【解决方案1】:

好像你把网页的字符串切错了位置,text[start_of_price:end_of_price]的结果是!DOC

这不是一个有效的数字,因此不能转换为浮点数。

【讨论】:

    【解决方案2】:

    这是 Head first Programming 中给出的确切代码。链接已损坏,我得到了更正它的输出。谢谢你的帮助。。

    【讨论】:

      猜你喜欢
      • 2017-08-31
      • 2021-07-14
      • 2022-01-01
      • 1970-01-01
      • 2011-01-14
      • 2020-12-12
      • 1970-01-01
      • 2016-09-20
      • 1970-01-01
      相关资源
      最近更新 更多