2016-10-25 7 views
0

私は説明することすらできません。ここに私のコード変数の重複は変数を変更しません

foods = {12345670 : 'orange(s)', 
    87654325 : 'pineapple(s)'} 
loop = 10 
while loop == 10: 
    full_list = input("Type: ") 
    if full_list == 'end': 
     break 
    amount = int(input("Amount: ")) 
    subtotal = 0 
    item = int(full_list) 
    if item in foods: 
     print("That would be {} {}".format(amount, foods[item])) 
     if full_list == '12345670': 
      price = (0.50 * amount) 
      print("Added Orange(s)") 
      print("Added "+str(price)) 
      subtotal = subtotal + price 
     if full_list == '87654325': 
      price = (1.00 * amount) 
      subtotal = subtotal + price 
      print("Added Pineapple(s)") 
      print("Added "+str(price)) 
print("Your subtotal is " +str(subtotal)) 

私は、ユーザーの購入は、私が購入可能アイテムの私のリストが終わっていないものに応じて変更することが私の小計を取得しようとしているので、私は名前を変更したくないです毎回変数のここでの問題は何ですか?変数subtotalが変更されないのはなぜですか?

+0

小計は変更されますが、各ループの先頭で0に初期化されます。ループが始まる前に0に設定するだけです。 –

+0

ああ、ありがとうございました:D – FlagShipKILLER

答えて

1
foods = {12345670 : 'orange(s)', 
    87654325 : 'pineapple(s)'} 
loop = 10 
subtotal = 0    # <------ moved it outside of the while loop 
while loop == 10: 
    full_list = input("Type: ") 
    if full_list == 'end': 
     break 
    amount = int(input("Amount: ")) 
    item = int(full_list) 
    if item in foods: 
     print("That would be {} {}".format(amount, foods[item])) 
     if full_list == '12345670': 
      price = (0.50 * amount) 
      print("Added Orange(s)") 
      print("Added "+str(price)) 
      subtotal = subtotal + price 
     if full_list == '87654325': #should be an elif not an if 
      price = (1.00 * amount) 
      subtotal = subtotal + price 
      print("Added Pineapple(s)") 
      print("Added "+str(price)) 
print("Your subtotal is " +str(subtotal)) 

あなたが0に総コストを再開し、それだけで最新の価格を保ってループするたびに。私がコメントしたwhileループの外にそれを移動し、あなたはうまくいくはずです。同様のif文を連鎖したい場合は、elifも使用してください。

0

if full_list == '12345670' 

を持っているしかし、あなたの入力タイプが整数でない文字列であるので、それは文の場合は、これを入力することはありません。代わりに、単一引用符なしでこれを行う:

if full_list == 12345670 
+0

Python 3.x(これは私が仮定していると思いますが)の入力は、printステートメントと 'full_list = input(あなたが 'eval( 'end')'を試みるように 'end'を打つとエラーを投げるでしょう。 – MooingRawr

+0

しかし、それは下にあることをしません。-_- – FlagShipKILLER

+0

@MooingRawrの解決策を見てください。 –

関連する問題