【问题标题】:Python: Need to get used to loops just kinda confused?Python:需要习惯循环只是有点困惑?
【发布时间】:2015-01-22 11:44:15
【问题描述】:

我将如何使用 while 循环添加从 1 到 100 的数字,然后使用 for 循环再次执行程序

【问题讨论】:

  • “有点困惑”有点不具体——哪一部分令人困惑?您是否阅读过有关 whilefor 循环的基本教程 - 如果是,还有什么不清楚的地方?
  • @imapython 这是另一个类似的问题:stackoverflow.com/questions/494594/…它会回答你的问题。

标签: python loops for-loop while-loop


【解决方案1】:

同时使用

count=0
b=0
while count <100:
    count+=1
    b+=count

对于:

b=0
for i in range(1,101):
    b+=i
print (b)

【讨论】:

  • 这完全是错误的。当问题要求总和时,您正在制作的列表会打印出 1、2、3、4 ...。
  • 还有一种只需要一行的好方法:lst = range(1,101)
  • 问题的总和在哪里?
  • “我将如何添加让我们说数字 1 到 100...”
  • 现在相应地编辑您的答案,而无需查看我制作的代码。有很多方法可以将数字 1 加到 100。哦,再次修复它。这就像一个斐波那契数仅供参考。
【解决方案2】:

这是使用 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

【讨论】:

    【解决方案3】:
    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)
    

    【讨论】:

      【解决方案4】:

      这将起作用:

      sum(xrange(101))
      

      【讨论】:

        【解决方案5】:

        使用reduce:

        >>> from itertools import *
        >>> reduce(lambda x,y:x+y,range(1,101))
            5050
        

        使用sum

        >>> sum(range(1,101))
            5050
        

        【讨论】:

        • 请为此提供更多解释/上下文,因为这会使答案更有用。
        猜你喜欢
        • 1970-01-01
        • 2020-05-15
        • 1970-01-01
        • 2011-11-04
        • 1970-01-01
        • 2013-06-19
        • 1970-01-01
        • 2023-01-13
        • 2020-04-18
        相关资源
        最近更新 更多