简体   繁体   中英

How do I make a variable made out of a string global in python?

I'm trying to make a blackjack game. I've made functions for drawing cards and checking if sum in one's hand exceeds 21 but only for 3 players. That was easy I had 3 lists.

But I want to do it for N number of players so I want to keep my functions and make another one that switches between players and their hands.

def create_hands():
global total_players
for x in range(1, total_players+1):
    vars()["hand_%d" % x] = []
    print hand_1

I want to create as many hands as in hand_1, hand_2, etc... for as many N players (total_players)

Because of the code above i get an global name 'hand_1' is not defined error

So it all comes down to:

  1. How do I make "hand_%d" % x global ?

  2. Is there a better way to do it ?

Yes, there is a better way. Simply create a list of lists. Playing with vars should be ommited, if possible. It's really hard to read and debug and you will regret that attitude lately. When you create a list like players -> hand -> cards , or even a dict of players like players['player1'][3] for player's one third card, you will be much more happy with that.

Yes, it is possible to do that. Replace

vars()["hand_%d" % x] = []

with

globals()["hand_%d" % x] = []

Be warned however that this solution is kinda hackish and can easily lead to problems (difficulty in maintenance, losing track of the spontaneously created variables, etc.)

The problem you are running into is that vars() is an alias for locals(), which has the following comment in the official documentation:

Note: The contents of this dictionary should not be modified; 
changes may not affect the values of local and free variables 
used by the interpreter.

In other words, adding keys to vars() does NOT necessarily update the local var iables table (which is why you're getting the global name hand_1 is not defined error - vars()[ "hand_1" ] doesn't make hand_1 into a local variable).

As Gandi mentioned, there are far easier ways to do what you are trying to do - use a list of lists or something similar. There are far more conventional ways to solve this problem than creating arbitrarily-named local variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM