【问题标题】:Making the For loop append, Prompt user to enter values into a list追加 For 循环,提示用户在列表中输入值
【发布时间】:2020-12-14 15:38:41
【问题描述】:
def apend():
    mylist[]
    for i in range(8):
        mylist.append(input("Enter your value:"))
        print (mylist)

append()

我不断收到错误消息;结果,程序无法运行。我哪里做错了?

【问题讨论】:

  • 请提供预期的minimal, reproducible example。显示中间结果与您的预期不同的地方。
  • 你遇到了什么错误?
  • 您将永远无法像以前那样附加 int 的迭代。只需按照我的解决方案。

标签: python for-loop append


【解决方案1】:

您的问题是您没有使用= 符号来定义您的列表。 另外,函数名有错别字,应该是append——和它的调用方式一样。

您的代码应如下所示。

def append():
    mylist = []
    for i in range(8):
        mylist.append(input('Enter your value:'))
        print(mylist)

append()

【讨论】:

    【解决方案2】:

    这只能在一行中完成。 0 == 开始,8 == 给定数字 - 1,您可以按照第二行中的说明执行 n+1 以完成给定数字的迭代,而 1 是 + 1 的步骤

    print(list(range(0, 8, 1))) #stops iteration at 7
    
    print(list(range(0, 8+1, 1))) #finish the iteration at the given number which is 8
    

    输出

    [0, 1, 2, 3, 4, 5, 6, 7]
    [0, 1, 2, 3, 4, 5, 6, 7, 8]
    

    【讨论】:

      猜你喜欢
      • 2018-11-16
      • 1970-01-01
      • 2022-01-21
      • 2018-10-08
      • 1970-01-01
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多