Skip to content Skip to sidebar Skip to footer

TypeError: 'NoneType' Object Is Not Iterable In Python In Csv

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

Solution 1:

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

Post a Comment for "TypeError: 'NoneType' Object Is Not Iterable In Python In Csv"