【发布时间】:2022-11-18 03:20:33
【问题描述】:
我创建了一个函数来计算带有 for 循环的 21 点手牌的价值,但它一直告诉我索引超出范围,我不知道为什么
我尝试从“for card in total_cards”切换到“for card in range(0, len(total_cards))”希望这能解决我的问题,但我一直遇到同样的错误。由于这两个错误似乎都源于函数,我在这里缺少什么?谢谢大家。
import random
def count_total(total_cards):
total = 0
for card in total_cards:
total += total_cards[card]
return total
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
house_cards = []
player_cards = []
for i in range (1, 5):
if i % 2 == 0:
player_cards.append(cards[random.randint(0, len(cards) - 1)])
elif i % 2 != 0:
house_cards.append(cards[random.randint(0, len(cards) - 1)])
print(house_cards)
print(player_cards)
should_continue = True
while should_continue:
action = input("Typr 'y' to ask for a card or 'n' to stop: ")
if action == "n":
should_continue = False
break
elif action == "y":
player_cards.append(cards[random.randint(0, len(cards) - 1)])
count_total(player_cards)
if count_total(player_cards) > 21:
should_continue = False
print("You have gone over 21, you lost!")
break
【问题讨论】:
标签: python python-3.x list