Re: [Tutor] using re to build dictionary
Le Tue, 24 Feb 2009 12:48:51 +0100, Norman Khine nor...@khine.net s'exprima ainsi: Hello, From my previous post on create dictionary from csv, i have broken the problem further and wanted the lists feedback if it could be done better: s = 'Association of British Travel Agents (ABTA) No. 56542\nAir Travel Organisation Licence (ATOL)\nAppointed Agents of IATA (IATA)\nIncentive Travel Meet. Association (ITMA)' licences = re.split(\n+, s) licence_list = [re.split(\((\w+)\), licence) for licence in licences] association = [] for x in licence_list: ... for y in x: ... if y.isupper(): ...association.append(y) ... association ['ABTA', 'ATOL', 'IATA', 'ITMA'] In my string 's', I have 'No. 56542', how would I extract the '56542' and map it against the 'ABTA' so that I can have a dictionary for example: my_dictionary = {'ABTA': '56542', 'ATOL': '', 'IATA': '', 'ITMA': ''} Here is what I have so far: my_dictionary = {} for x in licence_list: ... for y in x: ... if y.isupper(): ... my_dictionary[y] = y ... my_dictionary {'ABTA': 'ABTA', 'IATA': 'IATA', 'ITMA': 'ITMA', 'ATOL': 'ATOL'} This is wrong as the values should be the 'decimal' i.e. 56542 that is in the licence_list. here is where I miss the point as in my licence_list, not all items have a code, all but one are empty, for my usecase, I still need to create the dictionary so that it is in the form: my_dictionary = {'ABTA': '56542', 'ATOL': '', 'IATA': '', 'ITMA': ''} Any advise much appreciated. Norman I had a similar problem once. The nice solution was -- I think, don't take this for granted I have no time to verify -- simply using multiple group with re.findall again. Build a rule like: r'.+(code-pattern).+(number_pattern).+\n+' Then the results will be a list of tuples like [ (code1, n1), (code2, n2), ... ] where some numbers will be missing. from this it's straightforward to instantiate a dict, maybe using a default None value for n/a numbers. Someone will probably infirm or confirm this method. denis -- la vita e estrany ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] using re to build dictionary
On Tue, Feb 24, 2009 at 6:48 AM, Norman Khine nor...@khine.net wrote: Hello, From my previous post on create dictionary from csv, i have broken the problem further and wanted the lists feedback if it could be done better: s = 'Association of British Travel Agents (ABTA) No. 56542\nAir Travel Organisation Licence (ATOL)\nAppointed Agents of IATA (IATA)\nIncentive Travel Meet. Association (ITMA)' licences = re.split(\n+, s) licence_list = [re.split(\((\w+)\), licence) for licence in licences] This is awkward. You can match directly on what you want: In [7]: import re In [8]: s = 'Association of British Travel Agents (ABTA) No. 56542\nAir Travel Organisation Licence (ATOL)\nAppointed Agents of IATA (IATA)\nIncentive Travel Meet. Association (ITMA)' In [9]: licenses = re.split(\n+, s) In [10]: licenseRe = re.compile(r'\(([A-Z]+)\)( No. (\d+))?') In [11]: for license in licenses: : m = licenseRe.search(license) : print m.group(1, 3) ('ABTA', '56542') ('ATOL', None) ('IATA', None) ('ITMA', None) Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String to list conversion
On Tue, Feb 24, 2009 at 10:16 AM, Taylan Karaman taylankara...@gmail.comwrote: Hello, I am a beginner. And I am trying to get a user input converted to a list. print 'Enter your first name :' firstname = raw_input() So if the user input is firstname = 'foo'---should become firstlist['f','o','o'] thanks in advance if I understand this correctly, you want a name like foo to be changed to ['f', 'o','o'] This is what the list function does. for example, name = foo list(name) ['f', 'o', 'o'] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.محمد الغزالي No victim has ever been more repressed and alienated than the truth Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String to list conversion
On Tue, Feb 24, 2009 at 10:16 AM, Taylan Karaman taylankara...@gmail.com wrote: Hello, I am a beginner. And I am trying to get a user input converted to a list. print 'Enter your first name :' firstname = raw_input() So if the user input is firstname = 'foo' ---should become firstlist['f','o','o'] Strings behave as sequences of characters, so you can just do firstname = 'foo' firstlist = list(firstname) If you just want to iterate over the letters, there is no need to create a separate list, you can iterate over the string directly, e.g. for letter in firstname: print letter Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple CGI script and Apache configuration
wormwood_3 wrote: I wasn't sure if that was needed, so I took it out, sorry about that. I put ScriptAlias /cgi-bin/ /var/www/samuelhuckins.com/cgi-bin/ in place, reloaded, and it works! I think the problem throughout was that I was mixing up what was necessary between CGI and mod_python. The apache2 documentation isn't clear about the relationship between ExecCGI and ScriptAlias (rather, it's not clear to me) and unless I've missed something, seems to imply that either ScriptAlias or ExecCGI alone should be sufficient. Unfortunately, I don't have time to experiment. IIRC, all of the vanilla apache configs I've worked with recently include both in definitions for cgi-bin. In any case, glad it worked. If you'd like a random programming epigram served up by this new config, check out: http://samuelhuckins.com/cgi-bin/qotd.py Very cool, thanks. -Sam wormwood_3 wrote: Thanks for all the suggestions! I tried to go through them, and will relate what results I encountered. I changed my Apache config to: Directory /var/www/samuelhuckins.com/cgi-bin/ AllowOverride None Options ExecCGI Order allow,deny Allow from all /Directory I in fact did not have the cgi module enabled, so I did that. Then I ran sudo /etc/init.d/apache2 reload, and hit http://samuelhuckins.com/cgi-bin/hello.py, which contains simply: #!/usr/bin/python print Content-type: text/html print print html print centerHello!/center print /html I get prompted to download the file, but it does not execute or appear in plain text. The logs just show the request being made. What is the missing element to get this script to execute? When you look at the downloaded file, is it your python script? Looks like you changed the path where you're keeping your cgi script, did you update the ScriptAlias directive to suit? You may find this more helpful ... http://httpd.apache.org/docs/2.0/howto/cgi.html ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String to list conversion
Or, you could do: In [1]: print list(raw_input('name please...')) name please...John ['J', 'o', 'h', 'n'] Robert Berman Kent Johnson wrote: On Tue, Feb 24, 2009 at 10:16 AM, Taylan Karaman taylankara...@gmail.com wrote: Hello, I am a beginner. And I am trying to get a user input converted to a list. print 'Enter your first name :' firstname = raw_input() So if the user input is firstname = 'foo' ---should become firstlist['f','o','o'] Strings behave as sequences of characters, so you can just do firstname = 'foo' firstlist = list(firstname) If you just want to iterate over the letters, there is no need to create a separate list, you can iterate over the string directly, e.g. for letter in firstname: print letter Kent ___ 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] Passing perimeters in dictionary values?
I'm experimenting with OOP using the Critter Caretaker script from Python Programming for the Absolute Beginner as my basis. I've noticed that a dictionary/function combo is a great way to handle menus, and so I've adapted the menu to read as: selection = raw_input(Choice: ) choices = {0:quit, 1:crit.talk, 2:crit.eat, 3:crit.play} choice = choices[selection] choice() so that I can call methods from a dictionary, instead of having an excruciatingly long if structure. Unfortunately, the problem I'm running into with this is that I can't pass any perimeters through the dictionary. I can't figure out how, for example, I could have an option that calls crit.eat(2) and another that calls crit.eat(4). The only thing I can think of is going back to the if structure, but my instinct tells me that this is a Bad Idea. What can I do? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Accessing callers context from callee method
Le Tue, 24 Feb 2009 10:53:29 -0800, mobiledream...@gmail.com s'exprima ainsi: when i call a method foo from another method func. can i access func context variables or locals() from foo so def func(): i=10 foo() in foo, can i access func's local variables on in this case i Thanks a lot def func(): i=10 foo(i) -- la vita e estrany ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing parameters in dictionary values?
From: nathan virgil sdragon1...@gmail.com selection = raw_input(Choice: ) choices = {0:quit, 1:crit.talk, 2:crit.eat, 3:crit.play} choice = choices[selection] choice() ...so that I can call methods from a dictionary the problem I'm running into with this is that I can't pass any perimeters through the dictionary. What can I do? choices = {'a': lambda: crit.eat(2), 'b': lambda: crit.eat(4), ...} choice = choices[selection] choice() http://www.diveintopython.org/power_of_introspection/lambda_functions.html ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Accessing callers context from callee method
On Tue, Feb 24, 2009 at 10:53 AM, mobiledream...@gmail.com wrote: when i call a method foo from another method func. can i access func context variables or locals() from foo so def func(): i=10 foo() in foo, can i access func's local variables on in this case i You can, but it's an evil hack that I would avoid if at all possible; there are almost certainly better ways to accomplish whatever your goal is. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing perimeters in dictionary values?
Le Tue, 24 Feb 2009 14:03:09 -0500, nathan virgil sdragon1...@gmail.com s'exprima ainsi: I'm experimenting with OOP using the Critter Caretaker script from Python Programming for the Absolute Beginner as my basis. I've noticed that a dictionary/function combo is a great way to handle menus, and so I've adapted the menu to read as: selection = raw_input(Choice: ) choices = {0:quit, 1:crit.talk, 2:crit.eat, 3:crit.play} choice = choices[selection] choice() This is (to my taste) very good programming practice. The only detail is that in this precise case, as keys are ordinals starting at 0, you can use a simple list instead ;-) and choice = choices[int(selection)] so that I can call methods from a dictionary, instead of having an excruciatingly long if structure. Unfortunately, the problem I'm running into with this is that I can't pass any perimeters through the dictionary. I can't figure out how, for example, I could have an option that calls crit.eat(2) and another that calls crit.eat(4). The only thing I can think of is going back to the if structure, but my instinct tells me that this is a Bad Idea. What can I do? There is a syntactic trick for this, commonly called *args. You can call a function and pass it a variable holding a 'pack' of arguments prefixed with '*' so that the args will be automagically unpacked into the call message. Below an example: def sum(a,b): return a+b arg_list = (1,2) func_calls = {1:sum(*arg_list)} print func_calls[1] == 3 Like if I had written sum(1,2) -- except that the arg_list can now be unknown at design time! Conversely, when you want a function to accept an arbitrary number of args, you can write its def using the * trick: def sum(*values): s = 0 for v in values : s+= v return s print sum(1), sum(1,2), sum(1,2,3) == 1, 3, 6 There is a similar trick for named arguments using ** denis -- la vita e estrany ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing perimeters in dictionary values?
On Tue, Feb 24, 2009 at 2:03 PM, nathan virgil sdragon1...@gmail.com wrote: I'm experimenting with OOP using the Critter Caretaker script from Python Programming for the Absolute Beginner as my basis. I've noticed that a dictionary/function combo is a great way to handle menus, and so I've adapted the menu to read as: selection = raw_input(Choice: ) choices = {0:quit, 1:crit.talk, 2:crit.eat, 3:crit.play} choice = choices[selection] choice() so that I can call methods from a dictionary, instead of having an excruciatingly long if structure. Unfortunately, the problem I'm running into with this is that I can't pass any perimeters through the dictionary. I can't figure out how, for example, I could have an option that calls crit.eat(2) and another that calls crit.eat(4). The only thing I can think of is going back to the if structure, but my instinct tells me that this is a Bad Idea. What can I do? You can define a function that does what you want: def eat2(): crit.eat(2) Then put eat2 in your dictionary: choices = { '2': eat2, ...} Alternately you can use lambda expressions to do the same thing without an explicit def: choices = { '2': lambda: crit.eat(2), ... } Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing perimeters in dictionary values?
On Tue, Feb 24, 2009 at 2:35 PM, spir denis.s...@free.fr wrote: Le Tue, 24 Feb 2009 14:03:09 -0500, nathan virgil sdragon1...@gmail.com s'exprima ainsi: so that I can call methods from a dictionary, instead of having an excruciatingly long if structure. Unfortunately, the problem I'm running into with this is that I can't pass any perimeters through the dictionary. I can't figure out how, for example, I could have an option that calls crit.eat(2) and another that calls crit.eat(4). The only thing I can think of is going back to the if structure, but my instinct tells me that this is a Bad Idea. What can I do? There is a syntactic trick for this, commonly called *args. You can call a function and pass it a variable holding a 'pack' of arguments prefixed with '*' so that the args will be automagically unpacked into the call message. Below an example: def sum(a,b): return a+b arg_list = (1,2) func_calls = {1:sum(*arg_list)} print func_calls[1] == 3 Like if I had written sum(1,2) -- except that the arg_list can now be unknown at design time! I don't think this is addressing the OP's question. Your dict will contain the result of calling sum(1, 2). He wants a callable which he can call later. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Accessing callers context from callee method
when i call a method foo from another method func. can i access func context variables or locals() from foo so def func(): i=10 foo() in foo, can i access func's local variables A. python has statically-nested scoping, so you can do it as long as you: 1. define foo() as an inner function -- its def is contained within func()'s def: def func(): i = 10 def foo(): print i 2. you don't define a variable with the same name locally. in other words, you do have access to func()'s 'i' as long as you don't create another 'i' within foo() -- if you do, only your new local 'i' will be within your scope. B. another alterative is to pass in all of func()'s local variables to foo(): foo(**locals()) this will require you to accept the incoming dictionary in foo() and access the variables from it instead of having them be in foo()'s scope. C. in a related note, your question is similar to that of global vs. local variables. inside a function, you have access to the global as long as you don't define a local using the same name. should you only wish to manipulate the global one, i.e. assign a new value to it instead of creating a new local variable with that name, you would need to use the global keyword to specify that you only desire to use and update the global one. i = 0 def func(): i = 10 in this example, the local 'i' in func() hides access to the global 'i'. in the next code snippet, you state you only want to access/update the global 'i'... IOW, don't create a local one: i = 0 def func(): global i i = 10 D. this doesn't work well for inner functions yet: i = 0 def func(): i = 10 def foo(): i = 20 the 'i' in foo() shadows/hides access to func()'s 'i' as well as the global 'i'. if you issue the 'global' keyword, that only gives you access to the global one: i = 0 def func(): i = 10 def foo(): global i i = 20 you cannot get access to func()'s 'i' in this case. E. however, starting in Python 3.x, you'll be able to do somewhat better with the new 'nonlocal' keyword: i = 0 print('globally, i ==', i) def func(): i = 10 print('in func(), i ==', i) def foo(): nonlocal i i = 20 print('in foo(), i ==', i) foo() print('in func() after calling foo(), i ==', i) func() in this case, foo() modified func()'s 'i'. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Core Python Programming, Prentice Hall, (c)2007,2001 Python Fundamentals, Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing perimeters in dictionary values?
On Tue, Feb 24, 2009 at 5:13 PM, nathan virgil sdragon1...@gmail.com wrote: I'm not familiar with lambdas yet, and I don't think this book will introduce me to them; they aren't listed in the index, anyway. Here are two brief introductions: http://docs.python.org/tutorial/controlflow.html#lambda-forms http://www.ibiblio.org/swaroopch/byteofpython/read/lambda-forms.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Accessing callers context from callee method
mobiledream...@gmail.com wrote when i call a method foo from another method func. can i access func context variables or locals() from foo Yes and there are several ways to do it, but nearly always this is a bad idea. It will make foo almost totally unusable in any other context since it will rely on the calling function having local variables of a specific name (and possibly type). It is usually much better to pass the variables into foo at call time. Or even to use global variables! def func(): i=10 foo() How would you write foo? Would you require the variable in func() to be called i? Or would you assign a referece to it using a dictionary to access it? Can you explain what you really want to do with this? What is the motivation behind the request? There is probably a better alternative... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing perimeters in dictionary values?
On Tue, Feb 24, 2009 at 8:03 PM, nathan virgil sdragon1...@gmail.com wrote: I'm experimenting with OOP using the Critter Caretaker script from Python Programming for the Absolute Beginner as my basis. I've noticed that a dictionary/function combo is a great way to handle menus, and so I've adapted the menu to read as: selection = raw_input(Choice: ) choices = {0:quit, 1:crit.talk, 2:crit.eat, 3:crit.play} choice = choices[selection] choice() so that I can call methods from a dictionary, instead of having an excruciatingly long if structure. Unfortunately, the problem I'm running into with this is that I can't pass any perimeters through the dictionary. I can't figure out how, for example, I could have an option that calls crit.eat(2) and another that calls crit.eat(4). The only thing I can think of is going back to the if structure, but my instinct tells me that this is a Bad Idea. What can I do? You could use a tuple, consisting of the function and its parameter: choices = {0: (quit,), 1: (eat,2), 2: (eat,4)} choice = choices[selection] choice[0](*choice[1:]) But as said by someone else, if the choices are the lowest n natural numbers, a list feels more natural: choices = [(quit,), (eat,2), (eat,4)] choices = choice[int(selection)] choice[0](*choice[1:]) -- André Engels, andreeng...@gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing perimeters in dictionary values?
On Wed, Feb 25, 2009 at 12:47 AM, Andre Engels andreeng...@gmail.com wrote: - Show quoted text - On Tue, Feb 24, 2009 at 8:03 PM, nathan virgil sdragon1...@gmail.com wrote: I'm experimenting with OOP using the Critter Caretaker script from Python Programming for the Absolute Beginner as my basis. I've noticed that a dictionary/function combo is a great way to handle menus, and so I've adapted the menu to read as: selection = raw_input(Choice: ) choices = {0:quit, 1:crit.talk, 2:crit.eat, 3:crit.play} choice = choices[selection] choice() so that I can call methods from a dictionary, instead of having an excruciatingly long if structure. Unfortunately, the problem I'm running into with this is that I can't pass any perimeters through the dictionary. I can't figure out how, for example, I could have an option that calls crit.eat(2) and another that calls crit.eat(4). The only thing I can think of is going back to the if structure, but my instinct tells me that this is a Bad Idea. What can I do? You could use a tuple, consisting of the function and its parameter: choices = {0: (quit,), 1: (eat,2), 2: (eat,4)} choice = choices[selection] choice[0](*choice[1:]) But as said by someone else, if the choices are the lowest n natural numbers, a list feels more natural: choices = [(quit,), (eat,2), (eat,4)] choices = choice[int(selection)] choice[0](*choice[1:]) That last one should of course be: choices = [(quit,), (eat,2), (eat,4)] choice = choices[int(selection)] choice[0](*choice[1:]) -- André Engels, andreeng...@gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing perimeters in dictionary values?
nathan virgil sdragon1...@gmail.com wrote in selection = raw_input(Choice: ) choices = {0:quit, 1:crit.talk, 2:crit.eat, 3:crit.play} choice = choices[selection] choice() so that I can call methods from a dictionary, instead of having an excruciatingly long if structure. Unfortunately, the problem I'm running into with this is that I can't pass any perimeters through the dictionary. Yes you can. choice(x) will work as will choices[selection](param) So you can do something like: selection = raw_input(Choice: ) param = raw_input('Value: ') choices = {0:quit, 1:crit.talk, 2:crit.eat, 3:crit.play} choice = choices[selection] choice(param) Or you can build the param value into the dictionary: selection = raw_input(Choice: ) choices = { 0:(quit, None), 1:(crit.talk, Hi there), 2:(crit.eat, Nuts), 3: (crit.play, Soccer) 4: (crit.play, Baseball)} # same func different param choice = choices[selection] choice[0](choice[1]) There are plenty other ways too. I can't figure out how, for example, I could have an option that calls crit.eat(2) and another that calls crit.eat(4). The question is where are the 2 and 4 coming from? You could read them from the user or a file in option 1 above or store them with the function under a different menu in option 2. Or of course you could just hard code them at call time... It depends how you want to use it... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing perimeters in dictionary values?
nathan virgil sdragon1...@gmail.com wrote I'm not familiar with lambdas yet, and I don't think this book will introduce me to them; they aren't listed in the index, anyway. lambda is just a fancy mathematical name for a simple concept - its a block of code, like the body of a function. In Python its even simpler, it is an expression. And we store that expression and make it callable. def funcname(aParam): return expression using aParam is the same as funcname = lambda aParam: expression using aParam In some languages, including some Lisp dialects function definitions are syntactic sugar for exactly that kind of lambda assignment. Some even make it explicit as in: (define func ( lambda (aParam) (expression using aParam))) In Python its more like the other way around, functions are defined using def and lambdas are really syntax wrapped around that. lambdas are often offputting to beginners but they are useful in avoiding lots of small oneliner type functions (and the resultant namespace clutter) and they are very important in understanding the theory behind computing (ie. Lambda calculus). HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing perimeters in dictionary values?
On Tue, Feb 24, 2009 at 6:50 PM, Alan Gauld alan.ga...@btinternet.comwrote: Or you can build the param value into the dictionary: selection = raw_input(Choice: ) choices = { 0:(quit, None), 1:(crit.talk, Hi there), 2:(crit.eat, Nuts), 3: (crit.play, Soccer) 4: (crit.play, Baseball)} # same func different param choice = choices[selection] choice[0](choice[1]) This actually suits my needs wonderfully. Thanks! I can't figure out how, for example, I could have an option that calls crit.eat(2) and another that calls crit.eat(4). The question is where are the 2 and 4 coming from? You could read them from the user or a file in option 1 above or store them with the function under a different menu in option 2. Or of course you could just hard code them at call time... It depends how you want to use it... The critter has attributes for hunger and boredom; if you do anything but eat (for hunger) or play (for boredom), the attribute value goes up, and affects the critter's mood. If you access the right method, the corresponding attribute will go down by a certain value. As it is right now, it only uses the default value, but I was thinking of having different options for the method. Maybe the critter finds cabbage more tasty/filling then lettuce, or maybe it prefers playing baseball over playing soccer. This could be represented by having cabbage represented by crit.eat(4) and lettuce by crit.eat(2). In this case, getting the perimeters directly from the user would be a Very Bad Idea, but I'm sure there's some scenarios where it wouldn't be. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ 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] Passing perimeters in dictionary values?
Erm, it's still not working... Whenever I try to use the talk method (which reports the mood, and doesn't take parameters), it says I gave it too many parameters. Maybe it might help if I posted the code in it's entirety # Critter Caretaker # A virtual pet to care for class Critter(object): A virtual pet def __init__(self, name, hunger = 0, boredom = 0): self.name = name self.hunger = hunger self.boredom = boredom def __pass_time(self): self.hunger += 1 self.boredom += 1 def __get_mood(self): unhappiness = self.hunger + self.boredom if unhappiness 5: mood = happy elif 5 = unhappiness = 10: mood = okay elif 11 = unhappiness = 15: mood = frustrated else: mood = mad return mood mood = property(__get_mood) def talk(self): print I'm, self.name, and I feel, self.mood, now.\n self.__pass_time() def eat(self, food = 4): print Brruppp. Thank you. self.hunger -= food if self.hunger 0: self.hunger = 0 self.__pass_time() def play(self, fun = 4): print Wheee! self.boredom -= fun if self.boredom 0: self.boredom = 0 self.__pass_time() def backdoor(self): print hunger:, self.hunger, boredom:, self.boredom def quit(): print God-bye! def main(): crit_name = raw_input(What do you want to name your critter?: ) crit = Critter(crit_name) selection = None while selection != 0: print \ Critter Caretaker 0 - Quit 1 - Listen to your critter 2 - Feed your critter 3 - Play with your critter selection = raw_input(Choice: ) choices = {0:(quit, None), 1:(crit.talk, None), 2:(crit.eat, 3), 3:(crit.play, 3), Xyzzy:(crit.backdoor, None)} if selection in choices: choice = choices[selection] choice[0](choice[1]) main() (\n\nPress the enter key to exit.) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing perimeters in dictionary values?
nathan virgil wrote: Erm, it's still not working... snip if selection in choices: choice = choices[selection] choice[0](choice[1]) s/bchoice[0]() main() (\n\nPress the enter key to exit.) hth, Emile ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] calling user defined function
On Sun, 22 Feb 2009 22:21:22 +0100, roberto wrote: hello i have a question which i didn't solved yet: i can define a function using the text editor provided by IDLE 3.0; then i'd like to call this function from the python prompt but when i try to do it, python warns me that function doesn't exist of course if i define the function directly using the prompt, after that everything is fine may you tell me where i have to save the file that defines the function is order to use it later ? is it a problem of path ? my version of python is 3.0, OS windows xp thank you very much in advance or you can also run your module with -i (interactive) argument, which means to put you into the interactive mode after the module ends. # mycode.py def foo(): print 'bar' print 'output of program (if any)' # then run this in your shell: $ python -i mycode.py output of program (if any) foo() bar ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing perimeters in dictionary values?
On Tue, 24 Feb 2009 18:26:29 -0500, Kent Johnson wrote: On Tue, Feb 24, 2009 at 5:13 PM, nathan virgil sdragon1...@gmail.com wrote: I'm not familiar with lambdas yet, and I don't think this book will introduce me to them; they aren't listed in the index, anyway. Nobody remembers partial? from functools import partial newfunc = partial(myfunc, 1, 2, 3) newfunc() {'eatgrass': partial(eat, 'grass'), 'eatcarrot': partial(eat, 'carrot')} ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String to list conversion
name like foo to be changed Nitpick: foo is a string, not a name... ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Formatting
hi. s = 'Association of British Travel Agents (ABTA) No.56542\nAir Travel Organisation Licence (ATOL)\nAppointed Agents ofIATA (IATA)\nIncentive Travel Meet. Association (ITMA)' licenses = re.split(\n+, s) licenseRe = re.compile(r'\(([A-Z]+)\)( No. (\d+))?') for license in licenses: m = licenseRe.search(license) print m.group(1, 3) ('ABTA', None) ('ATOL', None) ('IATA', None) ('ITMA', None) The no 56542 is not getting into m.group() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Formatting
On Wed, Feb 25, 2009 at 10:37 AM, prasad rao prasadarao...@gmail.com wrote: licenseRe = re.compile(r'\(([A-Z]+)\)( No. (\d+))?') Change that to: licenseRe = re.compile(r'\(([A-Z]+)\)\s*(No.\d+)?') It now works. Thanks, Senthil ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Accessing callers context from callee method
mobiledream...@gmail.com wrote: when i call a method foo from another method func. can i access func context variables or locals() from foo so def func(): i=10 foo() in foo, can i access func's local variables on in this case i As others have already pointed out, this is a really bad idea. Instead you can do: def func(): i = 10 i = foo(i) def foo(i): i = i + 1 return i Sincerely, Albert ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor