我是Stack Overflow和Python的新手(但不是编程新手)
问题 - 为什么Trinket会显示运行时错误 -
TypeError: unsupported operand type(s) for Add: 'int' and 'list' on line 20 in main.py
在我看来,它认为l_score
是一个列表,即使我已经在子例程中明确定义为int。
如何将变量分配给数组的元素并保留已分配的变量类型,例如诠释?
我已经标记了发生此错误的代码部分(以及我尝试过的替代方案)
# A program to total 3 input numbers
m_score = []
total = 0
def input_scores(): # def = define.
for i in range(0,3):
i_score = int(input("score"))
m_score.append([i_score])
#end for
return m_score # returns the value to the calling line
# end input_scores
def CalculateMean(m_score): # def = define.
tot = 0
l_score = int(0)
for i in m_score:
l_score = (m_score[1])
tot = tot + l_score # - QUESTION
# tot = tot + int(l_score) This doesn't work either
# tot = sum(m_score) This doesn't work either
print('tot = ' + str(tot))
return(tot)
#end for
return(total)
#end CalculateQuartiles
input_scores()
for i in m_score:
print(i)
#end for
total = CalculateMean(m_score)
print('Total = ' + str(total))
答案 0 :(得分:0)
m_score
目前是一个列表列表,因此m_score[1]
仍然是一个列表,尽管只有一个项目。您可以在第1行中将其定义为空列表,然后在其中附加单项列表。
将m_score.append([i_score])
更改为m_score.append(i_score)
。