我試圖創建一個程序(作爲受控評估的一部分),它允許用戶從Excel中輸入3個GTIN產品代碼(.csv)文件。然後顯示每個產品的信息,然後在給出該產品的小計之前詢問您想購買多少產品。一旦輸入了所有三個代碼,您可以選擇顯示所有產品的收據。總的來說工作正常,但是當我嘗試打印產品的實際名稱時,它只是在Excel文件的最後一行打印產品名稱,三次分開三行。Python只顯示.csv文件的最後一行
(我知道這個代碼可能可笑笨拙,但我基本上一樣多,你會發現一個新手。)
import sys
while 1==1:
def gtin1():
global total
global product1
product_ordered=input("Input GTIN ")
f=open("Task 2 Product Spreadsheet.csv","r")
for line in f:
items =line.split(",")
ordernum=items[0]
product1=items[1]
price=float(items[2])
in_stock=int(items[3])
if ordernum==product_ordered:
print("Items Ordered: ")
print("Item name: ", product1)
print("Number in stock: " , in_stock)
print("Price: £",price)
number = int(input("Input the number of items to be ordered: "))
total = int(price) * int(number)
if number <= in_stock:
print("The total price is £" + str(total))
print ("")
else:
print ("There is insufficient stock.")
print ("")
def gtin2():
global total2
global item_name2
product_ordered=input("Input GTIN ")
f=open("Task 2 Product Spreadsheet.csv","r")
for line in f:
items =line.split(",")
ordernum=items[0]
item_name2=items[1]
price=float(items[2])
in_stock=int(items[3])
if ordernum==product_ordered:
print("Items Ordered: ")
print("Item name: ", item_name2)
print("Number in stock: " , in_stock)
print("Price: £",price)
number = int(input("Input the number of items to be ordered: "))
total2 = int(price) * int(number)
if number <= in_stock:
print("The total price is £" + str(total2))
print ("")
else:
print ("There is insufficient stock.")
print ("")
def gtin3():
global total3
global item_name3
product_ordered=input("Input GTIN ")
f=open("Task 2 Product Spreadsheet.csv","r")
for line in f:
items =line.split(",")
ordernum=items[0]
item_name3=items[1]
price=float(items[2])
in_stock=int(items[3])
if ordernum==product_ordered:
print("Items Ordered: ")
print("Item name: ", item_name3)
print("Number in stock: " , in_stock)
print("Price: £",price)
number = int(input("Input the number of items to be ordered: "))
total3 = int(price) * int(number)
if number <= in_stock:
print("The total price is £" + str(total3))
print ("")
else:
print ("There is insufficient stock.")
print ("")
break
def receipt():
receipt = int(total) + int(total2) + int(total3)
print ("")
print ("")
print (product1)
print (item_name2)
print (item_name3)
print ("The total price of your order is: £" + str(receipt))
print ("")
print ("")
menu = input("You may enter 3 GTIN codes. Press '1' for your first code, '2' for your \
second, and '3' for your third, 'r' to see your receipt, or 'c' to exit the program.")
if menu == "1":
gtin1()
elif menu == "2":
gtin2()
elif menu == "3":
gtin3()
elif menu == "r":
receipt()
elif menu == "c":
print ("Thank you for using the program.")
sys.exit()
else:
print("Enter a valid command.")
感謝** break **功能,它現在打印出用戶輸入的產品名稱......您可能已經保存了我的課程作業! –
很高興幫助,下一步你應該刪除這3個功能,只使用一個!在gtin()函數的末尾使用返回值,以返回名稱變量。那麼你應該可以使用name1 = gtin()或name2 = gtin()...直接在你的菜單中! :) – Retsim