我刚开始使用Python(3.x),虽然它很容易上手,但我正在尝试学习如何使用列表。
我写了一个小程序,询问输入的数字量,然后询问数字。我在哪里挠挠脑袋在这里;
t += numList[int(i)]
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
我确信这对其他人来说很明显。我以为列表使用整数索引?引用该索引会返回内容吗? (我有一个C ++背景,所以我发现有些东西不能按照我的想法运作。)
这里有完整的程序;
runLoop = True
numList = []
def avg():
t = 0
i = 0
while i < len(numList):
t += numList[i]
i += 1
print (" total is " + str(t))
while runLoop == True:
maxLen = int(input("Average Calculator : "
"Enter the amount of number "
"to calculate for"))
while len(numList) < maxLen:
numList.append(input("Enter number : "))
avg()
if input("Would you like to run again? (y/n) ") == "n":
quit()
答案 0 :(得分:1)
以下声明中缺少类型转换
numList.append(input("Enter number : "))
e.g。对 python 3.x
使用input()
方法
>>> a = raw_input("Enter number:")
Enter number:2
>>> type(a)
<type 'str'>
>>> b = int(a)
>>> type(b)
<type 'int'>
>>>
t += numList[i]
语句处引发异常,因为我们正在使用字符串变量添加整数变量,这是不允许的。 e.g。
>>> 1 + "1"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
while i < len(numList):
中检查列表的长度。我们可以直接在列表上进行迭代。e.g。
>> numList = [1,4,10]
>>> total = 0
>>> for i in numList:
... total += i
...
>>> print total
15
>>>
sum()
从列表中获取。e.g。
>>> numList = [1,4,10]
>>> sum(numList)
15
>>>
e.g。
>>> try:
... a = int(raw_input("Enter Number:"))
... except ValueError:
... print "Wrong number. Enters only digit."
...
Enter Number:e
Wrong number. Enters only digit.
答案 1 :(得分:0)
感谢Vivik的回答。 我现在调整了我的简单程序并解决了我的问题;代码如下。
runLoop = True
numList = []
def avg(workList):
t = sum(workList)
print ("Average is " + str(t/len(workList)) )
print ("Total is " + str(t) )
while runLoop == True:
maxLen = int(input("Average Calculator : "
"Enter the amount of number "
"to calculate for : "))
while len(numList) < maxLen:
numList.append(int(input("Enter number : ")))
avg(numList)
if input("Would you like to run again? (y/n) ") == "n":
quit()
我可以看到我可以很容易地缩短它;
runLoop = True
numList = []
while runLoop == True:
maxLen = int(input("Average Calculator: Enter the amount of number to calculate for : "))
while len(numList) < maxLen:
numList.append(int(input("Enter number : ")))
print ("Average is " + str(sum(numList)/len(numList)) )
print ("Total is " + str(sum(numList)) )
if input("Would you like to run again? (y/n) ") == "n":
quit()
但是,我的小点/无意义练习的目的是探索列表的关系,输入到列表和打印列表。
干杯!