Jordan Jordan - 5 months ago 33
Python Question

Getting an error when entering valid data

The program I am writing takes a GTIN-8 code from the user, searches for it in a CSV file and asks for the quantity etc. When I write a valid GTIN code, it still acts as if I have entered a wrong GTIN and asks me to re-enter the code. It basically does the opposite of what I want it to do.

My CSV file is as follows:

GTIN Name Price
12312313 Kit-Kat 0.5
12345670 Mars 0.2
76543210 Bounty 0.3
34563670 Milky Way 0.4


And my code is as follows:

def quantityQuestion():
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 = float(row[2]) * int(quantity)
receipt.write("- Price: " + str("%.2f" % round(price, 2)) + "\n")
restart()
break
elif str(gtinNum) not in row:
print("The code entered could not be found - Please re-enter")
gtinQuestion()

def gtinQuestion():
global gtinNum
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:
quantityQuestion()

gtinQuestion()

Answer

It's erroring because you're checking the entered code on each line of the csv and showing the prompt if any of the lines don't match the entered code.

for row in csv.reader(file2):
    if str(gtinNum) in row:
        ...
        break
    elif str(gtinNum) not in row:
        print("The code entered could not be found - Please re-enter")
        gtinQuestion()

Instead you only want to show the prompt if all the lines don't match the entered code.

for row in csv.reader(file2):
    if str(gtinNum) in row:
        ...
        break
else:
    print("The code entered could not be found - Please re-enter")
    gtinQuestion()

Here, if the if inside the loop never matches, control will flow off the end of the for loop and execute the else statement. If the if condition does match, it will break from the loop and the else clause won't be executed.

That being said, the way you're recursively calling the same function if conditions don't match is probably not a good design.

Here is another design that doesn't use recursive function calls, and doesn't require global variables.

def gtinQuestion():
    gtinNum = input("Please enter the GTIN-8 Code of the product you would like to order:")
    while not (gtinNum.isdigit() == True and len(gtinNum) == 8):
        gtinNum = input("Please enter the GTIN-8 Code of the product you would like to order:")
    return gtinNum

def main():
    gtinNumber = gtinQuestion()
    function_that_needs_gtinNumber(gtinNumber)