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)