码迷,mamicode.com
首页 > 其他好文 > 详细

4 流程控制》4.5 比较for循环和while循环

时间:2016-04-22 16:54:11      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:python

4.5.2 计算用户输入的数字的总和

下面的程序让用户输入一些数字,然后打印出这些数字的总和。

① 这是使用for循环的版本:

# 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))

技术分享

② 这是使用while循环的版本

# 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))

技术分享

同样,while循环版本比for循环版本更复杂些。

本文出自 “技术进阶” 博客,请务必保留此出处http://vipnoon.blog.51cto.com/7589908/1766609

4 流程控制》4.5 比较for循环和while循环

标签:python

原文地址:http://vipnoon.blog.51cto.com/7589908/1766609

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!