Я пытаюсь создать программу (как часть контролируемой оценки), которая позволяет пользователю вводить коды продуктов 3 GTIN из excel (.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