Python语言计算1+2+3+4,用while循环for循环分别实现
Python语言计算1+2+3+4,用while循环for循环分别实现
while循环
count = 0;
t=1;
while t < 5 :
count = count + t;
t=t+1;
print 'count:', count
for循环
count = 0;
range=[1,2,3,4];
for i in range:
count=count + i;
print 'count:', count
# 用while循环求出来的
numberList = [1,2,3,4] # 求和的数字
i=0 #用于标记求和和到那个地方
sum = 0 # 和
while i<len(numberList):
sum+=numberList[i]
i+=1
else: # while 循环完毕,输出
print("用while求出来: ",sum)
# 用for 循环求出来的
numberList = [1,2,3,4]
sum = 0
for i in numberList:
sum+=i
else:
print("用for求出来: ",sum)
# 为什么我用i+=1而不是i=i+1? 因为+=的运算一般比较快