TypeError: NoneType object is not iterable in Python in csv

2024/9/20 3:02:37

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 filedef 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_datadef get_user_input():""" get input from user """while True:try:GTIN = int(input("input your gtin-8 number: "))breakexcept:print ("Oops! That was not a valid number.  Try again")def search_user_input():""" search csv data for string """search_user_inputgtin = get_user_input()for row in PRODUCT_DATA:#print(row) #debug printif 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 loopdef quantity():gtin = 0product = 0price = 0.0product_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
Answer

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_datadef 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 valueexcept: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 = Truewhile 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 Noneproduct, 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 globalquantity()  # call the main function
https://en.xdnf.cn/q/119762.html

Related Q&A

No such Element Exception using selenium in python

from selenium import webdriver from selenium.webdriver.common.keys import Keys chrome_path=r"C:\Users\Priyanshu\Downloads\Compressed\chromedriver_win32\chromedriver.exe" driver=webdriver.Chro…

Web scraping, cant get the href of a tag

Im trying to scrape this Page https://rarity.tools/thecryptodads Using Selenium in python. At the top of the right of each card below, theres the owner name that contains a link once pressed, it takes …

Using Python Pandas to fill new table with NaN values

Ive imported data from a csv file which has columns NAME, ADDRESS, PHONE_NUMBER. Sometimes, at least 1 of the columns has a missing value for that row. e.g0 - Bill, Flat 2, 555123 1 - Katie, NaN, NaN 2…

sympy AttributeError: Pow object has no attribute sin

I have read this SO post which says namespace conflict is one reason for this error. I am falling to this error frequently. So, Id like to learn what exactly is happening here? What is expected by the…

Tkinter unbinding key event issue

In the code below, pressing the space bar twice results in two successive beeps. I want to avoid this and instead disable the key while the first beep is happening. I thought unbinding the space key mi…

Is there a way to find the largest change in a pandas dataframe column?

Im trying to find the largest difference between i and j in a series where i cannot be before j. Is there an efficient way to do this in pandas:x = [1, 2, 5, 4, 2, 4, 2, 1, 7] largest_change = 0for i i…

Updating scikit-learn to latest version with Anaconda environment fails with http error 000

I use Anaconda3 installed on my pc Win10 64bits. I noticed it runs with an outdated scikit learn version (0.21.3), and I am trying to update it (0.24.1 available on https://repo.anaconda.com/pkgs/main/…

Python RegEx remove new lines (that shouldnt be there)

I got some text extracted and wish to clean it up by RegEx.I have learned basic RegEx but not sure how to build this one:str = this is a line that has been cut. This is a line that should start on a …

Python CSV writer

I have a csv that looks like this:HA-MASTER,CategoryID 38231-S04-A00,14 39790-S10-A03,14 38231-S04-A00,15 39790-S10-A03,15 38231-S04-A00,16 39790-S10-A03,16 38231-S04-A00,17 39790-S10-A03,17 38231-S04-…

How to perform standardization on the data in GridSearchCV?

How to perform standardizing on the data in GridSearchCV?Here is the code. I have no idea on how to do it.import dataset import warnings warnings.filterwarnings("ignore")import pandas as pd …