【问题标题】:Using for/while loops and range() to list values使用 for/while 循环和 range() 列出值
【发布时间】:2019-11-13 08:04:19
【问题描述】:

我被 2 种方法困住了,如何使用 for 和 while 循环将值列出到空列表。

示例 1. 创建一个接受用户输入并在列表中列出正十进制值的函数,直到用户插入负值。然后列表结束,最后一个值应该是这个负值。输出应该是什么样子:

在列表中添加一个数字: 1.5 在列表中添加一个数字: 5.2 在列表中添加一个数字: 6 在列表中添加一个数字: -2 列表:[1.5, 5.2, 6.0, -2.0]

我的试训失败了

list = []
positive = float(input("Add number to put it in list:"))

while positive > 0: 
    list.append(positive)
else:
    print(list)

示例 2 另一个关于同时使用 for 循环和 range() 的问题:如何列出从数字 2 开始的前 20 个偶数。在函数结束时打印出包含 20 个值的列表。

我的试训失败了

emptylist = []
for days in range(40): 
    if days % 2 == 0: 
        print(emptylist)

在此先感谢您帮助我解决这些应用程序! :)

【问题讨论】:

  • 这对我来说似乎是一项学校作业
  • 您只要求input 一次,然后无限期地继续循环该输入。如果您想要求用户提供多个输入,则需要在循环中包含input()

标签: python for-loop while-loop range


【解决方案1】:

您需要在循环内询问用户输入

numbers = []
num = 1
while num > 0:
    num = float(input("Add number to put it in list:"))
    numbers.append(num)
else:
    print(numbers)

附带说明,不要使用list 作为变量,它是一个内置名称。

【讨论】:

    【解决方案2】:

    你必须用 if else 替换你的 while

    positive=1
    list = []
    while(positive):
    
        positive = float(input("Add number to put it in list:"))
    
        if positive > 0: 
            list.append(positive)
        else:
            print(list)
    

    【讨论】:

      【解决方案3】:

      第一部分的答案:

      output_list = []
      isPositive=True
      while(isPositive):
          num = float(input())
      
          if (num > 0):
              output_list.append(num)
          else:
              isPositive=False
              output_list.append(num)
              break
      
      print (output_list)
      

      第二部分的答案:

      >>> n=20
      >>> for num in range(2,n*2+1,2):
      ...     print(num)
      ... 
      2
      4
      6
      8
      10
      12
      14
      16
      18
      20
      22
      24
      26
      28
      30
      32
      34
      36
      38
      40
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-01
        • 1970-01-01
        • 2013-07-21
        • 2021-12-30
        • 2019-05-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多