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循环

相关文章
相关标签/搜索