将变量放入 Python 的列表中

Putting variables in the lists in Python

我想问一下我们如何使用变量来定义Python中数组的大小(我的意思是列表)。我在下面写了一些代码,你能告诉我吗代码有什么问题? 谢谢..

   elif(op=='+') :
     size=int(input("Please enter how many numbers you want to add"))
     for x in range(0,size):
     print("Please enter the number",x+1) 
     inp=(input()) 
     num[x]=inp #<<<-----the error comes up when trying to run this expression
   for z in range(0,size):
     num[z]=num[z]+num[z+1]    
   print("The result is " , num[size])

Python 列表未初始化为特定大小,而是动态增长。使用append添加元素:

size=int(input("Please enter how many numbers you want to add"))
num = [] # start with an empty list
for x in range(0,size):
    print("Please enter the number",x+1) 
    inp = input() 
    num.append(inp) # add elements

除了@Daniel 回答的 inp 中的问题,input() 的结果是一个字符串。因此,您的代码只会在您浏览列表时连接数字。此外,为什么你不断地将串联放入列表中?此外,在进入范围时,您将附加输入的位数,但索引操作从 0 索引到 "size" 索引,这比列表中的实际数字多一个。

 for z in range(0,size):
     num[z]=num[z]+num[z+1]    
 print("The result is " , num[size])

因此,当 z == size -1 时,您将在尝试引用 num[z+1] 时以及在尝试引用 num[size][=12 的最终打印中得到超出范围的索引=]

此外,如果您要添加而不是连接输入字符串,您应该说 inp = int(input())

size=int(input("Please enter how many numbers you want to add"))
mytotal = 0
for x in range(0,size):
    # The next two could have been on one line
    myval = int(input("Please enter the number"))
    mytotal += myval #This is split for clarity
print mytotal