从另一个函数使用时未定义的变量

时间:2018-04-24 15:56:41

标签: python

In the photo, you can see that line 24 shows up as an error - "pile1" is not defined,"pile2" is not defined, "pile3" is not defined

import random

def create_cards():
  deck = []
  for i in range(21):
    suits = ["♥","♦","♠","♣"]
    numbers = ['1','2','3','4','5','6','7','8','9','10','K','Q','J']
    card = (random.choice(numbers) + random.choice(suits))
    deck.append(card)
  return deck


def create_piles():
  pile1 = []
  pile2 = []
  pile3 = []
  for k in range(7):
    pile1.append(deck.pop())
    pile2.append(deck.pop())
    pile3.append(deck.pop())
  return piles

def user_input():

  print (pile1, pile2, pile3)
  choice = input("Which pile is your card in?")
  if choice == 1:
    deck = 
  elif choice == 2:
    deck = 
  else:
    deck = 

def trick():
  print(0)

deck = create_cards()
piles = create_piles()

我该如何解决这个问题(我已经尝试将函数create_piles放在user_input括号中,仍然显示为未定义。)

2 个答案:

答案 0 :(得分:1)

您的代码无法正常工作的原因是您的函数正在尝试访问不在其范围内的变量。请花点时间在这里阅读有关范围的更多信息:Short Description of the Scoping Rules?

另外,你应该缩进4个空格而不是2个

import random

def create_cards():
    deck = []
    for i in range(21):
        suits = ["♥","♦","♠","♣"]
        numbers = ['1','2','3','4','5','6','7','8','9','10','K','Q','J']
        card = (random.choice(numbers) + random.choice(suits))
        deck.append(card)
    return deck

def create_piles(deck):
    pile1 = []
    pile2 = []
    pile3 = []
    for k in range(7):
        pile1.append(deck.pop())
        pile2.append(deck.pop())
        pile3.append(deck.pop())
    return [pile1, pile2, pile3]

def user_input(pile1, pile2, pile3):
    print (pile1, pile2, pile3)

deck = create_cards()
piles = create_piles(deck)
user_input(*piles)

答案 1 :(得分:0)

看起来最简单的解决方法是简单地更改您的函数以包含桩作为参数。像这样:

def user_input(piles):
    print(piles)
    choice = input("which pile is your card in?")