[Tutor] New to programming question
This is an exercise from "How to think like a Computer Scientist." The following example shows how to use concatenation and a for loop to generate an abecedarian series. "Abecedarian" refers to a series or list in which the elements appear in alphabetical order. For example, in Robert McCloskey's book Make Way for Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names in order: prefixes = "JKLMNOPQ" suffix = "ack" for letter in prefixes: print letter + suffix The output of this program is: Jack Kack Lack Mack Nack Oack Pack Qack Of course, that's not quite right because "Ouack" and "Quack" are misspelled. As an exercise, modify the program to fix this error. == In trying to solve the problem I have come up with the following: prefixes = 'JKLMNOPQ' suffix = 'ack' xsuffix = 'uack' for letter in prefixes: n = 0 if prefixes[n] == 'O' or 'Q': print prefixes[n] + xsuffix else: print letter + suffix --- I know it doesn't work, but want to know if I am on the right track. And what is the solution? Thanks Ben ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] New to programming question (Ben M.) (Joseph Q.)
Thanks for everybodys input. Am learning slowly but surely. Ben On 4/13/05, [EMAIL PROTECTED] <[EMAIL PROTECTED] > wrote:Quoting Joseph Quigley <[EMAIL PROTECTED] >:> prefixes = 'JKLMNOPQ'> suffix = 'ack'>> for letter in prefixes:> if letter == ('O') or ('Q'):> print letter + 'u' + suffix> else:> print letter + suffix Hi Joseph,This still won't work. The reason is that your if statement is interpreted likethis:if letter == 'O':print letter + 'u' + suffixelif 'Q':print letter + 'u' + suffic else:print letter + suffixDo you see? The == "binds more tightly" than the or. And, in python, 'Q' isconsidered True for the purposes of tests.So this is what happens:>>> prefixes = 'JKLMNOPQ' >>> suffix = 'ack'>> for letter in prefixes:... if letter == ('O') or ('Q'):... print letter + 'u' + suffix... else:... print letter + suffix... JuackKuackLuackMuackNuackOuackPuackQuack>>>What you can do instead is this:for letter in prefixes:if letter in ['O', 'Q']:print letter + 'u' + suffix else:print letter + suffixHTH.--John.___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] Question regarding the len function of a list while using a loop
Could somebody explain to me why the code I used to complete this exercise doesn't work. And how do you send an integer to len? Thanks Ben == As an exercise, write a loop that traverses a list and prints the length of each element. What happens if you send an integer to len? >>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]] >>> i = 0 >>> while i < len(foo): print len(foo[i]) i = i+1 5 Traceback (most recent call last): File "", line 2, in -toplevel- print len(foo[i]) TypeError: len() of unsized object___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question regarding the len function of a list while using a loop
Yes this does make sense. Thank youOn 4/14/05, Brian van den Broek <[EMAIL PROTECTED]> wrote: Ben Markwell said unto the world upon 2005-04-14 08:14:> Could somebody explain to me why the code I used to complete this exercise > doesn't work.> And how do you send an integer to len?>> Thanks>> Ben>> ==>>> *As an exercise, write a loop that traverses a list and prints the length of > each element. What happens if you send an integer to len?>> *>>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]]>>>>>i = 0>>>>while i < len(foo): >> print len(foo[i])> i = i+1>>> 5>> Traceback (most recent call last):> File "", line 2, in -toplevel-> print len(foo[i]) > TypeError: len() of unsized objectHi Ben,Max and Alberto have already explained why you got the error message.Depending on the context in which you are doing this, the having theerror crash the program might be what is desired. (I get that the context is simply an exercise, but let's pretend it is an actualprogram, written in anger :-).) Or, you might want your program tohandle the problem more elegantly.Using the general framework Alberto suggested, here's a way to do that (I've also thrown some string formatting in to make the output morefriendly): >>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]] >>> for item in foo:... try:... print "Item: %s has length %s" %(item, len(item)) ... except TypeError:... print "Item: %s has no length" %item...Item: spam! has length 5Item: 1 has no lengthItem: ['brie', 'cheddar', 'swiss'] has length 3Item: [1, 2, 3] has length 3 >>>This works by attempting to do the thing in the try part, and catchingany case than raises a TypeError (as your original code did), doingthe routine of the except block instead.Does that make sense? If not, post back and I can try to explain in more detail.Best,Brian vdB___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Trying to enter text from a file to a Dictionary
Being new to programming, I made a text file that contains terms with their definitions that I have come across in my studying. As an exercise, I thought I would make a glossary using a dictionary so I can look up words, add new words, view all entries, etc. I want to enter the words and definitions from the text file into the dict. The way the text file is set up is that one line is the word and the next line is the definition. For example: Word Definition of the word. Second Word Definition of the second word. EtcI thought this would be rather simple (maybe it really is), but I'm stuck. I can't figure out how to tell Python to read the line with the word, add the word to the Key of the dict, then read the next line and add that line to the Value of the dict, then do it all again 'til the end of the file.I tried using a! for loop like thisf = open('glossary.txt','r') gloss = {}for line in f: gloss[line] = lineWhen I tried to print this, a huge list of key/values printed out. With many copies of the same key/value pair. And the key and the value were the same. (not word followed by definition) , which afterword made sense, because, I told it that gloss[line] = lineI tried :for line in f: gloss[line] = f.readline()That got me nowhere. Sorry for being so dense. I understand what needs to happen, but am having trouble implementing it. Thanks for your help and understanding. Bring words and photos together (easily) with PhotoMail - it's free and works with Yahoo! Mail.___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: Trying to enter text from a file to a Dictionary
Hello Danny Thanks for replying to my post. > I tried :>> for line in f:Thanks for your reply to my post. > gloss[line] = f.readline()> This should have worked, but there's one problem. Whenever we're doingsomething like:for line in f:...there can be some interference between the iteration and any readline() in the body of the loop. For efficiency reasons, the iterator's allowedto march through the file ahead several lines at with an internal buffer.This means our position in the file might be further along than we might realize, and that means that readline() will give nonsensical results.So we're getting caught by a low-level detail. We should try to avoidusing both the for loop and readline() on the same file. Here's one way we can avoid the problem: while True:word = f.readline()defn = f.readline()if not word or not defn: break...Does this make sense? It does mostly...I don't see why you need the: if not word or not defn: break If this is so that when python iterates to the end of the file, it knows to stop, and if that is so, then why doesn't python know it has gotten to the end of the file without it being told? ___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: Trying to enter text from a file to a Dictionary
Hi Ben,Yes, that's the point: Python doesn't know when to stop. *grin* The way we've rewritten the loop:while True:...is an "infinite" loop that doesn't stop unless something in the loop'sbody does something extraordinary, like "breaking" out of the loop. Python is much dumber than we might expect.In more detail: Python's readline() method doesn't fail when we reach theend of a file: we actually start hitting the empty string. For example:## >>> import StringIO>>> sampleTextFile = StringIO.StringIO("""This is... a sample... text file... """)>>> sampleTextFile.readline()'This is\n' >>> sampleTextFile.readline()'a sample\n'>>> sampleTextFile.readline()'text file\n'>>> sampleTextFile.readline()''>>> sampleTextFile.readline()''## Notice that when we hit the end of the file, readline() still continues torun and give us empty string values. That's why the loop above needs tomake sure it breaks out in this particular situation. Does this make sense? Please feel free to ask questions about this. Yes The -- while true loop -- needs something to be false or it needs to be told when to stop. If that is correct, then it makes sense. Thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trying to enter text from a file to a Dictionary
On 1/27/06, Bob Gailer <[EMAIL PROTECTED]> wrote: Bob Gailer wrote:> Alan Gauld wrote:>>> Hi Ben,> I want to enter the words and definitions from the text file into the>>> dict.>>> The way the text file is set up is that one line is the word and the >>> next line is the definition.> I tried using a for loop like this>> f = open('glossary.txt','r')>>> gloss = {} >> for line in f:>>> gloss[line] = line The problem that you have is that you really need to read two lines at a>> time. >> (Assuming that the definitions are all on one line which may not be true!)>> A while loop may be easier in this case. A for loop will read each line individually. You then need to set a >> definition>> flag to tell the loop body whether you are reading a definition or a key. Either type of loop is possible. Since you started with a for loop lets>> stick with it... definition = False>> currentKey = None for line in f:>> if isDefinition:>>gloss[currentKey] = line>>currentKey = None >>isDefinition = False>> else:>>currentKey = line>>isDefinition = True> Or you can use next():>> for line in f: > gloss[line] = f.next()>Or even:[gloss.setdefault(l,f.next()) for l in f] Hello Bob I understand f.next(), but [gloss.setdefault(l,f.next()) for l in f] is beyond me at this point. Thanks for your input. Ben ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trying to enter text from a file to a Dictionary
> I understand f.next(), but [gloss.setdefault(l,f.next()) for l in f]> is beyond me at this point. [expr for l in f] is a "list comprehension". expr is an _expression_ thatmay involve l.result = [expr for l in f] # is equivalent to:result = []for l in f:result.append(expr) "list comprehension" (once understood) is often easier to read and moreefficient than the for loop.result = xxx.setdefault(key, newvalue) is a dictionary method that triesto get an item from the dictionary xxx using key. If the key is not in the dictionary it adds the item assigning it newvalue. Equivalent to:if key not in xxx:xxx[key] = newvalueresult = xxx[key]Note that list comprehension and setdefault both return something. In my code the returned values are ignored. The outcome (populating adictionary via a loop) is a "side effect". Thank you Bob. This is much to think about. I very much appreciate your concise explanation. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor