python学习第七天
循环结构—>for-in循环
如果在python中想要输出10个"hello,world"应该怎么做呢?最笨的办法是:
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
那么问题来了,如果想输出一百万遍该怎么办呢?
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
print('hello,world')
………………………………………………
正确答案是:
for i in range(100):
print('hello,world')
再看一个例子,求1+2+…+100
total = 0
for i in range(1,101):
total += i
print(total)
上面这个例子用到的也是for-in循环
total = 0
for i in range(1,101):
if i%2==0:
total += i
print(total)
total = 0
for i in range(1,101):
if i%2==0:
total += i
else:
pass
print(total)
上面这两个例子是100以内的偶数求和,但是第二种要比第一种更差一些(美观,效率)
total= sum(range(1,101))
用sum计算1+…+100的值也可以