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
② 這是使用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
一樣,while循環版本比for循環版本更復雜些。for循環