【发布时间】:2015-01-22 11:44:15
【问题描述】:
我将如何使用 while 循环添加从 1 到 100 的数字,然后使用 for 循环再次执行程序
【问题讨论】:
-
@imapython 这是另一个类似的问题:stackoverflow.com/questions/494594/…它会回答你的问题。
标签: python loops for-loop while-loop
我将如何使用 while 循环添加从 1 到 100 的数字,然后使用 for 循环再次执行程序
【问题讨论】:
标签: python loops for-loop while-loop
同时使用
count=0
b=0
while count <100:
count+=1
b+=count
对于:
b=0
for i in range(1,101):
b+=i
print (b)
【讨论】:
lst = range(1,101)
这是使用 while 循环执行此操作的众多方法之一的示例。
iteration = 0
sum = 0
while iterations<len(range(1,101)): #You may need to add or subtract one from the left side of the inequality
sum+=range(1,101)[iteration]
iteration+=1
for 循环非常相似。
sum = 0
for num in range(1,101):
sum+=num
【讨论】:
my_list = [0]
count = 0
while count < 100:
count = count + 1
my_list.append(count)
print (sum(my_list))
count = 0
total = 0
for count in range(0,101):
total = total + count
print (total)
【讨论】:
这将起作用:
sum(xrange(101))
【讨论】:
使用reduce:
>>> from itertools import *
>>> reduce(lambda x,y:x+y,range(1,101))
5050
使用sum:
>>> sum(range(1,101))
5050
【讨论】: