4 流程控制》4.5 比較for循環和while循環

4.5.2 計算用戶輸入的數字的總和ide

下面的程序讓用戶輸入一些數字,而後打印出這些數字的總和。blog

① 這是使用for循環的版本:get

# forsum.py
n = int(input('How many numbers to sum?'))
total = 0
for i in range(n):
        s = input('Enter number ' + str(i + 1) + ':')
        total = total + int(s)
print('The sum is ' + str(total))input

wKiom1cZkIPxLTAXAABCyg1ewTU892.png

② 這是使用while循環的版本it

# whilesum.py
n = int(input('How many numbers to sum?'))
total = 0
i = 1
while i <= n:
        s = input('Enter number ' + str(i) + ':')
        total = total + int(s)
        i = i + 1
print('The sum is ' + str(total))io

wKioL1cZkyKwIwgyAAAod64hQ7A153.png

一樣,while循環版本比for循環版本更復雜些。for循環

相關文章
相關標籤/搜索