TypeError:"noneType"对象在csv中的Python中不可迭代 [英] TypeError: 'NoneType' object is not iterable in Python in csv

查看:378
本文介绍了TypeError:"noneType"对象在csv中的Python中不可迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,正在尝试创建一个打开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. 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

推荐答案

我已经清理了search_user_inputquantity的流程.在某些情况下,您使用多个参数调用了search_user_input(它不接受它们),并且使它递归.我在下面的代码中添加了一些注释.实际上,该函数在您的设置中返回了None,这会导致TypeError: 'NoneType' object is not iterable错误.

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.

if __name__ == '__main__:'在您的代码中不是必需的,我已将其更多地包含在其中,以备日后在您要开始导入自己的模块时使用.有关此主题的更多信息,请参见.

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

这篇关于TypeError:"noneType"对象在csv中的Python中不可迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆