Re: [Tutor] __iter__
danny: my apologies for sending this to your email instead of the list!! (There I was looking at the list going: WTF DOES IT TAKE SO LONG when it hit me...). *cuts in* No I don't :-) With this: class MyListOfNumbers: def __init__(self, data): self.data = data def __iter__(self): return Pointer(self) class Pointer: def __init__(self, numbers): self.numbers = numbers self.offset = 0 def next(self): if self.offset == len(self.numbers.data): raise StopIteration element = self.numbers.data[self.offset] self.offset = self.offset + 1 return element Where/how/when is 'def next(self(:' called? Oh and if someone has some newby tut's on this I'd appreciate it. All I find are not-so-newby-friendly websites regarding to classes :(* Wim > On 1/17/06, Danny Yoo <[EMAIL PROTECTED]> wrote: > > > > > > On Mon, 16 Jan 2006, Christopher Spears wrote: > > > > > I'm not sure if I understand __iter__. You use it to create an object > > > that iterates through itself using a next menthod ? > > > > Hi Chris, > > > > Yes, that's one application. > > > > > > But __iter__() doesn't necessarily have to return 'self'. For example, > > here's a useless toy class that might help explain what can happen if we > > do so without thinking: > > > > > > class MyListOfNumbers: > > def __init__(self, data): > > self.data = data > > def __iter__(self): > > return Pointer(self) > > > > > > class Pointer: > > def __init__(self, numbers): > > self.numbers = numbers > > self.offset = 0 > > def next(self): > > if self.offset == len(self.numbers.data): > > raise StopIteration > > element = self.numbers.data[self.offset] > > self.offset = self.offset + 1 > > return element > > > > > > Let's see how this might work: > > > > ### > > >>> nums = MyListOfNumbers([0, 1]) > > >>> for x in nums: > > ... for y in nums: > > ... print x, y > > ... > > 0 0 > > 0 1 > > 1 0 > > 1 1 > > ### > > > > > > > > Now imagine what might happen if we didn't return a separate Pointer > > iterator: > > > > > > class MyListOfNumbers2: > > def __init__(self, data): > > self.data = data > > self.offset = 0 > > > > def __iter__(self): > > return self > > > > def next(self): > > if self.offset == len(self.data): > > raise StopIteration > > element = self.data[self.offset] > > self.offset = self.offset + 1 > > return element > > > > > > On a glance, this also looks reasonable: > > > > ## > > >>> nums = MyListOfNumbers2([3, 1, 4, 1, 5]) > > >>> for n in nums: > > ... print n > > ... > > 3 > > 1 > > 4 > > 1 > > 5 > > ## > > > > > > But, of course, you know that there has to be SOMETHING wrong here. > > *grin* > > > > And here's one example that shows a problem: > > > > ## > > >>> nums = MyListOfNumbers2([0, 1]) > > >>> for x in nums: > > ... for y in nums: > > ... print x, y > > ... > > 0 1 > > >>> > > ## > > > > We expected to see all pairs of 0-1 combinations, but came up way short. > > Do you know why? > > > > > > Best of wishes! > > > > ___ > > 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] Guess Your Number Game
HiI hope someone can help me!I am currently learning Python using a book by Michael Dawson. In one of the exercises I have to right a program that will guess a number chosen by the user.It is partly working, however it does not seem to keep state of numbers that should have already been ruled out as too high or low. Any pointers would be very much appreciated!import random print "Welcome to 'Guess Your Number'!"print "\nThink of a number between 1 and 100."print "And I will try and guess it!\n" print "Valid inputs are: higher, lower and correct."raw_input("\n\nPress enter once you have thought of a number.")# set the initial valuesguess = random.randrange(100) + 1 tries = 1# guessing loopresponse = ""while response != "correct": print "Is it" ,guess, "?\n" response = raw_input ("") if response == "lower": guess = random.randrange(1, guess) elif response == "higher": guess = random.randrange(guess, 100)# Error message for invalid inputs else: print "Invalid entry!" tries += 1print "\nI guessed it! The number was", guessprint "And it only took me", tries, "tries!\n" raw_input("\n\nPress the enter key to exit.") -- Best RegardsJon-- Best RegardsJon Moore ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __getitem__
Alan Gauld wrote: >>map calls, list comprehension, etc. For loops, etc. >>work by indexing a sequences from zero to a higher >>index until out-of-bounds is reached. > > > What makes you think that? > So far as I know for loops work by calling next on > an iterator until nothing gets returned, no indexes > involved.(At least not in the for loop) But they could > just as well work by calling the len() function and > iterating that number of times. And len() could be > stored as part of the data structure ala Pascal arrays. Hmm. From the language ref description of 'for': "The expression list is evaluated once; it should yield an iterable object." which begs the question of, what is an iterable object? The iterator protocol was introduced in Python 2.2; the "What's New" document give a good description of the old and new methods of iterating. Prior to Python 2.2, the _only_ way to make an object iterable was to give in a __getitem__() method. With Python 2.2 you can alternatively define __iter__(). http://www.python.org/doc/2.2.3/whatsnew/node4.html From the language ref description of __getitem__(): "Note: for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence." In fact a class that just defines __getitem__() can be iterated in a for loop: >>> class stepper: ... def __getitem__(self, i): ... if i < 5: return i ... raise IndexError ... >>> for i in stepper(): print i ... 0 1 2 3 4 > > The point being that it is dangerous to assume how > a language feature works internally, it can change from > version to version. Dangerous to assume, maybe, but special methods are there to be used, and the usage is generally well understood if not always well documented. > > In this case the iterator solution means that the for > loop can work on any iterable entity - like files for > instance. Yes, and for backward compatibility it also works on anything implementing __getitem__(). In fact strings have no __iter__() method, they use __getitem__(): >>> ''.__iter__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'str' object has no attribute '__iter__' >>> ''.__getitem__ > > >>But why does this work? >> >> >class stepper: >> >>... def __getitem__(self, i): >>... return self.data[i] >>... >> >'p' in X >> >>True >> >>What does 'in' have to do with indexing? > > > Nothing unless its implementation uses a while loop > and index, but thats unlikely. But that is pretty close to what actually happens, according to the language ref docs for 'in' (see my previous post). Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __iter__
Danny Yoo wrote: > > On Mon, 16 Jan 2006, Christopher Spears wrote: > > >>I'm not sure if I understand __iter__. You use it to create an object >>that iterates through itself using a next menthod ? > > > Hi Chris, > > Yes, that's one application. > > > But __iter__() doesn't necessarily have to return 'self'. For example, > here's a useless toy class that might help explain what can happen if we > do so without thinking: > > > class MyListOfNumbers: > def __init__(self, data): > self.data = data > def __iter__(self): > return Pointer(self) > > > class Pointer: > def __init__(self, numbers): > self.numbers = numbers > self.offset = 0 > def next(self): > if self.offset == len(self.numbers.data): > raise StopIteration > element = self.numbers.data[self.offset] > self.offset = self.offset + 1 > return element > One small correction: Pointer should have an __iter__() method that returns self; this is part of the iterator protocol. See PEP 234 http://www.python.org/peps/pep-0234.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Guess Your Number Game
On 1/17/06, Jon Moore <[EMAIL PROTECTED]> wrote: > Hi > > I hope someone can help me! > > I am currently learning Python using a book by Michael Dawson. In one of the > exercises I have to right a program that will guess a number chosen by the > user. > > It is partly working, however it does not seem to keep state of numbers that > should have already been ruled out as too high or low. > > Any pointers would be very much appreciated! > > import random > > print "Welcome to 'Guess Your Number'!" > print "\nThink of a number between 1 and 100." > print "And I will try and guess it!\n" > print "Valid inputs are: higher, lower and correct." > > raw_input("\n\nPress enter once you have thought of a number.") > > > # set the initial values > guess = random.randrange(100) + 1 > tries = 1 > > > > # guessing loop > response = "" > while response != "correct": > print "Is it" ,guess, "?\n" > response = raw_input ("") > if response == "lower": > guess = random.randrange(1, guess) > elif response == "higher": > guess = random.randrange(guess, 100) > > > # Error message for invalid inputs > else: > print "Invalid entry!" > > > tries += 1 > > > print "\nI guessed it! The number was", guess > print "And it only took me", tries, "tries!\n" > > > raw_input("\n\nPress the enter key to exit.") > > -- > Best Regards > > Jon > > -- > Best Regards > > Jon Moore > sidenote: Hello, 1 thing I spotted: response = raw_input ("") if response == "lower": guess = random.randrange(1, guess) tries += 1 elif response == "higher": guess = random.randrange(guess, 100) tries += 1 # Error message for invalid inputs else: print "Invalid entry!" I myself consider an invalid entry not as a valid try ;) These 2 lines are wrong: > guess = random.randrange(1, guess) > guess = random.randrange(guess, 100) The 1 and 100 are being reset and if the answer WAS lower and is NOW higher you lost your 1st boundary. 1 and 100 should be the previous answer. Regarding your problem: A test needs to be between the highest lowest answer and the lowest highest answer you get. You test between 1 and guess and guess and 100. The 1 and 100 reset your boundary back to the original problem: it needs to be between 1 and 100. number = 40 random = 60 answer lower next test you do is between 1 and guess. new random = 20 answer = higher but now you test between 20 and 100 and NOT between 20 and 60 (<- lowest highest number). ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __getitem__
Kent Johnson wrote: > Alan Gauld wrote: >>>What does 'in' have to do with indexing? >> >> >>Nothing unless its implementation uses a while loop >>and index, but thats unlikely. > > > But that is pretty close to what actually happens, according to the > language ref docs for 'in' (see my previous post). I'm curious enough about this (OK, I admit it, I like to be right, too ;) to dig in to the details, if anyone is interested...one of the benefits of Python being open-source is you can find out how it works... First step, look at the bytecodes: >>> import dis >>> def f(x, y): ... return x in y ... >>> dis.dis(f) 2 0 LOAD_FAST0 (x) 3 LOAD_FAST1 (y) 6 COMPARE_OP 6 (in) 9 RETURN_VALUE So 'in' is implemented as a COMPARE_OP. Looking in ceval.c for COMPARE_OP, it has some optimizations for a few fast compares, then calls cmp_outcome() which, for 'in', calls PySequence_Contains(). PySequence_Contains() is implemented in abstract.c. If the container implements __contains__, that is called, otherwise _PySequence_IterSearch() is used. _PySequence_IterSearch() calls PyObject_GetIter() to constuct an iterator on the sequence, then goes into an infinite loop (for (;;)) calling PyIter_Next() on the iterator until the item is found or the call to PyIter_Next() returns an error. PyObject_GetIter() is also in abstract.c. If the object has an __iter__() method, that is called, otherwise PySeqIter_New() is called to construct an iterator. PySeqIter_New() is implemented in iterobject.c. It's next() method is in iter_iternext(). This method calls __getitem__() on its wrapped object and increments an index for next time. So, though the details are complex, I think it is pretty fair to say that the implementation uses a while loop (in _PySequence_IterSearch()) and a counter (wrapped in PySeqIter_Type) to implement 'in' on a container that defines __getitem__ but not __iter__. By the way the implementation of 'for' also calls PyObject_GetIter(), so it uses the same mechanism to generate an iterator for a sequence that defines __getitem__(). Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Design suggestion - is a cookie the answer?
> > you are using GET instead of POST? GET is the default > > submission method but POST is nearly always better and > > should avoid the problem here. (I think, I haven't tried it!) > > I believe the python CGI module is submission-method agnostic Thats true, but to frig it you would need to know how to read and interpret html form code and how to manually construct a GET url string complete with correct escape characters etc. It isn't impossible but simply answering the quiz is a lot easier! ;-) In fact any kid smart enough to do all of that probably deserves to marks anyhow, regardless of cheating! Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Open file error
I am starting to pull my hair here. There were some postings in the past, similar to my problem, but the response was not clear enough. Sorry if you thingk I am reposting this.I am trying to run (on an XP box) a simple open file using this: f = open(r'C:\Test.txt', 'r') but it keeps give me nagging error of: Traceback (most recent call last): File "", line 1, in -toplevel- f = open('Test.txt', 'r') IOError: [Errno 2] No such file or directory: 'C:\Test.txt' I know for sure that the file is there, I even put copies of the files here and there, just to guess how python does the file search, but it keeps giving me 'No such file or directory'. i also tried variation of the file location string, but gave me a variation of errors :). Any suggestions?Furthermore, how does Python assumes the search path? Will it look at /LIB first? How does it knows drive lettering, network mapping etc? Is there a configuration settings that I can tweak in my Python? FYI I am using Activestate's. Thx, Andy ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Open file error
On Tuesday 17 January 2006 12:11 pm, andy senoaji wrote: > I am starting to pull my hair here. There were some postings in the past, > similar to my problem, but the response was not clear enough. Sorry if you > thingk I am reposting this. > > I am trying to run (on an XP box) a simple open file using this: > f = open(r'C:\Test.txt', 'r')Newbie here but shouldn't it be. Newbie Here f = open( r'C:\\Test.txt','r') I think you are escaping the T with \T. Paul ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Open file error
On Tue, 17 Jan 2006, Paul Kraus wrote: > On Tuesday 17 January 2006 12:11 pm, andy senoaji wrote: > > I am starting to pull my hair here. There were some postings in the past, > > similar to my problem, but the response was not clear enough. Sorry if you > > thingk I am reposting this. > > > > I am trying to run (on an XP box) a simple open file using this: > > f = open(r'C:\Test.txt', 'r')Newbie here but shouldn't it be. > > Newbie Here > > f = open( r'C:\\Test.txt','r') > > I think you are escaping the T with \T. No, not if he's indicating a raw string (r' '). It should work: >>> f = open(r'C:\Test.txt', 'r') >>> f Although, even with non-raw strings, I prefer to use the forward-slash, making escaping unnecessary: >>> f = open('C:/Test.txt', 'r') >>> f But I suspect that won't help our questioner. My only suggestion is that he make very certain that the file's really there. For example, what does he get if he types: type c:\Test.txt from the DOS prompt? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] string object into reference
Hi, just joined. I've got a question that I'm guessing there's a ridiculously easy answer to, but I'm having trouble (no excuses, I'm just dumb!)... My problem is I want to make a string object into a reference to another object. To be more specific, I'm reading through a text file of amino acids. The first item on each line is the amino acid name, and a later item is its exposed surface area. For each amino acid, I want to add up the surface area as I go through the text file. So what I'm doing is, for each line, assigning the reference 'residue' to the amino acid name. I'd like to then make the string referred to by 'residue' (eg, 'CYS' or 'TRP') a reference to an object that I will subsquently increment by the surface area value. Thanks for any help. Perhaps I just need to be pointed to a relevent thread or given the correct words to search for in the archives or manual. Kirk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Open file error
On Tue, 2006-01-17 at 09:11 -0800, andy senoaji wrote: > I am starting to pull my hair here. There were some postings in the > past, similar to my problem, but the response was not clear enough. > Sorry if you thingk I am reposting this. > > I am trying to run (on an XP box) a simple open file using this: > f = open(r'C:\Test.txt', 'r') This looks correct! > > but it keeps give me nagging error of: > Traceback (most recent call last): > File "", line 1, in -toplevel- > f = open('Test.txt', 'r') This is not the same is the line above! > IOError: [Errno 2] No such file or directory: 'C:\Test.txt' And this does not match *either* of the lines above. If you really use that first line, I would expect it to work. If you get an error, from that line, the file will be identified as: 'C:\\Test.txt' > > I know for sure that the file is there, I even put copies of the files > here and there, just to guess how python does the file search, but it > keeps giving me 'No such file or directory'. i also tried variation of > the file location string, but gave me a variation of errors :). Any > suggestions? > > Furthermore, how does Python assumes the search path? Will it look > at /LIB first? How does it knows drive lettering, network mapping etc? > Is there a configuration settings that I can tweak in my Python? FYI I > am using Activestate's. > > > Thx, > > Andy > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Open file error
>> I am trying to run (on an XP box) a simple open file using this: >> f = open(r'C:\Test.txt', 'r')Newbie here but shouldn't it be. > > Newbie Here > > f = open( r'C:\\Test.txt','r') > > I think you are escaping the T with \T. The r in front of the string should prevent that problem. If the r wasn't there you would be right and he would need to escape the \ ...or use a forward slash! Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Open file error
> I am trying to run (on an XP box) a simple open file using this: > f = open(r'C:\Test.txt', 'r') > IOError: [Errno 2] No such file or directory: 'C:\Test.txt' > I know for sure that the file is there > Furthermore, how does Python assumes the search path? There is no search, you have specified exactly where to look so Python will look there and nowhere else. But it may not be able to open the file if it belongs to someone else who has denied access. Have you checked the security settings on C:\Test.txt? Thats the only other thing that I can think of if you are sure that a file called Test.txt exists in the root directory of the C drive. > How does it knows drive lettering, network mapping etc? Because you explicitly tell it. If you don;t specify the full path it will look in the current directory. You can find that with the os.getcwd() function. See my OS topic for more on how to test file status... http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __getitem__
>>>Nothing unless its implementation uses a while loop >>>and index, but thats unlikely. >> >> >> But that is pretty close to what actually happens, according to the >> language ref docs for 'in' (see my previous post). Only in certain cases. The point I was making (or trying to) is that both loops actually depend on how iterators work - and they currently use indexes, but the loops themselves don't. And its quite possible, likely even, that generic iterator code could appear that doesn't even store an index at all. > PySequence_Contains() is implemented in abstract.c. If the container > implements __contains__, that is called, otherwise > _PySequence_IterSearch() is used. And at this point we are out of the loop code and into iterator code which it where the index is stored. > So, though the details are complex, I think it is pretty fair to say > that the implementation uses a while loop (in _PySequence_IterSearch()) > and a counter (wrapped in PySeqIter_Type) to implement 'in' on a > container that defines __getitem__ but not __iter__. I'd say the implementation uses a while loop which uses an iterator and no counter - it relies on the iterator throwing an exception to detect the end, the loop code has no index and neither does the 'in' code. The 'in' is two levels of abstraction away from the index. > By the way the implementation of 'for' also calls PyObject_GetIter(), so > it uses the same mechanism to generate an iterator for a sequence that > defines __getitem__(). Which is what I said, it relies on the iterator. (But I didn't know about the legacy getitem() branch! ) In each case if the way iterators work changes the loops will carry on as they are. I'm actually surprised the C implementation uses an index, - I thought it would just manipulate pointers - but given the getitem mechanism maybe its not so surprising. Thanks for doing the research - I was too lazy to do it myself ;-) Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] PIL, fonts and making images (fwd)
-- Forwarded message -- Date: Tue, 17 Jan 2006 09:47:58 +0100 From: Rinzwind <[EMAIL PROTECTED]> To: Danny Yoo <[EMAIL PROTECTED]> Subject: Re: PIL, fonts and making images That's not good. Well I guess it does what it is suppose to do: make it able to create diagrams and the person who made them didn't intend them to be used as text. Oh and I guess it's made for Windows :P Pity. My idea seemed cool when I thought of it :-) Oh and I did it with a detour: opened up GIMP and made my own 90x90 PNG's. In my new 'chess' game I'll convert them to smaller if needed. It's just that with the way I tgought I'd do it I'd be able to have a fonts dir and people could add their own and I'd automagically made them into screens. I'll have a look at another chess font when I am home if it's also with others (only tried with one :-P ) On 1/17/06, Danny Yoo <[EMAIL PROTECTED]> wrote: > > Want I want though is to do this with MARRFONT.TTF. That is a (free) font > > that has chesspieces inside. (can be downloaded here: > > http://antraxja-fonts.iweb.pl/pobierz.php?font=3903 ) > > Hi Rinzwind, > > You might want to contact the folks who make that font: according to the > Fontbook on my Mac OS X box, that particular font has serious problems. > My system says that it's defective because it's missing a "Font Name > Table", whatever that is. > > Best of wishes to you! > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __iter__
> One small correction: Pointer should have an __iter__() method that > returns self; this is part of the iterator protocol. See PEP 234 > http://www.python.org/peps/pep-0234.html Hi Kent, Ah, thank you! Ok, the corrected code is: # class MyListOfNumbers: def __init__(self, data): self.data = data def __iter__(self): return Pointer(self) class Pointer: def __init__(self, numbers): self.numbers = numbers self.offset = 0 def __iter__(self): return self def next(self): if self.offset == len(self.numbers.data): raise StopIteration element = self.numbers.data[self.offset] self.offset = self.offset + 1 return element # ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Open file error
(replying back to the list also) On Tue, 2006-01-17 at 10:03 -0800, andy senoaji wrote: > Sorry for the inconsistent error message. I think I may pasted > incorretcly. I am now in a different machine, and have tested Paul's > suggestion, and it worked. But would the 'r' tackles the escape > sequence? I may misunderstood the intent of the r' switcher here. > > Thanks, > > Andy > f = open(r'C:\Test.txt', 'r') > This looks correct! r'C:\Test.txt' is a raw string. The r'strings' ignore the special use of the backslash character except that a raw string must not end with a backslash. This is strictly a convenience when entering a string. Since Windows uses backslash as the path separator, it helps ease the pain when constructing file paths in Windows. Raw strings are also very helpful when writing regular expression strings which often need to have backspace characters. Internally, a raw string is the same as any other Python string. When Python displays a raw string, Python will show the backslashes as \\ (doubled) because that is usually how you need to enter a backslash. Python does not track (as far as I know) that the string originated as a raw string. In regular strings, the backslash is used to mark characters that need special handling. '\t' is a tab character. '\n' is a newline (linefeed). '\r' is a carriage-return (Enter Key). http://docs.python.org/ref/strings.html provides the detailed documentation about how strings work and the definitive list of backspace usages. > > On 1/17/06, Python <[EMAIL PROTECTED]> wrote: > On Tue, 2006-01-17 at 09:11 -0800, andy senoaji wrote: > > I am starting to pull my hair here. There were some postings > in the > > past, similar to my problem, but the response was not clear > enough. > > Sorry if you thingk I am reposting this. > > > > I am trying to run (on an XP box) a simple open file using > this: > > f = open(r'C:\Test.txt', 'r') > This looks correct! > > > > > but it keeps give me nagging error of: > > Traceback (most recent call last): > > File "", line 1, in -toplevel- > > f = open('Test.txt', 'r') > This is not the same is the line above! > > > IOError: [Errno 2] No such file or directory: 'C:\Test.txt' > And this does not match *either* of the lines above. > > If you really use that first line, I would expect it to > work. If you > get an error, from that line, the file will be identified as: > 'C:\\Test.txt' > > > > > I know for sure that the file is there, I even put copies of > the files > > here and there, just to guess how python does the file > search, but it > > keeps giving me 'No such file or directory'. i also tried > variation of > > the file location string, but gave me a variation of > errors :). Any > > suggestions? > > > > Furthermore, how does Python assumes the search path? Will > it look > > at /LIB first? How does it knows drive lettering, network > mapping etc? > > Is there a configuration settings that I can tweak in my > Python? FYI I > > am using Activestate's. > > > > > > Thx, > > > > Andy > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > -- > Lloyd Kvam > Venix Corp > -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Open file error
At 09:23 AM 1/17/2006, Paul Kraus wrote: >On Tuesday 17 January 2006 12:11 pm, andy senoaji wrote: > > I am starting to pull my hair here. There were some postings in the past, > > similar to my problem, but the response was not clear enough. Sorry if you > > thingk I am reposting this. > > > > I am trying to run (on an XP box) a simple open file using this: > > f = open(r'C:\Test.txt', 'r')Newbie here but shouldn't it be. > >Newbie Here > >f = open( r'C:\\Test.txt','r') > >I think you are escaping the T with \T. More specifically you show us f = open(r'C:\Test.txt', 'r') but the traceback shows the statement to be f = open('Test.txt', 'r') Something is being lost between these 2 items. When I try f = open( r'C:\Test.txt','r') The traceback reports IOError: [Errno 2] No such file or directory: 'c:\\test.txt' Note the \\ Your traceback reports IOError: [Errno 2] No such file or directory: 'c:\test.txt' confirming the Paul's diagnosis. Are you using IDLE? Are you running a script vs trying a command interactively? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __iter__
> Where/how/when is 'def next(self(:' called? The 'for' loop statement does this internally when it marches across an iterable thing. We can write something something like this: ## for item in thing: print item ## Python is doing something like this behind the scenes: ## iterable = iter(thing) try: while True: item = iterable.next() print item except StopIteration: pass ## The for loop is the one that's calling next() repeatedly on its iterable. We can manually call next() ourselves, just to see what happens: ## >>> names = ['homer', 'marge', 'sideshow bob'] >>> iterable = iter(names) >>> iterable >>> >>> >>> iterable.next() 'homer' >>> iterable.next() 'marge' >>> iterable.next() 'sideshow bob' >>> iterable.next() Traceback (most recent call last): File "", line 1, in ? StopIteration ## Does this make sense? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] string object into reference
Hello Kirk,If I'm not mistaken your idea is referencing two columns: first column is your acid name and the later is your surface area.Later you want to connect the surface area if you name the acid name.If that what you want another question arises... is your acid name is unique. If it is you can make dictionary types.A csbB dskC dskyou can create mydic = []mydic['A'] = 'csb'mydic['B'] = 'dsk'mydic['C'] = 'dsk'you have to transform the file into a list and after that start building the dictionary variable. After this dictionary variable is filled. you can get the surface area by typing the acid name such as:print mydic['A'] # will result 'csb'Cheers,pujoOn 1/17/06, Kirk Vander Meulen <[EMAIL PROTECTED]> wrote: Hi, just joined. I've got a question that I'm guessing there's a ridiculously easy answer to, but I'm having trouble (no excuses, I'm just dumb!)... My problem is I want to make a string object into a reference to another object. To be more specific, I'm reading through a text file of amino acids. The first item on each line is the amino acid name, and a later item is its exposed surface area. For each amino acid, I want to add up the surface area as I go through the text file. So what I'm doing is, for each line, assigning the reference 'residue' to the amino acid name. I'd like to then make the string referred to by 'residue' (eg, 'CYS' or 'TRP') a reference to an object that I will subsquently increment by the surface area value. Thanks for any help. Perhaps I just need to be pointed to a relevent thread or given the correct words to search for in the archives or manual. Kirk ___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] Design suggestion - is a cookie the answer?
On 1/17/06, Alan Gauld <[EMAIL PROTECTED]> wrote: > > > you are using GET instead of POST? GET is the default > > > submission method but POST is nearly always better and > > > should avoid the problem here. (I think, I haven't tried it!) > > > > I believe the python CGI module is submission-method agnostic > > Thats true, but to frig it you would need to know how to read > and interpret html form code and how to manually construct > a GET url string complete with correct escape characters etc. > > It isn't impossible but simply answering the quiz is a lot easier! ;-) > > In fact any kid smart enough to do all of that probably deserves > to marks anyhow, regardless of cheating! > > Yes, I agree - I haven't disadvantaged the children who have worked this out (2 to date). Ingenuity should never be discouraged. OK - I think I must be using the GET method, as the url is already constructed for them and they just need to put the cursor in the URL bar and hit enter to get points each time. Sorry for not being clearer on this in this first place. Unfortunately, I've not had a chance to look at this (such is the life of a teacher). Hopefully, this weekend, I may get the chance to. Adam -- http://www.monkeez.org PGP key: 0x7111B833 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Guess Your Number Game
Check this: ### import random print "Welcome to 'Guess Your Number'!"print "\nThink of a number between 1 and 100."print "And I will try and guess it!\n"print "Valid inputs are: higher, lower and correct." raw_input("\n\nPress enter once you have thought of a number.") # set the initial valuesx = 1 ## Pay atention to these two variables.y = 100 guess = random.randrange(x, y) ## Now we use themtries = 1 # guessing loopresponse = ""while response != "correct": print "Is it" ,guess, "?\n" response = raw_input ("") if response == "lower": y = guess ## y is the 100 above, now, we take the guess as "y" and "y" as the maximum value of the parameters of guess. guess = random.randrange(x, y) elif response == "higher": x = guess guess = random.randrange(x, y) ## we take guess as the minimun value of our guess and plug it into x # Error message for invalid inputs else: print "Invalid entry!" tries += 1 print "\nI guessed it! The number was", guessprint "And it only took me", tries, "tries!\n" raw_input("\n\nPress the enter key to exit.") I hope this can help you. I am newbie, so if I did a mistake I hope you to understand my self ;) - Edgar A. Rodriguez ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] string object into reference
Pujo, I think your solution does not address Kirk's problem. You don't mention the addition of surface areas. If for any reason he had more than two types of amino acids, then he would need to use a dictionary for the totals, with each key being a specific amino acid. The actual steps to follow are: 1. open the file to read 2. initialize the dictionary to empty 3. for each line in the file 4. see if the key for that amino acid already \ exists in the dictionary 5. if it does not exist, create a new dictionary \ key for that new amino acid, and initialize it \ to zero 6. add the surface area of the current line to the \ corresponding dictionary key 7. print the totals dictionary Kirk, I would write the program (would take me less time), but the idea is for yo uto learn to program in Python ;-) Post your code for review. Regards. Victor On Tue, 2006-01-17 at 22:08 +0100, Pujo Aji wrote: > Hello Kirk, > > If I'm not mistaken your idea is referencing two columns: first column > is your acid name and the later is your surface area. > Later you want to connect the surface area if you name the acid name. > If that what you want another question arises... is your acid name is > unique. > If it is you can make dictionary types. > > A csb > B dsk > C dsk > > you can create > mydic = [] > mydic['A'] = 'csb' > mydic['B'] = 'dsk' > mydic['C'] = 'dsk' > > you have to transform the file into a list and after that start > building the dictionary variable. > > After this dictionary variable is filled. you can get the surface area > by typing the acid name such as: > print mydic['A'] # will result 'csb' > > Cheers, > pujo > > On 1/17/06, Kirk Vander Meulen <[EMAIL PROTECTED]> wrote: > Hi, just joined. I've got a question that I'm guessing > there's a ridiculously easy answer to, but I'm having trouble > (no excuses, I'm just dumb!)... > > My problem is I want to make a string object into a reference > to another object. To be more specific, I'm reading through a > text file of amino acids. The first item on each line is the > amino acid name, and a later item is its exposed surface area. > For each amino acid, I want to add up the surface area as I go > through the text file. So what I'm doing is, for each line, > assigning the reference 'residue' to the amino acid name. I'd > like to then make the string referred to by 'residue' (eg, > 'CYS' or 'TRP') a reference to an object that I will > subsquently increment by the surface area value. > > Thanks for any help. Perhaps I just need to be pointed to a > relevent thread or given the correct words to search for in > the archives or manual. > > Kirk > > ___ > 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 maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] string object into reference
Ooops. Did not respond to the mailing list. Here is my replied-to post. -- Hi Kirk, There is nothing as a dumb question. I am assuming your source file will have a amino acid residue ('CYS' or 'TRP'), followed by a space, and then the corresponding surface area. You have to define a variable for adding the surface areas of each residue type. As you only have one of two options, the easiest way is to define a variable for each (e.g. cys, trp) and then open the file and process each line, adding the surface area to the corresponding amino acid. As for reference, look for working with files (I/O), string variable splitting (split function), and basic operations to add each new surface area. Try writing some code and posting it back. Would be glad to review it. Victor On Tue, 2006-01-17 at 11:50 -0600, Kirk Vander Meulen wrote: > Hi, just joined. I've got a question that I'm guessing there's a > ridiculously easy answer to, but I'm having trouble (no excuses, I'm > just dumb!)... > > My problem is I want to make a string object into a reference to > another object. To be more specific, I'm reading through a text file > of amino acids. The first item on each line is the amino acid name, > and a later item is its exposed surface area. For each amino acid, I > want to add up the surface area as I go through the text file. So > what I'm doing is, for each line, assigning the reference 'residue' to > the amino acid name. I'd like to then make the string referred to by > 'residue' (eg, 'CYS' or 'TRP') a reference to an object that I will > subsquently increment by the surface area value. > > Thanks for any help. Perhaps I just need to be pointed to a relevent > thread or given the correct words to search for in the archives or > manual. > > Kirk > ___ > 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] Dictionaries [Was: Re: string object into reference]
> > My problem is I want to make a string object into a reference to > > another object. To be more specific, I'm reading through a text file > > of amino acids. The first item on each line is the amino acid name, > > and a later item is its exposed surface area. Hi Victor, It sounds like we'd like to maintain a mapping between amino acids and their exposed surface areas. This is traditionally known as a "key-value" pairing, and there are a few things in Python that we can use to represent this. The most direct way of doing this is with a dictionary: http://www.python.org/doc/tut/node7.html#SECTION00750 Let's show what dictionaries look like: ## >>> alphas = {'a': "Alpha", 'b' : 'Beta' } >>> alphas['a'] 'Alpha' >>> alphas['g'] = 'gama' >>> >>> >>> alphas {'a': 'Alpha', 'b': 'Beta', 'g': 'gama'} >>> alphas['g'] = 'gamma' ## In this way, we can collect a bunch of key-value pairs by setting elements in a dictionary. This is often prefered to having a variable for each key-value pair. A dictionary allows to ask things like this: ## >>> alphas.keys() ## What keys have we defined? ['a', 'b', 'g'] >>> alphas.values()## What values do we have? ['Alpha', 'Beta', 'gamma'] ## These kind of "bulk" questions are fairly easy to answer if we collect all the key-value pairs in a single dictionary container, because we're just asking that one container. But it's much harder to answer this if we use individual variables for each key-value pair, since we don't tell the system that those variables are somehow related as a group --- as far as Python knows, they're just disconnected variables. The terminology that the original poster uses ("references to another object") sounds a lot like the original usage of symbolic "soft" references in Perl. (http://www.perl.com/doc/manual/html/pod/perlref.html) Perl programmers, for the most part, avoid them now because they're so error prone. So if the original poster is thinking about symbolic references, then we should encourage the poster to look into dictionaries, since dictionaries are a fairly direct replacement for that usage. Best of wishes! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] [OT] How to report issues with Standard library modules
Hi all, After having a frustrating night last night trying to install pyid3lib on XP, which I think is due to something in distutils.core, I'm wondering how I should report it. I have the dotNET framework 2.0 installed, which should give distutils access to the MSVC++ compiler, but it's searching for the 1.1 framework, and so tells me I have no dotNET install. This is a pain in the donkey synonym, but after some mucking about trying to compile the extension myself (which never quite worked) I found that you can specify a different compiler, so I tried mingw32. Unfortunately, that errored to the extent that where the error started exceeded my console buffer, even when set to max. So... does anyone know how to pipe stderr in a cmd.exe console to a file? foo.exe > bob.txt only pipes stdout, stderr is still hitting the screen. Secondly, how and where do bug reports go? I thought I'd ask here because I want to avoid the "noob" comments and "use a real OS" comments... (In the end I gave up and downloaded ATAudio from Plone which had a compiled copy of eyeD3 in it.) I now understand the pain that Linux users feel when they have to deal with software that assumes everyone loves dialogs. Regards, Liam Clarke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] quick question about threads
Hey there, i have a program written in python that uses four threads that run all at the same time. Now i want to add a new thread with the same basic structure (threading.thread) that will run only when needed. This one will not run in a loop, it will just run once and quit. So, i may need this to be running several times at once because it will have a 15 second delay written into it. My question is, after the script is done, will it be safe ? i mean, over the course of a few days, it may run this thing a few hundred times. if it is simple like this threading.thread print 'here is something to say' time.sleep(15) print 'here is something else' do i need to include a special command to kill the thread, or will it just finish and everything will be ok then ? thanks for any tips. shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: [OT] How to report issues with Standard library modules
"Liam Clarke" <[EMAIL PROTECTED]> said: >Hi all, > [...] >So... does anyone know how to pipe stderr in a cmd.exe console to a file? >foo.exe > bob.txt only pipes stdout, stderr is still hitting the screen. > To have stderr go to a separate file: foo.exe > bob.txt &2>err.txt To have stderr go to the same file as stdout: foo.exe > bob.txt &2>&1 [...] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] quick question about threads
nephish wrote: > Hey there, i have a program written in python that uses four threads > that run all at the same time. Now i want to add a new thread with the > same basic structure (threading.thread) that will run only when needed. > This one will not run in a loop, it will just run once and quit. > So, i may need this to be running several times at once because it will > have a 15 second delay written into it. > My question is, after the script is done, will it be safe ? i mean, over > the course of a few days, it may run this thing a few hundred times. if > it is simple like this > > threading.thread > print 'here is something to say' > time.sleep(15) > print 'here is something else' > > do i need to include a special command to kill the thread, or will it > just finish and everything will be ok then ? Assuming you are showing the run() method of your thread above, it should be fine. If the run() method exits the thread terminates and you don't have to worry about it any more. Make sure you don't keep any references to the threads so they can be garbage-collected. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] quick question about threads
all i needed to know, thanks very much shawn On Tue, 2006-01-17 at 21:53 -0500, Kent Johnson wrote: > nephish wrote: > > Hey there, i have a program written in python that uses four threads > > that run all at the same time. Now i want to add a new thread with the > > same basic structure (threading.thread) that will run only when needed. > > This one will not run in a loop, it will just run once and quit. > > So, i may need this to be running several times at once because it will > > have a 15 second delay written into it. > > My question is, after the script is done, will it be safe ? i mean, over > > the course of a few days, it may run this thing a few hundred times. if > > it is simple like this > > > > threading.thread > > print 'here is something to say' > > time.sleep(15) > > print 'here is something else' > > > > do i need to include a special command to kill the thread, or will it > > just finish and everything will be ok then ? > > Assuming you are showing the run() method of your thread above, it > should be fine. If the run() method exits the thread terminates and you > don't have to worry about it any more. Make sure you don't keep any > references to the threads so they can be garbage-collected. > > 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
Re: [Tutor] Dictionaries [Was: Re: string object into reference]
Hi Danny, On Tue, 2006-01-17 at 16:03 -0800, Danny Yoo wrote: > > > My problem is I want to make a string object into a reference to > > > another object. To be more specific, I'm reading through a text file > > > of amino acids. The first item on each line is the amino acid name, > > > and a later item is its exposed surface area. > > These kind of "bulk" questions are fairly easy to answer if we collect all > the key-value pairs in a single dictionary container, because we're just > asking that one container. > > But it's much harder to answer this if we use individual variables for > each key-value pair, since we don't tell the system that those variables > are somehow related as a group --- as far as Python knows, they're just > disconnected variables. > I couldn't agree more. I love using dictionaries. I don't know why I suggested individual variables instead of the usage of a dictionary in the first place. > > The terminology that the original poster uses ("references to another > object") sounds a lot like the original usage of symbolic "soft" > references in Perl. > (http://www.perl.com/doc/manual/html/pod/perlref.html) > > Perl programmers, for the most part, avoid them now because they're so > error prone. So if the original poster is thinking about symbolic > references, then we should encourage the poster to look into dictionaries, > since dictionaries are a fairly direct replacement for that usage. > I did not know Perl programmers were moving away from references. That's new to me, and an interesting point. On the other hand, Kirk's comment about "references to another object" takes us into a discussion over references, when we actually should be focusing on Perl's hashes (or references to hashes for that matter). Or better still, get away from Perl and start programming in Python and use dictionaries instead! ;-) > Best of wishes! > Thanks a lot. Victor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Open file error
I'm back to my home machine, and ran again the open method, just to test my sanity Here are the results:>>> f=open(r'c:\Test.txt','r')Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'c:\\Test.txt'>>> f=open(r'c:\\Test.txt','r')Traceback (most recent call last): File "", line 1, in ?IOError: [Errno 2] No such file or directory: 'c:Test.txt' >>> f=open(r'C:/Test.txt','r')Traceback (most recent call last): File "", line 1, in ?IOError: [Errno 2] No such file or directory: 'C:/Test.txt'>>> f=open('c:\\Test.txt','r') Traceback (most recent call last): File "", line 1, in ?IOError: [Errno 2] No such file or directory: 'c:\\Test.txt'Now with all the explanations of r, slash, double slash, and backslash, I can't really figure out what's going on. Any hints is much appreciated.Thanks,AndyOn 1/17/06, Python < [EMAIL PROTECTED]> wrote: (replying back to the list also)On Tue, 2006-01-17 at 10:03 -0800, andy senoaji wrote:> Sorry for the inconsistent error message. I think I may pasted> incorretcly. I am now in a different machine, and have tested Paul's > suggestion, and it worked. But would the 'r' tackles the escape> sequence? I may misunderstood the intent of the r' switcher here.>> Thanks,>> Andy> f = open(r'C:\Test.txt', 'r') > This looks correct!r'C:\Test.txt' is a raw string. The r'strings' ignore the special useof the backslash character except that a raw string must not end with abackslash. This is strictly a convenience when entering a string. Since Windows uses backslash as the path separator, it helps ease thepain when constructing file paths in Windows. Raw strings are also veryhelpful when writing regular _expression_ strings which often need to have backspace characters.Internally, a raw string is the same as any other Python string. WhenPython displays a raw string, Python will show the backslashes as \\(doubled) because that is usually how you need to enter a backslash. Python does not track (as far as I know) that the string originated as araw string.In regular strings, the backslash is used to mark characters that needspecial handling. '\t' is a tab character. '\n' is a newline (linefeed). '\r' is a carriage-return (Enter Key).http://docs.python.org/ref/strings.htmlprovides the detailed documentation about how strings work and the definitive list of backspace usages. >> On 1/17/06, Python <[EMAIL PROTECTED]> wrote:> On Tue, 2006-01-17 at 09:11 -0800, andy senoaji wrote: > > I am starting to pull my hair here. There were some postings > in the> > past, similar to my problem, but the response was not clear> enough.> > Sorry if you thingk I am reposting this.> >> > I am trying to run (on an XP box) a simple open file using > this:> > f = open(r'C:\Test.txt', 'r')> This looks correct!>> >> > but it keeps give me nagging error of:> > Traceback (most recent call last): > > File "", line 1, in -toplevel-> > f = open('Test.txt', 'r')> This is not the same is the line above!>> > IOError: [Errno 2] No such file or directory: 'C:\Test.txt' > And this does not match *either* of the lines above.>> If you really use that first line, I would expect it to> work. If you> get an error, from that line, the file will be identified as: > 'C:\\Test.txt'>> >> > I know for sure that the file is there, I even put copies of> the files> > here and there, just to guess how python does the file > search, but it> > keeps giving me 'No such file or directory'. i also tried> variation of> > the file location string, but gave me a variation of> errors :). Any > > suggestions?> >> > Furthermore, how does Python assumes the search path? Will> it look> > at /LIB first? How does it knows drive lettering, network > mapping etc?> > Is there a configuration settings that I can tweak in my> Python? FYI I> > am using Activestate's.> >> > > > Thx,> >> > Andy> > ___> > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor> -- > Lloyd Kvam> Venix Corp>-- Lloyd KvamVenix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Open file error
>>> f=open(r'c:\Test.txt','r') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'c:\\Test.txt' Its pretty determined that Test.txt doesn't exist. What happens if you do: import os os.listdir('C:\\') In other words does Python see the file at all? And have you checked that you have access to the file in Windows Explorer? Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] References and list aliasing in Perl and Python [Was: Re: Dictionaries]
> > The terminology that the original poster uses ("references to another > > object") sounds a lot like the original usage of symbolic "soft" > > references in Perl. > > (http://www.perl.com/doc/manual/html/pod/perlref.html) > > > > Perl programmers, for the most part, avoid them now because they're so > > error prone. So if the original poster is thinking about symbolic > > references, then we should encourage the poster to look into > > dictionaries, since dictionaries are a fairly direct replacement for > > that usage. > > > I did not know Perl programmers were moving away from references. That's > new to me, and an interesting point. [Note: I'll write some Perl code below. Probably bad, nonidiomatic Perl code. I also have a high chance of saying something wrong. If I do so, someone please correct me. *grin* Also, whenever I say "Perl", I'll mean Perl 5 --- I understand that Perl 6 has a model that's similar to Python now.] Hi Victor, No, no, I'd better clarify this to try to avoid someone getting angry at me. Maybe I'll dig myself into a deeper hole, but oh well. Perl has a distinction between "soft" symbolic references and "hard" references. I think symbolic references may have been a language mistake; I think good Perl style these days has been to phase them out of usage. Perl programmers seem to be perfectly happy with "hard" references: (http://search.cpan.org/~nwclark/perl-5.8.7/pod/perlreftut.pod) Python programmers like myself struggle a little when we talk about this because, truthfully, we don't think about this much. In Python, we pass references around without with abandon: we might not even realize it! Values in Python are all references. For example: ### Python ### >>> msg = list("hello world"); >>> greeting = msg >>> id(msg) 466880 >>> id(greeting) 466880 ## In Python, both 'msg' and 'greeting' are names that refer to the same list value. We see this because they have the same id(). And if we apply mutation on the list value, we'll see this from both names: ### Python ### >>> msg[1] = 'a' >>> msg ['h', 'a', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] >>> greeting ['h', 'a', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] ## Perl makes a distinction between values and references to those values, so the following shows different results: ### Perl # mumak:~ dyoo$ cat > test.pl my @msg = split //, "hello world"; my @greeting = @msg; print [EMAIL PROTECTED], "\n"; print [EMAIL PROTECTED], "\n"; $msg[1] = 'a'; print "@msg\n"; print "@greeting\n"; mumak:~ dyoo$ perl -w test.pl ARRAY(0x180b560) ARRAY(0x180b5b4) h a l l o w o r l d h e l l o w o r l d ## Here, we see that @msg and @greeting are really separate things in Perl: the values are in different memory locations, and assignment copies the data structures around. To get the same aliasing effect as in Python, we'd have to explicitely ask Perl to reference and dereference: ### Perl ### my $msg = [split //, "hello world"]; my $greeting = $msg; print $msg, "\n"; print $greeting, "\n"; $msg->[1] = 'a'; print "@$msg\n"; print "@$greeting\n"; # So Perl folks have a slightly more complex conceptual model: they make a distinction bewteen values and references. Python just has references. There are tradeoffs here. On the one hand, Python folks get caught off guard when they first encounter list aliasing. On the other, Perl folks get caught off guard when they first try to make a hash whose values are themselves lists. *grin* Hope this helps! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Open file error
On Tue, 17 Jan 2006, andy senoaji wrote: > I'm back to my home machine, and ran again the open method, just to test > my sanity Here are the results: [cut] Hi Andy, Unfortunately, there are a few things that might be happening here. You mentioned earlier that: > I know for sure that the file is there, I even put copies of the files > here and there, just to guess how python does the file search, but it Do you mind trying the following? I want to double check that the filename doesn't have anything silly in it like spaces. ### import os print repr(os.listdir("C:/")) ### Can you copy-and-paste what you see from this? This will show us the names of things in the toplevel directory, and should help to reveal why we're having so much trouble opening up that darn file. *grin* Good luck to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tutorials
On 1/16/06, Alan Gauld <[EMAIL PROTECTED]> wrote: > > Has anyone got an easy way of printing the Python documentation in PDF > > format. Its all in HTML and is time consuming to print. > > You can buy it in paper book form. > It's a lot cheaper than trying to print the online stuff page by page! > ... But you do realise just how > much there is to print - many hundreds of pages, probably well over > a thousand! Thats a lot of big ring binders. i remember printing out the library reference for 1.4 (waaay back in '97), then having to take it to Kinko's to dupe for our engineering team... it was already BIG then -- i can't imagine doing it now. with that said, i've organized all of Python's downloadable doc files (all types) for most versions of Python in a nice easy-to-read grid. just go to http://corepython.com and click "Documentation" on the left-hand side. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor