Re: [Tutor] Using new style classes and __slots__
> Oh wait, I get it - you are passing bound methods to property(). So um is > bound to the instance when you access self.getA. Use Strange.getA instead of > self.getA, then use the normal signatures. Ahh... I get it. > But I don't get why you are doing this at all? Because some of the objects I'm working with have 65 attributes, each one needs to be typechecked and then passed down the line. As the knowledge of the file structure I'm reading is not complete, as it changes I'll have to update it. At the moment, what I'm doing is I have a docstring like so - """ Type: Track Item Tuple format: [0] header_id (4string) [1] header_length (int) [2] total_length (int)<-- (Of child strings + header) [3] num_of_strings (int) <-- (Above child strings) ... ... [62] unknown (int) [63] unknown (int) [64] unknown (int) """ and a struct string "4s6ih2c7i2h12iq2c3h10iq17i" Now, as knowledge of the format changes, so does that tuple format and struct string. I have a convenience function which parses my docstring for each class and creates a module dictionary of attribute name, type and length if applicable. It can also create a struct string based on those types. I can then call a generic set for all those attributes, which will pull the type out of the dict and check it, and also acts as a repository for attribute names. If the file structure changes, I simply update my doc string, call my convenience function, and my name:type dictionary is updated, as is my struct string. Alternatively, I can manually add header_id = property(..) and manually update the struct string and the doc string when something changes. However, on reflection, I just figured out that it'll be simpler using __setattr__ for this one, as I won't be able to get the attribute name using property() unless I use a function factory to generate 127 functions and use func.__name__, when using __setattr__ and a dictionary lookup is going to be much simpler. But, it's good to know how to use property. I can think of a couple of uses it for it. I wasn't thinking far enough ahead in this case, so please forgive my emailed meanderings. > It is passing self twice, because you are using a bound method as the > property method > rather than an unbound method. Erk. That seems obvious in hindsight, like a cryptic crossword answer. Once again, my lack of experience with this sorta stuff comes up. I've never really dealt with indepth oo stuff before, so this has all been a gigantic learning curve. Thanks for your help on this, Kent. >> This is a hassle for me because I'm a lazy typist, so I've been using >> setattr() to pull attribute names out of a list. And the first >> argument setattr() requires is an object, and self doesn't work >> outside of a method, and using the class name leads to no attribute >> being set. >I don't understand this at all, can you give an example? Basically, I just found that outside methods, "self" gives a NameError. The examples are all needless now, anyway. Regards, Liam Clarke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Error checking - very basic question
I have a call which needs to reply 2.1 or 2.8 and report an error if not: def ask_dau_version(): """Determine the product issue of the DAU.""" dau_version = None while dau_version not in ("2.8", "2.1"): dau_version = raw_input("\n\tIs the DAU a version 2.1 or 2.8, please enter only 2.1 or 2.8 ") print"\n\t\aError! - please enter only 2.1 or 2.8." else: print"" return dau_version I can see why it isn't working, the error message is in the wrong place, but I can't see a simple way around it (wood for the trees) Gaz ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] numbers from a name
On Sun, 2005-09-25 at 01:06 -0400, [EMAIL PROTECTED] wrote: > How could I change the program to accept something like: John Bob > Zelle Python or Kip Rada? > If it works for you with one word, all you need to make it accepts more is to add the space character " " with a weight of zero to "table". >>>table[' '] = 0 Alternatively, while creating the whole "table": table = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26, ' ': 0} Likewise, you could add the ',' (also with a weight of 0) for names like "Bob, Bob". Ziyad. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Error checking - very basic question
Garry Rowberry wrote: > def ask_dau_version(): > """Determine the product issue of the DAU.""" > dau_version = None > while dau_version not in ("2.8", "2.1"): > dau_version = raw_input("\n\tIs the DAU a version 2.1 or 2.8, please > enter only 2.1 or 2.8 ") > print"\n\t\aError! - please enter only 2.1 or 2.8." > else: > print"" > return dau_version > > I can see why it isn't working, the error message is in the wrong place, but > I can't see a simple way around it (wood for the trees) How about using a "while True" loop that you break out of only when a correct value has been identified: while True: dau_version = raw_input('blabla') if dau_version in ("2.8", "2.1"): break else: print "Error" -- Yours, Andrei = Mail address in header catches spam. Real contact info (decode with rot13): [EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] creating strings
I will use simple function: def getscore(val): if 90 < val <=100: return 'A' elif val >= 80: return 'B' elif val >= 70: return 'C' elif val >= 60: return 'D' else: return 'F' def main(): g = input('Enter score:') print 'the score of the exam is %s' % (getscore(int(g)))Cheers, pujo On 9/25/05, [EMAIL PROTECTED] <[EMAIL PROTECTED] > wrote: Hello How would I get the following program to accept inputs of exam scores from 0-100 with A being 100-90, B being 89-80, C being 79-70, D being 69-60, and F being everything less than 60? import string def main(): scores = ["F", "D", "C", "B", "A"] g = input("Enter a score number (0-100): ") print "The score of your exam is", scores [g-0] + "." main() ___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] Error checking - very basic question
Hi Garry, dau_version = None while dau_version not in ("2.8", "2.1"): dau_version = raw_input("\n\tIs the DAU a version 2.1 or 2.8, please enter only 2.1 or 2.8 ") print"\n\t\aError! - please enter only 2.1 or 2.8." else: print"" I don't know what they else is meant to do, I take it that's when your while loop exits. Here's how your code will run - dau_version = None (while statement) is dau_version "2.8" or "2.1"? Nope. dau_version = rawinput("Is...2.8") print "Error! - please enter only 2.1 or 2.8" is dau_version "2.8" or "2.1"? Yep - exit loop. Try doing it like this - while True: dau_version = raw_input("\n\tIs the DAU a version 2.1 or 2.8, please\ enter only 2.1 or 2.8 ") if dau_version in ("2.1", "2.8"): break print "Error! - please enter only 2.1 or 2.8" What will happen is that your while loop will loop forever (as True is always True). However, if dau_version is "2.1" or "2.8", the break command will be called, which exits out of the loop at that point. So your loop looks like this now - while True: get dau_version if dau_version is right, exit loop here. print error message Regards, Liam Clarke On 9/25/05, Garry Rowberry <[EMAIL PROTECTED]> wrote: > I have a call which needs to reply 2.1 or 2.8 and report an error if not: > > > def ask_dau_version(): > """Determine the product issue of the DAU.""" > dau_version = None > while dau_version not in ("2.8", "2.1"): > dau_version = raw_input("\n\tIs the DAU a version 2.1 or 2.8, please > enter only 2.1 or 2.8 ") > print"\n\t\aError! - please enter only 2.1 or 2.8." > else: > print"" > return dau_version > > I can see why it isn't working, the error message is in the wrong place, but > I can't see a simple way around it (wood for the trees) > > Gaz > > ___ > 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] creating strings
[EMAIL PROTECTED] wrote: > How would I get the following program to accept inputs of exam scores > from 0-100 with A being 100-90, B being 89-80, C being 79-70, D being > 69-60, and F being everything less than 60? > > import string There's no point in importing string. > def main(): > > scores = ["F", "D", "C", "B", "A"] > g = input("Enter a score number (0-100): ") > > print "The score of your exam is", scores [g-0] + "." > main() You could chain a bunch of if-statements. if g is between X1 and Y1: result is Z1 else if g is between X2 and Y2: result is Z2 else if ... -- Yours, Andrei = Mail address in header catches spam. Real contact info: ''.join([''.join(s) for s in zip( "[EMAIL PROTECTED] pmfe!Pes ontuei ulcpss edtels,s hr' one oC.", "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")]) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Error checking - very basic question
Hi Garry, break is essential for while loops like that one. You'll see that construct often enough in Python. While 1 or While True followed by an if : break Bit awkward, makes me miss the do - while construct. continue is very useful in for loops. Let's say I have a set of numbers, but I don't want to work with the number 5. I have a phobia or something. numbers = [1,2,3,4,5,6,7] for number in numbers: if number == 5: continue print number Continue will exit the loop at that point, but will continue with the next value in numbers. Try swapping break for continue. On 9/25/05, Garry Rowberry <[EMAIL PROTECTED]> wrote: > Thank you Liam, > > Works a treat, must look at the break and continue commands in more detail > > Regards > > Gaz > > -Original Message- > From: Liam Clarke [mailto:[EMAIL PROTECTED] > Sent: Sunday, September 25, 2005 12:10 PM > To: Garry Rowberry; Python Tutor Mailing List > Subject: Re: [Tutor] Error checking - very basic question > > Hi Garry, > dau_version = None > while dau_version not in ("2.8", "2.1"): > dau_version = raw_input("\n\tIs the DAU a version 2.1 or 2.8, > please > enter only 2.1 or 2.8 ") > print"\n\t\aError! - please enter only 2.1 or 2.8." > else: > print"" > > > I don't know what they else is meant to do, I take it that's when your > while loop exits. > > Here's how your code will run - > > dau_version = None > (while statement) is dau_version "2.8" or "2.1"? Nope. > dau_version = rawinput("Is...2.8") > print "Error! - please enter only 2.1 or 2.8" > is dau_version "2.8" or "2.1"? Yep - exit loop. > > Try doing it like this - > > while True: > dau_version = raw_input("\n\tIs the DAU a version 2.1 or 2.8, please\ >enter only 2.1 or 2.8 ") > if dau_version in ("2.1", "2.8"): >break > print "Error! - please enter only 2.1 or 2.8" > > > What will happen is that your while loop will loop forever (as True is > always True). > However, if dau_version is "2.1" or "2.8", the break command will be > called, which exits out of the loop at that point. > > So your loop looks like this now - > > while True: >get dau_version >if dau_version is right, exit loop here. >print error message > > Regards, > > Liam Clarke > On 9/25/05, Garry Rowberry <[EMAIL PROTECTED]> wrote: > > I have a call which needs to reply 2.1 or 2.8 and report an error if not: > > > > > > def ask_dau_version(): > > """Determine the product issue of the DAU.""" > > dau_version = None > > while dau_version not in ("2.8", "2.1"): > > dau_version = raw_input("\n\tIs the DAU a version 2.1 or 2.8, > please > > enter only 2.1 or 2.8 ") > > print"\n\t\aError! - please enter only 2.1 or 2.8." > > else: > > print"" > > return dau_version > > > > I can see why it isn't working, the error message is in the wrong place, > but > > I can't see a simple way around it (wood for the trees) > > > > Gaz > > > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Exception handling - syntaxerror?!
When I try to run the following piece of code, I get a SyntaxError, can someone help me out on this? try: ... os.system("cls") ... except: ... print "Foo" ... print "Bar" Traceback ( File "", line 5 print "Bar" ^ SyntaxError: invalid syntax What am I missing? Thanks in advance, Kris ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Exception handling - syntaxerror?!
On Sun, 2005-09-25 at 18:55 +0530, Krishna wrote: > When I try to run the following piece of code, I get a SyntaxError, > can someone help me out on this? > > try: > ... os.system("cls") > ... except: > ... print "Foo" > ... print "Bar" > Traceback ( File "", line 5 > print "Bar" > ^ > SyntaxError: invalid syntax > > What am I missing? > > Thanks in advance, > Kris What you're writing is this: try: os.system("cls") except: print "Foo" print "Bar" Which is wrong! Here's the correct way: try: os.system("cls") except: print "Foo" print "Bar" Note the indentation for "try:" and "except:"? They most be on the same level. This is how exception handling is done in Python. By the way, the last "print" statement, I didn't know if you want it to be printed all the time (like what I wrote it above) or just when there's an exception. Ziyad. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Exception handling - syntaxerror?!
On 25/09/05, ZIYAD A. M. AL-BATLY <[EMAIL PROTECTED]> wrote: > On Sun, 2005-09-25 at 18:55 +0530, Krishna wrote: > > When I try to run the following piece of code, I get a SyntaxError, > > can someone help me out on this? > > > > try: > > ... os.system("cls") > > ... except: > > ... print "Foo" > > ... print "Bar" > > Traceback ( File "", line 5 > > print "Bar" > > ^ > > SyntaxError: invalid syntax > > > > What am I missing? > > > > Thanks in advance, > > Kris > What you're writing is this: > try: > os.system("cls") > except: > print "Foo" > print "Bar" > > Which is wrong! Here's the correct way: > try: > os.system("cls") > except: > print "Foo" > print "Bar" > > > Note the indentation for "try:" and "except:"? They most be on the same > level. This is how exception handling is done in Python. > > By the way, the last "print" statement, I didn't know if you want it to > be printed all the time (like what I wrote it above) or just when > there's an exception. Think the mail system screwed up the formatting! But am fairly sure that I have indented it correctly in the console. Try and Except are in the column. Any other hints? BTW, I had just added the last print statement to see how try...except worked. Thanks for the response. -Kris > > Ziyad. > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] 'print' without newline or space appended
Hello, This statement: for c in 'hello': print c will generate following output: h e l l o and by adding comma at the end of the print statement: for c in 'hello': print c, we get this output: h e l l o How do I output something using 'print' such that there is no new line or space appended at the end of the output. Hehe... just answered my own question: import sys for c in 'hello' : sys.stdout.write(c) Is this the way to do it or is there a more appropriate approach. Thanks, Marcin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 'print' without newline or space appended
> Hello, > This statement: > for c in 'hello': print c > will generate following output: > h > e > l > l > o > and by adding comma at the end of the print statement: > for c in 'hello': print c, > we get this output: > h e l l o > How do I output something using 'print' such that there is no new line or > space appended at the end of the output. > > Hehe... just answered my own question: > import sys > for c in 'hello' : sys.stdout.write(c) > Is this the way to do it or is there a more appropriate approach. Also outstring = '' for c in 'hello': outstring += c print outstring ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Exception handling - syntaxerror?!
On Sun, 2005-09-25 at 19:44 +0530, Krishna wrote: > Think the mail system screwed up the formatting! But am fairly sure > that I have indented it correctly in the console. Try and Except are > in the column. Any other hints? Make sure you're not mixing "tabs" and "spaces". A lot of editors uses the ASCII "tab" character when hitting the Tab key, while other inserts 8 (or 4 on some cases) ASCII "space" character in that case. If you're sure "try:" and "except:" are on the same column, then the above advice is the only one I have for you. Sorry. > > BTW, I had just added the last print statement to see how try...except worked. > > Thanks for the response. You're welcome. > > -Kris > Ziyad. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Exception handling - syntaxerror?!
> Think the mail system screwed up the formatting! But am fairly sure > that I have indented it correctly in the console. Try and Except are > in the column. Any other hints? Yes :). Compare: >>> try: ... os.system('cls') ... except: ... print "Foo" ... Foo >>> print "Bar" Bar With (what you had): >>> try: ... os.system('cls') ... except: ... print "Foo" ... print "Bar" File "", line 5 print "Bar" ^ SyntaxError: invalid syntax Subtle, but important difference. You should terminate the try-except block (confirm with extra ENTER) before doing more stuff. -- Yours, Andrei = Mail address in header catches spam. Real contact info: ''.join([''.join(s) for s in zip( "[EMAIL PROTECTED] pmfe!Pes ontuei ulcpss edtels,s hr' one oC.", "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")]) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] __getattr__ causes TypeError
Hi, I experienced a strange side effect using a custom __getattr__ method. For a certain attribute, I'd like to return the value of another attribute if the former is not present. So I wrote: def __getattr__(self, attrname): if attrname == 'own_type': return self.child_type else: AttributeError, attrname But if I include this in my base class, I get a TypeError somewhere else: File "/Users/jan/Sites/janeden/cgi-bin/Pythonsite/Show.py", line 24, in Populate self.page_head = re.sub('%%author%%', self.first_name+' '+self.last_name, self.page_head) TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' How can this possibly be related? I am clueless. Best, Jan -- If all else fails read the instructions. - Donald Knuth ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __getattr__ causes TypeError
Sorry! Found the typo. - Jan Jan Eden wrote on 25.09.2005: >Hi, > >I experienced a strange side effect using a custom __getattr__ method. > >For a certain attribute, I'd like to return the value of another attribute if >the former is not present. So I wrote: > >def __getattr__(self, attrname): >if attrname == 'own_type': return self.child_type >else: AttributeError, attrname > >But if I include this in my base class, I get a TypeError somewhere else: > > File "/Users/jan/Sites/janeden/cgi-bin/Pythonsite/Show.py", line 24, in >Populate > self.page_head = re.sub('%%author%%', self.first_name+' '+self.last_name, >self.page_head) >TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' > >How can this possibly be related? I am clueless. > >Best, > >Jan -- Any sufficiently advanced technology is indistinguishable from a Perl script. - Programming Perl ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 'print' without newline or space appended
Thanks, This is the other 'work around'. I take there is no way to tell 'print' to do it, correct? Marcin - Original Message - From: "R. Alan Monroe" <[EMAIL PROTECTED]> To: "python-tutor" Sent: Sunday, September 25, 2005 10:29 AM Subject: Re: [Tutor] 'print' without newline or space appended >> Hello, > >> This statement: >> for c in 'hello': print c >> will generate following output: >> h >> e >> l >> l >> o >> and by adding comma at the end of the print statement: >> for c in 'hello': print c, >> we get this output: >> h e l l o >> How do I output something using 'print' such that there is no new line or >> space appended at the end of the output. > >> > >> Hehe... just answered my own question: >> import sys >> for c in 'hello' : sys.stdout.write(c) >> Is this the way to do it or is there a more appropriate approach. > > Also > > outstring = '' > for c in 'hello': >outstring += c > print outstring > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] help getting acronym to print?
Hello How could I get the following program to output UDP from the user entering user datagram protcol or IP if internet protocla was entered? currently it only prints out on letter import string def main(): phrase = (raw_input("Please enter a phrase:")) acr1 = string.split(phrase) print"",acr1 #only using print to see where I am acr2 = string.capwords(phrase) print"",acr2 #only using print to see where I am for phrase in string.split(phrase): acronym = string.upper(phrase[0]) print "", acronym main() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help getting acronym to print?
Didn't go through everything, but why do you do: >for phrase in string.split(phrase): > acronym = string.upper(phrase[0]) you are iterating with the name of the list? bad juju try something like acronym = "" for word in string.split(phrase): acronym = acronym + string.upper(word[0]) then the acronym variable will hold the initial letter to every word Hugo [EMAIL PROTECTED] wrote: > Hello > > How could I get the following program to output UDP from the user > entering user datagram protcol or IP if internet protocla was entered? > > currently it only prints out on letter > > > > import string > > def main(): > > >phrase = (raw_input("Please enter a phrase:")) > >acr1 = string.split(phrase) >print"",acr1 #only using print to see where I am > >acr2 = string.capwords(phrase) >print"",acr2 #only using print to see where I am >for phrase in string.split(phrase): > acronym = string.upper(phrase[0]) > >print "", acronym > main() > > > > > ___ > 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] Exception handling - syntaxerror?!
On 25/09/05, Andrei <[EMAIL PROTECTED]> wrote: > > Think the mail system screwed up the formatting! But am fairly sure > > that I have indented it correctly in the console. Try and Except are > > in the column. Any other hints? > > Yes :). Compare: > > >>> try: > ... os.system('cls') > ... except: > ... print "Foo" > ... > Foo > >>> print "Bar" > Bar > > With (what you had): > > >>> try: > ... os.system('cls') > ... except: > ... print "Foo" > ... print "Bar" >File "", line 5 > print "Bar" > ^ > SyntaxError: invalid syntax > > Subtle, but important difference. You should terminate the try-except > block (confirm with extra ENTER) before doing more stuff. When I have this piece of code in a function, it works fine. So is this some limitation of directly working out off the console? Seems the console supports complete code constructs only I.e., I can have one complete try...except block, a if block etc., but not a bunch of constructs? Is my assumption correct? Thanks. > > -- > Yours, > > Andrei ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor