Lewis Bellinger
Lewis Bellinger

Reputation: 13

Python syntax errors

I am having a few problems with my code.. I am following an example in the book "Beginning Game Development with Python and Pygame" (example 2-4 and 2-5) and I am getting syntax errors. Below is the code in question. I am new to Python and probably just did a typo.

The book uses python 2.4. I'm getting the error for 2.7 and 3.2.

Two problems:

the code line with:

my_tank = Tank("Bob")

is receiving a syntax error. my_tank is highlighted. I did get it to start working but I am not sure why it started to.

The code line with:

print self.name, "fires on", enemy.name

is also recieveing a syntax error. The self in this line is highlighted. When my_tank stared working I started to receive this error. Not sure whats going on here.

class Tank(object):

    def _init_(self, name):
        self.name = name
        self.alive = True
        self.ammo = 5
        self.armor = 60

    my_tank = Tank("Bob")

    def _str_(self):

        if self.alive:
            return "%s (%i armor, %i shells)" % (self.name, self.armor, self.ammo)
        else:
            return "%s (dead)" % self.name

    def fire_at(self, enemy):

        if self.ammo >= 1:
            self.ammo -= 1
            print self.name, "fires on", enemy.name
            enem.hit()
        else:
            print self.name, "has no shells!"

    def hit(self):

        self.armor -= 20
        print self.name, "is hit!"
        if self.armor <= 0:
            self.explode()

    def explode(self):

        self.alive = False
        print self.name, "explodes!"

Upvotes: 1

Views: 334

Answers (2)

Steven Rumbalski
Steven Rumbalski

Reputation: 45542

chrsaycock's answer looks correct, but I want to emphasize how important it is to pay attention to the traceback you receive.

When I run your code I get this error:

Traceback (most recent call last):
  File "<pyshell#86>", line 1, in <module>
    class Tank(object):
  File "<pyshell#86>", line 9, in Tank
    my_tank = Tank("Bob")
NameError: name 'Tank' is not defined

Your question should have been something along the lines of "Why am i getting a NameError here? I've defined Tank in line one."

Don't think of this error as a generic syntax error. The type of the error tells you much of what you need to know.

Upvotes: 2

chrisaycock
chrisaycock

Reputation: 37930

As @aland notes, the function names are supposed to be __init__ and __str__.

Also, this line should be outside the class:

my_tank = Tank("Bob")

After all, you want an instance of the class for later use.

Upvotes: 4

Related Questions