ばかげた質問をして申し訳ありません。
私はビデオや本で Python を学んでいますが、他に何の助けもありません。
基本的な python プログラミングの単純な違いを理解できません。
########################################AAAAAA costs = [5,10,15,20]
def sum_cart(item):
total_cost = 0
for this in costs:
this = this + total_cost
return total_cost
print sum_cart(costs)
########################################BBBBBBBBBBBB
def sum_cart(item):
total_cost = 0
for this in costs:
total_cost = this + total_cost
return total_cost
print sum_cart(costs)
##################################################CCCCCC
def sum_cart(item):
total_cost = 0
for this in costs:
total_cost = this + total_cost
return total_cost
print sum_cart(costs)
- - - - - -質問 - - - - - -
結果は、A --> 0、B --> 50、C --> 5 です。
なぜ結果がそのまま表示されるのか、まだ混乱しています。
私の理解が正しければ、A では、「this」はリストから 5 を取得し、5 が total_cost に追加されます。これは 0 です。「this」はそれぞれ 10、15、および 20 を呼び出し、「this」は新しい値を取得します。しかし、total_cost は 0 のままなので、結果は 0 です。
次に B で、'this' = 5 が呼び出され、現在の 'total_cost' = 0 (5) に追加されると、total_cost が更新されます。ループは戻り、それぞれ 10、15、20 と 'total_cost' を取り込みます。は 50 に更新されています。これまでのところ、良いと思います。
しかし、Cでは、「this」がリストから5の値をもたらすと「total_cost」が更新されるため、何が起こっているのかわかりません。次に、'total_cost' を 5 に戻す必要があります。for ループは戻って、total_cost = this (おそらく 10) + total_cost (現在は 5) を実行し、ループを再度実行するべきではありませんか? 「リターン」機能について何が欠けていますか?