<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # Python 程序:查找自然數總和 > 原文: [https://www.programiz.com/python-programming/examples/sum-natural-number](https://www.programiz.com/python-programming/examples/sum-natural-number) #### 在此程序中,您將學習使用`while`循環查找 n 個自然數的總和并顯示它。 要理解此示例,您應該了解以下 [Python 編程](/python-programming "Python tutorial")主題: * [Python `if...else`語句](/python-programming/if-elif-else) * [Python `while`循環](/python-programming/while-loop) * * * 在下面的程序中,我們結合使用了`if...else`語句和`while`循環來計算最大為`num`的自然數之和。 ## 源代碼 ```py # Sum of natural numbers up to num num = 16 if num < 0: print("Enter a positive number") else: sum = 0 # use while loop to iterate until zero while(num > 0): sum += num num -= 1 print("The sum is", sum) ``` **輸出** ```py The sum is 136 ``` **注意**:要測試程序的其他編號,請更改`num`的值。 最初,`sum`初始化為 0。并且,數字存儲在變量`num`中。 然后,我們使用`while`循環進行迭代,直到`num`變為零。 在循環的每次迭代中,我們將`num`加到`sum`,并且`num`的值減少了 1。 * * * 通過使用以下公式,我們可以在不使用循環的情況下解決上述問題。 ```py n*(n+1)/2 ``` 例如,如果`n = 16`,則總和為`(16 * 17) / 2 = 136`。 **輪到您了**:修改上述程序,使用以下公式查找自然數的總和。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看