如何使用 Python 找到自然數的和?
你可以使用 while 迴圈連續將變數 i 的值增加 1,然後累加。
s,i=0,0
n=10
while i<n:
i=i+1
s=s+i
print ("sum of first 10 natural numbers",s)for 迴圈也用於遍歷自然數範圍並累加。
s=0
for i in range(11):
s=s+i
print ("sum of first 10 natural numbers",s)最後,使用內建函式 sum() 也可以計算一系列數的和
s=sum(range(11))
print ("sum of first 10 natural numbers",s)廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP