我有这个功能
def calc_score(player):
"""Calculates the score of the specified player (player)"""
score = 0
if player == "user":
for card in range(0, len(user_cards)):
score += user_cards[int(card)]
elif player == "comp":
for card in range(0, len(comp_cards)):
score += comp_cards[int(card)]
else:
return
return score
当它被调用时,它给了我这个错误:
line 27, in calc_score
score += user_cards[int(card)]
TypeError: unsupported operand type(s) for +=: 'int' and 'list'
我在thonny中调试了它,结果发现它说
['placeholder1', 'placeholder2'][0]
只是给出了列表本身。
我什至用看似等效的代码对其进行了测试,并且它有效。
user_cards = [11,10]
comp_cards = [10,8]
score = 0
if "user" == "user":
for card in range(0, len(user_cards)):
score += user_cards[int(card)]
elif "user" == "comp":
for card in range(0, len(comp_cards)):
score += comp_cards[int(card)]
else:
print()
print(score)
输出:21
我检查了变量和列表的值,它们也正常。
我没发现什么问题。
最后这是整个脚本(截至发布此答案):
import random
# Define Variables
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
user_cards = []
comp_cards = []
user_score = 0
comp_score = 0
# Define Functions
def give_card(num):
"""Returns random cards of a certain amount (num)"""
num = int(num)
cards_give = []
for card in range(0, num):
cards_give.append(random.choice(cards))
return cards_give
def calc_score(player):
"""Calculates the score of the specified player (player)"""
score = 0
if player == "user":
for card in range(0, len(user_cards)):
score += user_cards[int(card)]
elif player == "comp":
for card in range(0, len(comp_cards)):
score += comp_cards[int(card)]
else:
return
return score
user_cards.append(give_card(2))
comp_cards.append(give_card(2))
user_score = calc_score("user")
comp_score = calc_score("comp")
您的问题在这里:
user_cards.append(give_card(2))
user_cards
是一个列表,give_card(2)
返回另一个包含两个数字的列表。将列表附加到列表使附加列表本身成为结果列表的元素:
list = [1, 2]
list.append([3,4])
print(list) # prints [1, 2, [3, 4]]
你需要的是
user_cards += give_card(2)