簡體   English   中英

Python:如何將while循環的值之和存儲到變量中?

[英]Python:How to make the sum of the values of a while loop store into a variable?

我只是一個初學者:P。 我正在編寫有關Codeacademy“單擊此處 !”的while循環的教程。 ,但我在這部分上theSum :編寫一個while循環,將前10個正整數(包括10個)的和存儲到“ theSum ”中。這是您可以使用的:

theSum = 0
num = 1
while num <= 10:
    print num
    num = num + 1

它在控制台的單獨行上輸出數字1到10。 誰能向我解釋如何將其值存儲在變量“ mySum ”中? 到目前為止,我嘗試過的所有方法都無法滿足我的要求。 :(

編輯:好的,所以我嘗試了這個:

theSum = 0
num = 1
while num <= 10:
    num += 1
    mySum = num
    mySum = mySum + num

print mySum

這給了我22,為什么呢? 反正我在附近嗎? (感謝所有答復,但明天我會再試一次。)

編輯:好的,我明白了! 感謝您的幫助。 :)

mySum = 0 
num = 1 
while num <= 10: 
    mySum += num 
    num += 1    
print mySum

您已經編寫的代碼幾乎顯示了所需的所有內容。

剩下的問題是,當您正確生成while循環內要添加的值( numwhile ,您並沒有在變量theSum累積這些值。

我不會故意為您提供缺少的代碼 ,以便您可以從問題中學習到一些東西……但是您需要在循環num的值添加到變量theSum 用於執行此操作的代碼(實際上僅是一條語句,即一行代碼)將有點類似於您在循環中處理/更新num的值的方式。

這有幫助嗎?

讓我們來看看您發布的代碼。 我已經對行進行了編號,以便可以參考它們。

1. num = 1
2. while num <= 10:
3.     num += 1
4.     mySum = num
5.     mySum = mySum + num

6. print mySum

這是一場空戰

1. simple enough, create a new variable `num` and bind it to the number `1`
2. `num` is less than 10, so do the body of the loop
3. `num` is `1` so now bind it to `2`
4. create a new variable `mySum` and bind to `2` (same as num)
5. `mySum` is `2` and `num` is `2` so bind `mySum` to `4`
Back to the top of the loop
2. `num` is less than 10, so do the body of the loop
3. `num` is `2` so now bind it to `3`
4. bind `mySum` to `3` (same as num)
5. `mySum` is `3` and `num` is `3` so bind `mySum` to `6`
Back to the top of the loop
2. `num` is less than 10, so do the body of the loop
3. `num` is `3` so now bind it to `4`
4. bind `mySum` to `4` (same as num)
5. `mySum` is `4` and `num` is `4` so bind `mySum` to `8`
Back to the top of the loop
...

看起來有些不對勁。 為什么要在循環中執行此mySum = num 你期望它做什么?

對於循環! 嗯,我說!

n=10
sum(range(n+1))

我對此也感到極大的掙扎。

這是我的解決方案,但我從Interactivepython.org( http://interactivepython.org/runestone/static/pip2/IndefiniteIteration/ThewhileStatement.html )獲得了幫助。

沒有“返回”功能,我無法弄清楚該如何做。 請參閱下面的解決方案和說明:

def problem1_3(x):
    my_sum=0
    count = 1
    while count<=x:
        my_sum=my_sum+count
        count = count+1
    return my_sum
    print(my_sum)

假設您設置x = 3我相信 python解釋的方式如下:set my_sum = 0且count = 11。第一次循環使用while循環:1 <= 3:true,因此my_sum = 0 + 1加上count增加乘以1,現在計數= 2'Return my_sum'是關鍵,因為它允許my_sum從1而不是0循環回到循環的頂部。

  1. while循環的第二次迭代:2 <= 3:是,所以my_sum = 1 + 2; count再次增加1,所以現在count = 3返回my_sum再次將my_sum的新值3返回到循環頂部

  2. while循環的第三次迭代:3 <= 3:是,所以my_sum = 3 + 3; 計數增加1,所以現在計數= 4再次返回my_sum,將my_sum的新值6返回到循環頂部

  3. while循環的第四次迭代從4 <= 3開始就不會發生:False現在程序打印my_sum,它等於6。

但是,我認為會有一種更簡單的方法來做到這一點。 python有沒有一種方法可以生成列表,然后對列表中的值求和? 例如,我可以編寫一個名為sumlist(n)的程序,其中python列出從0到n的整數,然后將它們加起來嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM