Jordan Jordan - 6 months ago 28
Python Question

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

I am writing a program that gathers a GTIN number from the user so that they can purchase an item. However, when trying to multiply the price by the quantity, I get the error:

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


With x being the price in the CSV.

My Code is as follows:

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()

Answer

"0.5" is not a value that can be turned into an integer, because integers can only represent whole numbers, not fractions.

>>> 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'

Consider using float instead, or possibly Decimal if you require exact precision. (always a good thing when it comes to money.)

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