Re: [Tutor] How to use a str object, to find the class in exact name?
On 3/14/2011 8:49 PM, Yaşar Arabacı wrote: As I try to implement things with getattr, I am getting a really strange error. This is my file: Various interspersed comments: #!/usr/bin/env python # -*- encoding:utf-8 -*- class global_variables: It is customary to start class names with an uppercase letter "Holds class attributes, so that other classes can share them" products = 0 best_bundle = [] class dispatcher: def GetMethod(self,class_name,method_name): It is customary to start method names with a lowercase letter """This method first finds a class if desired classexists. Then, instansites it, and returns a reference to desired method of the instance it created. """ from sys import modules It is customary to place import statements close to the top of the program, not in any class or function. module = modules[self.__module__] if hasattr(module,class_name): What are the module's attributes? insert print dir(module) to see ALL the attributes. print "#debug : hasattr is true" cls = getattr(module,class_name) else: print "#debug : hasattr is false" return None "if we get a valid class, lets instantie it" if cls: a=cls() else: return None return hasattr(a,method_name) and getattr(a,method_name) or None def dispatch_command(self): """Gets command from user, finds appropriate Class/method to run and then runs it. Beware of the fact that, to be able to successfully run the method, method should take exactly two arguments, arg 1: instance of class which method resides (e.g. self) arg 2: list of other needed variables list of other variables can be used to get as many variables as possible """ command = raw_input(">>>") args = command.split(" ") if len(args) < 2: return None method = self.GetMethod(args[0],args[1]) return method and method(args[2:]) or None class calculate(global_variables): def bundle(self,args): print "your best bundle is -->" a = dispatcher() a.dispatch_command() Alternative 1 - put all the user-callable class definitions inside a Container class (or whatever name you want) - then use getattr on the Container class class Container: class Calculate(global_variables): def bundle(self,args): print "your best bundle is -->" Alternative 2 - use the following to create a dictionary of classes in which you look up the desired class by name import sys, inspect thisModule = sys.modules[__name__] classDict = dict((name.lower(), value) for name, value in inspect.getmembers(thisModule, inspect.isclass)) ... cls = classDict[className] Alternative 3 cls = getattr(module,class_name) try: if issubclass(cls, global_variables) a=cls() except TypeError: pass I wanted to see what happens when someone gives an nonexistent function. But when I put a b, it gives me error, when I put c d it doesn't. I don't have either a or c classes, but a somehow causes problems :S This is what I did: yasar@yasar-laptop:~/best_buy> ./main.py >>>a b #debug : hasattr is true Traceback (most recent call last): File "./main.py", line 57, in a.dispatch_command() File "./main.py", line 44, in dispatch_command method = self.GetMethod(args[0],args[1]) File "./main.py", line 25, in GetMethod a=cls() AttributeError: dispatcher instance has no __call__ method The error tells you what a is. Isn't it obvious now? Remember to read and understand such messages. yasar@yasar-laptop:~/best_buy> ./main.py >>>c d #debug : hasattr is false -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simplistic drive simulation
> "R. Alan Monroe" wrote >> Neither of these seem like they'd scale very well (say, up to the >> resolution of your screen, with one block per pixel). The end goal >> is >> just a basic do-nothing light show that simulates >> fragmentation/defragmentation as eye candy. > For that purpose the basic style you are using will be adequate. > You are only talking about 2-5 million pixels at most on > typical monitors. Usually more like 1.5 million on a laptop. > And you are not too worried about speed, in fact too fast a > display would just be wasted as most chanmges would > never be seen! Here's my first cut. One thing that surprised me is that none of the earlier generation (single and double digit filenames) ever survive to the 80th generation. My expectation was that I would end up with a wider range of generations in the end. Alanclass Disk(list): def __init__(self, disksize): self.size = disksize self.free = disksize self.files = {} for i in range(self.size): self.append(None) def __str__(self): s = int(math.sqrt(len(self))) outstr = "" for row in range(s): for col in range(s): if self[row*s + col]==None: outstr += " " else: outstr += "%4d " % (self[row*s + col],) outstr += "\n" for i in self.files.items(): outstr += str(i) outstr += '\n' return outstr def fwrite(self, filename, filelen): if self.free >= filelen: self.files[filename] = [] block = 0 for i in range(filelen): while self[block] != None: block += 1 self[block]=filename self.files[filename].append(block) self.free -= filelen else: raise IndexError def fdel(self, filename): for i in self.files[filename]: self[i] = None self.free += len(self.files[filename]) del self.files[filename] import math import random #DISKSIZE = 64 #DISKSIZE = 100 #DISKSIZE = 144 #DISKSIZE = 256 #DISKSIZE = 1024 DISKSIZE = 2048 disk = Disk(DISKSIZE) countup = 0 for i in range(80): while disk.free / float(DISKSIZE) > 0.05: #fill er up try: countup += 1 attemptsize = int(random.paretovariate(1)) + 1 disk.fwrite(countup, attemptsize) except IndexError: print "full", countup, attemptsize while disk.free / float(DISKSIZE) < 0.20: #trim er down attemptdel = random.choice(disk.files.keys()) disk.fdel(attemptdel) print disk, disk.free ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to use a str object, to find the class in exact name?
As I try to implement things with getattr, I am getting a really strange error. This is my file: #!/usr/bin/env python # -*- encoding:utf-8 -*- class global_variables: "Holds class attributes, so that other classes can share them" products = 0 best_bundle = [] class dispatcher: def GetMethod(self,class_name,method_name): """This method first finds a class if desired classexists. Then, instansites it, and returns a reference to desired method of the instance it created. """ from sys import modules module = modules[self.__module__] if hasattr(module,class_name): print "#debug : hasattr is true" cls = getattr(module,class_name) else: print "#debug : hasattr is false" return None "if we get a valid class, lets instantie it" if cls: a=cls() else: return None return hasattr(a,method_name) and getattr(a,method_name) or None def dispatch_command(self): """Gets command from user, finds appropriate Class/method to run and then runs it. Beware of the fact that, to be able to successfully run the method, method should take exactly two arguments, arg 1: instance of class which method resides (e.g. self) arg 2: list of other needed variables list of other variables can be used to get as many variables as possible """ command = raw_input(">>>") args = command.split(" ") if len(args) < 2: return None method = self.GetMethod(args[0],args[1]) return method and method(args[2:]) or None class calculate(global_variables): def bundle(self,args): print "your best bundle is -->" a = dispatcher() a.dispatch_command() I wanted to see what happens when someone gives an nonexistent function. But when I put a b, it gives me error, when I put c d it doesn't. I don't have either a or c classes, but a somehow causes problems :S This is what I did: yasar@yasar-laptop:~/best_buy> ./main.py >>>a b #debug : hasattr is true Traceback (most recent call last): File "./main.py", line 57, in a.dispatch_command() File "./main.py", line 44, in dispatch_command method = self.GetMethod(args[0],args[1]) File "./main.py", line 25, in GetMethod a=cls() AttributeError: dispatcher instance has no __call__ method yasar@yasar-laptop:~/best_buy> ./main.py >>>c d #debug : hasattr is false ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to use a str object, to find the class in exact name?
Yaşar Arabacı wrote: And What I want to do is a small economy application. It will work this way: user add a product name, rate how much it like it over 10, and enter its price. [repeated as many times as wanted] user will enter h(is|er) budget. user will use "calcute bundle" to show much of each product s?he should buy user will repeat any step as long as s?he likes. My advice is not to mix the backend calculation engine with the frontend user interface in the same code. Keep them separate. So you should write your classes and functions to: * store products and prices * calculate best buys for a budget * etc. And then have a separate function for the user interface, which handles: * input and output to the user * converting the user's text input to numbers, products, etc. * calling the calculation functions * printing the results (The frontend and backend can be in the same file, but they should be separate functions or classes.) At the moment, your code combines calculation with user-interface, which is a poor design: class calculate: @staticmethod def bundle(): print "your best bundle is -->" You have the class responsible for calculating the bundle also responsible for displaying it to the user. It is better to separate those two functions, and have one class for calculating the bundle and returning it (not printing it!) and another function or class responsible for calling the calculate class with the user's input, and displaying the output to the user. This will let you more easily change the user-interface, without needing to change the engine. Want to put your application in a GUI, or on a website? Change the user-interface parts, not the engine. Hope this helps! -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to use a str object, to find the class in exact name?
Before being able to see 3rd answer, I did something like this and it worked for me: #!/usr/bin/env python # -*- encoding:utf-8 -*- def command_dispatcher(): "Takes comman line arguments and executes regardin method" command = raw_input(">>>") args = command.split(" ") query_string = ".".join(args[0:2]) method_args = ",".join(args[2:]) try: exec query_string+"("+method_args+")" except NameError: print "You are trying to get somethin that is not exist!" class calculate: @staticmethod def bundle(): print "your best bundle is -->" command_dispatcher() But after reading 3rd answer regarding the danger of exec, I had my doubts, Now I will try to implement what second person said about getattr, and will return here with result. And What I want to do is a small economy application. It will work this way: user add a product name, rate how much it like it over 10, and enter its price. [repeated as many times as wanted] user will enter h(is|er) budget. user will use "calcute bundle" to show much of each product s?he should buy user will repeat any step as long as s?he likes. 15-03-2011 00:14, Steven D'Aprano yazmış: Yaşar Arabacı wrote: Hi I am trying to do something like this: If you are trying to write a mini-language, the ``cmd`` and ``shlex`` modules in the standard library may be useful to you. #!/usr/bin/env python def command_dispatcher(): "Takes comman line arguments and executes regardin method" command = raw_input(">>>") args = command.split(" ") args[0].args[1] The error you get tells you exactly what is wrong: AttributeError: 'str' object has no attribute 'args' When you split the line, you get a list of strings. You extract the first string using args[0], and then look up the attribute "args" on that string, and finally look up the second element of that result. But strings don't have an attribute called args. Try this instead: getattr(args[0], args[1]) When you do that, you'll run into a bunch of new and exciting errors, starting with the fact that nothing appears to happen. Try it and see. What you will eventually need to do is: * create a class instance and store it somewhere * call the method on the class instance * print its output none of which is yet done by your script. So far, all it does it try to look up a method on a class, then throw the result away without doing anything :) class calculate: def bundle(self): print __class__ command_dispatcher() calculate.bundle won't do anything except fail, because __class__ is not a local variable. It's better to have the methods return a result, rather than print, and then have the command_dispatcher responsible for printing it. That lets you chain methods to make more powerful functions. Good luck, and have fun! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading in data files
Marc Tompkins wrote: On Mon, Mar 14, 2011 at 1:02 PM, Marc Tompkins wrote: On Mon, Mar 14, 2011 at 12:59 PM, paige crawford < plcrawf...@crimson.ua.edu> wrote: How do I split them by spaces? Google "Python split". That might have been a bit abrupt... but (in general) the Tutor list is happy to help point you in the right direction, not do your homework for you. I even gave you a big hint by writing it as split() in my original message. (It's a string function.) That's a bit harsh. Telling somebody about the existence and use of a built-in function isn't "doing your homework for you" unless the homework is "Write down what the string.split method does", in which case, the teacher is too lazy for words :) Paige, you are reading lines one at a time from a file. Each line is a string. You can split the strings on any delimiter using the split method: >>> mystr = "breakfast = spam and eggs -- spam spam spam glorious SPAM!!!" >>> mystr.split("--") ['breakfast = spam and eggs ', ' spam spam spam glorious SPAM!!!'] >>> mystr.split("=") ['breakfast ', ' spam and eggs -- spam spam spam glorious SPAM!!!'] The result is a list of substrings. You can then assign them to new variables and process them further. You may also find the string strip() method useful for getting rid of spaces around substrings. You can also look up functions and methods in the interactive interpreter using the help() function. If your Python is configured correctly, at the Python prompt, you can say: help() to start the help system, or go directly to a particular method or function, e.g.: help(len) # help about the ``len`` built-in function help(''.split) # help about the string split method Notice that you don't include parentheses after the function or method. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to use a str object, to find the class in exact name?
Prasad, Ramit wrote: Take a look at: http://stackoverflow.com/questions/701802/how-do-i-execute-a-string-containing-python-code-in-python And then please don't do it. eval and exec should be treated as the last resort, and then only if you really know what you are doing. They are slow, and dangerous, especially if there is *any* chance that the input strings could be coming from an untrusted user. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to use a str object, to find the class in exact name?
Yaşar Arabacı wrote: Hi I am trying to do something like this: If you are trying to write a mini-language, the ``cmd`` and ``shlex`` modules in the standard library may be useful to you. #!/usr/bin/env python def command_dispatcher(): "Takes comman line arguments and executes regardin method" command = raw_input(">>>") args = command.split(" ") args[0].args[1] The error you get tells you exactly what is wrong: AttributeError: 'str' object has no attribute 'args' When you split the line, you get a list of strings. You extract the first string using args[0], and then look up the attribute "args" on that string, and finally look up the second element of that result. But strings don't have an attribute called args. Try this instead: getattr(args[0], args[1]) When you do that, you'll run into a bunch of new and exciting errors, starting with the fact that nothing appears to happen. Try it and see. What you will eventually need to do is: * create a class instance and store it somewhere * call the method on the class instance * print its output none of which is yet done by your script. So far, all it does it try to look up a method on a class, then throw the result away without doing anything :) class calculate: def bundle(self): print __class__ command_dispatcher() calculate.bundle won't do anything except fail, because __class__ is not a local variable. It's better to have the methods return a result, rather than print, and then have the command_dispatcher responsible for printing it. That lets you chain methods to make more powerful functions. Good luck, and have fun! -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to use a str object, to find the class in exact name?
Take a look at: http://stackoverflow.com/questions/701802/how-do-i-execute-a-string-containing-python-code-in-python Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -Original Message- From: tutor-bounces+ramit.prasad=jpmchase@python.org [mailto:tutor-bounces+ramit.prasad=jpmchase@python.org] On Behalf Of Yasar Arabaci Sent: Monday, March 14, 2011 4:16 PM To: tutor@python.org Subject: [Tutor] How to use a str object, to find the class in exact name? Hi I am trying to do something like this: #!/usr/bin/env python def command_dispatcher(): "Takes comman line arguments and executes regardin method" command = raw_input(">>>") args = command.split(" ") args[0].args[1] class calculate: def bundle(self): print __class__ command_dispatcher() What I need this to do is, take a raw input, split it into parts and execute class args[0] and method args[1] using args[2:] as an argument. But what I have done isn't working. This is the error I get: :!/home/yasar/best_buy/main.py >>>calculate bundle Traceback (most recent call last): File "/home/yasar/best_buy/main.py", line 10, in command_dispatcher() File "/home/yasar/best_buy/main.py", line 6, in command_dispatcher args[0].args[1] AttributeError: 'str' object has no attribute 'args' shell returned 1 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to use a str object, to find the class in exact name?
Hi I am trying to do something like this: #!/usr/bin/env python def command_dispatcher(): "Takes comman line arguments and executes regardin method" command = raw_input(">>>") args = command.split(" ") args[0].args[1] class calculate: def bundle(self): print __class__ command_dispatcher() What I need this to do is, take a raw input, split it into parts and execute class args[0] and method args[1] using args[2:] as an argument. But what I have done isn't working. This is the error I get: :!/home/yasar/best_buy/main.py >>>calculate bundle Traceback (most recent call last): File "/home/yasar/best_buy/main.py", line 10, in command_dispatcher() File "/home/yasar/best_buy/main.py", line 6, in command_dispatcher args[0].args[1] AttributeError: 'str' object has no attribute 'args' shell returned 1 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] multiple if and or statement
On 3/14/2011 3:13 PM, Mike Franon wrote: Thank you everyone who responded, very fast responses I am impressed. OK now I see where I went wrong and had to do if (i == 'test1') or (i=='test2'): I guess I was thinking if I do a = ['test1', 'flag', 'monday'] for i in a: It would check each item in the list one at a time like a loop I was thinking, so the first time it would test for 'test1', and the second time it would test for 'flag', That is correct. Each iteration of the loop assigns one list element to a. if (i == 'test1') or (i=='test2'): is one way to do what you want. Another is if i in ('test1', 'test2'): Instead of a tuple of values you could also provide a list, a set or a dictionary. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] multiple if and or statement
On 3/14/2011 1:13 PM Mike Franon said... Thank you everyone who responded, very fast responses I am impressed. OK now I see where I went wrong Well, no, I don't think so. Your first test was: if i=='test1' or 'test2': which evaluates as true if _either_ i=='test1' _or_ 'test2' so, the first test is i=='test1' and the second test if simply 'test2'. Try the following: if 'test2': print "non-empty strings evaluate as true" if not "": print "the not of an empty string evaluates true" HTH, Emile and had to do if (i == 'test1') or (i=='test2'): I guess I was thinking if I do a = ['test1', 'flag', 'monday'] for i in a: It would check each item in the list one at a time like a loop I was thinking, so the first time it would test for 'test1', and the second time it would test for 'flag', did not realize it would test the entire list all at once. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] multiple if and or statement
Thank you everyone who responded, very fast responses I am impressed. OK now I see where I went wrong and had to do if (i == 'test1') or (i=='test2'): I guess I was thinking if I do a = ['test1', 'flag', 'monday'] for i in a: It would check each item in the list one at a time like a loop I was thinking, so the first time it would test for 'test1', and the second time it would test for 'flag', did not realize it would test the entire list all at once. On Mon, Mar 14, 2011 at 4:00 PM, Marc Tompkins wrote: > On Mon, Mar 14, 2011 at 12:41 PM, Mike Franon wrote: >> >> HI, >> >> I had a question, when running this small snippet of test code: >> >> >> >> a = ['test1', 'flag', 'monday'] >> >> for i in a: >> if i == 'test1' or 'test2': >> print 'true' >> >> >> It always prints true >> >> >> $ ./testing.py >> true >> true >> true >> >> >> I know I am missing something, but in reality it should only print >> true once correct? >> > No. The string 'test2' (actually, ALL non-empty strings) evaluates to True, > so your condition will always be met. > Try this: >> >> if (i == 'test1') or (i == 'test2'): > > or: >> >> if i in ('test1', 'test2'): > > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading in data files
On Mon, Mar 14, 2011 at 1:02 PM, Marc Tompkins wrote: > On Mon, Mar 14, 2011 at 12:59 PM, paige crawford < > plcrawf...@crimson.ua.edu> wrote: > >> How do I split them by spaces? >> >> Google "Python split". > > That might have been a bit abrupt... but (in general) the Tutor list is happy to help point you in the right direction, not do your homework for you. I even gave you a big hint by writing it as split() in my original message. (It's a string function.) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] multiple if and or statement
On Mon, Mar 14, 2011 at 12:41 PM, Mike Franon wrote: > HI, > > I had a question, when running this small snippet of test code: > > > > a = ['test1', 'flag', 'monday'] > > for i in a: >if i == 'test1' or 'test2': > print 'true' > > > It always prints true > > > $ ./testing.py > true > true > true > > > I know I am missing something, but in reality it should only print > true once correct? > > No. The string 'test2' (actually, ALL non-empty strings) evaluates to True, so your condition will always be met. Try this: > if (i == 'test1') or (i == 'test2'): > or: > if i in ('test1', 'test2'): > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading in data files
On Mon, Mar 14, 2011 at 12:08 PM, paige crawford wrote: > Hey, > > > How do I read in a data file that has comments then remove the comments to > get to the numbers? The numbers in the data file needs to be read into a > list. There are also comments next to the numbers. The file looks something > like this > > # DO NOT MODIFY > # > # This file is for the eyebrows > # > # Read in these numbers > # > # > # > > 3 # This is the amount of items in each list, m > > 30# number 1 > 10# number 3 > -110 # number 9 > > 39 40 30 > > 48 390 # extra data > > Those lines with multiple numbers (e.g. "39 40 30") - do you want to add 39, 40, and 30 to the list, or "39 40 30"? If you want to add the whole line as a unit, then just read each line, split() at the #, strip() the first part, and add it to the list. If you want them to be separate numbers, then read each line, split() at the #, split() the first part by spaces, and add each item to the list. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] multiple if and or statement
On 14/03/11 19:41, Mike Franon wrote: HI, I had a question, when running this small snippet of test code: a = ['test1', 'flag', 'monday'] for i in a: if i == 'test1' or 'test2': print 'true' It always prints true $ ./testing.py true true true I know I am missing something, but in reality it should only print true once correct? Any string that isn't blank ie '' is true. In your test you've asked whether i == 'test1' is true or 'test2' is true not i == 'test2' is true. I hope that's not too confusing, I can make it clearer if you're having a problem. Adam. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] multiple if and or statement
On 03/14/2011 03:41 PM, Mike Franon wrote: > HI, > > I had a question, when running this small snippet of test code: > > > > a = ['test1', 'flag', 'monday'] > > for i in a: > if i == 'test1' or 'test2': if i == 'test1' or i == 'test2' >print 'true' > I know I am missing something, but in reality it should only print > true once correct? You are missing something. Before, you're simply testing the existence of 'test2'. And since 'test2' is an immediate value (so to speak), it always exists. -- Corey Richardson ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] multiple if and or statement
HI, I had a question, when running this small snippet of test code: a = ['test1', 'flag', 'monday'] for i in a: if i == 'test1' or 'test2': print 'true' It always prints true $ ./testing.py true true true I know I am missing something, but in reality it should only print true once correct? Thanks in advance ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Reading in data files
Hey, How do I read in a data file that has comments then remove the comments to get to the numbers? The numbers in the data file needs to be read into a list. There are also comments next to the numbers. The file looks something like this # DO NOT MODIFY # # This file is for the eyebrows # # Read in these numbers # # # 3 # This is the amount of items in each list, m 30# number 1 10# number 3 -110 # number 9 39 40 30 48 390 # extra data ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Static Variable in Functions
Apologies to all, I didn't notice the [] around a. But the basic point remains that the list that he is appending to is the same list as b refers to, albeit indirectly. He is still "touching" the list. Although not directly modifying the list to which b refers, since it still only holds one member, the list to which a refers Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ - Original Message > From: Andre Engels > To: Alan Gauld > Cc: tutor@python.org > Sent: Monday, 14 March, 2011 9:23:47 > Subject: Re: [Tutor] Static Variable in Functions > > On Mon, Mar 14, 2011 at 9:56 AM, Alan Gauld wrote: > > "Yasar Arabaci" wrote > > > >> >>> a=["a"] > >> >>> b=[a] > >> >>> a.append("c") > >> >>> b > >> [['a', 'c']] > >> > >> Apperantly, I can change something (which is mutable) inside a list > >> without even touching the list itself :) > > > > But the point is that you *are* touching the list. > > In this case you have two names referring to the same list. > > You can modify that list (because it is mutable) via either name, it > > makes no difference because they both refer to the same list. > > > > So a.append() is exactly the same operation as b.append() > > No, they are not the same list. b is (a name of) a list with one > element, that one element being the list (denoted by) a. That's not > the same as a itself. > > -- > André Engels, andreeng...@gmail.com > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Static Variable in Functions
On Mon, Mar 14, 2011 at 9:56 AM, Alan Gauld wrote: > "Yasar Arabaci" wrote > >> >>> a=["a"] >> >>> b=[a] >> >>> a.append("c") >> >>> b >> [['a', 'c']] >> >> Apperantly, I can change something (which is mutable) inside a list >> without even touching the list itself :) > > But the point is that you *are* touching the list. > In this case you have two names referring to the same list. > You can modify that list (because it is mutable) via either name, it > makes no difference because they both refer to the same list. > > So a.append() is exactly the same operation as b.append() No, they are not the same list. b is (a name of) a list with one element, that one element being the list (denoted by) a. That's not the same as a itself. -- André Engels, andreeng...@gmail.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Static Variable in Functions
Alan Gauld wrote: > "Yasar Arabaci" wrote > >> >>> a=["a"] >> >>> b=[a] >> >>> a.append("c") >> >>> b >> [['a', 'c']] >> >> Apperantly, I can change something (which is mutable) inside a list >> without even touching the list itself :) > > But the point is that you *are* touching the list. > In this case you have two names referring to the same list. > You can modify that list (because it is mutable) via either name, it > makes no difference because they both refer to the same list. > > So a.append() is exactly the same operation as b.append() In this case it is not exactly the same since he said b = [a], not b = a. So b.append('c') would produce [['a'], 'c']. Best, Marcin ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Static Variable in Functions
On Mon, Mar 14, 2011 at 8:56 AM, Alan Gauld wrote: > "Yasar Arabaci" wrote >> Apperantly, I can change something (which is mutable) inside a list >> without even touching the list itself :) > But the point is that you *are* touching the list. > In this case you have two names referring to the same list. > You can modify that list (because it is mutable) via either name, it > makes no difference because they both refer to the same list. > > So a.append() is exactly the same operation as b.append() Actually, in this case it's not - a.append() is the same as b[0].append() ;) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Static Variable in Functions
"Yasar Arabaci" wrote >>> a=["a"] >>> b=[a] >>> a.append("c") >>> b [['a', 'c']] Apperantly, I can change something (which is mutable) inside a list without even touching the list itself :) But the point is that you *are* touching the list. In this case you have two names referring to the same list. You can modify that list (because it is mutable) via either name, it makes no difference because they both refer to the same list. So a.append() is exactly the same operation as b.append() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor