import random
def create_deck():
suits = ["♥","♣","♦","♠"]
values = ["1","2","3","4","5","6","7","8","9","10","J","Q","K"]
deck = []
card = ""
for suit in suits:
for value in values:
card = value + suit
deck.append(card)
random.shuffle(deck)
random.shuffle(deck)
cards = deck[:21]
print(cards)
return cards
#create the deck and keep 21 cards
def create_piles(deck):
pile1 = []
pile2 = []
pile3 = []
for i in range(7):
pile1.append(cards.pop())
pile2.append(cards.pop())
pile3.append(cards.pop())
print("\n" *3)
print(pile1)
print(pile2)
print(pile3)
return pile1,pile2,pile3
#create the three piles
def user_choice():
while True:
print("What pile is your card in?")
choice = input("----> ")
print(cards)
if choice in ["1","2","3"]:
return choice
#select the pile
def reassemble(choice,pile1,pile2,pile3):
if choice == "1":
cards = pile2 + pile1 + pile3
elif choice == "2":
cards = pile1 + pile2 + pile3
else:
cards = pile2 + pile3 + pile1
#reassemble the piles
def win(create_piles):
print("Your card was")
#the card that the user picked
def trick_compile(cards):
for i in range(3):
pile1,pile2,pile3 = create_piles(cards)
choice = user_choice()
cards = reassemble(choice,pile1,pile2,pile3)
win(create_piles)
quit()
#framework that runs the trick
cards = create_deck()
trick_compile(cards)
我是GCSE计算机科学专业的学生。这段代码基于去年的课程作业,要求提供卡片技巧。
运行脚本时,会显示以下错误:
Traceback (most recent call last):
File "main.py", line 71, in <module>
trick_compile(cards)
File "main.py", line 62, in trick_compile
pile1,pile2,pile3 = create_piles(cards)
File "main.py", line 26, in create_piles
pile1.append(cards.pop())
IndexError : pop from empty List
我得出结论,“空”列表是列表卡,但是,我已经为它分配了21个值(它们也形成了显示的第一个堆)。为什么列表在分别附加到Pile1,2和3之后是空的,以及可以做些什么来修复它。
所有帮助表示赞赏。
GCSE计划规范: http://filestore.aqa.org.uk/resources/computing/AQA-85203-SNEA3.PDF
答案 0 :(得分:0)
我在你的代码中发现了一些错误
在create_piles中,您从卡片中弹出,而您传递的参数是卡片。这是更正后的版本
def create_piles(deck):
pile1 = []
pile2 = []
pile3 = []
for i in range(7):
pile1.append(deck.pop())
pile2.append(deck.pop())
pile3.append(deck.pop())
print("\n" *3)
print(pile1)
print(pile2)
print(pile3)
return pile1,pile2,pile3
你也试图在user_choice中打印卡片,而卡片不是全局的,这会给出空列表。
在重新组装时,你创建的卡片没有返回它
def reassemble(choice,pile1,pile2,pile3):
if choice == "1":
cards = pile2 + pile1 + pile3
elif choice == "2":
cards = pile1 + pile2 + pile3
else:
cards = pile2 + pile3 + pile1
return cards