4 流程控制》4.5 比较for循环和while循环
2016-04-22 10:46
495 查看
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
下面的程序让用户输入一些数字,然后打印出这些数字的总和。
① 这是使用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
相关文章推荐
- 希尔排序
- Hashtable 中Entry[] Index计算
- 用openjtag调试s3c2440裸机程序
- C++第四次作业
- c++第四次实验-1
- javascript设计模式--抽象工厂模式
- 14. Longest Common Prefix
- 解决方案 错误:HttpServlet was not found on the Java build path
- 为RecyclerView的不同item项实现不同的布局(添加分类Header)
- Unity3D 图形优化
- Unity3D 性能优化
- iOS 中UIView contentMode 属性总结
- 美国人、英国人、中国人一生都是如何度过
- proxool 连接池警告分析:appears to have started a thread named [HouseKeeper] but has failed to stop it
- 浏览器UA
- c++第三次实验
- kindeditor富文本注释掉上传网络图片
- 归并算法(java 语言实现)
- 王高利:CentOS6.5__VNC Server配置
- Jquery datePicker 日期联动效果