我正在创建一个程序,将项目与code
,price
和quantity
以及 pickle 模块一起保存。
当有人想购物时,他们会输入code
。我正在尝试检查文本文档以查看是否保存了code
,但它似乎不起作用并且给了我这个错误:
TypeError:“NoneType”类型的参数不可迭代。
有人可以帮忙吗?
stock = readfile()
print("Please enter the GTIN-8 code of the items you want to buy, when you are done type DONE")
while True:
code = input("Enter GTIN-8 code or DONE ")
if code == "DONE":
break
else:
amount = int(input("How many would you like? "))
if code in stock:
print("Yes")
else:
print("No")
答案 0 :(得分:0)
stock
函数将None
变量设置为readfile
。问题可能出在该函数中(可能它实际上并没有打开文件?)。
答案 1 :(得分:0)
尝试使用readlines():
def readlines():
return [line.strip() for line in open('fruit.txt','r').readlines()]
答案 2 :(得分:0)
仅仅为了变化,这里是使用sqlite3
的替代版本。
(注意:钱被视为整数美分。)
import sqlite3
DATABASE = 'stock.db'
def get_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
pass
def money_str(price, min_width=6):
return "$ {1:{0:d}d}.{2:02d}".format(min_width - 5, price // 100, price % 100)
def make_stock_table(conn):
conn.execute("DROP TABLE IF EXISTS Stock;")
conn.execute(
"""
CREATE TABLE Stock (
code INTEGER PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
price INTEGER NOT NULL,
quantity INTEGER NOT NULL DEFAULT (0)
);
"""
)
conn.commit()
def add_stock_code(conn, code, name, price):
conn.execute(
"""
INSERT OR REPLACE INTO Stock (
code, name, price
) VALUES (
?, ?, ?
);
""",
(code, name, price)
)
conn.commit()
def add_stock_quantity(conn, code, quantity):
conn.execute(
"""
UPDATE Stock
SET quantity = quantity + ?
WHERE code = ?
""",
(quantity, code)
)
conn.commit()
def buy_stock(conn, code, quantity):
result = conn.execute("SELECT quantity, price FROM Stock WHERE code = ?", (code,)).fetchone()
if not result:
raise ValueError('No entry for code {}'.format(code))
on_hand, price = result
if on_hand < quantity:
raise ValueError('Cannot buy {}, only {} on hand'.format(quantity, on_hand))
conn.execute(
"""
UPDATE Stock
SET quantity = quantity - ?
WHERE code = ?
""",
(quantity, code)
)
conn.commit()
return quantity * price
def main():
conn = sqlite3.connect(DATABASE)
# create some test data
make_stock_table(conn)
add_stock_code(conn, 2429, "Golden Delicious Apples", 249)
add_stock_quantity(conn, 2429, 20)
add_stock_code(conn, 2514, "Macintosh Apples", 179)
add_stock_quantity(conn, 2514, 35)
# sell
while True:
code = get_int("Enter product GTIN-8 code (or 0 to quit): ")
if code == 0:
break
quantity = get_int("How many would you like? ")
try:
cost = buy_stock(conn, code, quantity)
print("Cost is {}".format(money_str(cost)))
except ValueError as ve:
print(ve)
if __name__ == "__main__":
main()