我想问一下如何使用变量来定义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])
答案 0 :(得分:1)
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
答案 1 :(得分:0)
除了@Daniel回答的inp中的问题,input()的结果是一个字符串。因此,当您浏览列表时,您的代码将只连接数字。另外,为什么要不断地将串联放入列表中?此外,当进入范围时,您将附加输入的数字位数,但索引操作从0索引到&#34;大小&#34;索引,它比列表中的实际值多一个。
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]
的最终打印时,您将获得超出范围的索引另外,如果你要添加而不是连接输入字符串,你应该说是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