Re: [Tutor] Spawning terminals from Python - A failed question
wormwood_3 wrote: >>> Umm, so just put the ampersand at the end of the command string and >>> call os.system() >>> > > Not sure what the point of this variation would be if os is being deprecated > along with commands... > He was pointing out that you already had a workable solution with os.system but you didn't take the time to think if your current tool set could be used to perform the task, and instead invested the time in searching for the commands module. -Luke > >>> However both os.system and the commands module are deprecated in >>> favour >>> of the new(ish) subprocess module where the equivalent incantation >>> would be: >>> p = subprocess.Popen("gnome-terminal", shell=True)HTH,-- Alan >>> > > Good to know! I will start using this instead. > > -Sam > > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Read dictionary data in a specific order...
"Trey Keown" <[EMAIL PROTECTED]> wrote > window_attrs_key_order = ["name", "title", "icon"] > for (tag,val) in attrs.iteritems(): > for (tag,val) in attrs.iteritems(): > if tag in window_attrs_key_order: > for tag in window_attrs_key_order: > if tag == u"name": > print "%s%s = Tk()" %(whitespace, val) > print "***^^^%s^^^***" %val > whatwindow = val > if tag == u"title": > print "%s%s.title(\"%s\")" % (whitespace, whatwindow, val) > if tag == u"icon": > print "%s%s.iconbitmap(\"%s\")" %(whitespace, whatwindow, > val) > " > attrs={u'title': u'example window title', u'name': u'SELF', u'icon': > u'e.ico'} > " > .. > Example Window Title = Tk() > ***^^^Example Window Title^^^*** > Example Window Title.title("Example Window Title") > Example Window Title.iconbitmap("Example Window Title") > SELF = Tk() > ***^^^SELF^^^*** > SELF.title("SELF") > SELF.iconbitmap("SELF") > e.ico = Tk() > ***^^^e.ico^^^*** > e.ico.title("e.ico") > e.ico.iconbitmap("e.ico") > " > > why would you think that the program would do this? Odd. I'd try a few things: 1) I'd make the keylist use unicode strings since thats what you use elsewhere. 2) I'd put a debugging print statement in at the top of the for loop to print out the tag values. That will show exactly what tag is set to and prove that the loop is being executed and how often 3) change the name of tag in the inner loop since as it is you are masking the name in the outer loop which is likely to cause strange behaviour. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Read dictionary data in a specific order...
"Trey Keown" <[EMAIL PROTECTED]> wrote I just spotted something. > for (tag,val) in attrs.iteritems(): >for tag in window_attrs_key_order: > print "%s%s = Tk()" %(whitespace, val) etc... You set tag and val in the outer loop, then you change tag in the innrter loop but you never change val. Thus for each tag in your list you print the same val. Then you gpo bavk to the outer loop and do the same for the next val. You need to rething your variable naming and how you access the val. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about classes
"Ara Kooser" <[EMAIL PROTECTED]> wrote > I am working on trying to understand classes by creating a > character generator for a rpg. You are so ar off base at the moment that I suggest you go back to basics and try a much simpler class. Your MAIN is not really a class at all, it's a function. Classes represent things(ie Objects). Main is not a thing. Secondly classes should not contain any directly executable code such as print/raw_input etc (they can but it's bad practice) Instead, a class should just be a collection of data attruibutes and methods. In your case it would be more appropriate to create a Character class with methods to do whatever characters do... > import random > > class Main: > >print """Welcome to the Classic Traveller character generator. > Written in Python""" >print """Press return to generate a character""" >raw_input() > > > >def upp(): methods of classes should have a first parameter of 'self' >print """Generating your UPP.""" >print > >strength = 0 >dexterity = 0 >endurance = 0 >intelligence = 0 >education = 0 >social = 0 > >strength = random.randrange(2,12) >dexterity = random.randrange(2,12) >endurance = random.randrange(2,12) >intelligence = random.randrange(2,12) >education = random.randrange(2,12) >social = random.randrange(2,12) There is no point in setting them all to zero then initialising them again via randrange. Just do it once. >return strength, dexterity, endurance, intelligence, > education, social But in a class you wouldn't expect to return these values here you would expect to store them as attributes of an object and return the object. >print upp() >def reroll(): > >a = raw_input("Are you satisfied with your UPP? Choose yes or > no.").lower() >try: > >if a == "yes": >career() > >elif a == "no": >upp() > >else: >print "Please choose a valid option." >print >reroll() > >except ValueError: >print "Please choose a valid option." >print >reroll() > >return > >print """You have a chance to reroll if needed.""" >reroll() > >def career(): >print """You will now choose are career path for your > character.""" Basically you don;t really have a class here at all you have a main function calling other functions but because you've wrapped them in a class its confusing things. Try simplifying your class to just define the attributes, something like this: class Upp: def __init__(self): print "Creating your Upp" self.strength = random.randrange(2,12) self.dexterity = random.randrange(2,12) self.endurance = random.randrange(2,12) self.intelligence = random.randrange(2,12) self.education = random.randrange(2,12) self.social = random.randrange(2,12) def display(self) print """ strength = %s dexterity = %s endurance = %s intelligence = %s education = %s social = %s""" % (self.strength, self.dexterity,self.endurance, self. intelligence,self.education, self.social) Now in your main function you can create Upps like so: #create 3 Upps: players = [] for p in range(3): players.append(Upp()) # show the players we created for p in players: p.display() If that is not clear then you need to go back to the tutorials again and work through the basics of wqhat a class and object are. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A fun puzzle
Dick Moores wrote: > At 12:12 PM 8/24/2007, Kent Johnson wrote: >> Dick Moores wrote: >>> At 10:22 AM 8/24/2007, Kent Johnson wrote: So you actually pasted that code into timeit.py? >>> Yeah. :-( I think I learned on the Tutor list to do it that way, but >>> I'm not sure. Thanks for showing me a correct way. >> >> I hope not! >> Using timeit more conventionally I get unsurprising results. This program has output: 0.497083902359 0.359513998032 which is more in line with what I would expect. >>> Using your exact code, I just got >>> 0.737564690484 >>> 1.17399585702 >>> Which is the reverse of your result, but on a slower computer. >>> What's up with that?? >> >> I have no idea. Some strange interaction with the memory cache? I'm >> running Python 2.5.1 on a MacBook Pro (Intel Core 2 Duo processor). >> How about you? > > Python 2.5; Dell Dimension 4600i; 2.80 gigahertz Intel Pentium 4. The > other day my computer guy put in a 512K stick of memory, making the > total 1024K. Wow, I don't think I've ever owned a computer with less than 32 Mb of memory! I hope you didn't pay him too much for that 1024K. > However, by doing so he shut off the dual channel memory. I understand > now that he should have put in a pair of 256k sticks to go with the > pair that were already there. Assuming you're meaning to talk about megabytes and not kilobytes, I'm not sure how easy it would be to get dual-channel 256 mb sticks anyway, the minimum I usually see is 512 (512x2 for 1024 total). Ah, never mind, I was wrong. Newegg has some 2x256MB sets for $30. -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about classes
On Aug 25, 2007, at 12:59 PM, Ara Kooser wrote: > Hello all, > >I am working on trying to understand classes by creating a > character generator for a rpg. I know I am doing something silly but I > am not sure what. When I run the program I and type no when prompted I > get the following message: > Traceback (most recent call last): > File "/Users/ara/Documents/ct_generator.py", line 10, in > class Main: > File "/Users/ara/Documents/ct_generator.py", line 68, in Main > reroll() > File "/Users/ara/Documents/ct_generator.py", line 53, in reroll > upp() > NameError: global name 'upp' is not defined > > I guess it doesn't recognize that I want to call the function upp() > again. I think I might be using the wrong syntax here. My code is > below. Thank you any help or guidance. This is exactly the level I'm at right now, so I got all excited and tried to solve this properly. Unfortunately I've hit a new snag, which I hope the OP or someone else can help me solve. At least the below should represent progress. Instead of calling general methods inside your class, you'll want to use the __init__ method, and then call the other methods from inside that, so that when a new instance of the class is created, all the methods act on that one new instance. That's what the first response was saying. So under __init__ we create a dictionary of attributes, and run both __upp and __career, all on the one new object. Showstats might as well be a separate function, because you'll want that available to players at any time. The new problem is the while loop inside __upp. Every time I say "no", and it generates a new set of attributes, it seems to add another "layer" of unfinished = True, so that once I've got attributes I like, I need to say "yes" as many times as I said "no" before it will let me break out of the loop and go on my way. I guess this is because it's calling the entire method over again, but I don't really understand this, or how else to get around it. Any solutions (and, obviously, general corrections of the whole thing) would be appreciated. Yrs, Eric == import random class Character(object): """Welcome to the Classic Traveller character generator. Written in Python """ def __init__(self): print "Generating statistics for your new character..." self.atts = {} self.__upp() self.__career() def __upp(self): for att in ('strength', 'dexterity', 'endurance', 'intelligence', 'education', 'social'): self.atts[att] = random.randrange(2,12) self.showstats() unhappy = True while unhappy: a = raw_input("Are you satisfied with your UPP? Choose yes or no.").lower() if a == "yes": unhappy = False elif a == "no": print "Rerolling attributes..." self.__upp() else: print "Please choose a valid option." continue return def __career(self): print "This is where the next step would go" def showstats(self): print "Your character's attributes are:" for attribute, value in self.atts.items(): print "%s: %d" % (attribute.title(), value) me = Character() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help Request: Nested While commands
Paul W Peterson wrote: > > Greeting! Greeting. Can you please make a new message next time you post to the list, instead of replying to an existing message and changing the subject line? There is more to an e-mail than just the subject, and threaded mail clients notice whether an e-mail is completely new or just a modified subject line, and consequently your e-mail was placed in the same thread as the "the and command" so your message got buried under an avalanche of unrelated discussion on my end. Thanks, -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about classes
"Eric Abrahamsen" <[EMAIL PROTECTED]> wrote > The new problem is the while loop inside __upp. Every time I say > "no", and it generates a new set of attributes, it seems to add > another "layer" of unfinished = True, so that once I've got > attributes I like, I need to say "yes" as many times as I said "no" Welcome to the wacky world of recursion. You call __upp from inside __upp so you do indeed generate a new layer, in fact you start a new while loop. You need to move the while loop out into init, something like this: class Character(object): def __init__(self): happy = False while not happy: upp = _upp() upp.showstats() ok = raw_input('Happy now?[y/n] ') if ok[0] in 'yY': happy = True def _upp(self): # all the randrange stuff self.career() def career(self): # all the career stuff But actually I'd take the whole happy test stuff outside the class entirely and make it a function: def getCharacter(): happy = False while not happy: upp = Character() upp.showstats() ok = raw_input('Happy now?[y/n] ') if ok[0] in 'yY': happy = True And the init becomes: def __init__(self) self._upp() self._career() That way the class only has to deal with creating an object and is much more reusable. Similarly for the career stuff, I'd put all the user interaction outside the class and then pass some kind of parameter(s) into the init method which passes them along to the career method def __init__(self, info=None) self._upp() if info == None: info = self.getCareerInfo() # does the interaction stuff if necessary self._career(info) HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about classes
> Welcome to the wacky world of recursion. > You call __upp from inside __upp so you do indeed generate > a new layer, in fact you start a new while loop. You need to > move the while loop out into init, something like this: So all those "yes"s were actually backing out of multiple while loops... Should have guessed that calling a method from inside itself was a bad idea. Thanks for your help, E ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about classes
"Eric Abrahamsen" <[EMAIL PROTECTED]> wrote >> Welcome to the wacky world of recursion. >> You call __upp from inside __upp so you do indeed generate >> a new layer, in fact you start a new while loop. You need to > > So all those "yes"s were actually backing out of multiple while > loops... Should have guessed that calling a method from inside > itself > was a bad idea. Actually recursion is a very powerful construction and not at all a bad idea, but it needs to be carefully controlled - as you discovered - but I have a topic on it in my tutorial (in the 'advanced' section) if you want to see some of the things it can be used for. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about classes
Ara Kooser wrote: > Hello all, > >I am working on trying to understand classes by creating a > character generator for a rpg. I know I am doing something silly but I > am not sure what. This is a procedural program wrapped in a class declaration. Just get rid of "class Main:" and outdent everything and it will work better. It is rare to have code other than function definitions (methods) and simple assignment (class attributes) in the body of a class. You might want to gather all the top-level code into a main() function and call that once, rather than intermingling the top-level code with the function definitions. You need to do a bit more reading about classes in Python, you clearly misunderstand. I don't have time to explain now but try the beginner tutorials. Kent > When I run the program I and type no when prompted I > get the following message: > Traceback (most recent call last): > File "/Users/ara/Documents/ct_generator.py", line 10, in > class Main: > File "/Users/ara/Documents/ct_generator.py", line 68, in Main > reroll() > File "/Users/ara/Documents/ct_generator.py", line 53, in reroll > upp() > NameError: global name 'upp' is not defined > > I guess it doesn't recognize that I want to call the function upp() > again. I think I might be using the wrong syntax here. My code is > below. Thank you any help or guidance. > > Ara > > ### > #Version: not even 0.1 > #By: Ara Kooser > # > > > import random > > > class Main: > > > > print """Welcome to the Classic Traveller character generator. > Written in Python""" > print """Press return to generate a character""" > > raw_input() > > > > def upp(): > print """Generating your UPP.""" > print > > strength = 0 > dexterity = 0 > endurance = 0 > intelligence = 0 > education = 0 > social = 0 > > strength = random.randrange(2,12) > dexterity = random.randrange(2,12) > endurance = random.randrange(2,12) > intelligence = random.randrange(2,12) > education = random.randrange(2,12) > social = random.randrange(2,12) > > return strength, dexterity, endurance, intelligence, education, social > > > print upp() > > def reroll(): > > a = raw_input("Are you satisfied with your UPP? Choose yes or > no.").lower() > try: > > if a == "yes": > career() > > elif a == "no": > upp() > > else: > print "Please choose a valid option." > print > reroll() > > except ValueError: > print "Please choose a valid option." > print > reroll() > > return > > print """You have a chance to reroll if needed.""" > reroll() > > def career(): > print """You will now choose are career path for your character.""" > > > > > > > > > > > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] using in over several entities
On 8/24/07, Chris Calloway <[EMAIL PROTECTED]> wrote Thanks everybody for their assistance! Makes my code a lot more elegant. -Tino ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor