发布时间:2017-11-11 10:28:34编辑:Run阅读(4579)
for循环表达形式如下:
for i in sequence:
执行语句
比如从1加到100,用for怎么实现?
写一个test_for.py来实验一下,代码如下
# coding: utf-8 __author__ = 'www.py3study.com' def cumulative(num): sum = 0 for i in range(1,num + 1): sum += i return sum #累加函数,返回累加函数后的值 def main(): while True: print(u"=================================") print(u"输入exit退出程序:") str_num = input("从1累加到:") if str_num == 'exit': break try: sum = cumulative(int(str_num)) except ValueError: print(u"除非退出输入exit,只能输入数字!") continue print(u"从1累加到{}的总和是{}".format(int(str_num), sum)) if __name__ == '__main__': main()
应该看到的结果
for循环用于数字循环时的生成方法可以用range(1,100)
上一篇: Python语句-if.....else......
下一篇: python语句-while
47745
46237
37110
34627
29229
25886
24745
19863
19417
17909
5716°
6315°
5836°
5888°
6985°
5829°
5846°
6361°
6316°
7673°