ValueError:基数为10的int()的无效文字:'0.5'

时间:2016-06-02 15:45:19

标签: python csv integer

我正在编写一个程序,从用户那里收集GTIN号码,以便他们可以购买物品。但是,当试图将价格乘以数量时,我得到错误:

ValueError: invalid literal for int() with base 10: 'x'

x是CSV中的价格。

我的代码如下:

import csv
import sys
import re
import os

addItem = ""
gtinNum = ""
quantity = 0
totalPrice = 0
restart = ""

f = open("ChocolateCSV.csv", "rt")

def restart():
    restart = input("Would you like to restart? Y/N")
    global receiptCont
    receiptCont = receipt.read()

    if restart.lower() == "y":
        gtinQuestion()
    else:
        receipt.close()
        print(receiptCont)
        sys.exit()

def quantityQuestion():
    quantity = input("How much would you like?")
    global price
    price = ""

    with open("ChocolateCSV.csv", 'r') as file2:
        for row in csv.reader(file2):
            if str(gtinNum) in row:
                receipt.write(str(row) + "\n")
                receipt.write(str("- Quantity: " + quantity + "\n"))
                price = int(row[2]) * quantity
                receipt.write("- Price: " + str(price))
                restart()

def scanGTIN():
    global rows
    rows = re.split('\n', f.read())

    for index, row in enumerate(rows):
        global cells
        cells = row.split(',')
        if gtinNum in cells:
            quantityQuestion()

def gtinQuestion():
    global gtinNum
    global receipt
    receipt = open("receipt.txt", "r+")
    gtinNum = input("Please enter the GTIN-8 Code of the product you would like to order:")

    if gtinNum.isdigit() == False or len(gtinNum) != 8:
        gtinQuestion()
    elif gtinNum.isdigit() == True and len(gtinNum) == 8:
        scanGTIN()


gtinQuestion()

2 个答案:

答案 0 :(得分:1)

您在代码中使用int()的唯一时间是第36行,

price = int(row[2]) * quantity

该行来自您未提供的文件ChocolateCSV.csv,因此我们无法具体说明您的错误原因。但显然字符串'x'中有row[2]个字符。确切地检查字符串是什么以及为什么有一个' x'在里面。正如@Tony指出的那样,你可能会将索引关闭一个。

通过将此行放在price =行:

,您可以看到该字符串是什么
print(repr(row[2]))

并在收到错误之前查看打印的字符串。换句话说,使用基本的调试策略。 (我使用了repr(),因此您可以轻松区分字符串和整数或其他类型之间的区别。)

答案 1 :(得分:0)

“0.5”不是可以转换为整数的值,因为整数只能表示整数而不是分数。

>>> s = "0.5"
>>> int(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '0.5'

如果您需要精确的精确度,请考虑使用float,或者可能使用Decimal。 (谈到金钱总是一件好事。)

>>> float(s)
0.5
>>> from decimal import Decimal
>>> Decimal(s)
Decimal('0.5')