Forums

Pyhton GURUZ I is New to py

OK so I want to learn python. Witch leads to me buying a book and I have gone about half way when I ran into trouble. I have coded a game (80' text) sample but it wont run and I have given it a good try to solve it my self, but no luck I DONT GET IT I have noticed that my dicts in the book use [ ] but on pythonAnywere its not working like that but it dose work with { } so theres one issue but the big one is it wont run. It runs with no errors as a skeliton but as soon as I feed it a scene it starts giveing errors I have twiked it a few ways .. pls help


from sys import exit from random import randint

class Scene(object):

def enter(self):
    print "This scene is not yet configured. Subclass it and implement enter."
    exit(1)

Now the engine

class Engine(object):

def __init__(self, scene_map):
    self.scene_map = scene_map

def play(self):
    current_scene = self.scene_map.opening_scene()

    while True:
        print "\n----------"
        next_scene_name = current_scene.enter()
        current_scene = self.scene_map.next_scene(next_scene_name)

make Class Death

class death(Scene):

quips = ["\nYou died. You kinda suck at this.", "\nYour mom would be so proud...IF she were smarter.", "\nLa-HAY LU-hoo ZAHER", "\nMy Grandma is better then this."]

def enter(self):
    print death.quips[randint(0, len(self.quips)-1)]
    exit(1)

Class Scenes

class central_corridor(Scene):

def enter(self):
    print "The Gothons of planet melmac 7 have invaded your ship and destroyed"
    print "your entire crew. You are the only surviving member of your team"
    print "and your last orders were to get the BIGFUCKINGBOMB or the BFB for"
    print "short, and put it on the bridge then get the hell out and blow this"
    print "bitch up"
    print "\n"
    print "Your running down the central corridor th the wepons room when"
    print "a Gothon jumps out at you, red scaly skin, dark grimy teeth and an"
    print " evil clown costume flowing around his hate filld body. He's"
    print " blocking the door to the weapons room and is about to pull his blaster"
    print "\n----------\n"
    print "You can::shoot::dodge::tell a joke"
    print "\n---------\n"
    action = raw_input(";@|>")

    if action == "shoot":
        print "Quick on the draw you pull your blaster and fire it at the Gothon."
        print "His clown costume is flowing and moving around his body, witch"
        print " throws off your aim. Your laser hits the wall behind the clown"
        print " and bounces back to hit you in the face. You've Died."
        return 'death'

    elif action == "dodge!":
        print "You think back on those days when you were a rug rat and think I'll "
        print " just jump out of the way so you try this but as your OLDER body jerks"
        print " its self in a febal atempt to jump you tork your back and fall to the"
        print " ground cring \"OH! my back\" as you lay there like a limp dick the Gothon"
        print " steps on your head and you die."
        return 'death'

    elif action == "tell a joke":
        print "You look the Gothon in his stupid face and say \"A Man and a Geraff walk into"
        print " a Bar the both get drunk, when the Geraff falls to the floor out cold the Man"
        print " gets up and walk out, as he dose this the Bar Tender Yells YOU CANT LEVE THAT LIEING THERE"
        print " The Man looks at him and says thats no Lion its a Geraff\" at that point the Gothon hits the floor"
        print " and befor he can react you brake his stupid face"
        return 'WeponsRoom'

    else:
        print "WHAT???"
        return 'central_corridor'

class WeponsRoom(Scene):

def enter(self):
    print "As you Enter the Wepons room you scan to see if there are any more Gothons hiding, once you find the BFB"
    print " you see that there is a key pad lock on it. You will need the code to get the BFB out. If you get the code"
    print " wrong 10 times the thermite safty switch will egnite melting the lock to a perma chunk of titainium then"
    print " will never get the Big Fucking Bomb The code is 3 digits."
    code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
    guess = raw_input("[{KEYPAD PASS CODE}]::")
    guesses = 0

    while guess != code and guesses <10:
        print "Like that Asian guy in the cubical next to me you sir are Jimmy WONG"
        guesses += 1
        guess = raw_input("[{KEYPAD PASS CODE}]::")

    if guess == code:
        print "YES! I had the same passcode on my locker at the gym.\n"
        print "Ok you grab the BFB and start heading to the Bridge were you will put the BFB and blow these SHIT HOLE CLOWNS"
        print " TO HELL!!!"
        return 'the_bridge'

    else:
        print "Thats it you idiot it was %s . As you try to think of what to do next your mommy calls and says "
        print " its time to come home so you blast your self in the face and die"
        return 'death'

class the_bridge(Scene): def enter(self): print "You get to the bridge like the flash and as you start to arm the BFB SUPRISE! there are 5 Gothons" print "\n What do you do?"

    print "\n----------\n"
    print "You can::Throw the Big Fucking Bomb::Place it slowly on the ground"
    print "\n---------\n"
    action = raw_input(";@|>")

    if action == "Throw the Big Fucking Bomb":
        print "You throw the BFB .... THE BFB.... REALLY your stupid so BOOM GOSE THE BOMB and now you are dead too GOOD JOB!"
        return 'death'

    elif action == "Place it slowly on the ground":
        print "Just then you pull your blaster and scream \"I'LL FUCKING DO IT MAN!\" as you point your blaster at the BFB"
        print " like little bitches they all step back and stay very still, you arm it and then step out shuting the door you blast the electro lock"
        print " making it spark and lock the door then you run to the escape pod"
        return 'escape_pod'

    else:
        print "What?"
        return 'the_bridge'

class escape_pod(Scene):

def enter(self):
    print "You get to the pod but for some reason theres a sighn that says only one works. What?"
    print "Well pick one and hope for the best. There are 5 pods"

    good_pod = randint(1,5)
    print "\n----------\n"
    print "You can pick::1::2::3::4::5"
    print "\n---------\n"
    guess = raw_input(";@|>")

    if guess != good_pod:
        print "You jump on to pod %s and as the doors shut you see the sighn on the back of the door that says OUT OF ORDER, Have a nice day :)" % guess
        print " The pod shoots out half way locking you in the pod. you think to your self well at lest I got those bas...just then you see the 5 Gothons jump onto their ship and fly off"
        print " SHIT!"
        return 'death'

    else:
        print "You jump on to pod %s and as the doors shut you hit the go switch and blast off to the vast emptyness of space I guess at lest I killd those bastards just then you see them jump onto their" % guess
        print " as they fly away your ship blows up and you think SHIT!"
        print "\n Game Over You win"

        return 'finished'

class map(object):

scenes = {
    'central_corridor': central_corridor() ,
    'WeponsRoom': WeponsRoom(),
    'the_bridge': the_bridge(),
    'escape_pod': escape_pod(),
    'death': death()
}

def __inti__(self, start_scene):
    self.start_scene = start_scene

def next_scene(self, scene_name):
    return map.scenes.get(scene_name)

def opening_scene(self):
    return self.next_scene(self.start_scene)

scene_map = map('central_corridor') scene_game = Engine(scene_map) scene_game.play()

WHAT IS WRONG??? IS IT IN THE CODE OR THE PyA??? like the [ ] - { } ???

Despite the

__inti__()

typo, what kind of errors you got?

Thank you for this! I died laughing at "clown costume"

It would be more useful if you could post the errors that you receive. Also, dicts in Python are represented with {} and lists with []. For code like this, the problem is going to be in your code, not PythonAnywhere.

Yes, plenty of gurus here willing to help, but you need to give us a clue by posting the error message you get...

(deleted)

noiv - That was the problem init not inti Thx

glenn- it must be some thing with some thing exaple ['dog', 'cat'] works [ 'dog' : 1, 'cat': 2] dose not but thats how the book I have has it so if it is as you say then the book is wrong cuz { 'dog' : 1, 'cat': 2} this works here but all three work on QPython ???? I guess the question should be What IS or were can I find the OFFICIAL format??

THAX TO ALL

Hi CW...

The official format for a dictionary is { 'dog' : 1, 'cat': 2}. However, you can also set a dictionary up like this:

my_dictionary = {}
my_dictionary['dog'] = 1
my_dictionary['cat'] = 2

Hi CW -- just a bit of background that might clarify things. The code you're writing is working with two different datatypes -- that is, two different ways of storing bits of data together:

  • Lists. A list contains a sequence of values, and uses square brackets. For example, a list of some prime numbers is [5, 3, 7, 2, 11]. If you want to extract a value from a list that you've stored in a variable (let's say my_list) you use square brackets again to say which element to extract. For example, if you ask for my_list[2] you will get 7, and if you ask for my_list[0] you'll get 5. Note that the first element in the list uses the index zero.
  • Dictionaries. Lists only let you extract a value from them by its position in this list, eg. "give me the eighth element". Dictionaries let you assign a "key" to each value. You can create them using curly brackets, like this: my_dictionary = { "dog": "woof", "cat": "miaow" }. And then you use the key to look up values you've stored in them. To do that, you use square brackets once again, so my_dictionary["dog"] gives you "woof".

So, to summarise: curly brackets are used when you're creating dictionaries. Square brackets are used in three different ways:

  • When you're creating lists.
  • When you're extracting the nth value from a list
  • When you're extracting a value from a dictionary using its key.

HTH

Giles

Was gone a min but am back. The most noteable diff I am seeing is the decleration i.e. the : between the identifier and the identified so exap in a dict it would be VAR1 : INFO and a list would be with out the declertion becuse the list is stored in the var. I.E. VAR1 1,2,3 witch is the question. In the book "Learn Python the hard way 3rd ed." by Zed A. Shaw you see in the section were he talks about dicts and list and runs a program that uses both he wrights (pg132 ex39.py)

>>>things = ['a', 'b', 'c', 'd']
//this IS a LIST


>>>stuff = {'name': 'zed', 'age': 36, 'hight' : 6*12+2}
//this IS a DICT.

BUT on pg 166 ex43.py he wrights

class Map(object): 
       scenes = [    //<-- here he uses the [ to make this object???
                'central_corridor' : CentralCorridor(), 
                'laser_wepon_armory' : LaserWeponArmory(), 
                'bla' : bla(),
        ] //<-- He closes the object???

is it a Dict I am lead to this by the : and pointer/objects this is whats throwing me off so if I am use the wrong syntax to discribe the above object in the defined class pls help me to not sound so .... ummmm..... stupid if not then is it a typo becuse in Qpython it works just as above but on PythonAnywhere it requiers {}

On a side note dose any one have a recomandation for a next book the one I am one is a newbies manule i need a newbie nxt step guide so to speak. and a good spelling teacher.

First of all, what version of Python are you using, and what was the book written for?

I would also recommend you work through the tutorial on http://python.org - get the one specific to your version of Python (2 or 3).

Working in Python your also going to want to keep a web page for the reference manual (and tutorial) open at all times.

The Tutorial explains data types and how to use them, you will be referring to it a lot wile you learn the syntax. And you will likely be using the reference manual to look up special syntax or details on a command or library forever.

the book says v2.7 witch is that is used here right the scripts default to v2.7 correct??? also the book I have and the web sites say mixed info witch is why I asked about the object because the : as all of them agree is a dict so it needs {} not [] but some of them use [] instead of {} witch is what I was asking. when you create an class with an object as the one I show in the inquiry what is that "list/dict" called? in the book its done with [ v:1 ] not { v: 1} but here it only woks with { v: 1} BUT on Qpython a scripting app it only works [ v:1 ] .... I guess I wasn't on dot in my description of the question.

..... well I went throw that with c++ and your right I still have 2 books and a quick guide on had always so I assumed python would be no diff. So thx, I already have python.org and a couple others book marked. what I am looking for tho Is off line books I like to pre read and with my life I find time were I can read only and time were I can read OR get on the commputer but not both and time were I can do both so I need to fill the off line time

Ohh look the book comes with 2.7 on the disk but it the 1st chap. when it shows how to install it shows v2.6 so ......

I used to work full time in Borland C++ before I switched to Python. Python was designed from the start to be an OOP language. But without the crazy syntax C evolved into as C++.

Consequently, Python can be easily learned by teenagers at summer camp!

A programmer with prior experience in C++ OOP can work through the Python tutorial (which is free) in a couple of weeks and be ready to work.

I have trained and taught a lot people. My advice to you is to do the tutorial first. Not only will the book examples make more sense, but you will be able to spot typos in the book examples that will save you a lot of grief.

I have a vague memory there was a time in an earlier version of Python that allowed some flex in how you declared data objects - or was it a 3.x change?

Regardless, you were wise to do some "sanity testing" and figure out it needs to be curly-braces for the version your using.

Well thx. I have never been able to program prof. as it's more of a hobby for me not to point out that you need a certi. some were in some lang. to even get given a job and as I hve never had time enuff to fallow the required curiculum even for the online stuff I will have to wait. but as it stand I make good money as a Prof. Driver so ... but ya I had gotten it to work was just trying to see whats what, and hows said. So I'll stick with object for the time being NOW a big one I know SL4A Is the multi tool for android and its aimed to python but should I jump from here to py3 or will I be ok to hold fast with 2.7?

Well thx. I have never been able to program prof. as it's more of a hobby for me not to point out that you need a certi. some were in some lang. to even get given a job and as I hve never had time enuff to fallow the required curiculum even for the online stuff I will have to wait. but as it stand I make good money as a Prof. Driver so ... but ya I had gotten it to work was just trying to see whats what, and hows said. So I'll stick with object for the time being NOW a big one I know SL4A Is the multi tool for android and its aimed to python but should I jump from here to py3 or will I be ok to hold fast with 2.7?

If its worth saying then its worth saying twice. on a not completly unrelated topic how do I un post???

you can't un-post, but you can edit your posts after you've written them, and replace all the old content with "<deleted>" or something. But that would be a shame!

Yeah, the evil slow post response gets everybody! It got me earlier: https://www.pythonanywhere.com/forums/topic/1090/#id_post_7673

And as harry says, you can only edit the duplicate to erase its contents. Maybe instead of putting "deleted" you could post a good joke or quote?

@cw: Don't sell yourself short. Gifted programmers have something different in the way they see the world. And its not something any vocational test can accurately detect. You are already showing signs of being something special. I have seem programmers "pop up" in all walks of life - any gender, background, no formal schooling required.

Put the books aside, and run through the Tutorial on Python.org. If you zip through that, and find your imagination opening up with ideas, then we should talk!

As for 2.x vs 3.x it depends upon your circumstances and future plans. Python 3 is a completely re-vamped language that makes advanced syntax and Object programming even easier than it was. They also fixed a lot of "oops" or inconsistencies in Python 2.x that everybody just lived with. So, if your new to Python V3 would be better. However, there are many reasons to stick with or at least learn 2.7 first.

For example, you might want some library or package that is not available for Py3 yet. Your books are all in 2.x, if they have advanced concepts you want to learn it will be easier to stick with 2.7 until you complete them. Also there are automated tools to convert Python 2.7 scripts to 3 so you won't loose any early work.

I - and many others - are still doing all our work in Python 2.7 so you won't be alone.

Cool that helps will keep on keeping on.