-1

I am new to python, and trying to create a program which opens a csv file. The user is supposed to enter a barcode , then the program finds that product and the cost of the product. However I got an error which is the title of my thread. Here is my code.

import csv  # imports should go at the top of the file


def read_csv_file():
     """ reads csv data and appends each row to list """
     csv_data = []
     with open("task2.csv") as csvfile:
         spamreader = csv.reader(csvfile, delimiter=",", quotechar="|")
         for row in spamreader:
             csv_data.append(row)
     return csv_data


def get_user_input():
     """ get input from user """
     while True:
        try:
            GTIN = int(input("input your gtin-8 number: "))
            break
        except:
            print ("Oops! That was not a valid number.  Try again")


def search_user_input():
     """ search csv data for string """
     search_user_input
     gtin = get_user_input()
     for row in PRODUCT_DATA:
         #print(row) #debug print
         if row[0] == str(gtin):
             product = row[1]
             price = round(float(row[2]),2)
             print(product, price)
             return(product, price)
     repeat = input("not in there? search again? If so (y), else press enter to continue")
     if repeat == 'y':
         search_user_input()  # calls function again in order to create a loop


def quantity():
    gtin = 0
    product = 0
    price = 0.0
    product_data = read_csv_file()
    product,price = search_user_input() 
    product, price = search_user_input(str(gtin), product_price)
    order = int(input("How much of " + product + " do you want?"))
    price = round(price * order, 2)
    print(quantity,price)

def order_making():
     print("Apples")     

PRODUCT_DATA = read_csv_file()  # call function to read csv 
quantity()  # call the main function
manvi77
  • 536
  • 1
  • 5
  • 15
aadoma123
  • 7
  • 3
  • at which line the error is coming and also the stacktraceback would be helpful – amit_183 Mar 15 '17 at 09:32
  • Please edit the question to include a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). This includes the stacktrace so we can actually see which line throws the error rather than searching through all of your code. – roganjosh Mar 15 '17 at 09:33
  • 1
    `get_user_input` needs to return `GTIN`. – Alex Hall Mar 15 '17 at 09:34
  • It is line 45 , sorry – aadoma123 Mar 15 '17 at 09:34
  • There several issues with this code. `search_user_input` does not accept arguments but you're calling it with two in `product, price = search_user_input(str(gtin), product_price)`. Also, I see no reason for `search_user_input` to call itself recursively. The flow of inputs seems a bit confused with functions being called multiple times. I think you should consider refactoring this tbh. – roganjosh Mar 15 '17 at 09:37
  • So how would it be best to improve this? Is it best for me to look at how to use functions correctly – aadoma123 Mar 15 '17 at 09:39
  • `read_csv` and `get_user_input` (if it includes `return GTIN`) are fine, I get a bit confused after that point in how you're putting them together. – roganjosh Mar 15 '17 at 09:40
  • I dont know what I am doing to be honest , i got it a bit muddled up ( if thats the correct word, my english isnt very good) – aadoma123 Mar 15 '17 at 09:41
  • It is the correct word :) I'll have a proper look through shortly if someone hasn't answered. It seems it's almost there. – roganjosh Mar 15 '17 at 09:42
  • I will also post the csv file , one second – aadoma123 Mar 15 '17 at 09:43
  • 12345670 bread 1.5 12345663 eggs 1 12345557 potato 2 11111115 tomato 1.3 69696961 celery 1.4 – aadoma123 Mar 15 '17 at 09:43

1 Answers1

0

I have cleaned the flow up a bit for search_user_input and quantity. In some cases you were calling search_user_input with multiple arguments (it doesn't accept them) and you made it recursive. I have added some comments in the code below. In fact, that function was returning None in your setup, which leads to the TypeError: 'NoneType' object is not iterable error.

The if __name__ == '__main__:' is not necessary in your code, I've included it more as a heads-up for later on when you'll want to start importing your own modules. See this for more info on this topic.

import csv 


def read_csv_file():
     """ reads csv data and appends each row to list """
     csv_data = []
     with open("task2.csv") as csvfile:
         spamreader = csv.reader(csvfile, delimiter=",", quotechar="|")
         for row in spamreader:
             csv_data.append(row)
     return csv_data


def get_user_input():
     """ get input from user """
     while True:
        try:
            GTIN = int(input("input your gtin-8 number: "))
            return GTIN # Breaks the loop and returns the value
        except:
            print ("Oops! That was not a valid number.  Try again")


def search_user_input(product_data): # Pass the csv data as an argument
    """ search csv data for string """
    keep_searching = True

    while keep_searching:
        gtin = get_user_input()
        for row in product_data:
            if row[0] == str(gtin):
                product = row[1]
                price = round(float(row[2]),2)
                return(product, price)
        repeat = input("not in there? search again? If so (y), else press enter to continue")
        if repeat != 'y':
            keep_searching = False 
            return None # This is done implicitly, I'm just making it obvious 


def quantity():

    product_data = read_csv_file()
    matches = search_user_input(product_data)
    if matches: # Will not be True if search_user_input returned None
        product, price = matches[0], matches[1]
        order = int(input("How much of {} do you want?".format(product)))
        price = round(price * order, 2)
        print("That costs {}".format(price))


if __name__ == '__main__': # You'll need this in future for importing modules
    # There was no need to read the csv_data here and make it global
    quantity()  # call the main function
Community
  • 1
  • 1
roganjosh
  • 12,594
  • 4
  • 29
  • 46
  • hello , thank you very much for the help , i have spent some time trying to improve my code and so the user can order multiple products – aadoma123 Mar 15 '17 at 19:37