2017-02-11 6 views
0

Я пытаюсь напечатать общее количество списка покупок, но каждый раз, когда я вызываю строку, она печатает 0 вместо того, что должно быть.str reset to 0, когда его не спрашивают?

cash_due = 0 
import pickle 
picklee = open('Store_stuff.pickle', 'rb') 
contents = pickle.load(picklee) 
picklee.close() 


shopping_list = ['Name  price  quantity  total'] 

store_contents ='''Store Contents 

Name  Price  GTIN-8 Code 
Butter  £1.20  70925647 
Chocolate £1.00  11826975 
Bread  £1.00  59217367 
Cheese  £2.80  98512508 
Bacon  £2.40  92647640 
Lamb  £4.80  49811230 
Ham   £2.59  53261496 
Potatoes £2.00  11356288 
Chicken  £3.40  89847268 
Eggs  £1.29  21271243''' 

def item(barcode, quantity, cash_due, shopping_list): 
    shopping_list.append(contents[barcode]['name']+'  £'+(str((int(contents[barcode]['price']))/100))+'   '+str(quantity)+'   £'+str((int(quantity)*int(contents[barcode]['price']))/100)) 
    print(cash_due) 
    print(contents[barcode]['price']) 
    print(quantity) 
    cash_due += ((int(contents[barcode]['price'])*(int(quantity)))/100) 
    print(cash_due) 

def shopkeeper_ui(): 
    print('Welcome to Stanmore\'s Food Emporium! Feel free to browse.') 
    print(store_contents) 
    user_input = '' 

    while user_input != 'finish': 
     user_input = input('''Welcome to the checkout. 
instructions - 
if you are entering text make sure your \'CAP\'s Lock\' is turned off 
if you are entering a barcode number, please enter it carefully 
if you want to print your current recipt, enter \'recipt\' 
if you want to see your current total, enter \'total\' 
and if you are finished, enter \'finish\' 

You can see the stores contents below 
Thanks for shopping: ''') 

     if len(user_input) == 8: 
      quantity = int(input('Enter the quantity that you want: ')) 
      item(user_input, quantity, cash_due, shopping_list) 
     elif user_input == 'recipt': 
      count8 = 0 
      for i in shopping_list: 
       print(shopping_list[count8]) 
       count8 += 1 
     elif user_input == 'finish': 
      print('Your shopping list is',shopping_list,' \nand your total was', total,'\n Thank you for shopping with Stanmore\'s Food Emporium') 
     elif user_input == 'total': 
      print('your total is, £',cash_due) 
     else: 
      print('User_input not valid. Try again...') 
shopkeeper_ui() 

Если я ввести код и моя первая запись 21271243 (штрих-код для яиц). тогда я ввожу 4 для количества. я могу получить shopping_listlist, чтобы понять итог, и если я напечатаю строку cash_due внутри функции элемента, она ее понимает, но как только я попытаюсь вызвать cash_due из функции shopkeeper_ui, она печатает 0 вместо того, что должно быть 5.12?

+1

cash_due не изменяет. Изменение функции элемента теряется при выходе из функции. –

+0

нормально, так что вы знаете способ сделать изменение недействительным – Lomore

ответ

2

cash_due is not mutable. Изменения в функции item теряются при выходе из функции.

Как правило, выход из этой функции позволяет вернуть функцию (item).

В этом случае я бы просто оставил cash_due из item и дал item только возврат стоимости этого товара. Что-то вроде этого:

def item(barcode, quantity, shopping_list): 
    shopping_list.append(contents[barcode]['name']+'  £'+(str((int(contents[barcode]['price']))/100))+'   '+str(quantity)+'   £'+str((int(quantity)*int(contents[barcode]['price']))/100)) 
    print(contents[barcode]['price']) 
    print(quantity) 
    cost = ((int(contents[barcode]['price'])*(int(quantity)))/100) 
    print(cost) 
    return cost 

[...] 

     if len(user_input) == 8: 
      quantity = int(input('Enter the quantity that you want: ')) 
      cash_due += item(user_input, quantity, shopping_list) 

Вам не один и тот же вопрос с shopping_list, потому что это изменчивая: она изменяется на месте. Прочитайте об изменяемых принципах, чтобы понять концепцию.

Однако, это может быть лучший дизайн, чтобы не допустить изменения элемента в списке. Он может просто вернуть элемент списка и стоимость, и вызывающий может изменить список.

def item(barcode, quantity): 
    stuff = (contents[barcode]['name']+'  £'+(str((int(contents[barcode]['price']))/100))+'   '+str(quantity)+'   £'+str((int(quantity)*int(contents[barcode]['price']))/100)) 
    cost = ((int(contents[barcode]['price'])*(int(quantity)))/100) 
    return stuff, cost 

[...] 

     if len(user_input) == 8: 
      quantity = int(input('Enter the quantity that you want: ')) 
      stuff, cost = item(user_input, quantity, shopping_list) 
      shopping_list.append(stuff) 
      cash_due += cost 

 Смежные вопросы

  • Нет связанных вопросов^_^