亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

學習 Python 2 Codeacademy,“超市的一天”

學習 Python 2 Codeacademy,“超市的一天”

慕村225694 2022-07-12 09:31:25
我正在編寫一個基本的 python 2 教程,以下代碼作為正確答案提供:total=0prices = {  "banana" : 4,  "apple"  : 2,  "orange" : 1.5,  "pear"   : 3,}stock = {  "banana" : 6,  "apple"  : 0,  "orange" : 32,  "pear"   : 15,}for fruit in prices:    print fruit    print "price: %s" % prices[fruit]    print "stock: %s" % stock[fruit]    total =  total + prices[fruit] * stock[fruit]  # pretend this line is bolded    print total     #prints sum of total (0) and prices multiplied by stock (117). Equals 117. 我想知道的是為什么下面的代碼替換倒數第二行(在上面的塊中加粗)返回零而不是返回 117。total2 = prices[fruit] * stock[fruit]print total2 + total #should be total2(117) plus total(0). Equals 117誰能告訴我為什么python邏輯將變量“total”與“total2”區別對待。我懷疑這與以下事實有關:總價格乘以庫存之一等于零,而零乘以任何東西都為零。在我看來,我應該能夠創建一個全新的變量(total2),其中包含價格 X 股票的結果,然后將其添加到總數中。對于代碼中缺少縮進,我深表歉意,似乎無法讓代碼完全按照格式發布。
查看完整描述

1 回答

?
浮云間

TA貢獻1829條經驗 獲得超4個贊

第一個片段和第二個片段之間的區別在于,在第二個片段中,您永遠不會將任何內容分配給total,而只會分配給total2。

total2 = prices[fruit] * stock[fruit]
print total2 + total

請注意,當您設置total2為特定值時,您并沒有告訴 python 設置total為任何其他值。打印 和 的總和total不會total2改變其中任何一個的值。

因此,您只需要正確添加total2total,并將結果實際放入total而不是打印它:

total = total + total2


查看完整回答
反對 回復 2022-07-12
  • 1 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號