发布时间:2017-11-11 10:28:34编辑:Run阅读(4528)
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
47605
45985
36909
34469
29080
25713
24566
19714
19245
17756
5565°
6155°
5691°
5737°
6705°
5483°
5484°
5988°
5965°
7295°