Python实现21点手牌计数函数出现列表索引越界问题求助
解决21点手牌计数函数的索引越界问题
你的count_total函数是索引越界的根源:
- 当你用
for card in total_cards遍历手牌列表时,card拿到的是手牌的点数值(比如11、10、2这类),但你却写了total += total_cards[card]——这相当于把点数数值当成列表索引来用。比如拿到点数11时,你的手牌列表长度肯定小于11,自然触发索引越界错误。 - 就算改成
for card in range(0, len(total_cards)),如果没把取值逻辑改对,错误依然存在。
修正后的count_total函数可以选两种写法:
- 直接遍历元素累加(最简洁):
def count_total(total_cards): total = 0 for card in total_cards: total += card # 直接累加手牌点数本身 return total
- 通过索引遍历累加:
def count_total(total_cards): total = 0 for idx in range(len(total_cards)): total += total_cards[idx] # 用索引取对应手牌点数 return total
另外提个小细节:输入提示里的Typr是拼写错误,应该改成Type。
内容的提问来源于stack exchange,提问作者Niccolò Baresani
相关产品推荐
相关产品推荐

