【问题标题】:Global variable playing keeps getting name error全局变量播放不断出现名称错误
【发布时间】:2019-10-07 01:50:09
【问题描述】:

在我的 hit_or_stay 函数中将播放声明为全局变量,但是当我运行我的程序说“名称错误:播放未定义”时不断收到错误我该如何解决这个问题?

我在 hit_or_stand() 中使用全局播放来根据玩家的输入来控制游戏流程。当我运行代码时,我收到错误“NameError:未定义名称播放”。我试图将“全局播放”移到 hit_or_stay() 之外,但似乎没有任何效果。

import random
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10,
    'Queen':10, 'King':10, 'Ace':11}

class Deck:
    '''
        CREATES DECK, SHUFFLES DECK, DEALS CARDS.
        '''

    #CREATES DECK BY ADDING EACH SUIT TO EACH RANK AND STORING IN LIST SELF.DECK
    def __init__(self):
        self.deck = []
        for s in suits:
            for r in ranks:
                self.deck.append(r + ' of ' + s)

#SHUFFLE DECK CREATED IN __init__()
    def shuffle(self):
        random.shuffle(self.deck)

    #DEALS CARD FROM SELF.DECK AT GAME START AND IF PLAYER CHOOSES TO HIT
    def deal(self):
        single_card = self.deck.pop()
        return single_card


    #PRINTS CARDS IN SELF.DECK (FOR TROUBLESHOOTING)
    def __str__(self):
        for card in self.deck:
            return str(self.deck)



#print('\n')
##create an instance of Deck class and print the deck
#test_deck = Deck()
#print(test_deck)
#print('\n')
##shuffle and print the deck
#test_deck.shuffle()
#print(test_deck)
#print('\n')


class Card:
    '''
        CREATES CLASS FOR INDIVIDUAL CARDS, PRINTS INIDIVIDUAL CARDS "SUIT OF RANK"
        '''

    #CREATES CHARACTERISITCS OF class Card; self.suit and self.rank
    def __init__(self,suit,rank):
        self.suit = suit
        self.rank = rank

class Hand:
    '''
        HOLDS CARD OBJECT FROM self.deck USING Deck.deal() method
        CALCULATES THE VALUE OF THE CARDS IN HAND
        ADJUST FOR ACES WHEN APPROPRIATE
        '''
    #CREATE CHARATERISTICS FOR CARDS IN HAND; self.card = cards in hand, self.value = value of cards in hand, self.aces = counts aces in hand
    def __init__(self):
        self.cards = []
        self.value = 0
        self.aces = 0

    #ADDS CARDS TO HANDS ONCE DEALT
    def add_card(self,card):

        #ADDS CARD TO HAND
        self.cards.append(card)

        #HOLDS THE VALUE OF THE HAND
        key = ''
        key = card.split()
        self.value += values[key[0]]

        #ACCOUNT FOR ACE
        if key[0] == 'Ace':
            self.aces += 1

    #KEEPS TRACK OF ACES; ADJUSTS VALUE FOR ACE WHEN APPROPARIATE
    def adjust_for_ace(self,card):

        if self.value > 21 and self.aces:
            self.value -= 10
            self.aces -= 1


class Chips:

    def __init__(self):
        self.total = 100
        self.bet = 0

    #ADD CHIPS TO TOTAL IF WIN
    def win_bet(self):
        self.total += self.bet

    #TAKE AWAY CHIPS FORM TOTAL IF LOSE
    def lose_bet(self):
        self.total -= self.bet

#TAKE BET FROM USER
def take_bet(Chips):


    while True:
        try:
            Chips.bet = int(input("How many chips do you want to bet?: "))

        except:
            print("There was an error! Enter an integer!\n")
            continue
        else:
            if Chips.bet > Chips.total:
                print("You don't have enough chips!\n")
            else:
                print("Your bet is {} chips\n".format(Chips.bet))
                break


#IF PLAYER CHOOSES TO HIT
def hit(deck,hand):

    #USE IN hit_or_stay function; ADDS CARD DEALT FROM DECK TO THE HAND and ADJUSTS FOR ACES
    Hand.add_card(deck.deal())
    Hand.adjust_for_ace()

#DETERMINE WHETHER PLAYER WANTS TO HIT OR STAY
def hit_or_stay(deck,hand):

    global playing         #controls upcoming loop

    while True:
        h_or_s = raw_input("Would you like to hit or stay? Enter 'hit' or 'stay': ")

        if h_or_s[0].lower() == "h":
            hit(deck,hand)

        elif h_or_s[0].lower() == "s":
            playing = False

        else:
            print("\nThere was an error. Try again.\n")
            continue
        break

def show_some(player,dealer):

    print("Dealer's Hand:")
    print(dealer.cards[0])
    print("< card hidden >\n")

    print("\nPlayer's hand value: {}".format(player.value))
    print("Player's Hand:", *player.cards, sep='\n')


def show_all(player,dealer):

    print("\nDealer's hand value: {}".format(dealer.value))
    print("\nDealer's Hand:", *dealer.cards, sep='\n')

    print("\nPlayer's hand value: {}\n".format(player.value))
    print("Player's Hand:", *player.cards, sep='\n')

#GAME ENDING FUNCTIONS
def player_busts(player,dealer,Chips):

    #PRINT PLAYER BUSTS; TAKE AWAY CHIPS BET FROM TOTAL CHIPS
    print("Dealer's hand value: {}\n Player's hand value: {}\n".format(dealer_hand.value,player_hand.value))
    print("Player busts! Dealer Wins\n")
    Chips.lose_bet()
    print("You lost {} chips!\n You have {} chips remaining.".format(Chips.bet,Chips.total))

def player_wins(player,dealer,Chips):

    print("Dealer's hand value: {}\n Player's hand value: {}\n".format(dealer_hand.value,player_hand.value))
    print("Player wins!\n")
    Chips.win_bet()
    print("You won {} chips!\n You have {} chips remaining.".format(Chips.bet,Chips.total))

def dealer_busts(player,dealer,Chips):

    print("Dealer's hand value: {}\n Player's hand value: {}\n".format(dealer_hand.value,player_hand.value))
    print("Dealer busts! Player wins!\n")
    Chips.lose_bet()
    print("You won {} chips!\n You have {} chips remaining.".format(Chips.bet,Chips.total))

def dealer_wins(player,dealer,Chips):

    print("Dealer's hand value: {}\n Player's hand value: {}\n".format(dealer_hand.value,player_hand.value))
    print("Dealer wins!\n")
    Chips.lose_bet()
    print("You lost {} chips!\n You have {} chips remaining.".format(Chips.bet,Chips.total))

def push(player,dealer,Chips):

    print("Player and Dealer tie, its a push!\n")





#GAMEPLAY

while True:
    print("Welcome to Black Jack. Get as close to 21 as you can without going over 21.\n")
    print("Dealer hits until he reaches 17. Aces count as 1 or 11\n")

    #create an instance of Deck class and print the deck
    game_deck = Deck()
    #shuffle and print the deck
    game_deck.shuffle()


    #CREATE PLAYER HAND AND DEAL TWO CARDS
    player_hand = Hand()
    player_hand.add_card(game_deck.deal())
    player_hand.add_card(game_deck.deal())

    #CREATE DEALER HAND AND DEAL TWO CARDS
    dealer_hand = Hand()
    dealer_hand.add_card(game_deck.deal())
    dealer_hand.add_card(game_deck.deal())

    #TAKE BET FROM PLAYER
    #player_chips = take_bet(Chips())

    #SHOW ONE OF DEALER'S CARDS AND ALL OF PLAYER'S CARDS
    show_some(player_hand,dealer_hand)

    while playing:      #THIS IS WHERE THE NAME ERROR OCCURS!!

        if player_hand.value < 21:

            #PLAYER CHOOSES HIT OR STAY
            hit_or_stay(game_deck(),player_hand)

            #SHOW PLAYERS CARDS AND KEEP ONE DEALER CARD HIDDEN
            show_some(player_hand,dealer_hand)

NameError: name 'playing' 没有定义

【问题讨论】:

  • 你在哪里定义了playing
  • 在程序顶部声明 global playingplaying = True。请注意,您需要在该代码中进行一些额外的调试。提示 `input` 或 raw_input 开始。
  • @RolfofSaxony 如果已经在全局范围内,则无需在代码顶部声明 global playing
  • @C.Nivs 是的,但如果你要使用global,明确一点也没有什么坏处。将其视为文档。

标签: python global-variables nameerror


【解决方案1】:

Python 中的global 不会创建变量,它是defining the existing variable as global。所以你试图声明某个变量是全局的(但它仍然不存在)然后调用它。所以你得到一个错误。

请不要在 Python 中使用 global!在 99.999% 的情况下,您无需任何全局变量即可轻松替换代码!例如,在这部分代码之后添加playing = True

#GAMEPLAY

while True:
    print("Welcome to Black Jack. Get as close to 21 as you can without going over 21.\n")
    print("Dealer hits until he reaches 17. Aces count as 1 or 11\n")

    #create an instance of Deck class and print the deck
    game_deck = Deck()
    #shuffle and print the deck
    game_deck.shuffle()

【讨论】:

    【解决方案2】:

    问题在于playing 是在hit_or_stay 中定义的,直到while 循环开始之后才会调用它。

    playing 定义为True 以开始,或包含明确的break 条件

    while True:
        print("Welcome to Black Jack. Get as close to 21 as you can without going over 21.\n")
        print("Dealer hits until he reaches 17. Aces count as 1 or 11\n")
    
        # ~snip~
    
        # define here
        playing = True
    
        while playing:
            # rest of your code
    

    此外,hit_or_stay 中似乎有一个 while 循环。我建议你看看到目前为止你是如何构建你的代码的,也许还可以重构它。除了hit_or_stay 中的break,也许你可以return playing

    def hit_or_stay(deck,hand):
        # no need for global playing anymore, as you return the proper bool
    
        h_or_s = raw_input("Would you like to hit or stay? Enter 'hit' or 'stay': ")
    
        if h_or_s[0].lower() == "h":
            hit(deck,hand)
            return True
    
        elif h_or_s[0].lower() == "s":
            return False
    
        else:
            raise ValueError("\nThere was an error. Try again.\n")
    
    
    playing = True
    
    while playing:
        try:
            playing = hit_or_stay(deck, hand)
        # Catch the error for unexpected input and retry
        except ValueError as e:
            print(e)
            continue
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      • 1970-01-01
      • 2016-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-09
      相关资源
      最近更新 更多