xzhang66 xzhang66 - 6 days ago 4
Python Question

NameError: name 'a' is not defined. using variable from another function inside the same class

I'm doing this BlackJack program and when I ran it, Python tells me this:

Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
c2.bj_value()
File "/Users/xuanruizhang/Desktop/lab_class_design.py", line 47, in bj_value
s = PlayingCard(a,b)
NameError: name 'a' is not defined


So the problem is with the function bj_value(self). I want to return corresponding value of the rank in the init function.
For example: If c2 = PlayingCard(11, "c"), then c2.bj_value() should return 10.

class PlayingCard:
def __init__(self, rank, suit):
if rank == 1:
self.rank = "Ace"
elif rank == (2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 or 10):
self.rank = rank
elif rank == 11:
self.rank = "Jack"
elif rank == 12:
self.rank = "Queen"
elif rank == 13:
self.rank = "King"
if suit == "h":
self.suit = "Hearts"
elif suit == "s":
self.suit = "Spades"
elif suit == "c":
self.suit = "Clubs"
elif suit == "d":
self.suit = "Diamonds"

def get_rank(self):
if self.rank == (2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 or 10):
return self.rank
elif self.rank == "Ace":
return 1
elif self.rank == "Jack":
return 11
elif self.rank == "Queen":
return 12
elif self.rank == "King":
return 13


def get_suit(self):
if self.suit == "Hearts":
return "h"
elif self.suit == "Jack":
return "j"
elif self.suit == "Clubs":
return "c"
elif self.suit == "Diamonds":
return "d"


def bj_value(self):
s = PlayingCard(a, b)
if s.a == 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 or 10:
return s.a
elif s.a == 11 or 12 or 13:
return 10



def __repr__(self):
return '%s of %s' % (self.rank, self.suit)

def main():

if __name__ == '__main__':
main()


Thank you!

Answer

No need to instantiate a new class. Store the ORIGINAL rank value as a variable (you should rename the variable storing the name values Jack, Queen, etc. Access self.rank within the bj_value function:

class PlayingCard:
    def __init__(self, rank, suit):
        self.rank = rank

        if rank == 1:
            self.card = "Ace"
        elif rank in range(2, 11):
            self.card = str(rank)
        elif rank == 11:
            self.card = "Jack"
        elif rank == 12:
            self.card = "Queen"
        elif rank == 13:
            self.card = "King"
        if suit == "h":
            self.suit = "Hearts"
        elif suit == "s":
            self.suit = "Spades"
        elif suit == "c":
            self.suit = "Clubs"
        elif suit == "d":
            self.suit = "Diamonds"

....

    def bj_value(self):
        if self.rank in range(1,11):
            return self.rank
        elif self.rank in range(11,14):
            return 10