2017年GCSE卡牌戏法:“从空列表中弹出”IndexE

2024-05-15 19:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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个值(这也构成了显示的第一堆)。为什么列表在分别附加到第1、第2和第3排之后是空的,我们可以做些什么来修复它。你知道吗

感谢大家的帮助。你知道吗

GCSE课程规范: http://filestore.aqa.org.uk/resources/computing/AQA-85203-SNEA3.PDF


Tags: theindefcreatecardpopcardsprint
1条回答
网友
1楼 · 发布于 2024-05-15 19:26:49

我在你的代码中发现了一些错误

在create\u piles中,您从卡片中弹出,而您传递的参数是deck。这是正确的版本

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

您还尝试在用户选择中打印卡片,而卡片不是全局的,这将给出空列表。你知道吗

在“重新组合”中,您创建的卡没有返回

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

相关问题 更多 >