Hey, how's it going? I decided to pick up Python for the heck of it and have been having some trouble creating this Card Deck class. All this class is supposed to do is initialize a deck, and then draw a card at total random:

import random
class CardDeck():
    suit = ["Spades","Clubs","Hearts","Diamonds"]
    number = ["Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"]
       
    def DrawCard():
        randomsuit = random.randrange(0,3)
        randomnumber = random.randrange(0,12)
        print ("You drew the " + number(randomnumber)+ " of " + suit(randomsuit) +"!")

CardDeck.DrawCard()

Each time I try this, the IDLE returns: "NameError: global name 'number' is not defined". Just for kicks, I tried putting the number and suit arrays in the DrawCard() function, and instead I get the error: "TypeError: 'list' object is not callable"

Any advice would be appreciated

Use "self"

import random
class CardDeck(self):
    self.suit = ["Spades","Clubs","Hearts","Diamonds"]
    self.number = ["Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"]
 
    def DrawCard(self):
        randomsuit = random.randrange(0,3)
        randomnumber = random.randrange(0,12)
        print ("You drew the " + self.number[randomnumber]+ " of " + self.suit[randomsuit] +"!")
 
CardDeck.DrawCard()

It's not tested, but should be worked.

Edited 6 Years Ago by Krstevski: n/a

Here is a little upgrade to your code.

import random
class Deck():
    def __init__(self):
        self.suit = ["Spades","Clubs","Hearts","Diamonds"]
        self.number = ["Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"]
    def DrawCard(self):
        randomsuit = random.randrange(0,3)
        randomnumber = random.randrange(0,12)
        print ("You drew the " + self.number[randomnumber]+ " of " +    self.suit[randomsuit] +"!") # Use "[]" in stead of "()" when using lists.  

x = Deck() # Create a new "Deck"
x.DrawCard() # Uses DrawCard

A few things to note.
~ Use brackets[] instead of parenthesis() when using lists.
~When defining functions in a class, you must put "self" 1st in the parenthesis.
There are a few other things, but I am not sure how to explain them.

Comments
:)

NameError: name 'self' is not defined

Do I have to declare a fresh object?

NameError: name 'self' is not defined

Do I have to declare a fresh object?

How do you get that error? Any one else ever have that error?

How do you get that error? Any one else ever have that error?

My code is not correct, in a previous post saying that I forgot "init".
Your code is correct. :)

This article has been dead for over six months. Start a new discussion instead.