1

I am new to python and have been practicing on Classes and methods. When I ran the script containing the code below, I get the error "NameError: Global name "nameCheck" is not defined." How can I fix it? Thanks in advance.

class game(object):
    def play(): 
         name = input("What's your name, my friend? ")
         check = nameCheck(name)

         if check == 1:
             print ("Hello %r " %(name))
         else:
             print ("Sorry, I can't print your name because you don't have one!")


    def nameCheck(name):
         if name == "":
             print("I can't believe you have no name!")
             return 0

         else:
             print("%s is a nice name!" %name)
             return 1
game.play()

Python “NameError: Global name ”nameCheck“ is not defined.”

Gerard
  • 13
  • 1
  • 3
  • 1
    I know you're practicing, but in Python you wouldn't typically write a class for this, unless you want to actually store some state about the game within the class. – Daniel Roseman Oct 13 '13 at 21:16

2 Answers2

3

Since the methods are in a class you need to give then the self attribute:

do this:

class game(object):
    def play(self): 
         name = input("What's your name, my friend? ")
         check = self.nameCheck(name)

         if check == 1:
             print ("Hello %r " %(name))
         else:
             print ("Sorry, I can't print your name because you don't have one!")


    def nameCheck(self, name):
         if name == "":
             print("I can't believe you have no name!")
             return 0

         else:
             print("%s is a nice name!" %name)
             return 1
game = Game()
game.play()

the selfis a placeholder for the instance so you have to create an instance of the object by doing this game = game() then you can call any of the methods for that instance

now you can call the method from anywhere in the class and if you give then variables the self attribute they can also be access anywhere in the class

more on self

Community
  • 1
  • 1
Serial
  • 7,925
  • 13
  • 52
  • 71
2

Inside a class, Python functions are called methods, and used like this:

class game(object):

    def play(self):
        self.nameCheck(name)

    def nameCheck(self):
        pass

The self contains the object of the class.

Noctua
  • 5,058
  • 1
  • 18
  • 23