From chayek777 at gmail.com Thu Feb 2 03:26:00 2012 From: chayek777 at gmail.com (Shane) Date: Wed, 01 Feb 2012 21:26:00 -0500 Subject: [Tutor] trouble placing code into wxpython Message-ID: <4F29F438.1060600@gmail.com> Do I have to rewrite my code directly into wxpython frame or can i just copy and paste it somehoe From steve at pearwood.info Thu Feb 2 03:37:52 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 2 Feb 2012 13:37:52 +1100 Subject: [Tutor] trouble placing code into wxpython In-Reply-To: <4F29F438.1060600@gmail.com> References: <4F29F438.1060600@gmail.com> Message-ID: <20120202023752.GB29467@ando> On Wed, Feb 01, 2012 at 09:26:00PM -0500, Shane wrote: > Do I have to rewrite my code directly into wxpython frame > or can i just copy and paste it somehoe I don't know. If you try to copy and paste it, what happens? I'm afraid your question doesn't make much sense to me, and unless there happens to be an expert on wxPython here, you may have better luck asking it on a dedicated wxPython forum or mailing list. Failing that, can you explain in more detail what you mean by a wxPython frame, and why you would be pasting code directly into it instead of in your .py program file? -- Steven From chayek777 at gmail.com Thu Feb 2 07:56:23 2012 From: chayek777 at gmail.com (shane) Date: Thu, 02 Feb 2012 01:56:23 -0500 Subject: [Tutor] Fwd: Re: trouble placing code into wxpython In-Reply-To: <4F29FD20.1030203@gmail.com> References: <4F29FD20.1030203@gmail.com> Message-ID: <4F2A3397.1070102@gmail.com> i was trying to put the math.py into a frame Ive watched many tutorials. But cant seem to find out how to or where to place the code the files I want combined are attached. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: basicframe.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: math.py URL: From alan.gauld at btinternet.com Thu Feb 2 09:54:01 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 02 Feb 2012 08:54:01 +0000 Subject: [Tutor] Fwd: Re: trouble placing code into wxpython In-Reply-To: <4F2A3397.1070102@gmail.com> References: <4F29FD20.1030203@gmail.com> <4F2A3397.1070102@gmail.com> Message-ID: On 02/02/12 06:56, shane wrote: > i was trying to put the math.py into a frame Ive watched many tutorials. That sounds like you've been using video tutorials? Those are a good start but you are probably better using a written one and working through them doing the examples. You can try my GUI topic as a quick start. It uses Tkinter but finishes with a wxPython version too so it might be enough to get you started. The concepts are similar. > But cant seem to find out how to or where to place the code > the files I want combined are attached. # import wx app = wx.PySimpleApp() frame = wx.Frame(None,-1,'hello') frame.Show(1) app.MainLoop() # This code creates the GUI(*) but does nothing. You need to define the event handling functions and bind them to the widgets/events. In this case you don't have much to bind things to... A Frame is just a container, it doesn't do anything as such. You need to add other widgets such as text labels, entries, buttons etc to the Frame. Then attach your functions to the widgets. Any wxPython tutorial will show you how to do that. (*) wxPython is very OOP oriented, you normally have to create your own sub-class of Frame. There is not much you can do with a standard Frame object... If you are not comfortable with creating subclasses then you should study OOP a bit more before attempting wxPython. Either that or use Tkinter instead which is more amenable to procedural style code. The other thing is your math code is full of print statements. They won't work in a GUI. You need to get your code to return strings and then display those strings in the GUI. Finally, rewrite your fin() method to be non-recursive. Use a while loop. Otherwise you are likely to get into all sorts of trouble, its one of the most common beginners mistakes but recursion is not a good looping technique in Python. However, in a GUI you won't need fin() because the GUI mainloop will take over that function. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Thu Feb 2 13:37:31 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 02 Feb 2012 23:37:31 +1100 Subject: [Tutor] Fwd: Re: trouble placing code into wxpython In-Reply-To: <4F2A3397.1070102@gmail.com> References: <4F29FD20.1030203@gmail.com> <4F2A3397.1070102@gmail.com> Message-ID: <4F2A838B.4000803@pearwood.info> shane wrote: > i was trying to put the math.py into a frame Ive watched many tutorials. > But cant seem to find out how to or where to place the code > the files I want combined are attached. Do you mean you want to show the code in the GUI? You need to know the location of the file, then read the file and put the text into the frame. The fact that the text is actually code is irrelevant -- it could be poetry, a shopping list, code, or random gibberish. I'm afraid I don't know enough about wxPython to tell you how to display text in the frame, but you can read the file like this: fp = open(r'C:\path\to\my\file\module.py', 'r') text = fp.read() fp.close() Also I see that you have a file called "math.py". That is a bad idea, because it will clash with a standard Python module also called "math". Best to find another name for it. -- Steven From tmikk at umn.edu Thu Feb 2 18:36:25 2012 From: tmikk at umn.edu (Tonu Mikk) Date: Thu, 2 Feb 2012 11:36:25 -0600 Subject: [Tutor] exercise with classes Message-ID: I am learning Python using the "Learn Python the Hard Way" book by Zed Shaw. I reached exercise 42 where we learn about Python classes. The exercise shows a game with one class that includes all the definitions for playing the game. For extra credit we are asked to create another version of this game where we use two classes - one for the room definitions and the other for the playing the game. I feel stumped and don't know how to go about creating this game with two classes. So far I have searched for info on how to pass variables from one class to another and have been able to create a small two class program (attached). But I seem unable to generalize from here and apply this to the game exercise. What would you suggest for me to try next? Thank you, Tonu -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: classes_test.py Type: application/octet-stream Size: 357 bytes Desc: not available URL: From ramit.prasad at jpmorgan.com Thu Feb 2 21:32:38 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 2 Feb 2012 20:32:38 +0000 Subject: [Tutor] exercise with classes In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47410D30B@SCACMX008.exchad.jpmchase.net> >I am learning Python using the "Learn Python the Hard Way" book by Zed Shaw. I reached exercise 42 where we learn about Python classes. The exercise shows a game with one class that includes all the definitions for playing the game. For extra credit we are asked to create another version of this game where we use two classes - one for the room definitions and the other for the playing the game. I feel stumped and don't know how to go about creating this game with two classes. > So far I have searched for info on how to pass variables from one class to another and have been able to create a small two class program (attached). But I seem unable to generalize from here and apply this to the game exercise. What would you suggest for me to try next? It is usually better to include short code directly in your email or link to something like pastebin for longer samples. Many of the people on this list do access it from email and they do not get attachments. As for the extra credit: You can store the possible actions in the room (dodge, shoot, etc.). So for central_corridor (an instance of class Room) you have the player do something like action = raw_input('>) consequence = central_corridor.do_action( action ) new_room = Game.getRoom( consequence ) # Might need to replace Game with self depending on where this code is located. action = raw_input('>) consequence = new_room.do_action( action ) ... Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From blongworth at whoi.edu Thu Feb 2 21:50:49 2012 From: blongworth at whoi.edu (Brett Longworth) Date: Thu, 02 Feb 2012 15:50:49 -0500 Subject: [Tutor] better looping construct for replacing elements in file? Message-ID: <4F2AF729.3060106@whoi.edu> Hello, Today I wrote a quick script to replace elements in multiple lines of a file with corresponding elements from a single line in another file, linking the two via an index element. The code iterates through the entire source file to find the matching index for each line of the destination file. This works, but it's clearly a terrible way to solve the problem. Can someone point me to a more efficient, pythonic solution? thanks, -Brett Code: wheel = "A794" wheelfile = "A794.txt" statusfile = "CURRENT.ams" sfile = csv.reader(open(statusfile), delimiter='\t') statusWriter = csv.writer(open('statustest.txt', 'wb'), delimiter='\t', quotechar='|', quoting=csv.QUOTE_MINIMAL) for sline in sfile: #print sline wfile = csv.reader(open(wheelfile)) for line in wfile: #print line[0] #print sline[18] if line[0] == sline[18]: sline[0] = line [1] sline[1] = "OSG"+str(line[4]) sline[17] = wheel sline[21] = line[9] statusWriter.writerow(sline) Excerpt of wheelfile: "2","X496","02/01/12","OSG","106788","85411","GS-13365","Outside Primary Standard | > Modern (1950)","2.43","149177" "3","C655","02/01/12","OSG","106534","83028","HY-19231","Outside Blank | > 30,000","3.63","149178" Excerpt of statusfile: Y002 BET2918 10/18/06 15:32:52 160.00 174 1.000 16408 1.306E-12 1.213E-10 402.6 405.9 -42.7 3.2 1.2242 -0.0220 1.822 -12.66 A499 2 1 5631 86523 data 3.7E-6 Y002 BET2918 10/18/06 15:35:46 150.00 162 1.000 15654 1.313E-12 1.226E-10 407.6 410.3 -43.9 2.0 1.2180 -0.0243 1.894 -13.03 A499 2 1 5631 86523 3.7E-6 0003 BET7147 10/18/06 15:55:33 170.00 186 1.000 3442 2.903E-13 2.693E-11 357.7 359.3 -46.1 2.5 1.2000 0.0276 1.734 -12.86 A499 3 1 5631 86524 3.3E-6 0003 BET7147 10/18/06 15:58:49 170.00 185 1.000 3232 2.772E-13 2.598E-11 351.8 353.4 -46.1 3.5 1.2000 0.0149 1.761 -12.66 A499 3 1 5631 86524 3.2E-6 0003 BET7147 10/18/06 16:02:06 170.00 185 1.000 3399 2.955E-13 2.753E-11 346.9 -- Brett Longworth Research Associate Woods Hole Oceanographic Institution ph: 508.289.3559 fax: 508.457.2183 From joel.goldstick at gmail.com Thu Feb 2 22:16:54 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 2 Feb 2012 16:16:54 -0500 Subject: [Tutor] better looping construct for replacing elements in file? In-Reply-To: <4F2AF729.3060106@whoi.edu> References: <4F2AF729.3060106@whoi.edu> Message-ID: On Thu, Feb 2, 2012 at 3:50 PM, Brett Longworth wrote: > Hello, > > Today I wrote a quick script to replace elements in multiple lines of a file > with corresponding elements from a single line in another file, linking the > two via an index element. The code iterates through the entire source file > to find the matching index for each line of the destination file. This > works, but it's clearly a terrible way to solve the problem. Can someone > point me to a more efficient, pythonic solution? > > thanks, > -Brett > > Code: > > wheel = "A794" > wheelfile = "A794.txt" > statusfile = "CURRENT.ams" > > sfile = csv.reader(open(statusfile), delimiter='\t') > statusWriter = csv.writer(open('statustest.txt', 'wb'), delimiter='\t', > quotechar='|', quoting=csv.QUOTE_MINIMAL) > > for sline in sfile: > ?#print sline > ?wfile = csv.reader(open(wheelfile)) > ?for line in wfile: > ? ?#print line[0] > ? ?#print sline[18] > ? ?if line[0] == sline[18]: > ? ? ?sline[0] = line [1] > ? ? ?sline[1] = "OSG"+str(line[4]) > ? ? ?sline[17] = wheel > ? ? ?sline[21] = line[9] > ? ? ?statusWriter.writerow(sline) > > Excerpt of wheelfile: > > "2","X496","02/01/12","OSG","106788","85411","GS-13365","Outside Primary > Standard | > Modern (1950)","2.43","149177" > "3","C655","02/01/12","OSG","106534","83028","HY-19231","Outside Blank | > > 30,000","3.63","149178" > > Excerpt of statusfile: > > Y002 ? ?BET2918 ? ?10/18/06 15:32:52 ? ?160.00 ? ?174 ? ?1.000 ? ?16408 > ?1.306E-12 ? ?1.213E-10 ? ?402.6 ? ?405.9 ? ?-42.7 ? ?3.2 ? ?1.2242 > ?-0.0220 ? ?1.822 ? ?-12.66 ? ?A499 ? ?2 ? ?1 ? ?5631 ? ?86523 ? ?data > ?3.7E-6 > Y002 ? ?BET2918 ? ?10/18/06 15:35:46 ? ?150.00 ? ?162 ? ?1.000 ? ?15654 > ?1.313E-12 ? ?1.226E-10 ? ?407.6 ? ?410.3 ? ?-43.9 ? ?2.0 ? ?1.2180 > ?-0.0243 ? ?1.894 ? ?-13.03 ? ?A499 ? ?2 ? ?1 ? ?5631 ? ?86523 ? ? ? ?3.7E-6 > 0003 ? ?BET7147 ? ?10/18/06 15:55:33 ? ?170.00 ? ?186 ? ?1.000 ? ?3442 > ?2.903E-13 ? ?2.693E-11 ? ?357.7 ? ?359.3 ? ?-46.1 ? ?2.5 ? ?1.2000 > ?0.0276 ? ?1.734 ? ?-12.86 ? ?A499 ? ?3 ? ?1 ? ?5631 ? ?86524 ? ? ? ?3.3E-6 > 0003 ? ?BET7147 ? ?10/18/06 15:58:49 ? ?170.00 ? ?185 ? ?1.000 ? ?3232 > ?2.772E-13 ? ?2.598E-11 ? ?351.8 ? ?353.4 ? ?-46.1 ? ?3.5 ? ?1.2000 > ?0.0149 ? ?1.761 ? ?-12.66 ? ?A499 ? ?3 ? ?1 ? ?5631 ? ?86524 ? ? ? ?3.2E-6 > 0003 ? ?BET7147 ? ?10/18/06 16:02:06 ? ?170.00 ? ?185 ? ?1.000 ? ?3399 > ?2.955E-13 ? ?2.753E-11 ? ?346.9 > > > -- > Brett Longworth > Research Associate > Woods Hole Oceanographic Institution > ph: 508.289.3559 > fax: 508.457.2183 > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor If you are a little savvy with sql you could write each csv to tables, Since you have csv file input why not write each to a db table. Then you could join on line[0] == sline[18] and update your 4 fields. Then dump table as csv -- Joel Goldstick From blongworth at whoi.edu Thu Feb 2 22:29:25 2012 From: blongworth at whoi.edu (Brett Longworth) Date: Thu, 02 Feb 2012 16:29:25 -0500 Subject: [Tutor] better looping construct for replacing elements in file? In-Reply-To: References: <4F2AF729.3060106@whoi.edu> Message-ID: <4F2B0035.70205@whoi.edu> Hi Joel, Thanks for the reply. The little voice in my head was yelling, "Easier with SQL!" the entire time, but I'm trying to learn Python. -Brett On 2/2/2012 4:16 PM, Joel Goldstick wrote: > On Thu, Feb 2, 2012 at 3:50 PM, Brett Longworth wrote: >> Hello, >> >> Today I wrote a quick script to replace elements in multiple lines of a file >> with corresponding elements from a single line in another file, linking the >> two via an index element. The code iterates through the entire source file >> to find the matching index for each line of the destination file. This >> works, but it's clearly a terrible way to solve the problem. Can someone >> point me to a more efficient, pythonic solution? >> >> thanks, >> -Brett >> >> Code: >> >> wheel = "A794" >> wheelfile = "A794.txt" >> statusfile = "CURRENT.ams" >> >> sfile = csv.reader(open(statusfile), delimiter='\t') >> statusWriter = csv.writer(open('statustest.txt', 'wb'), delimiter='\t', >> quotechar='|', quoting=csv.QUOTE_MINIMAL) >> >> for sline in sfile: >> #print sline >> wfile = csv.reader(open(wheelfile)) >> for line in wfile: >> #print line[0] >> #print sline[18] >> if line[0] == sline[18]: >> sline[0] = line [1] >> sline[1] = "OSG"+str(line[4]) >> sline[17] = wheel >> sline[21] = line[9] >> statusWriter.writerow(sline) >> >> Excerpt of wheelfile: >> >> "2","X496","02/01/12","OSG","106788","85411","GS-13365","Outside Primary >> Standard |> Modern (1950)","2.43","149177" >> "3","C655","02/01/12","OSG","106534","83028","HY-19231","Outside Blank |> >> 30,000","3.63","149178" >> >> Excerpt of statusfile: >> >> Y002 BET2918 10/18/06 15:32:52 160.00 174 1.000 16408 >> 1.306E-12 1.213E-10 402.6 405.9 -42.7 3.2 1.2242 >> -0.0220 1.822 -12.66 A499 2 1 5631 86523 data >> 3.7E-6 >> Y002 BET2918 10/18/06 15:35:46 150.00 162 1.000 15654 >> 1.313E-12 1.226E-10 407.6 410.3 -43.9 2.0 1.2180 >> -0.0243 1.894 -13.03 A499 2 1 5631 86523 3.7E-6 >> 0003 BET7147 10/18/06 15:55:33 170.00 186 1.000 3442 >> 2.903E-13 2.693E-11 357.7 359.3 -46.1 2.5 1.2000 >> 0.0276 1.734 -12.86 A499 3 1 5631 86524 3.3E-6 >> 0003 BET7147 10/18/06 15:58:49 170.00 185 1.000 3232 >> 2.772E-13 2.598E-11 351.8 353.4 -46.1 3.5 1.2000 >> 0.0149 1.761 -12.66 A499 3 1 5631 86524 3.2E-6 >> 0003 BET7147 10/18/06 16:02:06 170.00 185 1.000 3399 >> 2.955E-13 2.753E-11 346.9 >> >> >> -- >> Brett Longworth >> Research Associate >> Woods Hole Oceanographic Institution >> ph: 508.289.3559 >> fax: 508.457.2183 >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > If you are a little savvy with sql you could write each csv to tables, > Since you have csv file input why not write each to a db table. Then > you could join on line[0] == sline[18] and update your 4 fields. > > Then dump table as csv > -- Brett Longworth Research Associate Woods Hole Oceanographic Institution ph: 508.289.3559 fax: 508.457.2183 From joel.goldstick at gmail.com Thu Feb 2 22:44:30 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 2 Feb 2012 16:44:30 -0500 Subject: [Tutor] better looping construct for replacing elements in file? In-Reply-To: <4F2B0035.70205@whoi.edu> References: <4F2AF729.3060106@whoi.edu> <4F2B0035.70205@whoi.edu> Message-ID: On Thu, Feb 2, 2012 at 4:29 PM, Brett Longworth wrote: > Hi Joel, > > Thanks for the reply. The little voice in my head was yelling, "Easier with > SQL!" the entire time, but I'm trying to learn Python. > > -Brett > > > On 2/2/2012 4:16 PM, Joel Goldstick wrote: >> >> On Thu, Feb 2, 2012 at 3:50 PM, Brett Longworth >> ?wrote: >>> >>> Hello, >>> >>> Today I wrote a quick script to replace elements in multiple lines of a >>> file >>> with corresponding elements from a single line in another file, linking >>> the >>> two via an index element. The code iterates through the entire source >>> file >>> to find the matching index for each line of the destination file. This >>> works, but it's clearly a terrible way to solve the problem. Can someone >>> point me to a more efficient, pythonic solution? >>> >>> thanks, >>> -Brett >>> >>> Code: >>> >>> wheel = "A794" >>> wheelfile = "A794.txt" >>> statusfile = "CURRENT.ams" >>> >>> sfile = csv.reader(open(statusfile), delimiter='\t') >>> statusWriter = csv.writer(open('statustest.txt', 'wb'), delimiter='\t', >>> quotechar='|', quoting=csv.QUOTE_MINIMAL) >>> >>> for sline in sfile: >>> ?#print sline >>> ?wfile = csv.reader(open(wheelfile)) >>> ?for line in wfile: >>> ? ?#print line[0] >>> ? ?#print sline[18] >>> ? ?if line[0] == sline[18]: >>> ? ? ?sline[0] = line [1] >>> ? ? ?sline[1] = "OSG"+str(line[4]) >>> ? ? ?sline[17] = wheel >>> ? ? ?sline[21] = line[9] >>> ? ? ?statusWriter.writerow(sline) >>> >>> Excerpt of wheelfile: >>> >>> "2","X496","02/01/12","OSG","106788","85411","GS-13365","Outside Primary >>> Standard |> ?Modern (1950)","2.43","149177" >>> "3","C655","02/01/12","OSG","106534","83028","HY-19231","Outside Blank |> >>> 30,000","3.63","149178" >>> >>> Excerpt of statusfile: >>> >>> Y002 ? ?BET2918 ? ?10/18/06 15:32:52 ? ?160.00 ? ?174 ? ?1.000 ? ?16408 >>> ?1.306E-12 ? ?1.213E-10 ? ?402.6 ? ?405.9 ? ?-42.7 ? ?3.2 ? ?1.2242 >>> ?-0.0220 ? ?1.822 ? ?-12.66 ? ?A499 ? ?2 ? ?1 ? ?5631 ? ?86523 ? ?data >>> ?3.7E-6 >>> Y002 ? ?BET2918 ? ?10/18/06 15:35:46 ? ?150.00 ? ?162 ? ?1.000 ? ?15654 >>> ?1.313E-12 ? ?1.226E-10 ? ?407.6 ? ?410.3 ? ?-43.9 ? ?2.0 ? ?1.2180 >>> ?-0.0243 ? ?1.894 ? ?-13.03 ? ?A499 ? ?2 ? ?1 ? ?5631 ? ?86523 >>> ?3.7E-6 >>> 0003 ? ?BET7147 ? ?10/18/06 15:55:33 ? ?170.00 ? ?186 ? ?1.000 ? ?3442 >>> ?2.903E-13 ? ?2.693E-11 ? ?357.7 ? ?359.3 ? ?-46.1 ? ?2.5 ? ?1.2000 >>> ?0.0276 ? ?1.734 ? ?-12.86 ? ?A499 ? ?3 ? ?1 ? ?5631 ? ?86524 >>> ?3.3E-6 >>> 0003 ? ?BET7147 ? ?10/18/06 15:58:49 ? ?170.00 ? ?185 ? ?1.000 ? ?3232 >>> ?2.772E-13 ? ?2.598E-11 ? ?351.8 ? ?353.4 ? ?-46.1 ? ?3.5 ? ?1.2000 >>> ?0.0149 ? ?1.761 ? ?-12.66 ? ?A499 ? ?3 ? ?1 ? ?5631 ? ?86524 >>> ?3.2E-6 >>> 0003 ? ?BET7147 ? ?10/18/06 16:02:06 ? ?170.00 ? ?185 ? ?1.000 ? ?3399 >>> ?2.955E-13 ? ?2.753E-11 ? ?346.9 >>> >>> >>> -- >>> Brett Longworth >>> Research Associate >>> Woods Hole Oceanographic Institution >>> ph: 508.289.3559 >>> fax: 508.457.2183 >>> >>> _______________________________________________ >>> Tutor maillist ?- ?Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >> >> If you are a little savvy with sql you could write each csv to tables, >> Since you have csv file input why not write each to a db table. ?Then >> you could join on ?line[0] == sline[18] and update your 4 fields. >> >> Then dump table as csv >> > > > -- > Brett Longworth > Research Associate > Woods Hole Oceanographic Institution > ph: 508.289.3559 > fax: 508.457.2183 > Even so, you would be learning how to do some simple sql things in python. It comes with sqlite3 so you don't even need to have mysql on the machine -- Joel Goldstick From __peter__ at web.de Thu Feb 2 23:04:23 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 02 Feb 2012 23:04:23 +0100 Subject: [Tutor] better looping construct for replacing elements in file? References: <4F2AF729.3060106@whoi.edu> Message-ID: Brett Longworth wrote: > Hello, > > Today I wrote a quick script to replace elements in multiple lines of a > file with corresponding elements from a single line in another file, > linking the two via an index element. The code iterates through the > entire source file to find the matching index for each line of the > destination file. This works, but it's clearly a terrible way to solve > the problem. Can someone point me to a more efficient, pythonic solution? > > thanks, > -Brett > > Code: > > wheel = "A794" > wheelfile = "A794.txt" > statusfile = "CURRENT.ams" > > sfile = csv.reader(open(statusfile), delimiter='\t') > statusWriter = csv.writer(open('statustest.txt', 'wb'), delimiter='\t', > quotechar='|', quoting=csv.QUOTE_MINIMAL) > > for sline in sfile: > #print sline > wfile = csv.reader(open(wheelfile)) > for line in wfile: > #print line[0] > #print sline[18] > if line[0] == sline[18]: > sline[0] = line [1] > sline[1] = "OSG"+str(line[4]) > sline[17] = wheel > sline[21] = line[9] > statusWriter.writerow(sline) You could put the data from wheelfile into a dictionary with the first column as the key, something like import csv from contextlib import contextmanager from functools import partial @contextmanager def manager(mode, process, filename, **kw): with open(filename, mode) as f: yield process(f, **kw) reader = partial(manager, "rb", csv.reader) writer = partial(manager, "wb", csv.writer) wheel = "A794" wheelfilename = "A794.txt" statusfilename = "CURRENT.ams" wheel_lookup = {} with reader(wheelfilename) as rows: for row in rows: key = row[0] if key in wheel_lookup: raise ValueError("duplicate key {}".format(key)) lookup[key] = row with reader(statusfilename, delimiter="\t") as status_rows: with writer("statustest.txt", delimiter="\t") as dest: for status_row in status_rows: key = status_row[18] if key in lookup: wheel_row = wheel_lookup[key] status_row[0] = wheel_row[1] status_row[1] = "OSG{}".format(wheel_row[4]) status_row[17] = wheel status_row[21] = wheel_row[9] dest.writerow(status_row) I hope I didn't confuse the files or columns... From rhettnaxel at gmail.com Thu Feb 2 23:23:46 2012 From: rhettnaxel at gmail.com (Alexander Etter) Date: Thu, 2 Feb 2012 17:23:46 -0500 Subject: [Tutor] exercise with classes In-Reply-To: References: Message-ID: <0D8DAA07-90CE-48C4-8205-187D8C74B037@gmail.com> On Feb 2, 2012, at 12:36, Tonu Mikk wrote: > I feel stumped and don't know how to go about creating this game with two classes. > > So far I have searched for info on how to pass variables from one class to another and have been able to create a small two class program (attached). > Thank you, > Tonu > > ______________________________ Hi Tonu. I'm fairly certain that your second class is missing the most important function of a class, the __init__ function! It's necessary to initialize the object. Add it to your second class and see how it changes things. Alexander -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Feb 3 02:09:23 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 03 Feb 2012 01:09:23 +0000 Subject: [Tutor] exercise with classes In-Reply-To: References: Message-ID: On 02/02/12 17:36, Tonu Mikk wrote: > So far I have searched for info on how to pass variables from one class > to another and have been able to create a small two class program > (attached). But I seem unable to generalize from here and apply this > to the game exercise. What would you suggest for me to try next? Remember that OOP is about creating objects from classes. You can pass an object to another rather than just the variables, in fact its preferable! Also remember that you can create many objects from one class. So just because you have one Room class doesn't mean you are stuck with one room object. You can have many and each can be connected to another. You can get rooms to describe themselves, you can enter a room. You might even be able to create new rooms or destroy existing ones. These actions can all be methods of your Room class. Here is an example somewhat like yours that passes objects: class Printer: def __init__(self,number=0): self.value = number def sayIt(self): print self.value class MyApp: def __init__(self, aPrinter = None): if aPrinter == None: # if no object passed create one aPrinter = Printer() self.obj = aPrinter # assign object def doIt() self.obj.sayIt() # use object def test() p = Printer(42) a1 MyApp() a2 = MyApp(p) # pass p object into a2 a1.doIt() # prints default value = 0 a2.doIt() # prints 42, the value of p test() HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Feb 3 02:12:35 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 03 Feb 2012 01:12:35 +0000 Subject: [Tutor] better looping construct for replacing elements in file? In-Reply-To: References: <4F2AF729.3060106@whoi.edu> <4F2B0035.70205@whoi.edu> Message-ID: On 02/02/12 21:44, Joel Goldstick wrote: > On Thu, Feb 2, 2012 at 4:29 PM, Brett Longworth wrote: >> Hi Joel, >> >> Thanks for the reply. The little voice in my head was yelling, "Easier with >> SQL!" the entire time, but I'm trying to learn Python. > > Even so, you would be learning how to do some simple sql things in > python. It comes with sqlite3 so you don't even need to have mysql on > the machine > And you can run SQLite as an in-memory database so its even fast for temporary tables like this! (assuming you have enough RAM!) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From pine508 at hotmail.com Fri Feb 3 06:05:13 2012 From: pine508 at hotmail.com (Che M) Date: Fri, 3 Feb 2012 00:05:13 -0500 Subject: [Tutor] any cons to using a module of functions? Message-ID: I have a bunch of functions that do various utility-type tasks in an application (such as prettifying date strings, etc.), and they are used in many modules. Much of the time, I have just been lazily copying and pasting the functions into whichever modules need them. I realize that is very bad form and I should refactor, and so I am beginning to put these functions in their own module so that I can import the module and its functions when I need it; they will all be in one place and only only place. My question is about resources. Let's say I have the module, myUtils.py, and I import it into every other module that will need one or more of the functions within it. Is this in any way costly in terms of memory? (since each time I import myUtils.py I import *all* the functions, instead of in the cut&paste approach, where I just run the functions I need). I'm fairly sure this is not at all an issue, but I just want to understand why it's not. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Feb 3 09:56:14 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 03 Feb 2012 09:56:14 +0100 Subject: [Tutor] any cons to using a module of functions? References: Message-ID: Che M wrote: > > I have a bunch of functions that do various utility-type tasks in an > application (such as prettifying date strings, etc.), and they are used in > many modules. Much of the time, I have just been lazily copying and > pasting the functions into whichever modules need them. I realize that is > very bad form and I should refactor, and so I am beginning to put these > functions in their own module so that I can import the module and its > functions when I need it; they will all be in one place and only only > place. > > My question is about resources. Let's say I have the module, myUtils.py, > and I import it into every other module that will need one or more of the > functions within it. Is this in any way costly in terms of memory? > (since each time I import myUtils.py I import *all* the functions, instead > of in the cut&paste approach, where I just run the functions I need). I hope by "importing all functions" you mean import myutils or from myutils import foo, bar The oh-so-convenient from myutils import * will sooner or later result in nasty name clashes. > I'm fairly sure this is not at all an issue, but I just want to understand > why it's not. After entering the interactive interpreter (Python 2.7) I see >>> import sys >>> len(sys.modules) 39 >>> len(sys.builtin_module_names) 20 So there are already forty or sixty modules, depending on how you count; the memory and runtime impact of adding one more is likely negligable. There is an effect on your processes. If you hammer up a quick and dirty script using your kitchen-sink myutils.py, then forget the script, and in a year or so need it again it's likely that myutils have evolved and your script will not work out of the box. At that point it will start to pay off having unit tests in place that ensure a stable api and to put everything into version control. From alan.gauld at btinternet.com Fri Feb 3 09:59:38 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 03 Feb 2012 08:59:38 +0000 Subject: [Tutor] any cons to using a module of functions? In-Reply-To: References: Message-ID: On 03/02/12 05:05, Che M wrote: > is very bad form and I should refactor, and so I am beginning to put > these functions in their own module so that I can import the module and > its functions when I need it; they will all be in one place and only > only place. While that's tempting it is better if you use multiple modules such that the functions in them are related in some way. A single mixed bag of functions will eventually become messy to maintain. Even if some modules only contain a single function its a lot clearer than having a "bag of bits" > My question is about resources. Let's say I have the module, myUtils.py, > and I import it into every other module that will need one or more of > the functions within it. Is this in any way costly in terms of memory? Not really, Python creates one instance of the module and all the importing modules refer to that instance. The only way it's wasteful is if you have 20 functions and only need two then you have 18 function objects that you don't need. (see the point above about multiple modules!) But even then the memory usage is unlikely to be a major issue since 18 function objects will generally consume minimal memory on a modern PC. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From Simeon.Tesfaye at eaudeparis.fr Fri Feb 3 16:46:13 2012 From: Simeon.Tesfaye at eaudeparis.fr (Simeon Tesfaye) Date: Fri, 03 Feb 2012 16:46:13 +0100 Subject: [Tutor] Issue with a shapefile (ArcGIS) library (pyshp) "unpack requires a string argument of length 8" Message-ID: <4F2C0F55020000470000394B@groupwise.eaudeparis.net> Hello everyone, I am having a bit of trouble here with my code, which uses a shapefile library, named pyshp, to import, edit, and save GIS files within Python. So, I open up my shapefile (data is polylines, meaning, not points or polygons) "shapefile=shapefile.Reader("file.shp") shps=shapefile.shapes() shprec = shapefile.records() " Then I carry out some edits, and I save my file. When I want to open it again, within the same script, in order to access some of the data I just modified, I get this message : "Traceback (most recent call last): File "", line 1, in troncop=troncon.shapes() File "C:\Python25\Lib\shapefile.py", line 310, in shapes while shp.tell() < self.shpLength: File "C:\Python25\Lib\shapefile.py", line 222, in __shape print(f.read(8)) File "C:\Python25\lib\struct.py", line 87, in unpack return o.unpack(s) error: unpack requires a string argument of length 8" I reckon this part tries to import header information for shape data, which would be stored in C (?), and fails to "unpack" it in PYTHON. I've tried putting an "IF" to check whether f.read(8) was actually a string (type) and of length equal to 8. I still get the same error message. I've also tried skipping the "unpack" part altogther, not with much success. I'm really not too familiar with Python, si if anyone could help me out with this, I'd be really grateful. Thanks in advance, S.T. -------------- next part -------------- An HTML attachment was scrubbed... URL: From defensoft at gmail.com Fri Feb 3 17:15:24 2012 From: defensoft at gmail.com (Nate Lastname) Date: Fri, 3 Feb 2012 11:15:24 -0500 Subject: [Tutor] Issue with a shapefile (ArcGIS) library (pyshp) "unpack requires a string argument of length 8" In-Reply-To: <4F2C0F55020000470000394B@groupwise.eaudeparis.net> References: <4F2C0F55020000470000394B@groupwise.eaudeparis.net> Message-ID: On Fri, Feb 3, 2012 at 10:46 AM, Simeon Tesfaye < Simeon.Tesfaye at eaudeparis.fr> wrote: > Hello everyone, > > I am having a bit of trouble here with my code, which uses a shapefile > library, named pyshp, to import, edit, and save GIS files within Python. > So, I open up my shapefile (data is polylines, meaning, not points or > polygons) > "shapefile=shapefile.Reader("file.shp") > shps=shapefile.shapes() > shprec = shapefile.records() > " > Then I carry out some edits, and I save my file. > When I want to open it again, within the same script, in order to access > some of the data I just modified, I get this message : > > "Traceback (most recent call last): > File "", line 1, in > troncop=troncon.shapes() > File "C:\Python25\Lib\shapefile.py", line 310, in shapes > while shp.tell() < self.shpLength: > File "C:\Python25\Lib\shapefile.py", line 222, in __shape > print(f.read(8)) > File "C:\Python25\lib\struct.py", line 87, in unpack > return o.unpack(s) > error: unpack requires a string argument of length 8" > > > I reckon this part tries to import header information for shape data, > which would be stored in C (?), and fails to "unpack" it in PYTHON. > > I've tried putting an "IF" to check whether f.read(8) was actually a > string (type) and of length equal to 8. I still get the same error message. > I've also tried skipping the "unpack" part altogther, not with much > success. > > I'm really not too familiar with Python, si if anyone could help me out > with this, I'd be really grateful. > > Thanks in advance, > > S.T. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > All that this error means is that you have an array longer than the number of values that you are assigning to it. I.E: array = [1, 2, 3] a, b = array This causes an error since there are too many values in the array. To fix this, just change the second line to: a, b = array[:2] in my example. -- My Blog - Defenestration Coding http://defenestrationcoding.wordpress.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Fri Feb 3 17:26:56 2012 From: d at davea.name (Dave Angel) Date: Fri, 03 Feb 2012 11:26:56 -0500 Subject: [Tutor] Issue with a shapefile (ArcGIS) library (pyshp) "unpack requires a string argument of length 8" In-Reply-To: <4F2C0F55020000470000394B@groupwise.eaudeparis.net> References: <4F2C0F55020000470000394B@groupwise.eaudeparis.net> Message-ID: <4F2C0AD0.30807@davea.name> On 02/03/2012 10:46 AM, Simeon Tesfaye wrote: > Hello everyone, > Two thoughts, but realize I don't know anything about pyshp. > I am having a bit of trouble here with my code, which uses a shapefile library, named pyshp, to import, edit, and save GIS files within Python. > So, I open up my shapefile (data is polylines, meaning, not points or polygons) > "shapefile=shapefile.Reader("file.shp") > shps=shapefile.shapes() > shprec = shapefile.records() > " > Then I carry out some edits, and I save my file. 1) Do you close the file? > When I want to open it again, within the same script, in order to access some of the data I just modified, I get this message : > > "Traceback (most recent call last): > File "", line 1, in > troncop=troncon.shapes() > File "C:\Python25\Lib\shapefile.py", line 310, in shapes > while shp.tell()< self.shpLength: > File "C:\Python25\Lib\shapefile.py", line 222, in __shape > print(f.read(8)) 2) Did you add that line? I'm guessing you inserted that right before a read() , so you could see what the data looks like. But this statement reads the 8 bytes and prints them, then throws them away. So the original read() that follows will get the next 8 bytes of the file, which might not look right. > File "C:\Python25\lib\struct.py", line 87, in unpack > return o.unpack(s) > error: unpack requires a string argument of length 8" > > > I reckon this part tries to import header information for shape data, which would be stored in C (?), and fails to "unpack" it in PYTHON. > > I've tried putting an "IF" to check whether f.read(8) was actually a string (type) and of length equal to 8. I still get the same error message. > I've also tried skipping the "unpack" part altogther, not with much success. > > I'm really not too familiar with Python, si if anyone could help me out with this, I'd be really grateful. > You should supply a link to the pyshp so that people who are willing to install it, will be sure to get the same one you did. Likewise any other environmental data about your system. I can tell you're running Python 2.5 on some Windows system, but it'd be nice if you just said so. Other thoughts: If there's any binary data in that file, you might need to open it with a "b" mode. Without it Windows will convert crlf into linefeeds, which you don't want to do if it's binary data. We don't see your open here, so who knows? -- DaveA From silideba at gmail.com Fri Feb 3 21:32:13 2012 From: silideba at gmail.com (Debashish Saha) Date: Sat, 4 Feb 2012 02:02:13 +0530 Subject: [Tutor] (no subject) Message-ID: what is the basic difference between numpy and pylab? -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Feb 3 21:50:54 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 03 Feb 2012 21:50:54 +0100 Subject: [Tutor] Comparing numpy and pylab References: Message-ID: Debashish Saha wrote: Welcome! > what is the basic difference between numpy and pylab? You can find out yourself. Start Python's interactive interpreter and type help("pylab"): >>> help("pylab") ... This is a procedural interface to the matplotlib object-oriented plotting library. ... >>> help("numpy") ... NumPy ===== Provides 1. An array object of arbitrary homogeneous items 2. Fast mathematical operations over arrays 3. Linear Algebra, Fourier Transforms, Random Number Generation ... Get into the habit to look for an answer yourself before you ask here. Then tell us what you have already tried. From breamoreboy at yahoo.co.uk Sat Feb 4 00:57:05 2012 From: breamoreboy at yahoo.co.uk (Blockheads Oi Oi) Date: Fri, 03 Feb 2012 23:57:05 +0000 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On 03/02/2012 20:32, Debashish Saha wrote: > what is the basic difference between numpy and pylab? > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor http://catb.org/esr/faqs/smart-questions.html -- Cheers. Mark Lawrence. From stayvoid at gmail.com Sat Feb 4 01:30:45 2012 From: stayvoid at gmail.com (Stayvoid) Date: Sat, 4 Feb 2012 03:30:45 +0300 Subject: [Tutor] __getattribute__ Message-ID: Hi! Could you provide some examples (easy and hard ones) and comments on the topic? I'm trying to understand how this thing works. Cheers. From alan.gauld at btinternet.com Sat Feb 4 02:06:27 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 04 Feb 2012 01:06:27 +0000 Subject: [Tutor] __getattribute__ In-Reply-To: References: Message-ID: On 04/02/12 00:30, Stayvoid wrote: > Could you provide some examples (easy and hard ones) and comments on the topic? > I'm trying to understand how this thing works. Commenting on the topic... It's not one most beginners(*) should be worrying about you rarely need to use it. But its slightly easier than the related __setattribute__. (*)And this is a list for beginners... Now does that help, or would you like to be more specific? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Feb 4 03:36:24 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 04 Feb 2012 13:36:24 +1100 Subject: [Tutor] __getattribute__ In-Reply-To: References: Message-ID: <4F2C99A8.9000107@pearwood.info> Stayvoid wrote: > Hi! > > Could you provide some examples (easy and hard ones) and comments on the topic? > I'm trying to understand how this thing works. When you do an attribute lookup on an object, say obj.attr, Python uses something like a search path to find the attribute: it tries various things, and looks in various places, until it has a success or finally gives up. Here's a simplified version: 1) First try to create a computed attribute using the special method __getattribute__ (new style classes only). 2) If not successful, look in the instance itself. 3) If not found, look in the class. 4) If still not found, look in any superclasses (if any). 5) If still not found, try to create a computed attribute using the special __getattr__ method. 6) If not successful, raise AttributeError. "New style classes" are those that inherit from object, or a Python built-in type like str, int, list, etc. class Spam: # "classic class", __getattribute__ is ignored pass class Ham(object): # "new style" class, __getattribute__ is special pass "Classic classes" come from the earliest versions of Python. "New style classes" started in Python 2.2, which is not so new any more, but the name has stuck. Starting from Python 3, all classes are "new style" and the distinction can be ignored. Notice that there are two special methods: __getattribute__ is always called, and if it returns a value, that value is used. __getattr__ is only called if everything else fails. Here's an example of how you might use them: class Test(object): a = "this is attached to the class" def __init__(self): self.b = "this is attached to the instance" def __getattr__(self, name): print("calling __getattr__") if name == 'c': return "this is computed by __getattr__" else: # Nothing left to do. You have to raise an exception yourself. raise AttributeError('no such attribute') def __getattribute__(self, name): print("calling __getattribute__") if name == 'd': return "this is computed by __getattribute__" else: # Always let the superclass try. return super(Test, self).__getattribute__(name) To test it, copy and paste the class definition into IDLE or the interactive interpreter, and then experiment. E.g.: py> instance = Test() py> instance.d calling __getattribute__ 'this is computed by __getattribute__' What's the difference between class attribute a and instance attribute b? Class attributes are shared across all instances, while instances each get their own personal version of instance attributes. In the example above, where self.b gets assigned the same value every time, the difference is insignificant, but normally you might do something like this: class PrintJob(object): size = "A4" # Set the global default def __init__(self, data, size=None): if size is not None: self.size = size # override the default self.data = data Now each PrintJob gets its own size, but only when needed; otherwise the default A4 gets used instead. Last but not least... __getattribute__ and __getattr__ are used for looking up attributes. You can also write attributes, and delete them, and Python provides magic methods to handle them too: __setattr__ -- used to write the attribute, it is ALWAYS called if present __delattr__ -- used to delete the attribute, it is ALWAYS called if present Be warned that using __setattr__ is tricky to get right, and __delattr__ is hardly ever needed (at least in my experience). Actually all of these magic attr methods are hardly ever needed, but __delattr__ is even less common than the rest. Abuse of magic attr methods can lead to hard to understand code and mysterious, hard-to-solve bugs. Consider them for advanced use only. -- Steven From steve at pearwood.info Sat Feb 4 03:37:17 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 04 Feb 2012 13:37:17 +1100 Subject: [Tutor] __getattribute__ In-Reply-To: References: Message-ID: <4F2C99DD.5030701@pearwood.info> Alan Gauld wrote: > On 04/02/12 00:30, Stayvoid wrote: > >> Could you provide some examples (easy and hard ones) and comments on >> the topic? >> I'm trying to understand how this thing works. > > Commenting on the topic... It's not one most beginners(*) should be > worrying about you rarely need to use it. But its slightly easier than > the related __setattribute__. That is spelled "__setattr__". -- Steven From mjolewis at gmail.com Sat Feb 4 06:37:07 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Fri, 3 Feb 2012 21:37:07 -0800 Subject: [Tutor] Importing libraries Message-ID: Why don't I have to import str or list to access their attributes like I do with the math or random or any other library? -- Michael J. Lewis mjolewis at gmail.com 415.815.7257 -------------- next part -------------- An HTML attachment was scrubbed... URL: From silideba at gmail.com Sat Feb 4 06:38:34 2012 From: silideba at gmail.com (Debashish Saha) Date: Sat, 4 Feb 2012 11:08:34 +0530 Subject: [Tutor] SEE THE QUESTION AT THE BOTTOM Message-ID: INPUT: *for n in range(2, 1000):* * for x in range(2, n):* * if n % x == 0:* * print n, 'equals', x, '*', n/x* * break* * else:* * # loop fell through without finding a factor* * print n, 'is a prime number'* OUTPUT: 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 :QUESTION: BUT I COULD NOT UNDERSTAND HOW THE COMMAND ELSE CAN WORK,THOUGH IT IS IN THE OUTSIDE OF THE FOR LOOP IN WHICH IF COMMAND LIES. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Sat Feb 4 06:53:03 2012 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 03 Feb 2012 21:53:03 -0800 Subject: [Tutor] SEE THE QUESTION AT THE BOTTOM In-Reply-To: References: Message-ID: <4F2CC7BF.1090905@alchemy.com> On 03-Feb-12 21:38, Debashish Saha wrote: > BUT I COULD NOT UNDERSTAND HOW THE COMMAND ELSE CAN WORK,THOUGH IT IS IN > THE OUTSIDE OF THE FOR LOOP IN WHICH IF COMMAND LIES. The part that's confusing you is that it is not outside the for loop. It is PART of the for loop syntax. The loop construct used is: for in : else: This means you run , executing once for each iteration, and a statement in that body may elect to break out of the loop prematurely. If nothing breaks out of the loop (i.e., you exit the loop because the was exhausted), then and only then execute . It's a handy mechanism to handle the case where the for loop failed to find whatever it was searching for. Most other languages I've used don't have this, and you end up doing messier manual logic steps to accomplish the same thing. Tip: Please don't type a message IN ALL CAPITAL LETTERS; it gives the impression you are shouting at your audience. HTH, HAND -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From silideba at gmail.com Sat Feb 4 11:11:46 2012 From: silideba at gmail.com (Debashish Saha) Date: Sat, 4 Feb 2012 15:41:46 +0530 Subject: [Tutor] factorial of anumber Message-ID: *PROGRAM TO FIND FACTORIAL OF A NUMBER(I HAVE WRITTEN IT ON GEDIT)* x=1 n=input('enter a positive integer no:') for i in range(1,1+n): x=x*i print x *ERROR:* enter a positive integer no:--------------------------------------------------------------------------- EOFError Traceback (most recent call last) C:\Python27\lib\site-packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc) 166 else: 167 filename = fname --> 168 exec compile(scripttext, filename, 'exec') in glob, loc 169 else: 170 def execfile(fname, *where): C:\Users\as\mnb.py in () 1 x=1 ----> 2 n=input('enter a positive integer no:') 3 for i in range(1,1+n): 4 x=x*i 5 print x EOFError: EOF when reading a line *QUESTION*: HOW TO ASK INPUT FROM USER THEN? -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sat Feb 4 11:18:07 2012 From: breamoreboy at yahoo.co.uk (Blockheads Oi Oi) Date: Sat, 04 Feb 2012 10:18:07 +0000 Subject: [Tutor] Importing libraries In-Reply-To: References: Message-ID: On 04/02/2012 05:37, Michael Lewis wrote: > Why don't I have to import str or list to access their attributes like I > do with the math or random or any other library? > > -- > Michael J. Lewis > mjolewis at gmail.com > 415.815.7257 > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor They're built in to Python so... PythonWin 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32. Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information. >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'pywin'] >>> help(__builtins__) Help on built-in module __builtin__: NAME __builtin__ - Built-in functions, exceptions, and other objects. FILE (built-in) DESCRIPTION Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices. CLASSES object basestring str str unicode buffer etc. -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Sat Feb 4 11:24:03 2012 From: breamoreboy at yahoo.co.uk (Blockheads Oi Oi) Date: Sat, 04 Feb 2012 10:24:03 +0000 Subject: [Tutor] factorial of anumber In-Reply-To: References: Message-ID: On 04/02/2012 10:11, Debashish Saha wrote: > _PROGRAM TO FIND FACTORIAL OF A NUMBER(I HAVE WRITTEN IT ON GEDIT)_ > x=1 > n=input('enter a positive integer no:') > for i in range(1,1+n): > x=x*i > print x > > > _ERROR:_ > > enter a positive integer > no:--------------------------------------------------------------------------- > EOFError Traceback (most recent call last) > C:\Python27\lib\site-packages\IPython\utils\py3compat.pyc in > execfile(fname, glob, loc) > 166 else: > 167 filename = fname > --> 168 exec compile(scripttext, filename, 'exec') in glob, loc > 169 else: > 170 def execfile(fname, *where): > > C:\Users\as\mnb.py in () > 1 x=1 > ----> 2 n=input('enter a positive integer no:') > 3 for i in range(1,1+n): > 4 x=x*i > 5 print x > > EOFError: EOF when reading a line > > *QUESTION*: > HOW TO ASK INPUT FROM USER THEN? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor It works fine for me. >>> enter a positive integer no:>>> 6 720 And please DO NOT USE CAPITAL LETTERS or people may stop answering your questions. -- Cheers. Mark Lawrence. From steve at pearwood.info Sat Feb 4 12:35:31 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 04 Feb 2012 22:35:31 +1100 Subject: [Tutor] Importing libraries In-Reply-To: References: Message-ID: <4F2D1803.30001@pearwood.info> Michael Lewis wrote: > Why don't I have to import str or list to access their attributes like I do > with the math or random or any other library? Because they are built-in. That means they live inside the Python compiler/interpreter itself. They are built-in because str, list, etc. are fundamental data types, used by the core Python interpreter, so they need to be available from the moment Python starts up, even before your code starts to run. Other built-in objects include: None True and False Ellipsis NotImplemented int float tuple dict many different exceptions such as ValueError, TypeError, etc. many different functions, such as len, chr, abs, enumerate, etc. Some of these are built-in because the interpreter won't run without them. Some are built-in for convenience and speed: although the interpreter will run without them, they are so useful that it makes sense to treat them as critical, core objects. And some are built-in just because they were built-in many years ago, and for backwards compatibility they have to stay built-in. (I'm thinking of functions like compile and eval.) -- Steven From silideba at gmail.com Sat Feb 4 13:08:56 2012 From: silideba at gmail.com (Debashish Saha) Date: Sat, 4 Feb 2012 17:38:56 +0530 Subject: [Tutor] (no subject) Message-ID: *input:* import numpy as np def f(y): return (y/5)*2*(np.pi)*0.2 *results:* f(11) Out[109]: 2.5132741228718345 f(11.0) Out[110]: 2.7646015351590183 *question:* why did i get different values for the same input? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Feb 4 13:09:48 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 04 Feb 2012 23:09:48 +1100 Subject: [Tutor] SEE THE QUESTION AT THE BOTTOM In-Reply-To: References: Message-ID: <4F2D200C.7080401@pearwood.info> Debashish Saha wrote: > INPUT: > > > > *for n in range(2, 1000):* > > * for x in range(2, n):* > > * if n % x == 0:* Please don't add junk characters to your code. There is no need to add asterisks to each line, we can recognise Python code when we see it. Your code cannot run because of the junk added to the start and end of each line. [...] > :QUESTION: > > BUT I COULD NOT UNDERSTAND HOW THE COMMAND ELSE CAN WORK,THOUGH IT IS IN > THE OUTSIDE OF THE FOR LOOP IN WHICH IF COMMAND LIES. Please do not SHOUT in ALL CAPITALS, it is considered rude. In Python, "else" is not just for "if" statements: if condition: do_true_condition else: do_false_condition Python also has "else" for for-loops and while-loops: for x in sequence: ... else: # this part runs after the for loop is done while condition: ... else: # this part runs after the while loop is done In both cases, "break" inside the loop will skip past the "else" block without executing it. Try blocks also have an else: try: ... except TypeError: # code that runs if TypeError occurs except ValueError: # code that runs if ValueError occurs else: # code that runs if no error occurs finally: # code that runs no matter what See the tutorial: http://docs.python.org/tutorial/controlflow.html Start here: http://docs.python.org/tutorial/index.html (Although the site seems to be done just at the moment.) -- Steven From steve at pearwood.info Sat Feb 4 13:17:51 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 04 Feb 2012 23:17:51 +1100 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <4F2D21EF.4040604@pearwood.info> Debashish Saha wrote: [...] > why did i get different values for the same input? Please choose a sensible subject line when posting. The problem is with the division. Watch: py> 21/2 10 py> 21.0/2 10.5 By default, division in Python 2 is integer division: any remainder is ignored. To use floating point division, you need to make one of the arguments be a float. In your function, you have division y/5. When y is 11, 11/5 gives 2 exactly. If y is 11.0, you get 2.2 (and a tiny bit, due to rounding). This is confusing, so in Python 3 division works more like you expect, and you don't have to worry about this nonsense. Also, starting in Python 2.4, you can get the new, calculator-like behaviour by using a special command to change the interpreter: py> 11/5 2 py> from __future__ import division py> 11/5 2.2000000000000002 My advice is to always use "from __future__ import division" at the start of your programs. -- Steven From steve at pearwood.info Sat Feb 4 13:22:58 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 04 Feb 2012 23:22:58 +1100 Subject: [Tutor] factorial of anumber In-Reply-To: References: Message-ID: <4F2D2322.10902@pearwood.info> Debashish Saha wrote: > *PROGRAM TO FIND FACTORIAL OF A NUMBER(I HAVE WRITTEN IT ON GEDIT)* This program is irrelevant. Your question has nothing to do with factorial of numbers. It is about getting input from the user. As you ask: > HOW TO ASK INPUT FROM USER THEN? The answer is: Do not use input, as it is dangerous and should not used. Use raw_input instead. py> answer = raw_input("what is your name? ") what is your name? Steven py> print answer Steven This works fine. See if you can work out what is going on here, and understand why I say input is dangerous and should be avoided: py> answer = input("what is your name? ") what is your name? Steven Traceback (most recent call last): File "", line 1, in File "", line 1, in NameError: name 'Steven' is not defined -- Steven From zafrullahmehdi at gmail.com Sat Feb 4 14:17:20 2012 From: zafrullahmehdi at gmail.com (Zafrullah Syed) Date: Sat, 4 Feb 2012 14:17:20 +0100 Subject: [Tutor] Urgent Help Required Message-ID: Hi, I need urgent help: I am unable to commit code to svn, I am getting this warning: *svn: Commit failed (details follow):* *svn: Commit blocked by pre-commit hook (exit code 1) with output:* *:17: Warning: 'with' will become a reserved keyword in Python 2.6* *writeConf.py:17: invalid syntax* *Commited Python-Files refused, please check and retry...* How do i surpass this and commit my code?? -- Regards, Zafrullah Syed -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Feb 4 14:20:14 2012 From: bgailer at gmail.com (bob gailer) Date: Sat, 04 Feb 2012 08:20:14 -0500 Subject: [Tutor] factorial of anumber In-Reply-To: References: Message-ID: <4F2D308E.10001@gmail.com> I for one prefer plain text rather than HTML for email. Please in the future post plain text. No colors, no unusual fonts. Makes it a LOT easier to read. -- Bob Gailer 919-636-4239 Chapel Hill NC From zafrullahmehdi at gmail.com Sat Feb 4 14:29:51 2012 From: zafrullahmehdi at gmail.com (Zafrullah Syed) Date: Sat, 4 Feb 2012 14:29:51 +0100 Subject: [Tutor] Tutor Digest, Vol 96, Issue 8 In-Reply-To: References: Message-ID: Hi, I need urgent help: I am unable to commit code to svn, I am getting this warning: *svn: Commit failed (details follow):* *svn: Commit blocked by pre-commit hook (exit code 1) with output:* *:17: Warning: 'with' will become a reserved keyword in Python 2.6* *writeConf.py:17: invalid syntax* *Commited Python-Files refused, please check and retry...* How do i surpass this and commit my code?? -- Regards, Zafrullah Syed On Sat, Feb 4, 2012 at 12:00 PM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: SEE THE QUESTION AT THE BOTTOM (Steve Willoughby) > 2. factorial of anumber (Debashish Saha) > 3. Re: Importing libraries (Blockheads Oi Oi) > 4. Re: factorial of anumber (Blockheads Oi Oi) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Fri, 03 Feb 2012 21:53:03 -0800 > From: Steve Willoughby > To: tutor at python.org > Subject: Re: [Tutor] SEE THE QUESTION AT THE BOTTOM > Message-ID: <4F2CC7BF.1090905 at alchemy.com> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 03-Feb-12 21:38, Debashish Saha wrote: > > BUT I COULD NOT UNDERSTAND HOW THE COMMAND ELSE CAN WORK,THOUGH IT IS IN > > THE OUTSIDE OF THE FOR LOOP IN WHICH IF COMMAND LIES. > > The part that's confusing you is that it is not outside the for loop. > It is PART of the for loop syntax. The loop construct used is: > > for in : > > else: > > > This means you run , executing > once for each iteration, and a statement in that body may > elect to break out of the loop prematurely. If nothing breaks out of > the loop (i.e., you exit the loop because the was exhausted), > then and only then execute . > > It's a handy mechanism to handle the case where the for loop failed to > find whatever it was searching for. Most other languages I've used > don't have this, and you end up doing messier manual logic steps to > accomplish the same thing. > > Tip: Please don't type a message IN ALL CAPITAL LETTERS; it gives the > impression you are shouting at your audience. > > HTH, > HAND > > -- > Steve Willoughby / steve at alchemy.com > "A ship in harbor is safe, but that is not what ships are built for." > PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C > > > ------------------------------ > > Message: 2 > Date: Sat, 4 Feb 2012 15:41:46 +0530 > From: Debashish Saha > To: tutor at python.org > Subject: [Tutor] factorial of anumber > Message-ID: > > > Content-Type: text/plain; charset="iso-8859-1" > > *PROGRAM TO FIND FACTORIAL OF A NUMBER(I HAVE WRITTEN IT ON GEDIT)* > x=1 > n=input('enter a positive integer no:') > for i in range(1,1+n): > x=x*i > print x > > > *ERROR:* > > enter a positive integer > > no:--------------------------------------------------------------------------- > EOFError Traceback (most recent call last) > C:\Python27\lib\site-packages\IPython\utils\py3compat.pyc in > execfile(fname, glob, loc) > 166 else: > 167 filename = fname > --> 168 exec compile(scripttext, filename, 'exec') in glob, loc > 169 else: > 170 def execfile(fname, *where): > > C:\Users\as\mnb.py in () > 1 x=1 > ----> 2 n=input('enter a positive integer no:') > 3 for i in range(1,1+n): > 4 x=x*i > 5 print x > > EOFError: EOF when reading a line > > *QUESTION*: > HOW TO ASK INPUT FROM USER THEN? > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20120204/6b70ebd8/attachment-0001.html > > > > ------------------------------ > > Message: 3 > Date: Sat, 04 Feb 2012 10:18:07 +0000 > From: Blockheads Oi Oi > To: tutor at python.org > Subject: Re: [Tutor] Importing libraries > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 04/02/2012 05:37, Michael Lewis wrote: > > Why don't I have to import str or list to access their attributes like I > > do with the math or random or any other library? > > > > -- > > Michael J. Lewis > > mjolewis at gmail.com > > 415.815.7257 > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > They're built in to Python so... > > PythonWin 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit > (Intel)] on win32. > Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' > for further copyright information. > >>> dir() > ['__builtins__', '__doc__', '__name__', '__package__', 'pywin'] > >>> help(__builtins__) > Help on built-in module __builtin__: > > NAME > __builtin__ - Built-in functions, exceptions, and other objects. > > FILE > (built-in) > > DESCRIPTION > Noteworthy: None is the `nil' object; Ellipsis represents `...' in > slices. > > CLASSES > object > basestring > str > str > unicode > buffer > etc. > > -- > Cheers. > > Mark Lawrence. > > > > ------------------------------ > > Message: 4 > Date: Sat, 04 Feb 2012 10:24:03 +0000 > From: Blockheads Oi Oi > To: tutor at python.org > Subject: Re: [Tutor] factorial of anumber > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 04/02/2012 10:11, Debashish Saha wrote: > > _PROGRAM TO FIND FACTORIAL OF A NUMBER(I HAVE WRITTEN IT ON GEDIT)_ > > x=1 > > n=input('enter a positive integer no:') > > for i in range(1,1+n): > > x=x*i > > print x > > > > > > _ERROR:_ > > > > enter a positive integer > > > no:--------------------------------------------------------------------------- > > EOFError Traceback (most recent call > last) > > C:\Python27\lib\site-packages\IPython\utils\py3compat.pyc in > > execfile(fname, glob, loc) > > 166 else: > > 167 filename = fname > > --> 168 exec compile(scripttext, filename, 'exec') in glob, > loc > > 169 else: > > 170 def execfile(fname, *where): > > > > C:\Users\as\mnb.py in () > > 1 x=1 > > ----> 2 n=input('enter a positive integer no:') > > 3 for i in range(1,1+n): > > 4 x=x*i > > 5 print x > > > > EOFError: EOF when reading a line > > > > *QUESTION*: > > HOW TO ASK INPUT FROM USER THEN? > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > It works fine for me. > > >>> enter a positive integer no:>>> 6 > 720 > > And please DO NOT USE CAPITAL LETTERS or people may stop answering your > questions. > > -- > Cheers. > > Mark Lawrence. > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 96, Issue 8 > ************************************ > -- Regards, Zafrullah Syed -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Feb 4 14:31:37 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 04 Feb 2012 13:31:37 +0000 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On 04/02/12 12:08, Debashish Saha wrote: > f(11) > Out[109]: 2.5132741228718345 > > f(11.0) > Out[110]: 2.7646015351590183 > > *question:* > why did i get different values for the same input? Because they are not the same inputs. 11 is an integer and 11.0 is a float and Python (along with many programming languages) treats division slightly differently for ints and floats. You can bypass this by making your divisor a float: ###### def f(y): return (y/5.0)*2*(np.pi)*0.2 ########## Now it will return the same result regardless of int or float. In Python v3 this is the default behavior -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Sat Feb 4 14:35:08 2012 From: d at davea.name (Dave Angel) Date: Sat, 04 Feb 2012 08:35:08 -0500 Subject: [Tutor] Urgent Help Required In-Reply-To: References: Message-ID: <4F2D340C.3040700@davea.name> On 02/04/2012 08:17 AM, Zafrullah Syed wrote: > Hi, > > I need urgent help: > > I am unable to commit code to svn, I am getting this warning: > > *svn: Commit failed (details follow):* > *svn: Commit blocked by pre-commit hook (exit code 1) with output:* > *:17: Warning: 'with' will become a reserved keyword in Python 2.6* > *writeConf.py:17: invalid syntax* > *Commited Python-Files refused, please check and retry...* > > How do i surpass this and commit my code?? > Lousy choice of subject. Please make your subject reflect what your problem is, not how important it may or may not be to you. You're not just running svn. If you were, you'd not get some python error or warning. So you're running a more complex environment, perhaps svn integrated inside some IDE (like komodo, wingware, beans, whatever). If so, post a question on the forum that supports that particular IDE. Or if you must post here, at least give us a clue what environment you're using. For example, i can infer that you're running Python 2.5 or older. But it'd be much better to explicitly say what python version, which operating system (and version), and what IDE (and version), and what svn (get the pattern?). The svn command to submit changes to a file outside of the ide is svn commit filename. If the file is new, I believe you have to do an svn add. -- DaveA From ajarncolin at gmail.com Sat Feb 4 14:36:55 2012 From: ajarncolin at gmail.com (col speed) Date: Sat, 4 Feb 2012 20:36:55 +0700 Subject: [Tutor] Tutor Digest, Vol 96, Issue 8 In-Reply-To: References: Message-ID: On 4 February 2012 20:29, Zafrullah Syed wrote: > Hi, > > I need urgent help: Yes, I think you do. Take notice of the last replies. From d at davea.name Sat Feb 4 14:45:48 2012 From: d at davea.name (Dave Angel) Date: Sat, 04 Feb 2012 08:45:48 -0500 Subject: [Tutor] Tutor Digest, Vol 96, Issue 8 In-Reply-To: References: Message-ID: <4F2D368C.3000501@davea.name> On 02/04/2012 08:29 AM, Zafrullah Syed wrote: > Hi, > > I need urgent help: > > I am unable to commit code to svn, I am getting this warning: > > *svn: Commit failed (details follow):* > *svn: Commit blocked by pre-commit hook (exit code 1) with output:* > *:17: Warning: 'with' will become a reserved keyword in Python 2.6* > *writeConf.py:17: invalid syntax* > *Commited Python-Files refused, please check and retry...* > > How do i surpass this and commit my code?? > 1) Once again your subject does not reflect anything useful. In fact one of the first things in the digest is: When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > 2) Don't include anything in your message that's irrelevant to the subject at hand. If you must reply to a digest, at least trim out all the messages except the one you're replying to. In your case you weren't replying to anything in that digest, so it's a lousy starting point. Just email a new query to the list at tutor at python.org 3) Don't ask the same question twice in 12 minutes. It makes people think you're impatient. Why sometimes, no messages come in a 24 hour period. If you need immediate help, go someplace where they take your money in return for timely support. People who reply here are volunteers, in various time zones throughout the world, who are trying to be helpful. As for your question, I posted my reply to it 18 minutes after yours. Some of that may be because my mail program only polls every 10 minutes or so. Some may be because I thought a little about the reply before hitting send. -- DaveA From __peter__ at web.de Sat Feb 4 14:50:43 2012 From: __peter__ at web.de (Peter Otten) Date: Sat, 04 Feb 2012 14:50:43 +0100 Subject: [Tutor] Failing svn pre-commit hok was Re: Urgent Help Required References: Message-ID: Zafrullah Syed wrote: > I need urgent help: Remember that this isn't paid support. Don't frivolously consume the goodwill of volunteers. > I am unable to commit code to svn, I am getting this warning: > > *svn: Commit failed (details follow):* > *svn: Commit blocked by pre-commit hook (exit code 1) with output:* > *:17: Warning: 'with' will become a reserved keyword in Python > 2.6* *writeConf.py:17: invalid syntax* > *Commited Python-Files refused, please check and retry...* > > How do i surpass this and commit my code?? You have a pre-commit hook in place that ensures that you commit valid Python 2.5 code. To make your file 2.5-compliant you can either replace with output: ... with something else or add from __future__ import with_statement at the top of your file. Alternatively you can ask the person responsible for the svn installation to remove the hook or replace it with a check that accepts Python 2.6 or whatever version you are developing for. From alan.gauld at btinternet.com Sat Feb 4 15:28:16 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 04 Feb 2012 14:28:16 +0000 Subject: [Tutor] Tutor Digest, Vol 96, Issue 8 In-Reply-To: References: Message-ID: On 04/02/12 13:29, Zafrullah Syed wrote: > I need urgent help: Then you are going a very bad way of getting it. If you must post for help a) pick a forum that ir related to your problem. This is a python beginners mailing list not an svn problem list. b) Follow the rules of the forum you are using eg (1)don't post the same question multiple times, it doesn't elicit answers quicker it just annoys people so they don't answer at all. (2)Pick a sensible subject matter, neither of your posts tell us what you want to know (3) provide enough information so that folks can help - version numbers, OS, etc etc. (4) Don't post an entire digest to a mailing list where some people pay by the byte. (Actually, don't post the entire digest even if they don't pay by byte! It just wastes space) In short think. Think about what people need to know to help you and where are the people that can help most likely to be located. Make it easy for us to help you and we might respond, make it hard to help and we probably won't. > I am unable to commit code to svn, I am getting this warning: > > *svn: Commit failed (details follow):* > *svn: Commit blocked by pre-commit hook (exit code 1) with output:* > *:17: Warning: 'with' will become a reserved keyword in Python 2.6* > *writeConf.py:17: invalid syntax* > *Commited Python-Files refused, please check and retry...* Have you looked at the file in question? Have you looked at the lines around the error report? Are you using 'with' in an appropriate way? > How do i surpass this and commit my code?? You fix the error, one way or another. But without sight of your code or the svn hook or your local coding standards/environment there's not much we can do except guess. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From nsivaram.net at gmail.com Sat Feb 4 15:38:09 2012 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Sat, 04 Feb 2012 20:08:09 +0530 Subject: [Tutor] Return T/F vs print T/F Message-ID: <82aa4yu0j2.fsf@gmail.com> While trying out code, I have trouble following the difference between return True vs print True and the same with False. If I use return for the True/False statements, nothing gets printed. Why? And if I add a print before the function call I get an output like >>>True None --8<---------------cut here---------------start------------->8--- def first(word): return word[0] def last(word): return word[-1] def middle(word): return word[1:-1] def palin(text): if first(text) == last(text): # print first(text), last(text), middle(text), len(middle(text)) if len(middle(text)) == 0: print True else: palin(middle(text)) else: print False palin("o") palin("nxon") palin("nooxooxoon") print palin("nabban") --8<---------------cut here---------------end--------------->8--- sivaram -- From bgailer at gmail.com Sat Feb 4 16:08:46 2012 From: bgailer at gmail.com (bob gailer) Date: Sat, 04 Feb 2012 10:08:46 -0500 Subject: [Tutor] Return T/F vs print T/F In-Reply-To: <82aa4yu0j2.fsf@gmail.com> References: <82aa4yu0j2.fsf@gmail.com> Message-ID: <4F2D49FE.8060509@gmail.com> On 2/4/2012 9:38 AM, Sivaram Neelakantan wrote: > While trying out code, I have trouble following the difference between > > return True vs print True and the same with False. If I use return > for the True/False statements, nothing gets printed. Why? Why did you expect something to be printed? Perhaps you are confused between what happens in the interactive window vs running a program? Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def f(): ... return True ... >>> f() True >>> def g(): ... print True ... >>> g() True >>> print f() True >>> print g() True None In the interactive window, when you call a function, Python displays the returned value. When you run a program with a call to a function, Python does NOT display the returned value. A function that does not execute a return will return None; in the interactive window nothing is displayed. Is that sufficient? -- Bob Gailer 919-636-4239 Chapel Hill NC From nsivaram.net at gmail.com Sat Feb 4 17:42:35 2012 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Sat, 04 Feb 2012 22:12:35 +0530 Subject: [Tutor] Return T/F vs print T/F References: <82aa4yu0j2.fsf@gmail.com> <4F2D49FE.8060509@gmail.com> Message-ID: <8262fmturo.fsf@gmail.com> On Sat, Feb 04 2012,bob gailer wrote: > On 2/4/2012 9:38 AM, Sivaram Neelakantan wrote: >> While trying out code, I have trouble following the difference between >> >> return True vs print True and the same with False. If I use return >> for the True/False statements, nothing gets printed. Why? > > Why did you expect something to be printed? err...return sends something back as in True or False? > > Perhaps you are confused between what happens in the interactive > window vs running a program? Possibly. But I was coding in an Emacs buffer and sending it to the python subprocess from within Emacs. Does that have anything to do with it? > > Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> def f(): > ... return True > ... >>>> f() > True >>>> def g(): > ... print True > ... >>>> g() > True >>>> print f() > True >>>> print g() > True > None > > In the interactive window, when you call a function, Python displays > the returned value. When you run a program with a call to a > function, Python does NOT display the returned value. > > A function that does not execute a return will return None; in the > interactive window nothing is displayed. > > Is that sufficient? Right, thanks for this, will check this thing out again. sivaram -- From steve at pearwood.info Sat Feb 4 17:53:05 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 05 Feb 2012 03:53:05 +1100 Subject: [Tutor] Return T/F vs print T/F In-Reply-To: <82aa4yu0j2.fsf@gmail.com> References: <82aa4yu0j2.fsf@gmail.com> Message-ID: <4F2D6271.80801@pearwood.info> Sivaram Neelakantan wrote: > While trying out code, I have trouble following the difference between > return True vs print True and the same with False. If I use return > for the True/False statements, nothing gets printed. Why? Probably because you aren't printing anything. Python can't read your mind and know what you want printed and what you don't want printed, you have to tell it what to print. It is not clear how you are "trying out code". Are you running code as a script? Using IDLE or iPython? Using the standard interactive interpreter? The environment will make a difference in the behaviour. In the interactive interpreter, as a convenience, the result of each line is automatically printed for you: >>> 1+3 4 >>> len("hello world") 11 but this is only in the interactive environment. In a script, nothing is printed unless you call print. Functions should have a return result -- the value they calculate. You can then store the value in a variable for later use: >>> length = len("hello world") # store the value >>> print "The length is", length # and use it later The length is 11 The print command does not return a value, it just prints the argument. If you use print in the function, you cannot capture the result and use it in additional calculations. When writing your own functions, you should always aim for this same behaviour: use return inside the function, print outside. > And if I add a print before the function call I get an output like > >>>> True > None I can't see any possible way your code will give output including ">>>". Would you care to explain more carefully what you mean? -- Steven From steve at pearwood.info Sat Feb 4 18:00:13 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 05 Feb 2012 04:00:13 +1100 Subject: [Tutor] Return T/F vs print T/F In-Reply-To: <82aa4yu0j2.fsf@gmail.com> References: <82aa4yu0j2.fsf@gmail.com> Message-ID: <4F2D641D.4050308@pearwood.info> Sivaram Neelakantan wrote: > def palin(text): > if first(text) == last(text): > # print first(text), last(text), middle(text), len(middle(text)) > if len(middle(text)) == 0: > print True > else: > palin(middle(text)) > else: > print False Every branch of the function must include a return, or Python will just return None by default. You have three branches. Two of them print a flag. It is easy enough to fix them by changing print to return. The third branch has no return. It needs one. -- Steven From swiftone at swiftone.org Sat Feb 4 19:58:18 2012 From: swiftone at swiftone.org (Brett Ritter) Date: Sat, 4 Feb 2012 13:58:18 -0500 Subject: [Tutor] Return T/F vs print T/F In-Reply-To: <8262fmturo.fsf@gmail.com> References: <82aa4yu0j2.fsf@gmail.com> <4F2D49FE.8060509@gmail.com> <8262fmturo.fsf@gmail.com> Message-ID: On Sat, Feb 4, 2012 at 11:42 AM, Sivaram Neelakantan wrote: > On Sat, Feb 04 2012,bob gailer wrote: > >> On 2/4/2012 9:38 AM, Sivaram Neelakantan wrote: >>> While trying out code, I have trouble following the difference between >>> >>> return True vs print True and the same with False. ?If I use return >>> for the True/False statements, nothing gets printed. ?Why? >> >> Why did you expect something to be printed? > > err...return sends something back as in True or False? Yes, it returns it to the caller. It doesn't print it. When using the interactive mode, the program that creates that mode prints the return. When you are using it your program, the caller decides what to do. The flip side is that printing a value does NOT return it. -- Brett Ritter / SwiftOne swiftone at swiftone.org From bgailer at gmail.com Sat Feb 4 21:49:58 2012 From: bgailer at gmail.com (bob gailer) Date: Sat, 04 Feb 2012 15:49:58 -0500 Subject: [Tutor] Return T/F vs print T/F In-Reply-To: <4F2D6271.80801@pearwood.info> References: <82aa4yu0j2.fsf@gmail.com> <4F2D6271.80801@pearwood.info> Message-ID: <4F2D99F6.7010706@gmail.com> On 2/4/2012 11:53 AM, Steven D'Aprano wrote: [snip] > > In the interactive interpreter, as a convenience, the result of each > line is automatically printed for you: > Actually the interpreter prints the result of each /statement /that IS an /expression/. >>> 2 2 >>> a = 3 >>> a 3 IOW if the line is blank, start with # or is a statement the interpreter does not print anything (unless it is a print statement). For a messy example: >>> if 1:3;a=4;a ... 3 4 -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanpierreda at gmail.com Sun Feb 5 00:05:06 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sat, 4 Feb 2012 18:05:06 -0500 Subject: [Tutor] Importing libraries In-Reply-To: <4F2D1803.30001@pearwood.info> References: <4F2D1803.30001@pearwood.info> Message-ID: On Sat, Feb 4, 2012 at 6:35 AM, Steven D'Aprano wrote: > Michael Lewis wrote: >> >> Why don't I have to import str or list to access their attributes like I >> do >> with the math or random or any other library? > > > > Because they are built-in. That means they live inside the Python > compiler/interpreter itself. Blargh, lots of things are built in. The sys module is a built-in module, but you don't get access to it by default. It's because they're specially-chosen to be in the "builtin namespace". This is the namespace of things that are always accessible. This is different from being built into the interpreter -- hypothetically we could have something in the builtin namespace that is not part of Python itself. (You can do this by adding things to the builtin namespace by hand). -- Devin From mylesbroomes at hotmail.co.uk Sun Feb 5 00:43:32 2012 From: mylesbroomes at hotmail.co.uk (myles broomes) Date: Sat, 4 Feb 2012 23:43:32 +0000 Subject: [Tutor] Pizza panic game Message-ID: Im currently using a book called 'Programming in Python for the complete beginner' and at the end of each chapter, the reader is given challenges to do. The current chapter im on, one of the challenges is to take the source code for a 'Pizza Panic' game , and find a way to make the game more difficult. Basically, the premise of the game is the player controls a pan and has to try and catch falling pizzas that a computer controlled chef is dropping, and failure to drop any results in game over. The idea I came up with is as well as the chef dropping the pizzas, he also drops hazardous spikey balls that the player has to try and avoid. I'll try to explain the part that im having trouble with: Heres the code for the 'Spikey ball' class that creates the spikey ball object: class Spikey_ball(games.Sprite): """A hazardous spikey ball that falls to the ground.""" image = games.load_image("Spikey_ball.png") speed = 0.5 def __init__(self, x, y = 90): """Initialise the spikey ball object.""" super(Spikey_ball, self).__init__(image = Spikey_ball.image, x = x, y = y, dy = Spikey_ball.speed) def update(self): """Check if botton edge has reached the screen.""" if self.bottom > games.screen.height: self.destroy() def handle_caught(self): """Destroy if caught and end game.""" if self.bottom > Pan.top: Pizza.end_game() self.destroy() ...And heres the code for the pan class: class Pan(games.Sprite): """ A pan controlled by player to catch falling pizzas. """ image = games.load_image("pan.bmp") def __init__(self): """ Initialize Pan object and create Text object for score. """ super(Pan, self).__init__(image = Pan.image, x = games.mouse.x, bottom = games.screen.height) self.score = games.Text(value = 0, size = 25, color = color.black, top = 5, right = games.screen.width - 10) games.screen.add(self.score) def update(self): """ Move to mouse x position. """ self.x = games.mouse.x if self.left < 0: self.left = 0 if self.right > games.screen.width: self.right = games.screen.width self.check_catch() def check_catch(self): """ Check if catch pizzas. """ for pizza in self.overlapping_sprites: pizza.handle_caught() As you can see, when a sprite overlaps the pan object, the handle_caught attribute of said object is invoked. But the weird thing is, when a pizza is caught, it works fine and the pizza's handle_caught attribute is invoked without complaint. However, when a spikey ball is caught, the game comes up with an error and claims that the Spikey_ball object has no handle_caught attribute, but as you can see, it clearly does. Can anyone explain this to me? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Feb 5 01:16:55 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 05 Feb 2012 00:16:55 +0000 Subject: [Tutor] Pizza panic game In-Reply-To: References: Message-ID: On 04/02/12 23:43, myles broomes wrote: > game comes up with an error and claims that the Spikey_ball object has > no handle_caught attribute, but as you can see, it clearly does. Can > anyone explain this to me? Please post the entire error message, do not summarize. There is often important information in the message. Meantime can you try adding a print line in your last method to check that the attribute(i.e. method) does actually exist in the executing code at the point of use? ie. def check_catch(self): """ Check if catch pizzas. """ for pizza in self.overlapping_sprites: >>>> print (dir(pizza)) #<<< new line pizza.handle_caught() hth, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Sun Feb 5 02:23:09 2012 From: d at davea.name (Dave Angel) Date: Sat, 04 Feb 2012 20:23:09 -0500 Subject: [Tutor] Pizza panic game In-Reply-To: References: Message-ID: <4F2DD9FD.6030908@davea.name> On 02/04/2012 06:43 PM, myles broomes wrote: > Im currently using a book called 'Programming in Python for the complete beginner' and at the end of each chapter, the reader is given challenges to do. The current chapter im on, one of the challenges is to take the source code for a 'Pizza Panic' game , and find a way to make the game more difficult. Basically, the premise of the game is the player controls a pan and has to try and catch falling pizzas that a computer controlled chef is dropping, and failure to drop any results in game over. The idea I came up with is as well as the chef dropping the pizzas, he also drops hazardous spikey balls that the player has to try and avoid. I'll try to explain the part that im having trouble with: > > Heres the code for the 'Spikey ball' class that creates the spikey ball object: > > class Spikey_ball(games.Sprite): > """A hazardous spikey ball that falls to the ground.""" > image = games.load_image("Spikey_ball.png") > speed = 0.5 > > def __init__(self, x, y = 90): > """Initialise the spikey ball object.""" > super(Spikey_ball, self).__init__(image = Spikey_ball.image, > x = x, y = y, > dy = Spikey_ball.speed) > def update(self): > """Check if botton edge has reached the screen.""" > if self.bottom> games.screen.height: > self.destroy() > > def handle_caught(self): > """Destroy if caught and end game.""" > if self.bottom> Pan.top: > Pizza.end_game() > self.destroy() > > > ...And heres the code for the pan class: > > class Pan(games.Sprite): > """ > A pan controlled by player to catch falling pizzas. > """ > image = games.load_image("pan.bmp") > > def __init__(self): > """ Initialize Pan object and create Text object for score. """ > super(Pan, self).__init__(image = Pan.image, > x = games.mouse.x, > bottom = games.screen.height) > > self.score = games.Text(value = 0, size = 25, color = color.black, > top = 5, right = games.screen.width - 10) > games.screen.add(self.score) > > def update(self): > """ Move to mouse x position. """ > self.x = games.mouse.x > > if self.left< 0: > self.left = 0 > > if self.right> games.screen.width: > self.right = games.screen.width > > self.check_catch() > > def check_catch(self): > """ Check if catch pizzas. """ > for pizza in self.overlapping_sprites: > pizza.handle_caught() > > As you can see, when a sprite overlaps the pan object, the handle_caught attribute of said object is invoked. But the weird thing is, when a pizza is caught, it works fine and the pizza's handle_caught attribute is invoked without complaint. However, when a spikey ball is caught, the game comes up with an error and claims that the Spikey_ball object has no handle_caught attribute, but as you can see, it clearly does. Can anyone explain this to me? > There is a function handle_caught(), but it's not a method of the class, it's a nested function of method __init__() Unless of course, you haven't posted correctly, and the indentation doesn't match what you're really using. -- DaveA From mylesbroomes at hotmail.co.uk Sun Feb 5 12:56:33 2012 From: mylesbroomes at hotmail.co.uk (myles broomes) Date: Sun, 5 Feb 2012 11:56:33 +0000 Subject: [Tutor] Tutor Digest, Vol 96, Issue 12 In-Reply-To: References: Message-ID: The error message im getting is: 'AttributeError: 'Spikey_ball' object has no attribute 'handle_caught'. > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 4 Feb 2012 23:43:32 +0000 > From: myles broomes > To: > Subject: [Tutor] Pizza panic game > Message-ID: > Content-Type: text/plain; charset="iso-8859-1" > > > Im currently using a book called 'Programming in Python for the complete beginner' and at the end of each chapter, the reader is given challenges to do. The current chapter im on, one of the challenges is to take the source code for a 'Pizza Panic' game , and find a way to make the game more difficult. Basically, the premise of the game is the player controls a pan and has to try and catch falling pizzas that a computer controlled chef is dropping, and failure to drop any results in game over. The idea I came up with is as well as the chef dropping the pizzas, he also drops hazardous spikey balls that the player has to try and avoid. I'll try to explain the part that im having trouble with: > > Heres the code for the 'Spikey ball' class that creates the spikey ball object: > > class Spikey_ball(games.Sprite): > """A hazardous spikey ball that falls to the ground.""" > image = games.load_image("Spikey_ball.png") > speed = 0.5 > > def __init__(self, x, y = 90): > """Initialise the spikey ball object.""" > super(Spikey_ball, self).__init__(image = Spikey_ball.image, > x = x, y = y, > dy = Spikey_ball.speed) > def update(self): > """Check if botton edge has reached the screen.""" > if self.bottom > games.screen.height: > self.destroy() > > def handle_caught(self): > """Destroy if caught and end game.""" > if self.bottom > Pan.top: > Pizza.end_game() > self.destroy() > > > ...And heres the code for the pan class: > > class Pan(games.Sprite): > """ > A pan controlled by player to catch falling pizzas. > """ > image = games.load_image("pan.bmp") > > def __init__(self): > """ Initialize Pan object and create Text object for score. """ > super(Pan, self).__init__(image = Pan.image, > x = games.mouse.x, > bottom = games.screen.height) > > self.score = games.Text(value = 0, size = 25, color = color.black, > top = 5, right = games.screen.width - 10) > games.screen.add(self.score) > > def update(self): > """ Move to mouse x position. """ > self.x = games.mouse.x > > if self.left < 0: > self.left = 0 > > if self.right > games.screen.width: > self.right = games.screen.width > > self.check_catch() > > def check_catch(self): > """ Check if catch pizzas. """ > for pizza in self.overlapping_sprites: > pizza.handle_caught() > > As you can see, when a sprite overlaps the pan object, the handle_caught attribute of said object is invoked. But the weird thing is, when a pizza is caught, it works fine and the pizza's handle_caught attribute is invoked without complaint. However, when a spikey ball is caught, the game comes up with an error and claims that the Spikey_ball object has no handle_caught attribute, but as you can see, it clearly does. Can anyone explain this to me? > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > Message: 2 > Date: Sun, 05 Feb 2012 00:16:55 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Pizza panic game > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 04/02/12 23:43, myles broomes wrote: > > > game comes up with an error and claims that the Spikey_ball object has > > no handle_caught attribute, but as you can see, it clearly does. Can > > anyone explain this to me? > > Please post the entire error message, do not summarize. > There is often important information in the message. > > Meantime can you try adding a print line in your last > method to check that the attribute(i.e. method) does > actually exist in the executing code at the point > of use? > ie. > > def check_catch(self): > """ Check if catch pizzas. """ > for pizza in self.overlapping_sprites: > >>>> print (dir(pizza)) #<<< new line > pizza.handle_caught() > > hth, > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > ------------------------------ -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sun Feb 5 12:58:02 2012 From: d at davea.name (Dave Angel) Date: Sun, 05 Feb 2012 06:58:02 -0500 Subject: [Tutor] Pizza panic game In-Reply-To: References: , <4F2DD9FD.6030908@davea.name> Message-ID: <4F2E6ECA.6000202@davea.name> (You forgot to do a Reply-all, and thus your message(s) came only to me. I'm forwarding it, but with my response as well) On 02/05/2012 05:35 AM, myles broomes wrote: > > I apologise, this is what the code actually looks like: > > Spikey ball class: > > class Spikey_ball(games.Sprite): > """A hazardous spikey ball that falls to the ground.""" > image = games.load_image("Spikey_ball.png") > speed = 0.5 > > def __init__(self, x, y = 90): > """Initialise the spikey ball object.""" > super(Spikey_ball, self).__init__(image = Spikey_ball.image, > x = x, y = y, > dy = Spikey_ball.speed) > > def update(self): > """Check if botton edge has reached the screen.""" > if self.bottom> games.screen.height: > self.destroy() > > def handle_caught(self): > """Destroy if caught and end game.""" > if self.bottom> Pan.top: > Pizza.end_game() > self.destroy() > > Sorry for the confusion and thanks in advance. Sometimes I see this type of symptom when somebody mixes tabs and spaces, a definite no-no. This message looks like you use pure spaces for indentation, which is the style I prefer. Anyway, handle_caught() is still indented one more column than update(), so it gets an IndentationError exception: ^ IndentationError: unindent does not match any outer indentation level If you have any doubt, follow Alan's advice, to see just what the attributes of pizza are at that point. Or add a print in top-level code to see what the attributes of Spikey_ball class are. If all this is indeed a cut&paste error, and the indentation is correct, then I'd look to see what the type of the pizza is when it fails. Perhaps it's not really Spikey_Ball. -- DaveA From dave at hansonforensics.co.uk Sun Feb 5 14:26:18 2012 From: dave at hansonforensics.co.uk (Dave Hanson) Date: Sun, 5 Feb 2012 13:26:18 +0000 Subject: [Tutor] Cmd Advice Message-ID: Hi Everyone, I wonder if anyone here can help me? I have Googled the pants off this one and have found useful resources, I also asked in the #python IRC channel (no one seemed to know in there) but can't seem to crack it: I want to create a 'task list' type of program with no GUI - I found this: http://stevelosh.com/projects/t/ which is exactly what I want. I ran it from my Ubuntu machine with no trouble at all. I wish to extend the program myself to suit my personal needs. Here is the source: http://paste.pocoo.org/show/546100/ So far so good. I then realised that at work (XP) I have restricted access to a command line and so wouldn't be able to use it, restricted in the sense of I simply am not permitted to access it! Some googling revealed a class called "cmd" which I read up on http://docs.python.org/library/cmd.html and I also found a good site explaining the basics of how to use it http://www.doughellmann.com/PyMOTW/cmd/. I'm thinking of making it an executable file that pops up with a terminal that I can enter the commands as I would on my bash shell - if that makes sense? Now my questions are please: - Am I going down the right route by using "Cmd" or is there a better way. - Is anyone willing to 'have a go' for me and post the code back so I can start modifying the 'guts' of the program to what I need or even just start me off/point me in the right direction - I'd be most grateful for any level of assistance. Best Regards, Dave Hanson -------------- next part -------------- An HTML attachment was scrubbed... URL: From silideba at gmail.com Sun Feb 5 14:38:14 2012 From: silideba at gmail.com (Debashish Saha) Date: Sun, 5 Feb 2012 19:08:14 +0530 Subject: [Tutor] ploting of a square well Message-ID: from pylab import * x=linspace(1,1000,10000) a,b = 10,20 def v(x): i=5;v0=2 for n in range(1,1+i): if x>(n-1)*(a+b) and xa+(n-1)*(a+b) and x<(n)*(a+b) : return v0 #v=vectorize(v) plot(x,v) show() Error: x and y must have same first dimension Question: what is to be edited? From alan.gauld at btinternet.com Sun Feb 5 15:54:00 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 05 Feb 2012 14:54:00 +0000 Subject: [Tutor] Tutor Digest, Vol 96, Issue 12 In-Reply-To: References: Message-ID: On 05/02/12 11:56, myles broomes wrote: > The error message im getting is: > 'AttributeError: 'Spikey_ball' object has no attribute 'handle_caught'. Are you sure that's the entire error message? It looks like its only the last line. Usually there is a lot more information than that. How are you running the code? Are you using a special IDE or something similar that is hiding the full error text?? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Feb 5 16:04:14 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 05 Feb 2012 15:04:14 +0000 Subject: [Tutor] Cmd Advice In-Reply-To: References: Message-ID: On 05/02/12 13:26, Dave Hanson wrote: > So far so good. I then realised that at work (XP) I have restricted > access to a command line and so wouldn't be able to use it, restricted > in the sense of I simply am not permitted to access it! Are you prevented from using it or is it just a company policy? In other words can you type Windows-r and get the run dialog and type cmd into it to bring up a dos box? But if you do so you could be disciplined? Or is there something on your PC build that actually stops cmd from working (which would be really strange since it would stop a lot of windows tools from working!) > revealed a class called "cmd" which I read up on > http://docs.python.org/library/cmd.html and I also found a good > site explaining the basics of how to use it > http://www.doughellmann.com/PyMOTW/cmd/. > > I'm thinking of making it an executable file that pops up with a > terminal that I can enter the commands as I would on my bash shell - if > that makes sense? But that will still need to run in a cmd window, whether launched directly by you or indirectly by XP. What happens if you create a desktop shortcut to one of your python programs, say one like this: ################# print ("hello world") input("Hit return to quit") ################# Does it bring up a console? If so you have no problem, just use ypur normal script and create a shortcut. > * Am I going down the right route by using "Cmd" or is there a better way. cmd is a useful module but largely irrelevant to your question. It is a style of UI within a Python script. You may well decide to use cmd in your script rather than presenting menus etc. But it has no influence on whether your script will run on XP. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Feb 5 16:05:21 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 05 Feb 2012 15:05:21 +0000 Subject: [Tutor] ploting of a square well In-Reply-To: References: Message-ID: On 05/02/12 13:38, Debashish Saha wrote: > > Error: > x and y must have same first dimension Please send the complete error message not just the last line or a summary. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From dave at hansonforensics.co.uk Sun Feb 5 16:26:31 2012 From: dave at hansonforensics.co.uk (Dave Hanson) Date: Sun, 5 Feb 2012 15:26:31 +0000 Subject: [Tutor] Cmd Advice In-Reply-To: References: Message-ID: Thanks Alan. I have ran python programs before at work. But not ones you need to continually interact with from the command line. This particular program needs that. Dos isn't unavailable, just windows + r and cmd are disabled by IT. I can force a dos window to open by using a bat or python program. What I'm trying to get around is not being able to interact with the program using [options] like -l for list for example. Also, Apologies if this is a top post, my phone is difficult to write on. Thanks again, Dave On Feb 5, 2012 3:04 PM, "Alan Gauld" wrote: > On 05/02/12 13:26, Dave Hanson wrote: > > So far so good. I then realised that at work (XP) I have restricted >> access to a command line and so wouldn't be able to use it, restricted >> in the sense of I simply am not permitted to access it! >> > > Are you prevented from using it or is it just a company policy? > In other words can you type Windows-r and get the run dialog > and type cmd into it to bring up a dos box? But if you do so > you could be disciplined? Or is there something on your PC build that > actually stops cmd from working (which would be really strange since it > would stop a lot of windows tools from working!) > > > revealed a class called "cmd" which I read up on >> http://docs.python.org/**library/cmd.htmland I also found a good >> site explaining the basics of how to use it >> http://www.doughellmann.com/**PyMOTW/cmd/ >> . >> >> I'm thinking of making it an executable file that pops up with a >> terminal that I can enter the commands as I would on my bash shell - if >> that makes sense? >> > > But that will still need to run in a cmd window, whether launched > directly by you or indirectly by XP. > > What happens if you create a desktop shortcut to one of your python > programs, say one like this: > > ################# > print ("hello world") > input("Hit return to quit") > ################# > > Does it bring up a console? > If so you have no problem, just use ypur normal script and create a > shortcut. > > > * Am I going down the right route by using "Cmd" or is there a better >> way. >> > > cmd is a useful module but largely irrelevant to your question. It is a > style of UI within a Python script. You may well decide to use cmd in your > script rather than presenting menus etc. But it has no influence on whether > your script will run on XP. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bodsda at googlemail.com Sun Feb 5 17:07:38 2012 From: bodsda at googlemail.com (Bod Soutar) Date: Sun, 5 Feb 2012 16:07:38 +0000 Subject: [Tutor] Cmd Advice In-Reply-To: References: Message-ID: On Feb 5, 2012 3:31 PM, "Dave Hanson" wrote: > > Thanks Alan. > > I have ran python programs before at work. But not ones you need to continually interact with from the command line. This particular program needs that. > > Dos isn't unavailable, just windows + r and cmd are disabled by IT. > > I can force a dos window to open by using a bat or python program. What I'm trying to get around is not being able to interact with the program using [options] like -l for list for example. > > Also, Apologies if this is a top post, my phone is difficult to write on. > > Thanks again, > > Dave > > On Feb 5, 2012 3:04 PM, "Alan Gauld" wrote: >> >> On 05/02/12 13:26, Dave Hanson wrote: >> >>> So far so good. I then realised that at work (XP) I have restricted >>> access to a command line and so wouldn't be able to use it, restricted >>> in the sense of I simply am not permitted to access it! >> >> >> Are you prevented from using it or is it just a company policy? >> In other words can you type Windows-r and get the run dialog >> and type cmd into it to bring up a dos box? But if you do so >> you could be disciplined? Or is there something on your PC build that actually stops cmd from working (which would be really strange since it would stop a lot of windows tools from working!) >> >> >>> revealed a class called "cmd" which I read up on >>> http://docs.python.org/library/cmd.html and I also found a good >>> site explaining the basics of how to use it >>> http://www.doughellmann.com/PyMOTW/cmd/. >>> >>> I'm thinking of making it an executable file that pops up with a >>> terminal that I can enter the commands as I would on my bash shell - if >>> that makes sense? >> >> >> But that will still need to run in a cmd window, whether launched >> directly by you or indirectly by XP. >> >> What happens if you create a desktop shortcut to one of your python programs, say one like this: >> >> ################# >> print ("hello world") >> input("Hit return to quit") >> ################# >> >> Does it bring up a console? >> If so you have no problem, just use ypur normal script and create a shortcut. >> >> >>> * Am I going down the right route by using "Cmd" or is there a better way. >> >> >> cmd is a useful module but largely irrelevant to your question. It is a style of UI within a Python script. You may well decide to use cmd in your script rather than presenting menus etc. But it has no influence on whether your script will run on XP. >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Here are some other ways of launching cmd The following techniques are used at your own risk Task manager-> file-> New process-> cmd Rename cmd.exe to cmd2.exe and run it Try running command.com then cmd.exe Bodsda -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Sun Feb 5 17:34:47 2012 From: wprins at gmail.com (Walter Prins) Date: Sun, 5 Feb 2012 16:34:47 +0000 Subject: [Tutor] Cmd Advice In-Reply-To: References: Message-ID: Hello Dave, On 5 February 2012 15:26, Dave Hanson wrote: > I can force a dos window to open by using a bat or python program. OK, so the command prompt issue is really a red herring then from what I can tell. Work around the standard limitations of your desktop in whatever way suits you (providing you're not going to get yourself into trouble by doing so etc). As long as you can get to a command prompt you can then set up the program to work the same way as on Unix, with a bit of jiggery pokery. > What I'm > trying to get around is not being able to interact with the program using > [options] like -l for list for example. OK, so your real issue involved command line arguments it seems. What I'd do is write a wrapper batch file for your Python program named "t.bat", and place it in a location that's on your search path, or add it to the search path if you like (perhaps put it alongside t.py and then put that location on the system PATH.) t.bat should contain something like this (adjust paths as required obviously): c:\Python27\python.exe c:\src\t\t.py %1 %2 %3 %4 %5 %6 %7 %8 %9 This command line will obviously pass the first 9 command line argument strings given to the batch file on to the Python program. What this does is to allow you to run the command like you do on Unix, e.g: t -f 5 ... which in turn should will find and run t.bat with the command line arguments "-5 5" which then pass them on to the Python program etc. HTH, Walter From silideba at gmail.com Sun Feb 5 18:07:42 2012 From: silideba at gmail.com (Debashish Saha) Date: Sun, 5 Feb 2012 22:37:42 +0530 Subject: [Tutor] ploting of a square well In-Reply-To: References: Message-ID: ---------- Forwarded message ---------- From: Debashish Saha Date: Sun, Feb 5, 2012 at 7:08 PM Subject: ploting of a square well To: tutor at python.org from pylab import * x=linspace(1,1000,10000) a,b = 10,20 def v(x): ? ?i=5;v0=2 ? ?for n in range(1,1+i): ? ? ? ?if x>(n-1)*(a+b) and xa+(n-1)*(a+b) and x<(n)*(a+b) : ? ? ? ? ? ?return v0 #v=vectorize(v) plot(x,v) show() Error: ValueError Traceback (most recent call last) C:\Python27\lib\site-packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc) 166 else: 167 filename = fname --> 168 exec compile(scripttext, filename, 'exec') in glob, loc 169 else: 170 def execfile(fname, *where): C:\Users\as\klj.py in () 10 return v0 11 #v=vectorize(v) ---> 12 plot(x,v) 13 show() C:\Python27\lib\site-packages\matplotlib\pyplot.pyc in plot(*args, **kwargs) 2456 ax.hold(hold) 2457 try: -> 2458 ret = ax.plot(*args, **kwargs) 2459 draw_if_interactive() 2460 finally: C:\Python27\lib\site-packages\matplotlib\axes.pyc in plot(self, *args, **kwargs) 3846 lines = [] 3847 -> 3848 for line in self._get_lines(*args, **kwargs): 3849 self.add_line(line) 3850 lines.append(line) C:\Python27\lib\site-packages\matplotlib\axes.pyc in _grab_next_args(self, *args, **kwargs) 321 return 322 if len(remaining) <= 3: --> 323 for seg in self._plot_args(remaining, kwargs): 324 yield seg 325 return C:\Python27\lib\site-packages\matplotlib\axes.pyc in _plot_args(self, tup, kwargs) 298 x = np.arange(y.shape[0], dtype=float) 299 --> 300 x, y = self._xy_from_xy(x, y) 301 302 if self.command == 'plot': C:\Python27\lib\site-packages\matplotlib\axes.pyc in _xy_from_xy(self, x, y) 238 y = np.atleast_1d(y) 239 if x.shape[0] != y.shape[0]: --> 240 raise ValueError("x and y must have same first dimension") 241 if x.ndim > 2 or y.ndim > 2: 242 raise ValueError("x and y can be no greater than 2-D") ValueError: x and y must have same first dimension Question: what is to be edited? From __peter__ at web.de Sun Feb 5 18:42:38 2012 From: __peter__ at web.de (Peter Otten) Date: Sun, 05 Feb 2012 18:42:38 +0100 Subject: [Tutor] ploting of a square well References: Message-ID: Debashish Saha wrote: > from pylab import * > x=linspace(1,1000,10000) > a,b = 10,20 > def v(x): > i=5;v0=2 > for n in range(1,1+i): > if x>(n-1)*(a+b) and x return 0 > elif x>a+(n-1)*(a+b) and x<(n)*(a+b) : > return v0 > #v=vectorize(v) > plot(x,v) > show() > > Error: > x and y must have same first dimension > Question: > what is to be edited? When you want to plot a graph you can't pass the function as an argument. import pylab def f(x): return x*x x = [1, 2, 3] #wrong, one list and a function pylab.plot(x, f) # error pylab.show() You must instead pass the values, one list with the x-values and another with the same number of y-values: import pylab def f(x): return x*x x = [1, 2, 3] y = [f(xi) for xi in x] #correct, two lists pylab.plot(x, y) pylab.show() From pasokan at talentsprint.com Sun Feb 5 18:46:33 2012 From: pasokan at talentsprint.com (Asokan Pichai) Date: Sun, 5 Feb 2012 23:16:33 +0530 Subject: [Tutor] ploting of a square well In-Reply-To: References: Message-ID: Try changing plot(x, v) to plot(x, v(x)) Asokan Pichai We are all atheists about most of the gods that societies have ever believed in. Some of us just go one god further. ? Richard Dawkins From pasokan at talentsprint.com Sun Feb 5 18:48:22 2012 From: pasokan at talentsprint.com (Asokan Pichai) Date: Sun, 5 Feb 2012 23:18:22 +0530 Subject: [Tutor] ploting of a square well In-Reply-To: References: Message-ID: On Sun, Feb 5, 2012 at 11:16 PM, Asokan Pichai wrote: > Try changing > plot(x, v) > to > plot(x, v(x)) > > Asokan Pichai But your v(x) is probably in need of changing. I am answering from a machine with a small screen and no python Hence no definite statements. Asokan Pichai From dave at hansonforensics.co.uk Sun Feb 5 19:22:28 2012 From: dave at hansonforensics.co.uk (Dave Hanson) Date: Sun, 5 Feb 2012 18:22:28 +0000 Subject: [Tutor] Cmd Advice In-Reply-To: References: Message-ID: Thanks walter. Ill have a go and report back. Thanks Dave On Feb 5, 2012 4:35 PM, "Walter Prins" wrote: > Hello Dave, > > On 5 February 2012 15:26, Dave Hanson wrote: > > I can force a dos window to open by using a bat or python program. > > OK, so the command prompt issue is really a red herring then from what > I can tell. Work around the standard limitations of your desktop in > whatever way suits you (providing you're not going to get yourself > into trouble by doing so etc). As long as you can get to a command > prompt you can then set up the program to work the same way as on > Unix, with a bit of jiggery pokery. > > > What I'm > > trying to get around is not being able to interact with the program using > > [options] like -l for list for example. > > OK, so your real issue involved command line arguments it seems. What > I'd do is write a wrapper batch file for your Python program named > "t.bat", and place it in a location that's on your search path, or add > it to the search path if you like (perhaps put it alongside t.py and > then put that location on the system PATH.) > > t.bat should contain something like this (adjust paths as required > obviously): > > c:\Python27\python.exe c:\src\t\t.py %1 %2 %3 %4 %5 %6 %7 %8 %9 > > This command line will obviously pass the first 9 command line > argument strings given to the batch file on to the Python program. > > What this does is to allow you to run the command like you do on Unix, e.g: > > t -f 5 > > ... which in turn should will find and run t.bat with the command line > arguments "-5 5" which then pass them on to the Python program etc. > > HTH, > > Walter > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From defensoft at gmail.com Sun Feb 5 20:45:06 2012 From: defensoft at gmail.com (Nate Lastname) Date: Sun, 5 Feb 2012 14:45:06 -0500 Subject: [Tutor] Sandbox Game In-Reply-To: References: Message-ID: > > More details: I want it to be something similar to this: powdertoy.co.uk. > It will have different elements, though. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From defensoft at gmail.com Sun Feb 5 20:43:27 2012 From: defensoft at gmail.com (Nate Lastname) Date: Sun, 5 Feb 2012 14:43:27 -0500 Subject: [Tutor] Sandbox Game Message-ID: Hey List, I am thinking about making a sandbox game. Where should I start? Has anyone done this before? I'm having trouble in MANY places, and I couldn't find any similar projects with a Google search. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Sun Feb 5 21:42:14 2012 From: bermanrl at cfl.rr.com (Robert Berman) Date: Sun, 05 Feb 2012 15:42:14 -0500 Subject: [Tutor] Sandbox Game In-Reply-To: References: Message-ID: <4F2EE9A6.9040901@cfl.rr.com> On 02/05/2012 02:43 PM, Nate Lastname wrote: > Hey List, > > I am thinking about making a sandbox game. Where should I start? Has > anyone done this before? I'm having trouble in MANY places, and I > couldn't find any similar projects with a Google search. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Really no information. Just an immediate search on Google listed approximately 20,100,00 general articles on sandbox games. Searching the same category including python there are at least 1,100,000. What is your experience level doing basic research? Robert Berman -------------- next part -------------- An HTML attachment was scrubbed... URL: From defensoft at gmail.com Sun Feb 5 21:44:50 2012 From: defensoft at gmail.com (Nate Lastname) Date: Sun, 5 Feb 2012 15:44:50 -0500 Subject: [Tutor] Sandbox Game In-Reply-To: <4F2EE9A6.9040901@cfl.rr.com> References: <4F2EE9A6.9040901@cfl.rr.com> Message-ID: Hello Robert, I appreciate the reply, but I have two things to say: 1. Your nastiness is not appreciated or really needed. 2. If you look at the results, none of them actually give relavant info. I DID do research before I asked here, extensively, and found nothing. Thanks, The Defenestrator. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Feb 5 23:07:35 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 05 Feb 2012 22:07:35 +0000 Subject: [Tutor] Sandbox Game In-Reply-To: References: <4F2EE9A6.9040901@cfl.rr.com> Message-ID: On 05/02/12 20:44, Nate Lastname wrote: > I appreciate the reply, but I have two things to say: > 1. Your nastiness is not appreciated or really needed. I don't think Robert intended to be nasty. But you don't really give us much of a clue what you want. There is a ton of stuff on Google, if it doesn't answer your questions you need to be more precise about what kind of help you need. What have you tried, what are you planning, what don't you understand? If you say "everything" then we will just tell you to start at the beginning. The more precisely you frame your questions the more likely you are to get a useful answer. > 2. If you look at the results, none of them actually give relavant info. Relevant to what? the ones I looked at were all relevant in some way or another. But I don't know what you were expecting to find. Blender seems to be a common theme. And here is one such game with downloadable source code. Maybe you can use that as a starter? Or maybe just join their project? http://code.google.com/p/epik-project/wiki/EpikKickstart HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Mon Feb 6 00:47:35 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 06 Feb 2012 10:47:35 +1100 Subject: [Tutor] Sandbox Game In-Reply-To: References: Message-ID: <4F2F1517.1090705@pearwood.info> Nate Lastname wrote: > Hey List, > > I am thinking about making a sandbox game. Where should I start? Has > anyone done this before? I'm having trouble in MANY places, and This mailing list is for learning the Python programming language, not for answering arbitrary questions about anything vaguely related to Python. But in general, if you want to make games in Python, you can do far worse than to start with PyGame. Please define what you mean by "sandbox game". Do you mean a game that simulates playing in a sandbox? Or a game that runs in a (security) sandbox? Or something else? Running Python in a sandbox is a big, big task. In general, I would say it can't be done without assistance from the operating system, e.g. using a Unix chroot to limit access to the file system. But you could try PyPy, which I understand has a restricted Python mode. > I couldn't > find any similar projects with a Google search. I find that difficult to believe. Perhaps you have other constraints that you are keeping secret, because the first page of Google search includes a link to someone who wrote a sandbox game (whatever that is!) similar to "World of Goo" using Pygame: http://www.pygame.org/project-World+of+Goo+physics-1018-1785.html -- Steven From nikolay.moskvin at gmail.com Mon Feb 6 12:05:20 2012 From: nikolay.moskvin at gmail.com (Nikolay Moskvin) Date: Mon, 6 Feb 2012 18:05:20 +0700 Subject: [Tutor] Problem with smtplib Message-ID: <201202061805.20462.nikolay.moskvin@gmail.com> Hi, all I have a problem with sending mail via smtp. This error does not always happen. Does somebody seen this stacktrace? smtp.sendmail(send_from, send_to, msg.as_string()) File "/usr/local/lib/python2.7/smtplib.py", line 725, in sendmail (code, resp) = self.data(msg) File "/usr/local/lib/python2.7/smtplib.py", line 482, in data (code, repl) = self.getreply() File "/usr/local/lib/python2.7/smtplib.py", line 352, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") -- Best regards, Nikolay Moskvin From defensoft at gmail.com Mon Feb 6 15:13:48 2012 From: defensoft at gmail.com (Nate Lastname) Date: Mon, 6 Feb 2012 09:13:48 -0500 Subject: [Tutor] Sandbox Game In-Reply-To: <4F2F1A05.7050303@pearwood.info> References: <4F2EE9A6.9040901@cfl.rr.com> <4F2F1A05.7050303@pearwood.info> Message-ID: Hello List, I am quite sorry for my attitude. I will look more thoroughly into the search results. Thanks for the link to Epik. I had found this, but I didn't realize that it was Python. I apologize once again, and thank you for your help. I did give you a link to a sandbox game (powdertoy.co.uk) as an example of what I wanted, but that must not have been delivered properly. My Apologies, The Defenestrator -------------- next part -------------- An HTML attachment was scrubbed... URL: From defensoft at gmail.com Mon Feb 6 15:16:31 2012 From: defensoft at gmail.com (Nate Lastname) Date: Mon, 6 Feb 2012 09:16:31 -0500 Subject: [Tutor] Sandbox Game In-Reply-To: References: <4F2EE9A6.9040901@cfl.rr.com> <4F2F1A05.7050303@pearwood.info> Message-ID: P.S.: I also would like to say that I am a noob at Python, Pygame, and the list. I'll try not to post more stupid questions, though. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tony.pelletier at gmail.com Mon Feb 6 16:11:12 2012 From: tony.pelletier at gmail.com (Tony Pelletier) Date: Mon, 6 Feb 2012 10:11:12 -0500 Subject: [Tutor] Trouble with encoding/decoding a file Message-ID: Hi, I've been tasked with getting the encoded value using a SOAP call and then writing the file out. I first used the interpreter to do so like such: import base64 encoded = 'super long encoded string' data = base64.b64decode(encoded) outfile = open('test.xls', 'w') outfile.write(data) outfile.close And that all worked just fine. The difference here is I am cutting and pasting the encoded value into a string from notepad++. So, I then did the following which I can't get working. It keeps telling me "excel found unreadable content in the file' essentially being corrupt and I can't tell what I'm doing wrong. try: eventresult = service.client.service.EventQueryById(event, 'true') filename = eventresult.Event[0].EventFileArgs.EventFileArg[0].UserFileName encodedfile = str(eventresult.Event[0].EventFileArgs.EventFileArg[0].EncodedValue) encodedstring = encodedfile.encode('utf-8') str_list = [] for line in encodedstring: line = line.strip() str_list.append(line) string = ''.join(str_list) print string data = base64.b64decode(string) txtfile = open('trp.txt', 'w') txtfile.write(string) outfile = open(filename, 'w') outfile.write(data) outfile.close() except suds.WebFault as e: print e.fault.detail The txt file is only there to make sure I'm writing out one long string which is what I'm pasting in so I'm assuming that's correct. Any help is greatly appreciated. Thanks Tony -------------- next part -------------- An HTML attachment was scrubbed... URL: From shukla.kapil at gmail.com Mon Feb 6 16:25:53 2012 From: shukla.kapil at gmail.com (Kapil Shukla) Date: Mon, 6 Feb 2012 23:25:53 +0800 Subject: [Tutor] decimal precision in python Message-ID: i tried writing a small code to calculate option price using the binomial tree model. I compared my results with results of the same program in excel. There seems to be a minor difference due to decimal precision as excel is using 15 decimal precision and python (both 2.7 and 3.1) using 11. (at least that's what shown on shell) can some one guide me whats the equivalent of using a double datatype on python and i can't use long() in 3.1 any more. Please also suggest a free editor for python which can at least repeat previous command with a key stroke regards kapil -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Mon Feb 6 16:40:29 2012 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 06 Feb 2012 07:40:29 -0800 Subject: [Tutor] decimal precision in python In-Reply-To: References: Message-ID: <4F2FF46D.4050207@alchemy.com> On 06-Feb-12 07:25, Kapil Shukla wrote: > i tried writing a small code to calculate option price using the > binomial tree model. I compared my results with results of the same > program in excel. There seems to be a minor difference due to decimal > precision as excel is using 15 decimal precision and python (both 2.7 > and 3.1) using 11. (at least that's what shown on shell) If you need lots of precision, you might consider using the decimal class. It'll cost you speed vs. the native floating-point type but won't cause you round-off errors. natively, Python uses IEEE double-precision math for all float objects. For a float value x, instead of just printing it, try this: print('{0:.30f}'.format(x)) > can some one guide me whats the equivalent of using a double datatype on > python and i can't use long() in 3.1 any more. Equivalent to what degree? Python's float class generally will get you where you need to go. Also the int type automatically extends to arbitrary-precision integer values so you don't need explicit "long" type anymore. (Unless I misunderstood your question there.) > Please also suggest a free editor for python which can at least repeat > previous command with a key stroke I use vim, which has that feature. I suspect any editor worth its salt does, or could be programmed to. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From eire1130 at gmail.com Mon Feb 6 16:41:24 2012 From: eire1130 at gmail.com (James Reynolds) Date: Mon, 6 Feb 2012 10:41:24 -0500 Subject: [Tutor] decimal precision in python In-Reply-To: References: Message-ID: On Mon, Feb 6, 2012 at 10:25 AM, Kapil Shukla wrote: > i tried writing a small code to calculate option price using the binomial > tree model. I compared my results with results of the same program in > excel. There seems to be a minor difference due to decimal precision as > excel is using 15 decimal precision and python (both 2.7 and 3.1) using 11. > (at least that's what shown on shell) > > can some one guide me whats the equivalent of using a double datatype on > python and i can't use long() in 3.1 any more. > > Please also suggest a free editor for python which can at least repeat > previous command with a key stroke > > regards > kapil > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Have you looked into the decimal module? (you need to import decimal) http://docs.python.org/library/decimal.html You can specify the amount of precision needed. Also, i would suggest using 3.2, if it's not too late in your project. As for editors, I hear VIM is good. I use Eclipse as an IDE personally. People seem to have some fairly definite ideas on what editor other people should use, bordering on religious fanaticism. -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Feb 6 16:52:55 2012 From: d at davea.name (Dave Angel) Date: Mon, 06 Feb 2012 10:52:55 -0500 Subject: [Tutor] decimal precision in python In-Reply-To: References: Message-ID: <4F2FF757.60908@davea.name> On 02/06/2012 10:25 AM, Kapil Shukla wrote: > i tried writing a small code to calculate option price using the binomial > tree model. I compared my results with results of the same program in > excel. There seems to be a minor difference due to decimal precision as > excel is using 15 decimal precision and python (both 2.7 and 3.1) using 11. > (at least that's what shown on shell) > > can some one guide me whats the equivalent of using a double datatype on > python and i can't use long() in 3.1 any more. > > Please also suggest a free editor for python which can at least repeat > previous command with a key stroke > > regards > kapil > > A Python float is equivalent to a C double; it's already about 18 digits, using the IEEE binary hardware available on most modern systems. However, it's a binary value, so it'll round in different places than the decimal values that Excel probably uses. You might want to read this: http://docs.python.org/tutorial/floatingpoint.html From the subject you choose, you are apparently asking for a decimal package. You can use the python decimal package if you actually need the round-off to be according to decimal's quirks. Certainly that's easier (and slower) to deal with. Or you can use decimal because you need more than about 18 digits. It defaults to 28, but you can set it higher or lower. import decimal. http://docs.python.org/library/decimal.html For a free editor that's python friendly, I'd suggest Komodo Edit, http://www.activestate.com/komodo-edit I use the non-free Komodo-ide, which is based on the free editor. -- DaveA From bgailer at gmail.com Mon Feb 6 17:02:32 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 06 Feb 2012 11:02:32 -0500 Subject: [Tutor] Sandbox Game In-Reply-To: References: <4F2EE9A6.9040901@cfl.rr.com> <4F2F1A05.7050303@pearwood.info> Message-ID: <4F2FF998.8050500@gmail.com> On 2/6/2012 9:13 AM, Nate Lastname wrote: > Hello List, > > I am quite sorry for my attitude. I will look more thoroughly into > the search results. Thanks for the link to Epik. I had found this, > but I didn't realize that it was Python. I apologize once again, and > thank you for your help. I did give you a link to a sandbox game > (powdertoy.co.uk ) as an example of what I > wanted, but that must not have been delivered properly. The link came thru fine. I expected some description of the game rather than having to download something. I am reluctant todownload unknowns. I even tried the Play Online and got to another messy connfusing site, Could you give an overview of the game? -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Feb 6 17:05:36 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 06 Feb 2012 11:05:36 -0500 Subject: [Tutor] Sandbox Game In-Reply-To: References: <4F2EE9A6.9040901@cfl.rr.com> <4F2F1A05.7050303@pearwood.info> Message-ID: <4F2FFA50.9010308@gmail.com> On 2/6/2012 9:16 AM, Nate Lastname wrote: > P.S.: I also would like to say that I am a noob at Python, Pygame, > and the list. I'll try not to post more stupid questions, though. We are here to help the newcomers. Questions are not "stupid". The easier you make it for us to answer the more likely you are to get answers. We volunteer our time to help you; we are not paid money for our service. -- Bob Gailer 919-636-4239 Chapel Hill NC From tmikk at umn.edu Mon Feb 6 17:12:25 2012 From: tmikk at umn.edu (Tonu Mikk) Date: Mon, 6 Feb 2012 10:12:25 -0600 Subject: [Tutor] exercise with classes In-Reply-To: References: Message-ID: Alan, thanks for explaining about passing objects to classes. This is an important concept for me to understand. I tried running the code, but run into an error that I could not resolve: TypeError: doIt() takes no arguments (1 given). Tonu On Thu, Feb 2, 2012 at 7:09 PM, Alan Gauld wrote: > On 02/02/12 17:36, Tonu Mikk wrote: > > So far I have searched for info on how to pass variables from one class >> to another and have been able to create a small two class program >> (attached). But I seem unable to generalize from here and apply this >> to the game exercise. What would you suggest for me to try next? >> > > Remember that OOP is about creating objects from classes. > You can pass an object to another rather than just the > variables, in fact its preferable! > > Also remember that you can create many objects from one class. > So just because you have one Room class doesn't mean you are > stuck with one room object. You can have many and each can > be connected to another. > > You can get rooms to describe themselves, you can enter a room. > You might even be able to create new rooms or destroy existing ones. These > actions can all be methods of your Room class. > > Here is an example somewhat like yours that passes objects: > > class Printer: > def __init__(self,number=0): > self.value = number > def sayIt(self): > print self.value > > class MyApp: > def __init__(self, aPrinter = None): > if aPrinter == None: # if no object passed create one > aPrinter = Printer() > self.obj = aPrinter # assign object > def doIt() > self.obj.sayIt() # use object > > def test() > p = Printer(42) > a1 MyApp() > a2 = MyApp(p) # pass p object into a2 > a1.doIt() # prints default value = 0 > a2.doIt() # prints 42, the value of p > > test() > > HTH, > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Tonu Mikk Disability Services, Office for Equity and Diversity 612 625-3307 tmikk at umn.edu -------------- next part -------------- An HTML attachment was scrubbed... URL: From defensoft at gmail.com Mon Feb 6 17:16:40 2012 From: defensoft at gmail.com (Nate Lastname) Date: Mon, 6 Feb 2012 11:16:40 -0500 Subject: [Tutor] Sandbox Game In-Reply-To: <4F2FFA50.9010308@gmail.com> References: <4F2EE9A6.9040901@cfl.rr.com> <4F2F1A05.7050303@pearwood.info> <4F2FFA50.9010308@gmail.com> Message-ID: Hey all, The basic idea is that there are different types of sand. They fall and move (or don't, if they are solid) and interact with each other in different ways. I.E.; there is a lava type; it falls, and when it hits other sand types, it heats them up. If it gets cold, it becomes sand. I don't want to copy the game, I want to make my own to play around with Py(thon/game). Thanks for your help! -- My Blog - Defenestration Coding http://defenestrationcoding.wordpress.com/ From modulok at gmail.com Mon Feb 6 17:17:40 2012 From: modulok at gmail.com (Modulok) Date: Mon, 6 Feb 2012 09:17:40 -0700 Subject: [Tutor] decimal precision in python In-Reply-To: References: Message-ID: For money, you should probably use the builtin module 'decimal' instead: http://docs.python.org/library/decimal.html There's also the third party module 'mpmath' which provides arbitrary precision floating point arithmetic. http://mpmath.googlecode.com/svn/trunk/doc/build/index.html -Modulok- On 2/6/12, Kapil Shukla wrote: > i tried writing a small code to calculate option price using the binomial > tree model. I compared my results with results of the same program in > excel. There seems to be a minor difference due to decimal precision as > excel is using 15 decimal precision and python (both 2.7 and 3.1) using 11. > (at least that's what shown on shell) > > can some one guide me whats the equivalent of using a double datatype on > python and i can't use long() in 3.1 any more. > > Please also suggest a free editor for python which can at least repeat > previous command with a key stroke > > regards > kapil > From defensoft at gmail.com Mon Feb 6 17:19:31 2012 From: defensoft at gmail.com (Nate Lastname) Date: Mon, 6 Feb 2012 11:19:31 -0500 Subject: [Tutor] exercise with classes In-Reply-To: References: Message-ID: Hey Tonu, The problem is that in your statement definition, you are not including the self argument. Your definition needs to be something like: def dolt(self): # Do stuff. For more info on the self keyword, see http://docs.python.org/tutorial/classes.html, section 9.3.2. On 2/6/12, Tonu Mikk wrote: > Alan, thanks for explaining about passing objects to classes. This is an > important concept for me to understand. > > I tried running the code, but run into an error that I could not resolve: > > TypeError: doIt() takes no arguments (1 given). > > Tonu > > On Thu, Feb 2, 2012 at 7:09 PM, Alan Gauld wrote: > >> On 02/02/12 17:36, Tonu Mikk wrote: >> >> So far I have searched for info on how to pass variables from one class >>> to another and have been able to create a small two class program >>> (attached). But I seem unable to generalize from here and apply this >>> to the game exercise. What would you suggest for me to try next? >>> >> >> Remember that OOP is about creating objects from classes. >> You can pass an object to another rather than just the >> variables, in fact its preferable! >> >> Also remember that you can create many objects from one class. >> So just because you have one Room class doesn't mean you are >> stuck with one room object. You can have many and each can >> be connected to another. >> >> You can get rooms to describe themselves, you can enter a room. >> You might even be able to create new rooms or destroy existing ones. These >> actions can all be methods of your Room class. >> >> Here is an example somewhat like yours that passes objects: >> >> class Printer: >> def __init__(self,number=0): >> self.value = number >> def sayIt(self): >> print self.value >> >> class MyApp: >> def __init__(self, aPrinter = None): >> if aPrinter == None: # if no object passed create one >> aPrinter = Printer() >> self.obj = aPrinter # assign object >> def doIt() >> self.obj.sayIt() # use object >> >> def test() >> p = Printer(42) >> a1 MyApp() >> a2 = MyApp(p) # pass p object into a2 >> a1.doIt() # prints default value = 0 >> a2.doIt() # prints 42, the value of p >> >> test() >> >> HTH, >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > > > -- > Tonu Mikk > Disability Services, Office for Equity and Diversity > 612 625-3307 > tmikk at umn.edu > -- My Blog - Defenestration Coding http://defenestrationcoding.wordpress.com/ From bgailer at gmail.com Mon Feb 6 18:10:35 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 06 Feb 2012 12:10:35 -0500 Subject: [Tutor] Problem with smtplib In-Reply-To: <201202061805.20462.nikolay.moskvin@gmail.com> References: <201202061805.20462.nikolay.moskvin@gmail.com> Message-ID: <4F30098B.8020004@gmail.com> On 2/6/2012 6:05 AM, Nikolay Moskvin wrote: > Hi, all > I have a problem with sending mail via smtp. This error does not always > happen. Does somebody seen this stacktrace? I've seen many like that. It means exactly what it says. "Connection unexpectedly closed" Most likely something went awry with the internet connection between your computer and the SMTP server. Best strategy I know of is to trap the exception and retry, but for a limited # of times. -- Bob Gailer 919-636-4239 Chapel Hill NC From bgailer at gmail.com Mon Feb 6 18:17:42 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 06 Feb 2012 12:17:42 -0500 Subject: [Tutor] python editor Message-ID: <4F300B36.3010303@gmail.com> On 2/6/2012 10:25 AM, Kapil Shukla wrote: > Please also suggest a free editor for python which can at least repeat > previous command with a key stroke It is better to ask an unrelated question in a separate email, with its own relevant subject. Please give an example of what you mean by "epeat previous command". I can think of several unrelated meanings. Personally I prefer an IDE. My favorites are PyCharm ($) and Python for Windows (free). -- Bob Gailer 919-636-4239 Chapel Hill NC From bgailer at gmail.com Mon Feb 6 19:02:04 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 06 Feb 2012 13:02:04 -0500 Subject: [Tutor] Sandbox Game In-Reply-To: References: <4F2EE9A6.9040901@cfl.rr.com> <4F2F1A05.7050303@pearwood.info> <4F2FFA50.9010308@gmail.com> Message-ID: <4F30159C.60402@gmail.com> On 2/6/2012 11:16 AM, Nate Lastname wrote: > Hey all, > > The basic idea is that there are different types of sand. They fall > and move (or don't, if they are solid) and interact with each other in > different ways. I.E.; there is a lava type; it falls, and when it > hits other sand types, it heats them up. If it gets cold, it becomes > sand. Thanks for a top-level overview. I have no practical experience with game /programming /, just some general concepts which I offer here, and leave it to others to assist. You might add more specifics - do you want a graphics display? User interaction? Anything you add to your description helps us and helps you move to your goal. I suggest you start simple, get something working then add another feature. Simple? Could be as simple as 1 grain falling till it hits bottom. Does it have an initial velocity? Does it accelerate under the pull of gravity? Velocity means speed and direction. What happens when it hits bottom? Then add a 2nd grain. What happens if the 2 collide? What is your update rate (how often do you recompute the positions of all the grains)? What is the smallest increment of position change? I assume you will create a class for each type of sand grain. with relevant properties and methods. You will need a program that runs in a loop (probably with a sleep) to - update positions and velocities of each grain (by invoking class methods) - detect and manage collisions - display each grain (by invoking class methods) If you are using a graphics package I assume you will have a "canvas" on which you will draw some kind of object to represent a particular class of grain at the current x,y(,z?) coordinates of each grain. It is possible to change the base class of an object on-the-fly, so a lava drop could become a sand grain. That's all for now. Good coding! I don't want to copy the game Is there a Python version out there? > , I want to make my own to play around with Py(thon/game). > -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 6 19:11:13 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 06 Feb 2012 18:11:13 +0000 Subject: [Tutor] python editor In-Reply-To: <4F300B36.3010303@gmail.com> References: <4F300B36.3010303@gmail.com> Message-ID: On 06/02/12 17:17, bob gailer wrote: > On 2/6/2012 10:25 AM, Kapil Shukla wrote: > >> Please also suggest a free editor for python which can at least repeat >> previous command with a key stroke That depends on the editor's mode of operation. In an editor like vi (elvis, vim etc) there is a repeat key (the period) that repeats most things because most things are a "command" - even inserting text. but in a so called modeless editor (most modern ones) repeat will be restricted to things that are recognised as atomic operations, like search/replace, change case etc. And some of those will only be valid when text is selected (so not really modeless!). Other editors like emacs allow you to specify how often an action is repeated. So esc-16 n will insert 16 n's for example. You would need to be more specific in terms of what you want in a repeat operation. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Feb 6 19:13:30 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 06 Feb 2012 18:13:30 +0000 Subject: [Tutor] Trouble with encoding/decoding a file In-Reply-To: References: Message-ID: On 06/02/12 15:11, Tony Pelletier wrote: > Hi, > > I've been tasked with getting the encoded value using a SOAP call and > then writing the file out. I first used the interpreter to do so like such: > > import base64 > > encoded = 'super long encoded string' > data = base64.b64decode(encoded) > outfile = open('test.xls', 'w') Have you tried opening as a binary file? Excel .xls uses binary data... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Feb 6 19:15:26 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 06 Feb 2012 18:15:26 +0000 Subject: [Tutor] exercise with classes In-Reply-To: References: Message-ID: On 06/02/12 16:12, Tonu Mikk wrote: > Alan, thanks for explaining about passing objects to classes. This is > an important concept for me to understand. > > I tried running the code, but run into an error that I could not resolve: > > TypeError: doIt() takes no arguments (1 given). Sorry the code was only meant for illustration and had not nbeen tested. I forgot the self in the definition of doit()... And probably other stuff too! Alan G. From tmikk at umn.edu Mon Feb 6 19:24:55 2012 From: tmikk at umn.edu (Tonu Mikk) Date: Mon, 6 Feb 2012 12:24:55 -0600 Subject: [Tutor] exercise with classes In-Reply-To: References: Message-ID: Now I get an error: NameError: global name 'self' is not define. Tonu On Mon, Feb 6, 2012 at 10:19 AM, Nate Lastname wrote: > Hey Tonu, > > The problem is that in your statement definition, you are not > including the self argument. Your definition needs to be something > like: > def dolt(self): > # Do stuff. > For more info on the self keyword, see > http://docs.python.org/tutorial/classes.html, section 9.3.2. > > On 2/6/12, Tonu Mikk wrote: > > Alan, thanks for explaining about passing objects to classes. This is an > > important concept for me to understand. > > > > I tried running the code, but run into an error that I could not resolve: > > > > TypeError: doIt() takes no arguments (1 given). > > > > Tonu > > > > On Thu, Feb 2, 2012 at 7:09 PM, Alan Gauld >wrote: > > > >> On 02/02/12 17:36, Tonu Mikk wrote: > >> > >> So far I have searched for info on how to pass variables from one class > >>> to another and have been able to create a small two class program > >>> (attached). But I seem unable to generalize from here and apply this > >>> to the game exercise. What would you suggest for me to try next? > >>> > >> > >> Remember that OOP is about creating objects from classes. > >> You can pass an object to another rather than just the > >> variables, in fact its preferable! > >> > >> Also remember that you can create many objects from one class. > >> So just because you have one Room class doesn't mean you are > >> stuck with one room object. You can have many and each can > >> be connected to another. > >> > >> You can get rooms to describe themselves, you can enter a room. > >> You might even be able to create new rooms or destroy existing ones. > These > >> actions can all be methods of your Room class. > >> > >> Here is an example somewhat like yours that passes objects: > >> > >> class Printer: > >> def __init__(self,number=0): > >> self.value = number > >> def sayIt(self): > >> print self.value > >> > >> class MyApp: > >> def __init__(self, aPrinter = None): > >> if aPrinter == None: # if no object passed create one > >> aPrinter = Printer() > >> self.obj = aPrinter # assign object > >> def doIt() > >> self.obj.sayIt() # use object > >> > >> def test() > >> p = Printer(42) > >> a1 MyApp() > >> a2 = MyApp(p) # pass p object into a2 > >> a1.doIt() # prints default value = 0 > >> a2.doIt() # prints 42, the value of p > >> > >> test() > >> > >> HTH, > >> > >> -- > >> Alan G > >> Author of the Learn to Program web site > >> http://www.alan-g.me.uk/ > >> > >> > >> ______________________________**_________________ > >> Tutor maillist - Tutor at python.org > >> To unsubscribe or change subscription options: > >> http://mail.python.org/**mailman/listinfo/tutor< > http://mail.python.org/mailman/listinfo/tutor> > >> > > > > > > > > -- > > Tonu Mikk > > Disability Services, Office for Equity and Diversity > > 612 625-3307 > > tmikk at umn.edu > > > > > -- > My Blog - Defenestration Coding > > http://defenestrationcoding.wordpress.com/ > -- Tonu Mikk Disability Services, Office for Equity and Diversity 612 625-3307 tmikk at umn.edu -------------- next part -------------- An HTML attachment was scrubbed... URL: From tony.pelletier at gmail.com Mon Feb 6 19:40:29 2012 From: tony.pelletier at gmail.com (Tony Pelletier) Date: Mon, 6 Feb 2012 13:40:29 -0500 Subject: [Tutor] Trouble with encoding/decoding a file In-Reply-To: References: Message-ID: On Mon, Feb 6, 2012 at 1:13 PM, Alan Gauld wrote: > On 06/02/12 15:11, Tony Pelletier wrote: > >> Hi, >> >> I've been tasked with getting the encoded value using a SOAP call and >> then writing the file out. I first used the interpreter to do so like >> such: >> >> import base64 >> >> encoded = 'super long encoded string' >> data = base64.b64decode(encoded) >> outfile = open('test.xls', 'w') >> > > > Have you tried opening as a binary file? >> Excel .xls uses binary data... > > Unbelievable. In the snippet you quoted above, it didn't matter. That one always worked, but changing it in the code I wrote, it totally fixed it. :) Thanks! > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Feb 6 19:58:06 2012 From: d at davea.name (Dave Angel) Date: Mon, 06 Feb 2012 13:58:06 -0500 Subject: [Tutor] exercise with classes In-Reply-To: References: Message-ID: <4F3022BE.2000608@davea.name> On 02/06/2012 01:24 PM, Tonu Mikk wrote: > Now I get an error: NameError: global name 'self' is not define. > > Tonu > > Put your remarks after the stuff you quote. You're top-posting, which makes the reply difficult to follow. Use copy/paste to describe an error message. You retyped the one above, and added a typo. Include the whole error, which includes the stack trace. If you had followed Nate's advice, you couldn't have gotten that error at all, so you'll also need to post the code that actually triggers the error. -- DaveA From alan.gauld at btinternet.com Mon Feb 6 20:02:13 2012 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 6 Feb 2012 19:02:13 +0000 (GMT) Subject: [Tutor] Trouble with encoding/decoding a file In-Reply-To: References: Message-ID: <1328554933.29994.YahooMailNeo@web86706.mail.ird.yahoo.com> That's not too surprising. Text files use an end-of-file character combination.? You might be lucky and not encounter that set of bytes in your file or you? might be unlucky and find it, in which case the file gets truncated.? That's why you need the binary setting, to ensure you read the? whole file! ? Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ >________________________________ > From: Tony Pelletier >To: Alan Gauld >Cc: tutor at python.org >Sent: Monday, 6 February 2012, 18:40 >Subject: Re: [Tutor] Trouble with encoding/decoding a file > > > > > >On Mon, Feb 6, 2012 at 1:13 PM, Alan Gauld wrote: > >On 06/02/12 15:11, Tony Pelletier wrote: >> >>Hi, >>> >>>I've been tasked with getting the encoded value using a SOAP call and >>>then writing the file out. ?I first used the interpreter to do so like such: >>> >>>import base64 >>> >>>encoded = 'super long encoded string' >>>data = base64.b64decode(encoded) >>>outfile = open('test.xls', 'w') >>> >> >> >>Have you tried opening as a binary file? >>>Excel .xls uses binary data... > > >Unbelievable. ?In the snippet you quoted above, it didn't matter. ?That one always worked, but changing it in the code I wrote, it totally fixed it. ?:) > > >Thanks!? > >>-- >>Alan G >>Author of the Learn to Program web site >>http://www.alan-g.me.uk/ >> >>_______________________________________________ >>Tutor maillist ?- ?Tutor at python.org >>To unsubscribe or change subscription options: >>http://mail.python.org/mailman/listinfo/tutor >> > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mylesbroomes at hotmail.co.uk Mon Feb 6 20:05:56 2012 From: mylesbroomes at hotmail.co.uk (myles broomes) Date: Mon, 6 Feb 2012 19:05:56 +0000 Subject: [Tutor] Backwards message program Message-ID: Im trying to code a program where the user enters a message and it is returned backwards. Here is my code so far: message = input("Enter your message: ") backw = "" counter = len(message) while message != 0: backw += message[counter-1] counter -= 1 print(backw) input("\nPress enter to exit...") I run the program, type in my message but get back the error code: 'IndexError: String out of range' I was thinking that maybe the problem is that each time a letter is taken from 'message' and added to 'backw', the length of message becomes a letter shorter but for whatever reason the variable 'counter' doesnt change when its supposed to be minused by 1 letter so its always bigger than message if that makes sense. Any help is much appreciated and thanks in advance. Myles Broomes -------------- next part -------------- An HTML attachment was scrubbed... URL: From silideba at gmail.com Mon Feb 6 20:12:59 2012 From: silideba at gmail.com (Debashish Saha) Date: Tue, 7 Feb 2012 00:42:59 +0530 Subject: [Tutor] what is the basic difference Message-ID: what is the basic difference between the commands import pylab as * import matplotlib.pyplot as plt import numpy as np import numpy as * From d at davea.name Mon Feb 6 20:23:13 2012 From: d at davea.name (Dave Angel) Date: Mon, 06 Feb 2012 14:23:13 -0500 Subject: [Tutor] Backwards message program In-Reply-To: References: Message-ID: <4F3028A1.7050709@davea.name> On 02/06/2012 02:05 PM, myles broomes wrote: > Im trying to code a program where the user enters a message and it is returned backwards. Here is my code so far: > > > > > > message = input("Enter your message: ") > > backw = "" > counter = len(message) > > while message != 0: > backw += message[counter-1] > counter -= 1 > print(backw) > input("\nPress enter to exit...") > > > > > > I run the program, type in my message but get back the error code: > > 'IndexError: String out of range' > > I was thinking that maybe the problem is that each time a letter is taken from 'message' and added to 'backw', the length of message becomes a letter shorter but for whatever reason the variable 'counter' doesnt change when its supposed to be minused by 1 letter so its always bigger than message if that makes sense. Any help is much appreciated and thanks in advance. > > Myles Broomes > > First, what's the python version and OS? If you run that program under 2.x, it'll quit a lot sooner. So I figure Python 3.2 Next, don't retype the message, copy& paste it. Your retype missed an important word of the message, and you didn't include the traceback, which is also important. Now to your problem: You never change message, so the while loop never terminates (except with the exception when it tries an index that's too far negative. The obvious answer is to terminate the loop when counter goes negative. But it might also be readable to terminate it when the two strings have the same length. There are many other ways to reverse a string, but I wanted to show you what went wrong in this particular code. If I were an instructor, the next thing I'd suggest is to ask you how to use a for-loop, instead of a while. Or to look up the slice syntax, and see what the restrictions are of getting substrings from that. -- DaveA From d at davea.name Mon Feb 6 20:26:20 2012 From: d at davea.name (Dave Angel) Date: Mon, 06 Feb 2012 14:26:20 -0500 Subject: [Tutor] what is the basic difference In-Reply-To: References: Message-ID: <4F30295C.6090702@davea.name> On 02/06/2012 02:12 PM, Debashish Saha wrote: > what is the basic difference between the commands > import pylab as * > import matplotlib.pyplot as plt > import numpy as np > import numpy as * import pylab as * pollutes your global namespace with all kinds of symbols. If you don't know them all, you might accidentally use one of them in your own code, and wonder why things aren't working the way you expected. Better is import pylab and then use pylab.something to access a symbol from pylab Some prefer import pylab as pab (or something) and then use pab.something to save some typing. import matplotlib.pyplot as plt looks in the matplotlib *package" for the module pyplot, then imports it with a shortcut name of plt -- DaveA From bgailer at gmail.com Mon Feb 6 20:55:07 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 06 Feb 2012 14:55:07 -0500 Subject: [Tutor] Backwards message program In-Reply-To: References: Message-ID: <4F30301B.8010907@gmail.com> On 2/6/2012 2:05 PM, myles broomes wrote: > Im trying to code a program where the user enters a message and it is > returned backwards. Here is my code so far: > > ------------------------------------------------------------------------ > > > message = input("Enter your message: ") > > backw = "" > counter = len(message) > > while message != 0: > backw += message[counter-1] > counter -= 1 > > print(backw) > input("\nPress enter to exit...") > > ------------------------------------------------------------------------ > > > I run the program, type in my message but get back the error code: > > 'IndexError: String out of range' > > I was thinking that maybe the problem is that each time a letter is > taken from 'message' and added to 'backw', the length of message > becomes a letter shorter 1 - message never changes. Why did you think letters were "taken" from it? They are copied. 2 - comparing an integer to a string is always False -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From defensoft at gmail.com Mon Feb 6 22:08:10 2012 From: defensoft at gmail.com (Nate Lastname) Date: Mon, 6 Feb 2012 16:08:10 -0500 Subject: [Tutor] Sandbox Game In-Reply-To: <4F30159C.60402@gmail.com> References: <4F2EE9A6.9040901@cfl.rr.com> <4F2F1A05.7050303@pearwood.info> <4F2FFA50.9010308@gmail.com> <4F30159C.60402@gmail.com> Message-ID: Some more info: It's in pygame. It's 2d. I cannot find any python versions out there. Yes, there is a graphical interface, and yes, it is a user-controlled game. Thank you all for your help! The Defenestrator On 2/6/12, bob gailer wrote: > On 2/6/2012 11:16 AM, Nate Lastname wrote: >> Hey all, >> >> The basic idea is that there are different types of sand. They fall >> and move (or don't, if they are solid) and interact with each other in >> different ways. I.E.; there is a lava type; it falls, and when it >> hits other sand types, it heats them up. If it gets cold, it becomes >> sand. > Thanks for a top-level overview. I have no practical experience with > game /programming /, just some general concepts which I offer here, and > leave it to others to assist. > > You might add more specifics - do you want a graphics display? User > interaction? Anything you add to your description helps us and helps you > move to your goal. > > I suggest you start simple, get something working then add another feature. > > Simple? Could be as simple as 1 grain falling till it hits bottom. Does > it have an initial velocity? Does it accelerate under the pull of > gravity? Velocity means speed and direction. What happens when it hits > bottom? > > Then add a 2nd grain. What happens if the 2 collide? > > What is your update rate (how often do you recompute the positions of > all the grains)? What is the smallest increment of position change? > > I assume you will create a class for each type of sand grain. with > relevant properties and methods. > > You will need a program that runs in a loop (probably with a sleep) to > - update positions and velocities of each grain (by invoking class > methods) > - detect and manage collisions > - display each grain (by invoking class methods) > > If you are using a graphics package I assume you will have a "canvas" on > which you will draw some kind of object to represent a particular class > of grain at the current x,y(,z?) coordinates of each grain. > > It is possible to change the base class of an object on-the-fly, so a > lava drop could become a sand grain. > > That's all for now. Good coding! > > I don't want to copy the game > > Is there a Python version out there? >> , I want to make my own to play around with Py(thon/game). >> > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > -- My Blog - Defenestration Coding http://defenestrationcoding.wordpress.com/ From defensoft at gmail.com Mon Feb 6 22:11:22 2012 From: defensoft at gmail.com (Nate Lastname) Date: Mon, 6 Feb 2012 16:11:22 -0500 Subject: [Tutor] Sandbox Game In-Reply-To: References: <4F2EE9A6.9040901@cfl.rr.com> <4F2F1A05.7050303@pearwood.info> <4F2FFA50.9010308@gmail.com> <4F30159C.60402@gmail.com> Message-ID: Hold on... I just found one! It's not ideal, but it will work at least for a base - http://www.pygame.org/project-pysand-1387-2577.html. Thanks again, all, for your excellent help! The Defenestrator On 2/6/12, Nate Lastname wrote: > Some more info: > > It's in pygame. > It's 2d. > I cannot find any python versions out there. Yes, there is a > graphical interface, and yes, it is a user-controlled game. > Thank you all for your help! > > The Defenestrator > > On 2/6/12, bob gailer wrote: >> On 2/6/2012 11:16 AM, Nate Lastname wrote: >>> Hey all, >>> >>> The basic idea is that there are different types of sand. They fall >>> and move (or don't, if they are solid) and interact with each other in >>> different ways. I.E.; there is a lava type; it falls, and when it >>> hits other sand types, it heats them up. If it gets cold, it becomes >>> sand. >> Thanks for a top-level overview. I have no practical experience with >> game /programming /, just some general concepts which I offer here, and >> leave it to others to assist. >> >> You might add more specifics - do you want a graphics display? User >> interaction? Anything you add to your description helps us and helps you >> move to your goal. >> >> I suggest you start simple, get something working then add another >> feature. >> >> Simple? Could be as simple as 1 grain falling till it hits bottom. Does >> it have an initial velocity? Does it accelerate under the pull of >> gravity? Velocity means speed and direction. What happens when it hits >> bottom? >> >> Then add a 2nd grain. What happens if the 2 collide? >> >> What is your update rate (how often do you recompute the positions of >> all the grains)? What is the smallest increment of position change? >> >> I assume you will create a class for each type of sand grain. with >> relevant properties and methods. >> >> You will need a program that runs in a loop (probably with a sleep) to >> - update positions and velocities of each grain (by invoking class >> methods) >> - detect and manage collisions >> - display each grain (by invoking class methods) >> >> If you are using a graphics package I assume you will have a "canvas" on >> which you will draw some kind of object to represent a particular class >> of grain at the current x,y(,z?) coordinates of each grain. >> >> It is possible to change the base class of an object on-the-fly, so a >> lava drop could become a sand grain. >> >> That's all for now. Good coding! >> >> I don't want to copy the game >> >> Is there a Python version out there? >>> , I want to make my own to play around with Py(thon/game). >>> >> >> >> -- >> Bob Gailer >> 919-636-4239 >> Chapel Hill NC >> >> > > > -- > My Blog - Defenestration Coding > > http://defenestrationcoding.wordpress.com/ > -- My Blog - Defenestration Coding http://defenestrationcoding.wordpress.com/ From gollumgreg407366 at gmail.com Mon Feb 6 22:52:30 2012 From: gollumgreg407366 at gmail.com (Greg Nielsen) Date: Mon, 6 Feb 2012 16:52:30 -0500 Subject: [Tutor] Sandbox Game In-Reply-To: References: <4F2EE9A6.9040901@cfl.rr.com> <4F2F1A05.7050303@pearwood.info> <4F2FFA50.9010308@gmail.com> <4F30159C.60402@gmail.com> Message-ID: Nate, I myself am a newer programmer with most of my experience in the use of pygame, perhaps I could help point you in the right direction. First, there is a lot of cool stuff over at the main pygame website, and a lot of the users will post projects with images, general overviews, and a link to their main codebase / content. It might take some searching, but you could definitely find something similar to what you are working on there. While finding something similar to what you are working on would really help you out, something you might find even better is this book by Andy Harris http://www.amazon.com/Game-Programming-Line-Express-Learning/dp/0470068221/ref=sr_1_5?s=books&ie=UTF8&qid=1328564353&sr=1-5 It's an amazing resource that takes you from installing python to creating your own games and even a game engine. There is a good chance that your local library has a copy. If you are serious about learning game programming in python, this is what you need to read. Lastly, speaking from experience. Start small. Just like Bob said, start with just the absolute basics and slowly add to your program. Mr. Harris' book demonstrates this in Chapter 7 perfectly. So check out pygame's website and check out that book from your library. I promise it will help you get started. Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From defensoft at gmail.com Mon Feb 6 23:29:07 2012 From: defensoft at gmail.com (Nate Lastname) Date: Mon, 6 Feb 2012 17:29:07 -0500 Subject: [Tutor] Sandbox Game In-Reply-To: References: <4F2EE9A6.9040901@cfl.rr.com> <4F2F1A05.7050303@pearwood.info> <4F2FFA50.9010308@gmail.com> <4F30159C.60402@gmail.com> Message-ID: Thanks, Greg. I actually have two projects on the pygame website, and I already have a great book, too. But thank you very much :D -- My Blog - Defenestration Coding http://defenestrationcoding.wordpress.com/ From alan.gauld at btinternet.com Tue Feb 7 01:17:32 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 07 Feb 2012 00:17:32 +0000 Subject: [Tutor] what is the basic difference In-Reply-To: References: Message-ID: On 06/02/12 19:12, Debashish Saha wrote: > what is the basic difference between the commands > import pylab as * Are you sure you don't mean from pylab import * ??? The other form won't work because * is not a valid name in Python. You should ghet a syntax error. > import matplotlib.pyplot as plt This is just an abbreviation to save typing matplotlib.pyplot in front of every reference to the module names. > import numpy as np as above > import numpy as * again an error. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Tue Feb 7 01:50:19 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 7 Feb 2012 11:50:19 +1100 Subject: [Tutor] Sandbox Game In-Reply-To: References: <4F2EE9A6.9040901@cfl.rr.com> <4F2F1A05.7050303@pearwood.info> Message-ID: <20120207005019.GA28570@ando> On Mon, Feb 06, 2012 at 09:13:48AM -0500, Nate Lastname wrote: > Hello List, > > I am quite sorry for my attitude. I will look more thoroughly into the > search results. Thanks for the link to Epik. I had found this, but I > didn't realize that it was Python. I apologize once again, and thank you > for your help. I did give you a link to a sandbox game (powdertoy.co.uk) > as an example of what I wanted, but that must not have been delivered > properly. Thank you for the gracious apology, and welcome to the group! Don't worry about asking stupid questions, we don't mind them so long as you make an effort to solve them yourself first, and that you learn from them as you go. -- Steven From williamjstewart at rogers.com Tue Feb 7 01:54:57 2012 From: williamjstewart at rogers.com (William Stewart) Date: Mon, 6 Feb 2012 16:54:57 -0800 (PST) Subject: [Tutor] Question on how to do exponents In-Reply-To: <20120207005019.GA28570@ando> Message-ID: <1328576097.19791.YahooMailClassic@web88603.mail.bf1.yahoo.com> Hello everyone, I am making a calculator and I need to know how to make it do exponents and remainders How can I input this info in python? Any help would be appreciated Thanks --- On Mon, 2/6/12, Steven D'Aprano wrote: From: Steven D'Aprano Subject: Re: [Tutor] Sandbox Game To: "tutor" Date: Monday, February 6, 2012, 7:50 PM On Mon, Feb 06, 2012 at 09:13:48AM -0500, Nate Lastname wrote: > Hello List, > > I am quite sorry for my attitude.? I will look more thoroughly into the > search results.? Thanks for the link to Epik.? I had found this, but I > didn't realize that it was Python.? I apologize once again, and thank you > for your help.? I did give you a link to a sandbox game (powdertoy.co.uk) > as an example of what I wanted, but that must not have been delivered > properly. Thank you for the gracious apology, and welcome to the group! Don't worry about asking stupid questions, we don't mind them so long as you make an effort to solve them yourself first, and that you learn from them as you go. -- Steven _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From defensoft at gmail.com Tue Feb 7 02:01:16 2012 From: defensoft at gmail.com (Nate Lastname) Date: Mon, 6 Feb 2012 20:01:16 -0500 Subject: [Tutor] Question on how to do exponents In-Reply-To: <1328576097.19791.YahooMailClassic@web88603.mail.bf1.yahoo.com> References: <20120207005019.GA28570@ando> <1328576097.19791.YahooMailClassic@web88603.mail.bf1.yahoo.com> Message-ID: Exponents and remainder (modulus) are **(or ^) and % respectively. I.E.; d = a ** b (exponent) c = a % b (modulus) There you are! -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Feb 7 02:07:08 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 7 Feb 2012 12:07:08 +1100 Subject: [Tutor] Question on how to do exponents In-Reply-To: <1328576097.19791.YahooMailClassic@web88603.mail.bf1.yahoo.com> References: <20120207005019.GA28570@ando> <1328576097.19791.YahooMailClassic@web88603.mail.bf1.yahoo.com> Message-ID: <20120207010708.GB28570@ando> On Mon, Feb 06, 2012 at 04:54:57PM -0800, William Stewart wrote: > Hello everyone, I am making a calculator and I need to know how to make it do exponents and remainders > How can I input this info in python? > Any help would be appreciated You can do exponents either with the ** operator or the pow() function: py> 2**4 16 py> pow(3, 5) 243 The pow() function is especially useful for advanced mathematics where you want to perform exponents modulo some base: py> pow(3, 5, 2) 1 That is, it calculates the remainder when divided by 2 of 3**5 *without* needing to calculate 3**5 first. This is especially useful when the intermediate number could be huge: py> pow(1357924680, 2468013579, 1256711) 418453L To get the remainder, use the % operator or the divmod() function: py> 17 % 2 1 py> divmod(17, 2) (8, 1) Hope this helps. P.S. please don't hijack threads by replying to an existing message, as it could lead to some people not seeing your email. It is better to start a new thread by using "New Message", not with "Reply". -- Steven From gollumgreg407366 at gmail.com Tue Feb 7 02:17:05 2012 From: gollumgreg407366 at gmail.com (Greg Nielsen) Date: Mon, 6 Feb 2012 20:17:05 -0500 Subject: [Tutor] Class Nesting Message-ID: Hello List, My name is Greg, and while working on a project I've come across a rather interesting problem. I'm trying to create a rough model of a star cluster and all of the stars and planets contained within. Kind of a cool project; hopefully it should work a little like this. I create a Star Cluster object, which goes through a list of positions and decides if it should build a Star System there. If it does, it then creates a Star System object at that position which in turn calls upon and creates several Planet objects to reside inside of it. All in all, about 64 positions to check, on average 24 Star Systems, each with between 2 and 9 planets. So here is the problem, to create an object, you need to assign it to a variable, and you need to know what that variable is to call upon it later, so to have a object build a second object, it would need to somehow create a variable name, and you would somehow have to know what name it picked. Unless perhaps you had a Star Cluster list which had all of your created Star System objects, each with their own list of Planets which you could use list to call upon maybe.... I have a general grasp on the idea of nesting and calling upon objects which you don't know the name of, but this goes far beyond my level of understanding. Can anyone shed some light on how this would work, or perhaps point me in the right direction of some documentation on this? Thanks for the help, and I hope this is not too difficult of a question. Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue Feb 7 03:45:31 2012 From: d at davea.name (Dave Angel) Date: Mon, 06 Feb 2012 21:45:31 -0500 Subject: [Tutor] Class Nesting In-Reply-To: References: Message-ID: <4F30904B.8050703@davea.name> On 02/06/2012 08:17 PM, Greg Nielsen wrote: > Hello List, > > My name is Greg, and while working on a project I've come across a > rather interesting problem. I'm trying to create a rough model of a star > cluster and all of the stars and planets contained within. Kind of a cool > project; hopefully it should work a little like this. I create a Star > Cluster object, which goes through a list of positions and decides if it > should build a Star System there. If it does, it then creates a Star System > object at that position which in turn calls upon and creates several Planet > objects to reside inside of it. All in all, about 64 positions to check, on > average 24 Star Systems, each with between 2 and 9 planets. > So here is the problem, to create an object, you need to assign it to > a variable, and you need to know what that variable is to call upon it > later, so to have a object build a second object, it would need to somehow > create a variable name, and you would somehow have to know what name it > picked. Unless perhaps you had a Star Cluster list which had all of your > created Star System objects, each with their own list of Planets which you > could use list to call upon maybe.... > I have a general grasp on the idea of nesting and calling upon objects > which you don't know the name of, but this goes far beyond my level of > understanding. Can anyone shed some light on how this would work, or > perhaps point me in the right direction of some documentation on this? > Thanks for the help, and I hope this is not too difficult of a question. > > Greg > Since you talk of creating a StarCluster object, presumably you know how to make a class. So in the class definition, you can define attributes that each instance has. One of those attributes can be a list. So the list has a name, but not the individual items in the list. Generally, it's best to create an empty list attribute in the initializer of the class. Then whatever class method wants to create these items can simply append them to the list. At this point, you should write some code, and it'll either work, or you'll tell us what part of it you can't understand. -- DaveA From mjolewis at gmail.com Tue Feb 7 06:40:20 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Mon, 6 Feb 2012 21:40:20 -0800 Subject: [Tutor] Lists/raw_input Message-ID: I want to prompt the user only once to enter 5 numbers. I then want to create a list out of those five numbers. How can I do that? I know how to do it if I prompt the user 5 different times, but I only want to prompt the user once. Thanks. -- Michael -------------- next part -------------- An HTML attachment was scrubbed... URL: From walksloud at gmail.com Tue Feb 7 07:03:59 2012 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Mon, 6 Feb 2012 22:03:59 -0800 Subject: [Tutor] Lists/raw_input In-Reply-To: References: Message-ID: Hi Michael, I bet there is a better way (which I would like to see), but here is what I have come up with for my own uses. """ ints = [] u_in = False while u_in == False: try: u_input = raw_input('please enter 5 integers, space separated\n ') for n in u_input.split(): ints.append(int(n)) u_in = True except: print(' input error, try again') """ The while loop is set up in case your user inputs a float or string instead of just integers. You can also imagine putting checks in case you want exactly 5 integers, etc. Cheers, Andre On Feb 6, 2012, at 9:40 PM, Michael Lewis wrote: > I want to prompt the user only once to enter 5 numbers. I then want to create a list out of those five numbers. How can I do that? > > I know how to do it if I prompt the user 5 different times, but I only want to prompt the user once. > > Thanks. > > -- > Michael > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From cwitts at compuscan.co.za Tue Feb 7 07:08:00 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 07 Feb 2012 08:08:00 +0200 Subject: [Tutor] Lists/raw_input In-Reply-To: References: Message-ID: <4F30BFC0.7050700@compuscan.co.za> On 2012/02/07 07:40 AM, Michael Lewis wrote: > I want to prompt the user only once to enter 5 numbers. I then want to > create a list out of those five numbers. How can I do that? > > I know how to do it if I prompt the user 5 different times, but I only > want to prompt the user once. > > Thanks. > > -- > Michael > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor You can take your input from your user in one line seperated by something like a space and then split it after you capture it so for eg. user_input = raw_input('enter 5 numbers seperated by a space each: ') list_from_input = user_input.split() # Split by default splits on spaces, otherwise you need to specify the delimiter # Then you can validate the list to ensure all 5 are actually numbers, otherwise prompt the user to re-enter them Hope that help. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Feb 7 08:48:34 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 7 Feb 2012 18:48:34 +1100 Subject: [Tutor] Class Nesting In-Reply-To: References: Message-ID: <20120207074834.GA10945@ando> On Mon, Feb 06, 2012 at 08:17:05PM -0500, Greg Nielsen wrote: [...] > So here is the problem, to create an object, you need to assign it to > a variable, and you need to know what that variable is to call upon it > later, so to have a object build a second object, it would need to somehow > create a variable name, and you would somehow have to know what name it > picked. Unless perhaps you had a Star Cluster list which had all of your > created Star System objects, each with their own list of Planets which you > could use list to call upon maybe.... Yes, that's exactly the way to do it. Rather than assigning each object to a name: cluster1 = StarCluster() cluster2 = StarCluster() ... you can work with a list of clusters: clusters = [StarCluster(), StarCluster(), ...] You can then operate on then one at a time. Say you want to do something to the 3rd cluster. Remembering that Python starts counting positions at zero, you would write something like: clusters[2].name = "Local Cluster 12345" # give the cluster a name If your StarCluster objects are mutable (and if you don't know what that means, don't worry about it, by default all classes are mutable), you can grab a temporary reference to a cluster while working on it: for cluster in clusters: # work on each one sequentially if cluster.stars == []: print("Cluster %s has no stars." % cluster.name) Here I have assumed that each cluster is given a list of stars. Something like this: class StarCluster(object): def __init__(self): self.name = "no name yet" self.stars = [] def add_star(self, *args, **kw_args): self.stars.append(Star(*args, **kw_args)) Here I have given the StarCluster a method, "add_star", which takes an arbitrary set of arguments, passes them on to the Star class, and adds the resultant star to the list. class Star(object): def __init__(self, name="no name yet", kind="red giant", planets=None): if planets is None: planets = [] self.planets = planets self.name = name self.kind = kind sol = Star( "Sol", "yellow dwarf", ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'] # ha ha, Pluto can bite me ) I hope this helps, -- Steven From alan.gauld at btinternet.com Tue Feb 7 09:19:10 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 07 Feb 2012 08:19:10 +0000 Subject: [Tutor] Question on how to do exponents In-Reply-To: References: <20120207005019.GA28570@ando> <1328576097.19791.YahooMailClassic@web88603.mail.bf1.yahoo.com> Message-ID: On 07/02/12 01:01, Nate Lastname wrote: > Exponents ... are **(or ^) Not quite the ^ operator is a bitwise XOR... >>> 2^2 0 >>> 2^1 3 pow() is the other way to do exponents. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From Simeon.Tesfaye at eaudeparis.fr Tue Feb 7 09:34:35 2012 From: Simeon.Tesfaye at eaudeparis.fr (Simeon Tesfaye) Date: Tue, 07 Feb 2012 09:34:35 +0100 Subject: [Tutor] =?utf-8?q?R=C3=A9p=2E_=3A_Re=3A__Issue_with_a_shapefile_?= =?utf-8?q?=28ArcGIS=29_library_=28pyshp=29_=22unpack_requires_a_string_ar?= =?utf-8?q?gument_of_length_8=22?= In-Reply-To: References: <4F2C0F55020000470000394B@groupwise.eaudeparis.net> Message-ID: <4F30F02B0200004700003976@groupwise.eaudeparis.net> I just realized my first email was not very self explanatory, so let me start over. My system is Windows XP Professional, with Python 2.5, and the library I'm experiencing trouble with is pyshp, available (single version for all systems) here : http://code.google.com/p/pyshp/ Here is the correct error message I get (I removed my failed attempt at correcting the library, thanks for pointing that out Dave) : Traceback (most recent call last): "File "", line 1, in rsh=shreader.shapes() File "C:\Python25\shapefile.py", line 310, in shapes shapes.append(self.__shape()) File "C:\Python25\shapefile.py", line 222, in __shape (recNum, recLength) = unpack(">2i", f.read(8)) File "C:\Python25\lib\struct.py", line 87, in unpack return o.unpack(s) error: unpack requires a string argument of length 8" My code can be summarized as that "f=shapefile.Editor(shapefile="C:\Sampler\Shpfiles\ROUTE.shp") f.line(parts=[[coord[0],[0,0],[10,10]]]) f.record("i put my attributes here") f.save('ROUTE')" The error happens when I do "shreader=shapefile.Reader("ROUTE.shp") rsh=shreader.shapes()" afterwards. @ Alex : I didn't read instead of editing, it was a typo in my initial message, sorry but thanks anyway @ Dave : There is no binary data in my file that I'm aware of, if you mean in the shapefile, I reckon the library takes care of it, otherwise it would'nt work at all ? @ Nate : OK, but I do not understand where to put your correction ? f.read(8) seems to be required to have a length of 8, due to the format of the unpack ("<2i"), but even though I tried to replace it with f.read(8)[:8], it does not work. Sorry again if I seem kinda slow, I'm really a beginner in python coding. ST >>> ???????? ????????? 06/02/2012 07:14 >>> I am having a bit of trouble here with my code, which uses a shapefile library, named pyshp, to import, edit, and save GIS files within Python. So, I open up my shapefile (data is polylines, meaning, not points or polygons) "shapefile=shapefile.Reader("file.shp") shps=shapefile.shapes() shprec = shapefile.records() " Then I carry out some edits, and I save my file. If you wish to edit your shapefiles, you need to create object: shapefile.Editor() or shapefile.Write() - if you want create new file. and then save your edits... shapefile.Reader object/class for READING shapefile, not for edit/update -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Feb 7 11:41:52 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 07 Feb 2012 21:41:52 +1100 Subject: [Tutor] Backwards message program In-Reply-To: References: Message-ID: <4F30FFF0.5020200@pearwood.info> myles broomes wrote: > Im trying to code a program where the user enters a message and it is returned backwards. Here is my code so far: > > > message = input("Enter your message: ") > > backw = "" > counter = len(message) > while message != 0: > backw += message[counter-1] > counter -= 1 > print(backw) > input("\nPress enter to exit...") When you want to do something with each item in a sequence, such as each character in a string, you can do it directly: for char in message: print(char) prints the characters one at a time. Python has a built-in command to reverse strings. Actually, two ways: the hard way, and the easy way. The hard way is to pull the string apart into characters, reverse them, then assemble them back again into a string: chars = reversed(message) # Gives the characters of message in reverse order. new_message = ''.join(chars) Or written in one line: new_message = ''.join(reversed(message)) Not very hard at all, is it? And that's the hard way! Here's the easy way: using string slicing. new_message = message[::-1] I know that's not exactly readable, but slicing is a very powerful tool in Python and once you learn it, you'll never go back. Slices take one, two or three integer arguments. Experiment with these and see if you can understand what slicing does and what the three numbers represent: message = "NOBODY expects the Spanish Inquisition!" message[0] message[1] message[39] message[38] message[-1] message[-2] message[0:6] message[:6] message[19:38] message[19:-1] message [19:-2] message[::3] message[:30:3] message[5:30:3] Hint: the two and three argument form of slices is similar to the two and three argument form of the range() function. Python gives you many rich and powerful tools, there's no need to mess about with while loops and indexes into a string and nonsense like that if you don't need to. As the old saying goes, why bark yourself if you have a dog? -- Steven From steve at pearwood.info Tue Feb 7 12:15:28 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 07 Feb 2012 22:15:28 +1100 Subject: [Tutor] decimal precision in python In-Reply-To: <4F2FF46D.4050207@alchemy.com> References: <4F2FF46D.4050207@alchemy.com> Message-ID: <4F3107D0.6020200@pearwood.info> Steve Willoughby wrote: > On 06-Feb-12 07:25, Kapil Shukla wrote: >> i tried writing a small code to calculate option price using the >> binomial tree model. I compared my results with results of the same >> program in excel. There seems to be a minor difference due to decimal >> precision as excel is using 15 decimal precision and python (both 2.7 >> and 3.1) using 11. (at least that's what shown on shell) > > If you need lots of precision, you might consider using the decimal > class. It'll cost you speed vs. the native floating-point type but > won't cause you round-off errors. I'm afraid that's not correct. Decimal is still subject to rounding errors. >>> from decimal import Decimal >>> x = 1/Decimal(3) # one third, as close as a Decimal can give >>> x + x + x == 1 False The difference is that the rounding errors you get with Decimal are usually different to the ones you get with binary floats. For example: >>> y = 0.1 # one tenth, as close as a binary float can give >>> y+y + y+y + y+y + y+y + y+y == 1 False while the same calculation is exact with Decimal. The reason for the error is the same in both cases: in the first, 1/3 takes an infinite number of decimal digits, while in the second, 1/10 takes an infinite number of binary digits. So Decimal 1/3 is not *precisely* 1/3, and float 1/10 is not precisely 1/10 either. Binary floats can store exactly any fraction which can be written as a sum of powers of 1/2, e.g.: 0.40625 = 13/32 = 1/4 + 1/8 + 1/32 so can be stored exactly in a float Every other number is rounded. The same applies to Decimal: it can store exactly any fraction which can be written as a sum of powers of 1/10. The advantage of Decimal is that anything which can be stored as an exact float can also be stored as an exact Decimal, plus some numbers which can't be written as exact floats. But there are still plenty of numbers which can't be stored exactly as either. -- Steven From steve at pearwood.info Tue Feb 7 14:17:34 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 08 Feb 2012 00:17:34 +1100 Subject: [Tutor] decimal precision in python In-Reply-To: References: <4F2FF46D.4050207@alchemy.com> <4F3107D0.6020200@pearwood.info> Message-ID: <4F31246E.9030000@pearwood.info> Col, I think you wrote to me personally by accident, instead of to the Tutor list. Nothing you said seems to be private, so I've taken the liberty of answering back on the list. col speed wrote: > Just an idea - I'm not an expert by any means, just a dabbler, but: > many years ago, when I was looking at options(I assume you mean the > same as me as in puts etc.) > they were quoted as fractions. > Some fractions can't be quoted as exact decimals and some decimals as > binary, so fractions *may* be more exact. > I believe there is a fractions module, but it is quite easy to create > your own Rational class. Starting in Python 2.6, there is a fractions module in the standard library. Unlike float and Decimal, it is effectively infinite precision: >>> from fractions import Fraction >>> z = 1/Fraction(3) >>> z + z + z == 1 True This comes at a cost, of course. Unless you are very careful, you can end up with fractions like this: Fraction(2573485501354569, 18014398509481984) That is very close to 1/7, and in fact it is the exact fraction equal to the binary float closest to 1/7: >>> Fraction.from_float(1/7.0) Fraction(2573485501354569, 18014398509481984) So Fraction is not a panacea either. Unless you take care, you can easily end up using an unlimited amount of memory for an extremely precise number, when a much lower precision would be close enough -- or possibly even BETTER: >>> Fraction.from_float(1/7.0).limit_denominator(10) Fraction(1, 7) But yes, Fractions are a sadly under-appreciated tool for numeric calculations. -- Steven From steve at alchemy.com Tue Feb 7 15:25:20 2012 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 07 Feb 2012 06:25:20 -0800 Subject: [Tutor] decimal precision in python In-Reply-To: <4F3107D0.6020200@pearwood.info> References: <4F2FF46D.4050207@alchemy.com> <4F3107D0.6020200@pearwood.info> Message-ID: <4F313450.6060806@alchemy.com> On 07-Feb-12 03:15, Steven D'Aprano wrote: > Steve Willoughby wrote: >> If you need lots of precision, you might consider using the decimal >> class. It'll cost you speed vs. the native floating-point type but >> won't cause you round-off errors. > > I'm afraid that's not correct. Decimal is still subject to rounding errors. > > >>> from decimal import Decimal > >>> x = 1/Decimal(3) # one third, as close as a Decimal can give > >>> x + x + x == 1 > False Sorry, I guess I took it for granted that was understood. I was referring to round-off caused by binary representation of a number that by all appearances is a simple, rational, non-repeating decimal number expressed in base 10. In other words, when you're adding up financial figures, you'll get an accurate sum without "mysterious" rounding off, but of course certain fractions which don't have a straightforward way to represent as a decimal value, like 1/3, are going to be an issue. Good catch, though, it was better to point that out. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From tvssarma.omega9 at gmail.com Tue Feb 7 17:54:37 2012 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Tue, 7 Feb 2012 22:24:37 +0530 Subject: [Tutor] Question on how to do exponents In-Reply-To: References: <20120207005019.GA28570@ando> <1328576097.19791.YahooMailClassic@web88603.mail.bf1.yahoo.com> Message-ID: On 7 February 2012 13:49, Alan Gauld wrote: > On 07/02/12 01:01, Nate Lastname wrote: > >> Exponents ... are **(or ^) >> > > Not quite the ^ operator is a bitwise XOR... > > >>> 2^2 > 0 > >>> 2^1 > 3 > > pow() is the other way to do exponents. > > Is is better to use pow() against **? > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Sarma Tangirala, Class of 2012, Department of Information Science and Technology, College of Engineering Guindy - Anna University -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue Feb 7 18:00:44 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 7 Feb 2012 12:00:44 -0500 Subject: [Tutor] Backwards message program In-Reply-To: <4F30FFF0.5020200@pearwood.info> References: <4F30FFF0.5020200@pearwood.info> Message-ID: On Tue, Feb 7, 2012 at 5:41 AM, Steven D'Aprano wrote: > myles broomes wrote: >> >> Im trying to code a program where the user enters a message and it is >> returned backwards. Here is my code so far: >> ?message = input("Enter your message: ") >> ?backw = "" >> counter = len(message) >> while message != 0: >> ? ?backw += message[counter-1] >> ? ?counter -= 1 >> print(backw) >> input("\nPress enter to exit...") > > > When you want to do something with each item in a sequence, such as each > character in a string, you can do it directly: > > for char in message: > ? ?print(char) > > > prints the characters one at a time. > > Python has a built-in command to reverse strings. Actually, two ways: the > hard way, and the easy way. The hard way is to pull the string apart into > characters, reverse them, then assemble them back again into a string: > > > chars = reversed(message) ?# Gives the characters of message in reverse > order. > new_message = ''.join(chars) > > > Or written in one line: > > > new_message = ''.join(reversed(message)) > > > Not very hard at all, is it? And that's the hard way! Here's the easy way: > using string slicing. > > new_message = message[::-1] > > > I know that's not exactly readable, but slicing is a very powerful tool in > Python and once you learn it, you'll never go back. Slices take one, two or > three integer arguments. Experiment with these and see if you can understand > what slicing does and what the three numbers represent: > > > message = "NOBODY expects the Spanish Inquisition!" > > message[0] > message[1] > > message[39] > message[38] > > message[-1] > message[-2] > > message[0:6] > message[:6] > > message[19:38] > message[19:-1] > message [19:-2] > > message[::3] > message[:30:3] > message[5:30:3] > > > Hint: the two and three argument form of slices is similar to the two and > three argument form of the range() function. > > > Python gives you many rich and powerful tools, there's no need to mess about > with while loops and indexes into a string and nonsense like that if you > don't need to. As the old saying goes, why bark yourself if you have a dog? > > > > -- > Steven > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor While you should know about reverse, and understand slices, your program will work if you test for while counter != 0 instead of message. Message doesn't change message = input("Enter your message: ") backw = "" counter = len(message) #while message != 0: # not this while counter != 0: # this backw += message[counter-1] counter -= 1 print(backw) input("\nPress enter to exit...") -- Joel Goldstick From garland.binns at gmail.com Tue Feb 7 18:19:06 2012 From: garland.binns at gmail.com (Garland W. Binns) Date: Tue, 7 Feb 2012 11:19:06 -0600 Subject: [Tutor] Backspace Escape Sequence; \b Message-ID: Could someone please tell me a common or semi-frequent scenario in which a person would use a backspace escape sequence? Thanks, Garland -- Sent via Mobile -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Feb 7 18:41:12 2012 From: __peter__ at web.de (Peter Otten) Date: Tue, 07 Feb 2012 18:41:12 +0100 Subject: [Tutor] Backspace Escape Sequence; \b References: Message-ID: Garland W. Binns wrote: > Could someone please tell me a common or semi-frequent scenario in which a > person would use a backspace escape sequence? Does $ python -c 'print "this is b\bbo\bol\bld\bd"' | less qualify? If you are using (e. g.) Linux this technique is used to show some text in boldface when you type something like >>> help(str) in Python's interactive interpreter. From steve at pearwood.info Tue Feb 7 19:18:35 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 08 Feb 2012 05:18:35 +1100 Subject: [Tutor] Backspace Escape Sequence; \b In-Reply-To: References: Message-ID: <4F316AFB.7040803@pearwood.info> Peter Otten wrote: > Garland W. Binns wrote: > >> Could someone please tell me a common or semi-frequent scenario in which a >> person would use a backspace escape sequence? > > Does > > $ python -c 'print "this is b\bbo\bol\bld\bd"' | less > > qualify? If you are using (e. g.) Linux this technique is used to show some > text in boldface Gah, that has got to be the ugliest hack in the universe. I don't think that is guaranteed to work everywhere. less supports the \b trick, but the Python interactive interpreter doesn't support it directly. -- Steven From alan.gauld at btinternet.com Tue Feb 7 19:29:49 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 07 Feb 2012 18:29:49 +0000 Subject: [Tutor] Question on how to do exponents In-Reply-To: References: <20120207005019.GA28570@ando> <1328576097.19791.YahooMailClassic@web88603.mail.bf1.yahoo.com> Message-ID: On 07/02/12 16:54, Sarma Tangirala wrote: > Is is better to use pow() against **? I suspect ** will be faster since it doesn't have the function call overhead. But I haven't tried timing it. Feel free to do some tests and find out. Let us know how you get on! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Tue Feb 7 19:31:07 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 08 Feb 2012 05:31:07 +1100 Subject: [Tutor] Question on how to do exponents In-Reply-To: References: <20120207005019.GA28570@ando> <1328576097.19791.YahooMailClassic@web88603.mail.bf1.yahoo.com> Message-ID: <4F316DEB.3070001@pearwood.info> Sarma Tangirala wrote: > Is is better to use pow() against **? Advantages of ** - it is shorter to type x**y vs pow(x, y) - being an operator, it is slightly faster than calling a function - you can't monkey-patch it Disadvantages of ** - being an operator, you can't directly use it as a function-object - it can't take three arguments - hard to google for "**" - you can't monkey-patch it Advantages of pow() - it is a function, so you can pass it around as an object - three argument form - easy to call help(pow) to see documentation - easy to google for "pow" - can be monkey-patched Disadvantages of pow() - a tiny bit slower due to the function call - slightly longer to type - can be monkey-patched Weigh up the advantages and disadvantages of each, and make the call which is better for you. (My preference is to use the ** operator.) -- Steven From alan.gauld at btinternet.com Tue Feb 7 19:42:09 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 07 Feb 2012 18:42:09 +0000 Subject: [Tutor] Backspace Escape Sequence; \b In-Reply-To: References: Message-ID: On 07/02/12 17:19, Garland W. Binns wrote: > Could someone please tell me a common or semi-frequent scenario in which > a person would use a backspace escape sequence? Do you mean backspace specifically or do you really mean backslash? In other words are you looking for a use of literal backspaces in a string or are you looking at the use of escaped characters in general? backspace specifically is not commonly used but is sometimes handy for positioning the cursor in the middle of a line. eg raw_input("Area: acres\b\b\b\b\b\b\b\b") Should output the prompt line with the cursor positioned in the gap between Area: and acres. >>> raw_input("Area: acres\b\b\b\b\b\b\b\b") Area: 45 acres '45' >>> But in the general sense there are lots of scenarios where we use escaped characters. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From silideba at gmail.com Tue Feb 7 19:50:29 2012 From: silideba at gmail.com (Debashish Saha) Date: Wed, 8 Feb 2012 00:20:29 +0530 Subject: [Tutor] (no subject) Message-ID: for i in range(1, 8): print(i) if i==3: break else: print('The for loop is over') Output: 1 2 3 Question:but after breaking the for loop why the else command could not work? From silideba at gmail.com Tue Feb 7 19:52:32 2012 From: silideba at gmail.com (Debashish Saha) Date: Wed, 8 Feb 2012 00:22:32 +0530 Subject: [Tutor] confusion with else command Message-ID: for i in range(1, 8): print(i) if i==3: break else: print('The for loop is over') Output: 1 2 3 Question: but after breaking the for loop why the else loop could not work? From tvssarma.omega9 at gmail.com Tue Feb 7 19:57:02 2012 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Wed, 8 Feb 2012 00:27:02 +0530 Subject: [Tutor] Question on how to do exponents In-Reply-To: <4F316DEB.3070001@pearwood.info> References: <20120207005019.GA28570@ando> <1328576097.19791.YahooMailClassic@web88603.mail.bf1.yahoo.com> <4F316DEB.3070001@pearwood.info> Message-ID: On 8 February 2012 00:01, Steven D'Aprano wrote: > Sarma Tangirala wrote: > > Is is better to use pow() against **? >> > > > Advantages of ** > > - it is shorter to type x**y vs pow(x, y) > - being an operator, it is slightly faster than calling a function > - you can't monkey-patch it > > Disadvantages of ** > > - being an operator, you can't directly use it as a function-object > - it can't take three arguments > - hard to google for "**" > - you can't monkey-patch it > > Advantages of pow() > > - it is a function, so you can pass it around as an object > - three argument form > - easy to call help(pow) to see documentation > - easy to google for "pow" > - can be monkey-patched > > Disadvantages of pow() > > - a tiny bit slower due to the function call > - slightly longer to type > - can be monkey-patched > > > Weigh up the advantages and disadvantages of each, and make the call which > is better for you. > > (My preference is to use the ** operator.) > > A simple "function call" argument would have done! :D Thanks for the survey! Anyway, I was wondering about this, if internally pow() actually uses **. :P > > > -- > Steven > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Sarma Tangirala, Class of 2012, Department of Information Science and Technology, College of Engineering Guindy - Anna University -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue Feb 7 19:58:03 2012 From: d at davea.name (Dave Angel) Date: Tue, 07 Feb 2012 13:58:03 -0500 Subject: [Tutor] confusion with else command In-Reply-To: References: Message-ID: <4F31743B.10505@davea.name> On 02/07/2012 01:52 PM, Debashish Saha wrote: > for i in range(1, 8): > print(i) > if i==3: > break > else: > print('The for loop is over') > > > Output: > 1 > 2 > 3 > > Question: > > but after breaking the for loop why the else loop could not work? It works fine. The else clause of a for loop executes only if the loop completes without breaking out. If the language designers had wanted it to always execute, why have an extra keyword? -- DaveA From __peter__ at web.de Tue Feb 7 20:08:16 2012 From: __peter__ at web.de (Peter Otten) Date: Tue, 07 Feb 2012 20:08:16 +0100 Subject: [Tutor] confusion with else command References: Message-ID: Debashish Saha wrote: > for i in range(1, 8): > print(i) > if i==3: > break > else: > print('The for loop is over') > Output: > 1 > 2 > 3 > > Question: > > but after breaking the for loop why the else loop could not work? The else suite is not invoked because that's the way Guido intended it ;) It was designed for sitiuations like the following: for beast in animals: if is_it_a_cat(beast): print("There's a cat among those animals") break else: print("Sorry, there aren't any cats") print("I've been looking for a cat") # you don't need an else for that i. e. it's only invoked if the loop terminates normally (no break, and of course no return or exception). From hugo.yoshi at gmail.com Tue Feb 7 20:07:30 2012 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 7 Feb 2012 20:07:30 +0100 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On Tue, Feb 7, 2012 at 7:50 PM, Debashish Saha wrote: > for i in range(1, 8): > ? ?print(i) > ? ?if i==3: > ? ? ? ?break > else: > ? ?print('The for loop is over') > > > ?Output: > 1 > 2 > 3 > > Question:but after breaking the for loop why the else command could not work? > because the else statement was designed to be that way: http://docs.python.org/reference/compound_stmts.html#for quoting the relevant part: "When the items are exhausted (which is immediately when the sequence is empty), the suite in the else clause, if present, is executed, and the loop terminates. A break statement executed in the first suite terminates the loop without executing the else clause?s suite." in short, the else clause only executes if you do *not* break out of the loop. HTH, Hugo From d at davea.name Tue Feb 7 20:09:12 2012 From: d at davea.name (Dave Angel) Date: Tue, 07 Feb 2012 14:09:12 -0500 Subject: [Tutor] Question on how to do exponents In-Reply-To: References: <20120207005019.GA28570@ando> <1328576097.19791.YahooMailClassic@web88603.mail.bf1.yahoo.com> <4F316DEB.3070001@pearwood.info> Message-ID: <4F3176D8.9050102@davea.name> On 02/07/2012 01:57 PM, Sarma Tangirala wrote: > On 8 February 2012 00:01, Steven D'Aprano wrote: > >> Sarma Tangirala wrote: >> >> Is is better to use pow() against **? >> >> Advantages of ** >> >> - it is shorter to type x**y vs pow(x, y) >> - being an operator, it is slightly faster than calling a function >> - you can't monkey-patch it >> >> Disadvantages of ** >> >> - being an operator, you can't directly use it as a function-object >> - it can't take three arguments >> - hard to google for "**" >> - you can't monkey-patch it >> >> Advantages of pow() >> >> - it is a function, so you can pass it around as an object >> - three argument form >> - easy to call help(pow) to see documentation >> - easy to google for "pow" >> - can be monkey-patched >> >> Disadvantages of pow() >> >> - a tiny bit slower due to the function call >> - slightly longer to type >> - can be monkey-patched >> >> >> Weigh up the advantages and disadvantages of each, and make the call which >> is better for you. >> >> (My preference is to use the ** operator.) >> >> > A simple "function call" argument would have done! :D Thanks for the survey! > > Anyway, I was wondering about this, if internally pow() actually uses **. :P > > I have no idea, but I'd assume so, unless there's a 3rd argument. At that point, the algorithm must change drastically. -- DaveA From malaclypse2 at gmail.com Tue Feb 7 20:09:34 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 7 Feb 2012 14:09:34 -0500 Subject: [Tutor] For/Else loops Message-ID: On Tue, Feb 7, 2012 at 1:50 PM, Debashish Saha wrote: > for i in range(1, 8): > ? ?print(i) > ? ?if i==3: > ? ? ? ?break > else: > ? ?print('The for loop is over') > > > ?Output: > 1 > 2 > 3 > > Question:but after breaking the for loop why the else command could not work? Because that's the way a for/else statement works. The else suite is only run if you do not break out of the loop. See the docs here: http://docs.python.org/reference/compound_stmts.html#the-for-statement Jerry From __peter__ at web.de Tue Feb 7 20:13:55 2012 From: __peter__ at web.de (Peter Otten) Date: Tue, 07 Feb 2012 20:13:55 +0100 Subject: [Tutor] Backspace Escape Sequence; \b References: <4F316AFB.7040803@pearwood.info> Message-ID: Steven D'Aprano wrote: > Peter Otten wrote: >> Garland W. Binns wrote: >> >>> Could someone please tell me a common or semi-frequent scenario in which >>> a person would use a backspace escape sequence? >> >> Does >> >> $ python -c 'print "this is b\bbo\bol\bld\bd"' | less >> >> qualify? If you are using (e. g.) Linux this technique is used to show >> some text in boldface > > Gah, that has got to be the ugliest hack in the universe. > > I don't think that is guaranteed to work everywhere. less supports the \b > trick, but the Python interactive interpreter doesn't support it directly. Well, the beauty in that hack is that output devices that don't understand it usually interpret "\b" as backspace and thus still produce a readable fallback. From bgailer at gmail.com Tue Feb 7 20:20:27 2012 From: bgailer at gmail.com (bob gailer) Date: Tue, 07 Feb 2012 14:20:27 -0500 Subject: [Tutor] Question on how to do exponents In-Reply-To: References: <20120207005019.GA28570@ando> <1328576097.19791.YahooMailClassic@web88603.mail.bf1.yahoo.com> <4F316DEB.3070001@pearwood.info> Message-ID: <4F31797B.3000000@gmail.com> On 2/7/2012 1:57 PM, Sarma Tangirala wrote: > > Anyway, I was wondering about this, if internally pow() actually uses > **. :P > >>> from dis import dis >>> dis(lambda a,b:a**b) 1 0 LOAD_FAST 0 (a) 3 LOAD_FAST 1 (b) 6 BINARY_POWER 7 RETURN_VALUE >>> dis(lambda a,b:pow(a,b)) 1 0 LOAD_GLOBAL 0 (pow) 3 LOAD_FAST 0 (a) 6 LOAD_FAST 1 (b) 9 CALL_FUNCTION 2 12 RETURN_VALUE Now you know, and you know how to find out! To delve any deeper you'd have to inspect the c source for pow. I'd assume it uses the c exponent operator -- Bob Gailer 919-636-4239 Chapel Hill NC From bgailer at gmail.com Tue Feb 7 20:24:03 2012 From: bgailer at gmail.com (bob gailer) Date: Tue, 07 Feb 2012 14:24:03 -0500 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <4F317A53.9060003@gmail.com> Do Not Use (no subject) as a subject! Read the manual before asking questions like this. If you do not understand the documentation tell us what you do not understand. On 2/7/2012 1:50 PM, Debashish Saha wrote: > for i in range(1, 8): > print(i) > if i==3: > break > else: > print('The for loop is over') > > > Output: > 1 > 2 > 3 > > Question:but after breaking the for loop why the else command could not work? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 919-636-4239 Chapel Hill NC From matt.gregory at oregonstate.edu Tue Feb 7 20:32:28 2012 From: matt.gregory at oregonstate.edu (Gregory, Matthew) Date: Tue, 7 Feb 2012 11:32:28 -0800 Subject: [Tutor] dictionary of methods calling syntax Message-ID: <1D673F86DDA00841A1216F04D1CE70D646FF7D86A7@EXCH2.nws.oregonstate.edu> Hi list, I'm trying to understand how to use a class-level dictionary to act as a switch for class methods. In the contrived example below, I have the statistic name as the key and the class method as the value. class Statistics(object): STAT = { 'MEAN': get_mean, 'SUM': get_sum, } def __init__(self, a, b): self.a = a self.b = b def get_mean(self): return (self.a + self.b) / 2.0 def get_sum(self): return (self.a + self.b) def get_stat(self, stat): f = self.STAT[stat.upper()] return f(self) if __name__ == '__main__': spam = Statistics(4, 3) print spam.get_stat('mean') print spam.get_stat('sum') When I try to run this, I get: NameError: name 'get_mean' is not defined If I move the STAT dictionary to the bottom of the class, it works fine. I understand why I get an error, i.e. when the dictionary is created get_mean hasn't yet been defined, but I'm wondering if there is a better common practice for doing this type of lookup. My web searches didn't come up with anything too applicable. thanks, matt From mjolewis at gmail.com Tue Feb 7 20:45:00 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Tue, 7 Feb 2012 11:45:00 -0800 Subject: [Tutor] Tutor Digest, Vol 96, Issue 26 In-Reply-To: References: Message-ID: On Tue, Feb 7, 2012 at 10:57 AM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Backspace Escape Sequence; \b (Peter Otten) > 2. Re: Backspace Escape Sequence; \b (Steven D'Aprano) > 3. Re: Question on how to do exponents (Alan Gauld) > 4. Re: Question on how to do exponents (Steven D'Aprano) > 5. Re: Backspace Escape Sequence; \b (Alan Gauld) > 6. (no subject) (Debashish Saha) > 7. confusion with else command (Debashish Saha) > 8. Re: Question on how to do exponents (Sarma Tangirala) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Tue, 07 Feb 2012 18:41:12 +0100 > From: Peter Otten <__peter__ at web.de> > To: tutor at python.org > Subject: Re: [Tutor] Backspace Escape Sequence; \b > Message-ID: > Content-Type: text/plain; charset="ISO-8859-1" > > Garland W. Binns wrote: > > > Could someone please tell me a common or semi-frequent scenario in which > a > > person would use a backspace escape sequence? > > Does > > $ python -c 'print "this is b\bbo\bol\bld\bd"' | less > > qualify? If you are using (e. g.) Linux this technique is used to show some > text in boldface when you type something like > > >>> help(str) > > in Python's interactive interpreter. > > > > > ------------------------------ > > Message: 2 > Date: Wed, 08 Feb 2012 05:18:35 +1100 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] Backspace Escape Sequence; \b > Message-ID: <4F316AFB.7040803 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Peter Otten wrote: > > Garland W. Binns wrote: > > > >> Could someone please tell me a common or semi-frequent scenario in > which a > >> person would use a backspace escape sequence? > > > > Does > > > > $ python -c 'print "this is b\bbo\bol\bld\bd"' | less > > > > qualify? If you are using (e. g.) Linux this technique is used to show > some > > text in boldface > > Gah, that has got to be the ugliest hack in the universe. > > I don't think that is guaranteed to work everywhere. less supports the \b > trick, but the Python interactive interpreter doesn't support it directly. > > > > -- > Steven > > > ------------------------------ > > Message: 3 > Date: Tue, 07 Feb 2012 18:29:49 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Question on how to do exponents > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 07/02/12 16:54, Sarma Tangirala wrote: > > > Is is better to use pow() against **? > > I suspect ** will be faster since it doesn't have the function > call overhead. > > But I haven't tried timing it. Feel free to do some tests and find out. > Let us know how you get on! > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > ------------------------------ > > Message: 4 > Date: Wed, 08 Feb 2012 05:31:07 +1100 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] Question on how to do exponents > Message-ID: <4F316DEB.3070001 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Sarma Tangirala wrote: > > > Is is better to use pow() against **? > > > Advantages of ** > > - it is shorter to type x**y vs pow(x, y) > - being an operator, it is slightly faster than calling a function > - you can't monkey-patch it > > Disadvantages of ** > > - being an operator, you can't directly use it as a function-object > - it can't take three arguments > - hard to google for "**" > - you can't monkey-patch it > > Advantages of pow() > > - it is a function, so you can pass it around as an object > - three argument form > - easy to call help(pow) to see documentation > - easy to google for "pow" > - can be monkey-patched > > Disadvantages of pow() > > - a tiny bit slower due to the function call > - slightly longer to type > - can be monkey-patched > > > Weigh up the advantages and disadvantages of each, and make the call which > is > better for you. > > (My preference is to use the ** operator.) > > > > -- > Steven > > > ------------------------------ > > Message: 5 > Date: Tue, 07 Feb 2012 18:42:09 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Backspace Escape Sequence; \b > Message-ID: > Content-Type: text/plain; charset=UTF-8; format=flowed > > On 07/02/12 17:19, Garland W. Binns wrote: > > Could someone please tell me a common or semi-frequent scenario in which > > a person would use a backspace escape sequence? > > Do you mean backspace specifically or do you really mean backslash? > > In other words are you looking for a use of literal backspaces in a > string or are you looking at the use of escaped characters in general? > > backspace specifically is not commonly used but is sometimes handy for > positioning the cursor in the middle of a line. > eg > > raw_input("Area: acres\b\b\b\b\b\b\b\b") > > Should output the prompt line with the cursor positioned in the gap > between Area: and acres. > > > >>> raw_input("Area: acres\b\b\b\b\b\b\b\b") > Area: 45 acres > '45' > >>> > > But in the general sense there are lots of scenarios where we use > escaped characters. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > ------------------------------ > > Message: 6 > Date: Wed, 8 Feb 2012 00:20:29 +0530 > From: Debashish Saha > To: tutor at python.org > Subject: [Tutor] (no subject) > Message-ID: > > > Content-Type: text/plain; charset=ISO-8859-1 > > for i in range(1, 8): > print(i) > if i==3: > break > else: > print('The for loop is over') > > > Output: > 1 > 2 > 3 > > Question:but after breaking the for loop why the else command could not > work? > > > ------------------------------ > > Message: 7 > Date: Wed, 8 Feb 2012 00:22:32 +0530 > From: Debashish Saha > To: tutor at python.org > Subject: [Tutor] confusion with else command > Message-ID: > > > Content-Type: text/plain; charset=ISO-8859-1 > > for i in range(1, 8): > print(i) > if i==3: > break > else: > print('The for loop is over') > > > Output: > 1 > 2 > 3 > > Question: > > but after breaking the for loop why the else loop could not work? > > > ------------------------------ > > Message: 8 > Date: Wed, 8 Feb 2012 00:27:02 +0530 > From: Sarma Tangirala > To: "Steven D'Aprano" > Cc: tutor at python.org > Subject: Re: [Tutor] Question on how to do exponents > Message-ID: > > > Content-Type: text/plain; charset="iso-8859-1" > > On 8 February 2012 00:01, Steven D'Aprano wrote: > > > Sarma Tangirala wrote: > > > > Is is better to use pow() against **? > >> > > > > > > Advantages of ** > > > > - it is shorter to type x**y vs pow(x, y) > > - being an operator, it is slightly faster than calling a function > > - you can't monkey-patch it > > > > Disadvantages of ** > > > > - being an operator, you can't directly use it as a function-object > > - it can't take three arguments > > - hard to google for "**" > > - you can't monkey-patch it > > > > Advantages of pow() > > > > - it is a function, so you can pass it around as an object > > - three argument form > > - easy to call help(pow) to see documentation > > - easy to google for "pow" > > - can be monkey-patched > > > > Disadvantages of pow() > > > > - a tiny bit slower due to the function call > > - slightly longer to type > > - can be monkey-patched > > > > > > Weigh up the advantages and disadvantages of each, and make the call > which > > is better for you. > > > > (My preference is to use the ** operator.) > > > > > A simple "function call" argument would have done! :D Thanks for the > survey! > > Anyway, I was wondering about this, if internally pow() actually uses **. > :P > > > > > > > > -- > > Steven > > > > ______________________________**_________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/**mailman/listinfo/tutor< > http://mail.python.org/mailman/listinfo/tutor> > > > > > > -- > Sarma Tangirala, > Class of 2012, > Department of Information Science and Technology, > College of Engineering Guindy - Anna University > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20120208/1c12a5c9/attachment.html > > > > Message: 7 Date: Wed, 8 Feb 2012 00:22:32 +0530 From: Debashish Saha To: tutor at python.org Subject: [Tutor] confusion with else command Message-ID: Content-Type: text/plain; charset=ISO-8859-1 for i in range(1, 8): print(i) if i==3: break else: print('The for loop is over') Output: 1 2 3 Question: but after breaking the for loop why the else loop could not work? The else statement is only executed if the if statement is never true. Each time i iterates in your for loop, the if statement is checked, if the if statement is not true, your for loop continues until it either reaches the end of the range specified in the for loop or until the loop breaks. In your case, the loop breaks once i is set to 3. If you DO want to print the string 'the for loop is over', you should do the following. for i in range(1, 8): print(i) print('The for loop is over') You'll notice that you don't need the if/else statement. Your output here will print i for each iteration until the end of the range and then break out of the for loop and print 'The for loop is over'. > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 96, Issue 26 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue Feb 7 21:20:34 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 7 Feb 2012 15:20:34 -0500 Subject: [Tutor] dictionary of methods calling syntax In-Reply-To: <1D673F86DDA00841A1216F04D1CE70D646FF7D86A7@EXCH2.nws.oregonstate.edu> References: <1D673F86DDA00841A1216F04D1CE70D646FF7D86A7@EXCH2.nws.oregonstate.edu> Message-ID: On Tue, Feb 7, 2012 at 2:32 PM, Gregory, Matthew wrote: > Hi list, > > I'm trying to understand how to use a class-level dictionary to act as a switch for class methods. ?In the contrived example below, I have the statistic name as the key and the class method as the value. > > class Statistics(object): > ? ?STAT = { > ? ? ? ?'MEAN': get_mean, > ? ? ? ?'SUM': get_sum, > ? ?} > ? ?def __init__(self, a, b): > ? ? ? ?self.a = a > ? ? ? ?self.b = b > ? ?def get_mean(self): > ? ? ? ?return (self.a + self.b) / 2.0 > ? ?def get_sum(self): > ? ? ? ?return (self.a + self.b) > ? ?def get_stat(self, stat): > ? ? ? ?f = self.STAT[stat.upper()] > ? ? ? ?return f(self) > > if __name__ == '__main__': > ? ?spam = Statistics(4, 3) > ? ?print spam.get_stat('mean') > ? ?print spam.get_stat('sum') > > When I try to run this, I get: > > ?NameError: name 'get_mean' is not defined > > If I move the STAT dictionary to the bottom of the class, it works fine. ?I understand why I get an error, i.e. when the dictionary is created get_mean hasn't yet been defined, but I'm wondering if there is a better common practice for doing this type of lookup. ?My web searches didn't come up with anything too applicable. > > thanks, matt > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor You might want to read through this: http://stackoverflow.com/questions/5213166/python-forward-declaration-of-functions-inside-classes Specifically from an answer: "First, in class B, the function foo() is called before being declared. A does not have this problem because foo() is only called when the class is instantiated--after the function foo is defined." So, I think you could move your STAT dictionary definition into the __init__ method so that is doesn't actually run until you create an instance of your class. That being said, I'm not sure that is more 'pythonic' than moving it to the bottom of the class definition -- Joel Goldstick From alan.gauld at btinternet.com Wed Feb 8 00:51:30 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 07 Feb 2012 23:51:30 +0000 Subject: [Tutor] dictionary of methods calling syntax In-Reply-To: <1D673F86DDA00841A1216F04D1CE70D646FF7D86A7@EXCH2.nws.oregonstate.edu> References: <1D673F86DDA00841A1216F04D1CE70D646FF7D86A7@EXCH2.nws.oregonstate.edu> Message-ID: On 07/02/12 19:32, Gregory, Matthew wrote: > class Statistics(object): > STAT = { > 'MEAN': get_mean, > 'SUM': get_sum, > } ... > > if __name__ == '__main__': > spam = Statistics(4, 3) > print spam.get_stat('mean') > print spam.get_stat('sum') Since a class is effectively a disguised dictionary I'm not sure why you want to do this? If you just want to access the method by name then why not just call getattr(spam,'get_mean')? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Feb 8 00:56:04 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 07 Feb 2012 23:56:04 +0000 Subject: [Tutor] Tutor Digest, Vol 96, Issue 26 In-Reply-To: References: Message-ID: On 07/02/12 19:45, Michael Lewis wrote: As the instructions in the message you posted say... > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." And also please delete all the irrelevant stuff, it's almost impossible to spot the new material amongst all the other messages. Also it is inconsiderate to those who pay for their mail by the byte. -- Alan G Moderator. From mjolewis at gmail.com Wed Feb 8 06:56:41 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Tue, 7 Feb 2012 21:56:41 -0800 Subject: [Tutor] Character Buffer Object Error Message-ID: I want to find all digits in a string and then increment those digits by 1 and then return the same string with the incremented digits. I've tried the following code, but I am getting the following error. How do I do this properly? def AlterInput(user_input): print user_input new_output = '' for index, char in enumerate(user_input): if char.isdigit(): new_char = int(char) new_char += 1 new_output = ' '.join(user_input) new_output.replace(char, new_char) print new_output def GetUserInput(): '''Get a string from the user and pass it''' user_input = '''I got 432 when I counted, but Jim got 433 which is a lot for only 6 cats, or were there 12 cats?''' AlterInput(user_input.split()) Traceback (most recent call last): File "C:/Python27/Homework/Homework 4_1.py", line 25, in GetUserInput() File "C:/Python27/Homework/Homework 4_1.py", line 23, in GetUserInput AlterInput(user_input.split()) File "C:/Python27/Homework/Homework 4_1.py", line 15, in AlterInput new_output.replace(char, new_char) TypeError: expected a character buffer object Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Wed Feb 8 07:38:13 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Wed, 08 Feb 2012 08:38:13 +0200 Subject: [Tutor] Character Buffer Object Error In-Reply-To: References: Message-ID: <4F321855.9050402@compuscan.co.za> On 2012/02/08 07:56 AM, Michael Lewis wrote: > I want to find all digits in a string and then increment those digits > by 1 and then return the same string with the incremented digits. > > I've tried the following code, but I am getting the following error. > How do I do this properly? > > def AlterInput(user_input): > print user_input > new_output = '' > for index, char in enumerate(user_input): > if char.isdigit(): > new_char = int(char) > new_char += 1 > new_output = ' '.join(user_input) > new_output.replace(char, new_char) > print new_output > > def GetUserInput(): > '''Get a string from the user and pass it''' > user_input = '''I got 432 when I counted, but Jim got 433 which > is a lot for only 6 cats, or were there 12 cats?''' > AlterInput(user_input.split()) > > > Traceback (most recent call last): > File "C:/Python27/Homework/Homework 4_1.py", line 25, in > GetUserInput() > File "C:/Python27/Homework/Homework 4_1.py", line 23, in GetUserInput > AlterInput(user_input.split()) > File "C:/Python27/Homework/Homework 4_1.py", line 15, in AlterInput > new_output.replace(char, new_char) > TypeError: expected a character buffer object > > Thanks. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor new_char is of type int and not type str, so cast it back to a string before using it in your call to .replace as it expects both arguments to be strings. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From pasokan at talentsprint.com Wed Feb 8 07:51:31 2012 From: pasokan at talentsprint.com (Asokan Pichai) Date: Wed, 8 Feb 2012 12:21:31 +0530 Subject: [Tutor] Character Buffer Object Error In-Reply-To: References: Message-ID: Dear Michael Overall I see a few problems. 0. Functions should return values. Not print them 1. Why use enumerate? The code is not using the index anyway 2. The following line appears wrong. new_output = ' '.join(user_input) 3. This line has a very buggy possibility. new_output.replace(char, new_char) Let us say you have 234. First time you will replace 2 with 3, getting 334. And then you will replace the first 3 with 4 getting 434 and finally end up with 534. Of course due to other coding errors this does not come to pass. But your basic idea of using str.replace() is prone to this problem. 4. How are you supposed to treat 9? Anyway back to your problem: > I want to find all digits in a string and then increment those digits by 1 > and then return the same string with the incremented digits. Pseudocode ------------------ Initialise and outstring (empty) Read the instring character by character if the current character is not a digit append it to outstring else append the transform(current char) to outstring If you can organize your code like this it may be easier HTH Regards Asokan Pichai From alan.gauld at btinternet.com Wed Feb 8 10:12:06 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 08 Feb 2012 09:12:06 +0000 Subject: [Tutor] Character Buffer Object Error In-Reply-To: References: Message-ID: On 08/02/12 05:56, Michael Lewis wrote: > I've tried the following code, but I am getting the following error. How > do I do this properly? Christian answered the reason for the error. Here are some other comments... > def AlterInput(user_input): > print user_input > new_output = '' make this a list not a string > for index, char in enumerate(user_input): you don;t need index or enumerate just a simple for loop. > if char.isdigit(): > new_char = int(char) > new_char += 1 How will you handle 9? Insert 10 or lose the 1 (or the zero?) Your choice... I'll assume you insert 10 > new_output = ' '.join(user_input) I gave no idea what this is for, why insert spaces? Instead append new_char as a str to the list new_output.append(str(new_char)) This needs to be outside the if statement because you want to add all the chars. You will need to play with the assignments to make that work but it should be a lot simpler... At the very end join the list back to a string: return ''.join(new_output) > new_output.replace(char, new_char) You don't need this with a list > print new_output Best to keep print statements outside the function and just return the value > AlterInput(user_input.split()) You don't need to split, just pass in the users string. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jamie at kontrol.kode5.net Wed Feb 8 14:24:02 2012 From: jamie at kontrol.kode5.net (Jamie Paul Griffin) Date: Wed, 8 Feb 2012 13:24:02 +0000 Subject: [Tutor] python editor In-Reply-To: References: <4F300B36.3010303@gmail.com> Message-ID: <20120208132402.GB11738@kontrol.kode5.net> On Mon, Feb 06, 2012 at 06:11:13PM +0000, Alan Gauld wrote: > On 06/02/12 17:17, bob gailer wrote: > >On 2/6/2012 10:25 AM, Kapil Shukla wrote: > > > >>Please also suggest a free editor for python which can at least repeat > >>previous command with a key stroke > > That depends on the editor's mode of operation. > In an editor like vi (elvis, vim etc) there is a repeat key (the period) > that repeats most things because most things are a "command" - even > inserting text. but in a so called modeless editor (most modern > ones) > repeat will be restricted to things that are recognised as atomic > operations, like search/replace, change case etc. And some of those > will only be valid when text is selected (so not really modeless!). > > Other editors like emacs allow you to specify how often an action is > repeated. So esc-16 n will insert 16 n's for example. > > You would need to be more specific in terms of what you want in a > repeat operation. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > !DSPAM:4f3018592251995719914! > > My personal choices are nvi for command line editor and TextMate for GUI on Mac OS X. I don't use Windows systems so haven't a clue what's on offer for that platform. I learned nvi just because it's the default editor installed on NetBSD base system which is my primary computing platform. There's just so many editors now it's difficult to know what will suit you best. It would mostly come down to the environment you are most comfortable working in; I spend 90% of my time in a UNIX shell so the command line editors suit me better. Jamie From krush1954 at yahoo.com Wed Feb 8 14:40:27 2012 From: krush1954 at yahoo.com (ken brockman) Date: Wed, 8 Feb 2012 05:40:27 -0800 (PST) Subject: [Tutor] general basic question Message-ID: <1328708427.79664.YahooMailNeo@web39306.mail.mud.yahoo.com> Hello all: I have a general and very basic question if I may. I am in the process of?attempting?to write my first python app. I wanted to collect information and save it to lists and dictionaries. My question is, is it possible to save said lists and dictionaries in the program proper, or do i need to save the information to files on the hard drive. I apologize for the simplistic nature of my query. I have been reading various python books on and off for well over a month and I have to admit i am having a hard time ingesting the concepts. I have been?googling?and perusing articles and books but i can't grasp more then the most basic of concepts of what i'v gone over. I'm not looking for any thing more then a yes or no, I plan on beating my head against python until it starts to sink in or it kills me. Any help would be greatly appreciated. thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Wed Feb 8 14:54:55 2012 From: wprins at gmail.com (Walter Prins) Date: Wed, 8 Feb 2012 13:54:55 +0000 Subject: [Tutor] general basic question In-Reply-To: <1328708427.79664.YahooMailNeo@web39306.mail.mud.yahoo.com> References: <1328708427.79664.YahooMailNeo@web39306.mail.mud.yahoo.com> Message-ID: Hi Ken, Welcome to Python and to programming in general. On 8 February 2012 13:40, ken brockman wrote: > Hello all: > I have a general and very basic question if I may. I am in the process > of?attempting?to write my first python app. I wanted to collect information > and save it to lists and dictionaries. My question is, is it possible to > save said lists and dictionaries in the program proper, or do i need to save > the information to files on the hard drive. You would save the information in files external and seperate to the source code of your program. Note however that you can in fact directly serialize or persist (fancy object oriented terms that basically means "to save to permanent storage, e.g. disk") Python objects very easily with Python standard functionality, referred to in Python terms as "pickling". See the "pickle" module for more information: http://docs.python.org/library/pickle.html Note that it is more common for applications to use a database for data storage, such as SQLite, Postgres, MySQL, SQL Server etc etc, rather than simple pickling, but for simple cases it (or even simple text files) might suffice. It all depends on your requirements... ;) Regards Walter From bgailer at gmail.com Wed Feb 8 15:04:36 2012 From: bgailer at gmail.com (bob gailer) Date: Wed, 08 Feb 2012 09:04:36 -0500 Subject: [Tutor] Character Buffer Object Error In-Reply-To: References: Message-ID: <4F3280F4.1040709@gmail.com> On 2/8/2012 12:56 AM, Michael Lewis wrote: > I want to find all digits in a string and then increment those digits > by 1 and then return the same string with the incremented digits. [snip] You got lots of good advice from others and some not-so-good advice. Michael said: 2. The following line appears wrong. new_output = ' '.join(user_input) He did not say why! I add: Master the art of "Desk Checking". Take pencil & paper. Write down the input and output of each statement as though you were the computer. Also learn to read the & understand the Python Manuals: str.replace(old, new[, count]) Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. Notice "return a copy". It does NOT say that this will convert old in place. No one else caught this problem! Since this is homework we we probably should not be offering alternative solutions. However I can't resist offering the one-line solution: ''.join(str(int(x)+1) if x.isdigit() else x for x in 'user_input) -- Bob Gailer 919-636-4239 Chapel Hill NC From krush1954 at yahoo.com Wed Feb 8 15:17:15 2012 From: krush1954 at yahoo.com (ken brockman) Date: Wed, 8 Feb 2012 06:17:15 -0800 (PST) Subject: [Tutor] general basic question Message-ID: <1328710635.42799.YahooMailNeo@web39306.mail.mud.yahoo.com> On 8 February 2012 13:40, ken brockman wrote: > Hello all: > I have a general and very basic question if I may. I am in the process > of?attempting?to write my first python app. I wanted to collect information > and save it to lists and?dictionaries. My question is, is it possible to > save said lists and dictionaries in the program proper, or do i need to save > the information to files on the hard drive. Python objects very easily with Python standard functionality, referred to in Python terms as "pickling".? See the "pickle" module for? more information:??http://docs.python.org/library/pickle.html Thank you Walter for your help and speedy reply. Using pickling I have somehow managed to save two?separate?lists, but the dictionary is giving me much more of a struggle. I will reference the link you were gracious enough to provide me. Hopefully a few pots of coffee and my last few remaining brain cells will get me through it. Thanks again... PS the last few times i had?attempted?reading the docs on the python site, well, I might as well have been reading a book in ?ancient?Sanskrit. But if at?first?you don't succeed,try, try, try, again. Have a great day.? -------------- next part -------------- An HTML attachment was scrubbed... URL: From zoreander at gmail.com Wed Feb 8 15:17:29 2012 From: zoreander at gmail.com (R.S.) Date: Wed, 8 Feb 2012 15:17:29 +0100 Subject: [Tutor] python editor In-Reply-To: <20120208132402.GB11738@kontrol.kode5.net> References: <4F300B36.3010303@gmail.com> <20120208132402.GB11738@kontrol.kode5.net> Message-ID: I'm using Spyder (http://code.google.com/p/spyderlib/) and Notepad++ on Windows. I don't like pycharm. This software is consuming too much resources witch for me is poinless. Pycharm can eat even 500MB+ of RAM for simple application. 2012/2/8 Jamie Paul Griffin > On Mon, Feb 06, 2012 at 06:11:13PM +0000, Alan Gauld wrote: > > On 06/02/12 17:17, bob gailer wrote: > > >On 2/6/2012 10:25 AM, Kapil Shukla wrote: > > > > > >>Please also suggest a free editor for python which can at least repeat > > >>previous command with a key stroke > > > > That depends on the editor's mode of operation. > > In an editor like vi (elvis, vim etc) there is a repeat key (the period) > > that repeats most things because most things are a "command" - even > > inserting text. but in a so called modeless editor (most modern > > ones) > > repeat will be restricted to things that are recognised as atomic > > operations, like search/replace, change case etc. And some of those > > will only be valid when text is selected (so not really modeless!). > > > > Other editors like emacs allow you to specify how often an action is > > repeated. So esc-16 n will insert 16 n's for example. > > > > You would need to be more specific in terms of what you want in a > > repeat operation. > > > > -- > > Alan G > > Author of the Learn to Program web site > > http://www.alan-g.me.uk/ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > !DSPAM:4f3018592251995719914! > > > > > My personal choices are nvi for command line editor and TextMate for GUI > on Mac OS X. I don't use Windows systems so haven't a clue what's on offer > for that platform. I learned nvi just because it's the default editor > installed on NetBSD base system which is my primary computing platform. > There's just so many editors now it's difficult to know what will suit you > best. It would mostly come down to the environment you are most comfortable > working in; I spend 90% of my time in a UNIX shell so the command line > editors suit me better. > > Jamie > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From silideba at gmail.com Wed Feb 8 15:24:51 2012 From: silideba at gmail.com (Debashish Saha) Date: Wed, 8 Feb 2012 19:54:51 +0530 Subject: [Tutor] how to change the current working directory path in ipython. Message-ID: how to change the current working directory path in ipython. my current directory path is pwd Out[2]: u'C:\\Users\\as' now if i want to take the path to a subfolder of above 'C:\\Users\\as', what do i have to do? From wprins at gmail.com Wed Feb 8 15:29:34 2012 From: wprins at gmail.com (Walter Prins) Date: Wed, 8 Feb 2012 14:29:34 +0000 Subject: [Tutor] general basic question In-Reply-To: <1328710635.42799.YahooMailNeo@web39306.mail.mud.yahoo.com> References: <1328710635.42799.YahooMailNeo@web39306.mail.mud.yahoo.com> Message-ID: Hi Ken, On 8 February 2012 14:17, ken brockman wrote: > Thank you Walter for your help and speedy reply. You're welcome. > Using pickling I have somehow managed to save two?separate?lists, but the > dictionary is giving me much more of a struggle. Well do post back if you don't manage to solve your issues (with full error messages & stack traces as relevant please.) Re dictionaries -- I actually forgot to mention, there's a specialized type of dictionary class available in Python, called a "shelf", implented/available via the "shelve" module, which is basically a dict with pickling built in. See here: http://docs.python.org/library/shelve.html HTH, Walter From joel.goldstick at gmail.com Wed Feb 8 15:33:01 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 8 Feb 2012 09:33:01 -0500 Subject: [Tutor] how to change the current working directory path in ipython. In-Reply-To: References: Message-ID: On Wed, Feb 8, 2012 at 9:24 AM, Debashish Saha wrote: > how to change ?the current working directory path in ipython. > > my current directory path is > ? ? ? ? ? ? ? ? ? ? ? pwd > ? ? ? ? ? ? ? Out[2]: u'C:\\Users\\as' > > now if i want to take the path to a subfolder of above > 'C:\\Users\\as', what do i have to do? > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Try looking here: http://docs.python.org/tutorial/stdlib.html#operating-system-interface There is a module in python called os Here is an example from the documentation >>> import os >>> os.getcwd() # Return the current working directory 'C:\\Python26' >>> os.chdir('/server/accesslogs') # Change current working directory >>> os.system('mkdir today') # Run the command mkdir in the system shell 0 -- Joel Goldstick From zoreander at gmail.com Wed Feb 8 15:46:46 2012 From: zoreander at gmail.com (R.S.) Date: Wed, 8 Feb 2012 15:46:46 +0100 Subject: [Tutor] PyQT GUI Threading example Message-ID: I can't find any full example of threading with many threads working and updating GUI (precisely i need QTreeWidget). I can only find: not updating GUI examples, updating GUI examples with one thread. But i just can't find what i need. Could anyone share working example with many threads updating GUI like for example connecting to several www sites and adding the response in a list on QTreeWidget? -------------- next part -------------- An HTML attachment was scrubbed... URL: From oberoc at gmail.com Wed Feb 8 16:32:43 2012 From: oberoc at gmail.com (Tino Dai) Date: Wed, 8 Feb 2012 10:32:43 -0500 Subject: [Tutor] python editor In-Reply-To: References: <4F300B36.3010303@gmail.com> <20120208132402.GB11738@kontrol.kode5.net> Message-ID: On Wed, Feb 8, 2012 at 9:17 AM, R.S. wrote: > I'm using Spyder (http://code.google.com/p/spyderlib/) and Notepad++ on > Windows. > > I don't like pycharm. This software is consuming too much resources witch > for me is poinless. Pycharm can eat even 500MB+ of RAM for simple > application. > > > 2012/2/8 Jamie Paul Griffin > >> On Mon, Feb 06, 2012 at 06:11:13PM +0000, Alan Gauld wrote: >> > On 06/02/12 17:17, bob gailer wrote: >> > >On 2/6/2012 10:25 AM, Kapil Shukla wrote: >> > > >> > >>Please also suggest a free editor for python which can at least repeat >> > >>previous command with a key stroke >> > >> > That depends on the editor's mode of operation. >> > In an editor like vi (elvis, vim etc) there is a repeat key (the period) >> > that repeats most things because most things are a "command" - even >> > inserting text. but in a so called modeless editor (most modern >> > ones) >> > repeat will be restricted to things that are recognised as atomic >> > operations, like search/replace, change case etc. And some of those >> > will only be valid when text is selected (so not really modeless!). >> > >> > Other editors like emacs allow you to specify how often an action is >> > repeated. So esc-16 n will insert 16 n's for example. >> > >> > You would need to be more specific in terms of what you want in a >> > repeat operation. >> > >> > -- >> > Alan G >> > Author of the Learn to Program web site >> > http://www.alan-g.me.uk/ >> > >> > _______________________________________________ >> > Tutor maillist - Tutor at python.org >> > To unsubscribe or change subscription options: >> > http://mail.python.org/mailman/listinfo/tutor >> > >> > !DSPAM:4f3018592251995719914! >> > >> > >> My personal choices are nvi for command line editor and TextMate for GUI >> on Mac OS X. I don't use Windows systems so haven't a clue what's on offer >> for that platform. I learned nvi just because it's the default editor >> installed on NetBSD base system which is my primary computing platform. >> There's just so many editors now it's difficult to know what will suit you >> best. It would mostly come down to the environment you are most comfortable >> working in; I spend 90% of my time in a UNIX shell so the command line >> editors suit me better. >> >> I'm using vim with a number of plugins to turn the text editor into a Python IDE. Some of the setup highlights are: * code highlighting * syntax checking * code folding * and a whole bunch more For more information: http://sontek.net/turning-vim-into-a-modern-python-ide -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From silideba at gmail.com Wed Feb 8 16:48:46 2012 From: silideba at gmail.com (Debashish Saha) Date: Wed, 8 Feb 2012 21:18:46 +0530 Subject: [Tutor] confusion about scipy Message-ID: ImportError Traceback (most recent call last) C:\Python27\lib\site-packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc) 166 else: 167 filename = fname --> 168 exec compile(scripttext, filename, 'exec') in glob, loc 169 else: 170 def execfile(fname, *where): C:\Users\as\hemanta\noorm.py in () 1 import numpy as np ----> 2 from scipy import brentq 3 import matplotlib.pyplot as plt 4 from pylab import twinx 5 from scipy.integrate import quad ImportError: cannot import name brentq Question: like 'from pylab import twinx' why could not i write 'from scipy import brentq'.Instead i have to write 'from scipy.optimize import brentq'.But why??? From evert.rol at gmail.com Wed Feb 8 17:10:04 2012 From: evert.rol at gmail.com (Evert Rol) Date: Wed, 8 Feb 2012 17:10:04 +0100 Subject: [Tutor] confusion about scipy In-Reply-To: References: Message-ID: > ImportError Traceback (most recent call last) > C:\Python27\lib\site-packages\IPython\utils\py3compat.pyc in > execfile(fname, glob, loc) > 166 else: > 167 filename = fname > --> 168 exec compile(scripttext, filename, 'exec') in glob, loc > 169 else: > 170 def execfile(fname, *where): > > C:\Users\as\hemanta\noorm.py in () > 1 import numpy as np > ----> 2 from scipy import brentq > 3 import matplotlib.pyplot as plt > 4 from pylab import twinx > 5 from scipy.integrate import quad > > ImportError: cannot import name brentq > > > Question: > like 'from pylab import twinx' why could not i write 'from scipy > import brentq'.Instead i have to write 'from scipy.optimize import > brentq'.But why??? Because that's where the scipy developers put the brentq function: in the optimize module. It's basically the same as your line 5, where quad is in the integrate module in the scipy package. It makes sense to organise a large library into (sub)packages/(sub)modules. Just as the tutorial shows as well: http://docs.python.org/tutorial/modules.html#packages The fact that twinx can be imported straight from the pylab module, is actually just a convenient shortcut. Evert From krush1954 at yahoo.com Wed Feb 8 18:33:54 2012 From: krush1954 at yahoo.com (ken brockman) Date: Wed, 8 Feb 2012 09:33:54 -0800 (PST) Subject: [Tutor] general basic question Message-ID: <1328722434.69149.YahooMailNeo@web39301.mail.mud.yahoo.com> > Using pickling I have somehow managed to save two?separate?lists, but the >?dictionary?is giving me much more of a struggle. Well do post back if you don't manage to solve your issues (with full error messages & stack traces as relevant please.)? Re?dictionaries?-- I actually forgot to mention, there's a specialized type of dictionary class available in Python, called a "shelf", implented/available via the "shelve" module, which is basically a dict with pickling built in. See here: http://docs.python.org/library/shelve.html HTH, Walter Walter, you're the man. I've read of the shelve command. Not that i understood it, but i've read it. I'm going to hit the books and google some more before i waste anymore of your time. But if i can't sort it out, I may just take you up on your kind offer. Have a good day . Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Wed Feb 8 18:45:44 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 8 Feb 2012 12:45:44 -0500 Subject: [Tutor] general basic question In-Reply-To: <1328722434.69149.YahooMailNeo@web39301.mail.mud.yahoo.com> References: <1328722434.69149.YahooMailNeo@web39301.mail.mud.yahoo.com> Message-ID: On Wed, Feb 8, 2012 at 12:33 PM, ken brockman wrote: >> Using pickling I have somehow managed to save two?separate?lists, but the >>?dictionary?is giving me much more of a struggle. > > Well do post back if you don't manage to solve your issues (with full > error messages & stack traces as relevant please.)? Re?dictionaries?-- > I actually forgot to mention, there's a specialized type of dictionary > class available in Python, called a "shelf", implented/available via > the "shelve" module, which is basically a dict with pickling built in. > See here: > http://docs.python.org/library/shelve.html > > HTH, > > Walter > > Walter, you're the man. > I've read of the shelve command. Not that i understood it, but i've read it. > I'm going to hit the books and google some more before i waste anymore of > your time. But if i can't sort it out, I may just take you up on your kind > offer. > Have a good day . > Ken > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > You might want to find some tutorials that suit you. On the right column of this site there is a list of several online: www.reddit.com/r/Python/ -- Joel Goldstick From matt.gregory at oregonstate.edu Wed Feb 8 18:41:26 2012 From: matt.gregory at oregonstate.edu (Gregory, Matthew) Date: Wed, 8 Feb 2012 09:41:26 -0800 Subject: [Tutor] dictionary of methods calling syntax In-Reply-To: References: <1D673F86DDA00841A1216F04D1CE70D646FF7D86A7@EXCH2.nws.oregonstate.edu> Message-ID: <1D673F86DDA00841A1216F04D1CE70D646FF7D8855@EXCH2.nws.oregonstate.edu> Alan Gauld wrote: > Since a class is effectively a disguised dictionary I'm not sure why you > want to do this? If you just want to access the method by name then why > not just call getattr(spam,'get_mean')? Thanks for the feedback and, yes, this makes sense. My use case was when the statistic desired was going to be specified at runtime (through file input or UI) and that a dictionary would be a convenient crosswalk to associate the statistic name with the method name (and thus avoid an if/else ladder). But I understand that as long as there is a direct relationship between the name of the statistic and my class method (e.g. 'mean' -> get_mean), that I should be able to use the getattr() syntax as above. Thanks also to Joel for the suggestion to put the dictionary inside of __init__. thanks, matt From brad.hudson at gmail.com Wed Feb 8 19:03:43 2012 From: brad.hudson at gmail.com (Brad Hudson) Date: Wed, 8 Feb 2012 12:03:43 -0600 Subject: [Tutor] Python Database Scripting Message-ID: Can someone provide information on the best modules/python tools to use for general database scripting? I'm interested in something that works across the board for Oracle, MySQL, MS SQL Server, and DB2. I was hoping a good generic ODBC module would be out there, but I'm having difficulty locating one that works for all. -------------- next part -------------- An HTML attachment was scrubbed... URL: From modulok at gmail.com Wed Feb 8 19:26:11 2012 From: modulok at gmail.com (Modulok) Date: Wed, 8 Feb 2012 11:26:11 -0700 Subject: [Tutor] Python Database Scripting In-Reply-To: References: Message-ID: The closest thing you'll find will probably be the third party module 'sqlalchemy'. You can install it via easy_install or pip. If that doesn't meet your needs I'm not sure what else would. (But would love to hear about it.) -Modulok- On 2/8/12, Brad Hudson wrote: > Can someone provide information on the best modules/python tools to use for > general database scripting? I'm interested in something that works across > the board for Oracle, MySQL, MS SQL Server, and DB2. I was hoping a good > generic ODBC module would be out there, but I'm having difficulty locating > one that works for all. > From breamoreboy at yahoo.co.uk Wed Feb 8 19:58:56 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 08 Feb 2012 18:58:56 +0000 Subject: [Tutor] dictionary of methods calling syntax In-Reply-To: <1D673F86DDA00841A1216F04D1CE70D646FF7D8855@EXCH2.nws.oregonstate.edu> References: <1D673F86DDA00841A1216F04D1CE70D646FF7D86A7@EXCH2.nws.oregonstate.edu> <1D673F86DDA00841A1216F04D1CE70D646FF7D8855@EXCH2.nws.oregonstate.edu> Message-ID: On 08/02/2012 17:41, Gregory, Matthew wrote: > Alan Gauld wrote: >> Since a class is effectively a disguised dictionary I'm not sure why you >> want to do this? If you just want to access the method by name then why >> not just call getattr(spam,'get_mean')? > > Thanks for the feedback and, yes, this makes sense. My use case was when the statistic desired was going to be specified at runtime (through file input or UI) and that a dictionary would be a convenient crosswalk to associate the statistic name with the method name (and thus avoid an if/else ladder). But I understand that as long as there is a direct relationship between the name of the statistic and my class method (e.g. 'mean' -> get_mean), that I should be able to use the getattr() syntax as above. > > Thanks also to Joel for the suggestion to put the dictionary inside of __init__. > > thanks, matt > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > This should help if you need more info http://code.activestate.com/lists/python-list/403361/ -- Cheers. Mark Lawrence. From paddy at paddy-dempster.org.uk Wed Feb 8 20:04:29 2012 From: paddy at paddy-dempster.org.uk (Patrick Dempster) Date: Wed, 08 Feb 2012 19:04:29 +0000 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <4F32C73D.5040701@paddy-dempster.org.uk> On 07/02/2012 19:07, Hugo Arts wrote: > On Tue, Feb 7, 2012 at 7:50 PM, Debashish Saha wrote: >> for i in range(1, 8): >> print(i) >> if i==3: >> break >> else: >> print('The for loop is over') >> >> >> Output: >> 1 >> 2 >> 3 >> >> Question:but after breaking the for loop why the else command could not work? >> > because the else statement was designed to be that way: > > http://docs.python.org/reference/compound_stmts.html#for > > quoting the relevant part: > > "When the items are exhausted (which is immediately when the sequence > is empty), the suite in the else clause, if present, is executed, and > the loop terminates. > > A break statement executed in the first suite terminates the loop > without executing the else clause?s suite." > > in short, the else clause only executes if you do *not* break out of the loop. I might be missing something but I can't see a reason for the "else:" clause attached to the "for" statement, could anyone provide an example where or why someone might use the "else:" clause with the for loop? P. From alan.gauld at btinternet.com Wed Feb 8 20:10:44 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 08 Feb 2012 19:10:44 +0000 Subject: [Tutor] Python Database Scripting In-Reply-To: References: Message-ID: On 08/02/12 18:03, Brad Hudson wrote: > Can someone provide information on the best modules/python tools to use > for general database scripting? I'm interested in something that works > across the board for Oracle, MySQL, MS SQL Server, and DB2. I was hoping > a good generic ODBC module would be out there, but I'm having difficulty > locating one that works for all. There are a few object-database wrappers such as SQLAlchemy that has been mentioned. But be aware that any such generic database wrapper will have compromises in performance/scalability. Every database has its own foibles and if you need power access you will need to use native access. The Python DBAPI is pretty standard but it also allows you to access the database features too. There is an ODBC wrapper too but of course ODBC adds yet another layer of limitations. Given the choice of using ODBC via Python DBAPI or using Sqlalchemy I'd probably go with SqlAlchemy. Either approach is valid, it just depends on whether performance/flexibility or compatibility/transparency matters most. You have to pick your poison. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From brad.hudson at gmail.com Wed Feb 8 20:20:02 2012 From: brad.hudson at gmail.com (Brad Hudson) Date: Wed, 8 Feb 2012 13:20:02 -0600 Subject: [Tutor] Python Database Scripting In-Reply-To: References: Message-ID: Thanks for the responses Alan & Modulok. I will start with SQLAlchemy and see where it takes me. -------------- next part -------------- An HTML attachment was scrubbed... URL: From krush1954 at yahoo.com Wed Feb 8 20:57:15 2012 From: krush1954 at yahoo.com (ken brockman) Date: Wed, 8 Feb 2012 11:57:15 -0800 (PST) Subject: [Tutor] general basic question Message-ID: <1328731035.10927.YahooMailNeo@web39303.mail.mud.yahoo.com> On Wed, Feb 8, 2012 at 12:33 PM, ken brockman wrote: >> Using pickling I have somehow managed to save two?separate?lists, but the >>?dictionary?is giving me much more of a struggle. Got it. I manage to get it to save to disk, but only by using the shell to create an empty dictionary then pickling it and saving it to a file. Priming the pump as it were. I had thought i had read that when you pickle and save a list or dictionary to file, if it didn't already exist, it would be created. That?hasn't?been my experience. Had I?misunderstood?or Am i doing something wrong? Just for future reference. I'm as happy as the proverbial pig in excrement just to get it to function. Thanks all for your help. Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Wed Feb 8 21:45:06 2012 From: timomlists at gmail.com (Timo) Date: Wed, 08 Feb 2012 21:45:06 +0100 Subject: [Tutor] Python Database Scripting In-Reply-To: References: Message-ID: <4F32DED2.4050604@gmail.com> Op 08-02-12 20:20, Brad Hudson schreef: > Thanks for the responses Alan & Modulok. I will start with SQLAlchemy > and see where it takes me. I was looking for something similar a couple of months ago and chose to use SQLObject over SQLAlchemy. In my eyes it was much easier to use. Timo > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From bermanrl at cfl.rr.com Wed Feb 8 22:08:07 2012 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 8 Feb 2012 16:08:07 -0500 Subject: [Tutor] general basic question In-Reply-To: References: <1328731035.10927.YahooMailNeo@web39303.mail.mud.yahoo.com> Message-ID: On Wed, Feb 8, 2012 at 2:57 PM, ken brockman wrote: > > > On Wed, Feb 8, 2012 at 12:33 PM, ken brockman wrote: > >> Using pickling I have somehow managed to save two separate lists, but > the > >> dictionary is giving me much more of a struggle. > > Got it. I manage to get it to save to disk, but only by using the shell to > create an empty dictionary then pickling it and saving it to a file. > Priming the pump as it were. I had thought i had read that when you pickle > and save a list or dictionary to file, if it didn't already exist, it would > be created. That hasn't been my experience. Had I misunderstood or Am i > doing something wrong? Just for future reference. I'm as happy as the > proverbial pig in excrement just to get it to function. > Thanks all for your help. > Ken > > Ken, Let me see if I understand your problem. You are pickling a dictionary and finding that it will not work unless there already is an existing dictionary for your pickled dictionary to write over. Otherwise, there is either no write at all or the write is followed by a delete. Is that a reasonable definition of your current problem? Robert Berman -------------- next part -------------- An HTML attachment was scrubbed... URL: From krush1954 at yahoo.com Wed Feb 8 22:28:26 2012 From: krush1954 at yahoo.com (ken brockman) Date: Wed, 8 Feb 2012 13:28:26 -0800 (PST) Subject: [Tutor] general basic question Message-ID: <1328736506.18576.YahooMailNeo@web39304.mail.mud.yahoo.com> Got it. I manage to get it to save to disk, but only by using the shell to create an empty?dictionary?then pickling it and saving it to a file. Priming the pump as it were. I had thought i had read that when you pickle and save a list or dictionary to file, if it didn't already exist, it would be created. That?hasn't?been my experience. Had I?misunderstood?or Am i doing something wrong? Let me see if I understand your problem. You are pickling a dictionary and finding that it will not work unless there already is an existing dictionary for your pickled dictionary to write over. Otherwise, there is either no write at all or the write is?followed?by a delete. ?Is that a reasonable definition of your current?problem?? Robert Berman Really close to it Robert. No delete but an?error?msg. Something akin to file dosen't?exist, not found?, or words to that effect . ?Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Wed Feb 8 23:14:31 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 8 Feb 2012 17:14:31 -0500 Subject: [Tutor] general basic question In-Reply-To: <1328736506.18576.YahooMailNeo@web39304.mail.mud.yahoo.com> References: <1328736506.18576.YahooMailNeo@web39304.mail.mud.yahoo.com> Message-ID: On Wed, Feb 8, 2012 at 4:28 PM, ken brockman wrote: > Got it. I manage to get it to save to disk, but only by using the shell to > create an empty?dictionary?then pickling it and saving it to a file. Priming > the pump as it were. I had thought i had read that when you pickle and save > a list or dictionary to file, if it didn't already exist, it would be > created. That?hasn't?been my experience. Had I?misunderstood?or Am i doing > something wrong? > > Let me see if I understand your problem. You are pickling a dictionary and > finding that it will not work unless there already is an existing dictionary > for your pickled dictionary to write over. Otherwise, there is either no > write at all or the write is?followed?by a delete. ?Is that a reasonable > definition of your current?problem? > > Robert Berman > > Really close to it Robert. No delete but an?error?msg. Something akin to > file dosen't?exist, not found?, or words to that effect . > ?Ken > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Ken, The best way to get help here is to post a small example of your code that shows the problem, along with the complete traceback. Although at first they seem a little daunting, the traceback will make the problem obvious -- Joel Goldstick From alan.gauld at btinternet.com Wed Feb 8 23:20:53 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 08 Feb 2012 22:20:53 +0000 Subject: [Tutor] general basic question In-Reply-To: <1328736506.18576.YahooMailNeo@web39304.mail.mud.yahoo.com> References: <1328736506.18576.YahooMailNeo@web39304.mail.mud.yahoo.com> Message-ID: On 08/02/12 21:28, ken brockman wrote: > Really close to it Robert. No delete but an error msg. Something akin to > file dosen't exist, not found , or words to that effect . Without sight of code it's only a guess but are you creating the file with the 'wb' mode - ie. write binary? :- myPickleFile = open("somefilename.dat", "wb") If you are not using the 'b' for binary pickle and shelve tend to run into problems, this might be one of those cases. Its not glaringly obvious from the docs that you need to use binary mode and beginners often get caught out. Could that be it? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From joel.goldstick at gmail.com Wed Feb 8 23:21:35 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 8 Feb 2012 17:21:35 -0500 Subject: [Tutor] (no subject) In-Reply-To: <4F32C73D.5040701@paddy-dempster.org.uk> References: <4F32C73D.5040701@paddy-dempster.org.uk> Message-ID: On Wed, Feb 8, 2012 at 2:04 PM, Patrick Dempster wrote: > On 07/02/2012 19:07, Hugo Arts wrote: >> On Tue, Feb 7, 2012 at 7:50 PM, Debashish Saha wrote: >>> for i in range(1, 8): >>> ? ?print(i) >>> ? ?if i==3: >>> ? ? ? ?break >>> else: >>> ? ?print('The for loop is over') >>> >>> >>> ?Output: >>> 1 >>> 2 >>> 3 >>> >>> Question:but after breaking the for loop why the else command could not work? >>> >> because the else statement was designed to be that way: >> >> http://docs.python.org/reference/compound_stmts.html#for >> >> quoting the relevant part: >> >> "When the items are exhausted (which is immediately when the sequence >> is empty), the suite in the else clause, if present, is executed, and >> the loop terminates. >> >> A break statement executed in the first suite terminates the loop >> without executing the else clause?s suite." >> >> in short, the else clause only executes if you do *not* break out of the loop. > > I might be missing something but I can't see a reason for the "else:" > clause attached to the "for" statement, could anyone provide an example > where or why someone might use the "else:" clause with the for loop? > > P. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Here is and interesting article: http://nedbatchelder.com/blog/201110/forelse.html The else clause runs if the loop breaks for some reason. So you would use it only to do some processing if the loop completes completely. -- Joel Goldstick From alan.gauld at btinternet.com Wed Feb 8 23:25:58 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 08 Feb 2012 22:25:58 +0000 Subject: [Tutor] For/else construct was: Re: (no subject) In-Reply-To: <4F32C73D.5040701@paddy-dempster.org.uk> References: <4F32C73D.5040701@paddy-dempster.org.uk> Message-ID: On 08/02/12 19:04, Patrick Dempster wrote: > I might be missing something but I can't see a reason for the "else:" > clause attached to the "for" statement, could anyone provide an example > where or why someone might use the "else:" clause with the for loop? There have been a couple of sample cases given already but here is an example of what you would need to do without it. broken_loop = False for item in collection: process(item) if condition: broken_loop = True break if not broken_loop: do_the_else_part() do_this_regardless() It's not a huge pain but this is easier: for item in collection: process(item) if condition: break else: do_the_else_part() do_this_regardless() HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From malaclypse2 at gmail.com Thu Feb 9 00:00:59 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 8 Feb 2012 18:00:59 -0500 Subject: [Tutor] (no subject) In-Reply-To: References: <4F32C73D.5040701@paddy-dempster.org.uk> Message-ID: On Wed, Feb 8, 2012 at 5:21 PM, Joel Goldstick wrote: > The else clause runs if the loop breaks for some reason. So you would > use it only to do some processing if the loop completes completely. > > No. The else clause only runs if the loop does NOT break out early. The else clause only runs if the loop runs to completion without breaking. For what it's worth, I loathe for/else loops, and will probably never use them in my code. They confuse me every time I see them, and I have to go look up the behavior. My brain always jumps to the conclusion that the "else" clause should run when we do hit a break, which is the exact opposite of how it actually works. Maybe if they had been written into the language as for/then loops I would remember it correctly. Jerry -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu Feb 9 00:25:15 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 8 Feb 2012 18:25:15 -0500 Subject: [Tutor] (no subject) In-Reply-To: References: <4F32C73D.5040701@paddy-dempster.org.uk> Message-ID: On Wed, Feb 8, 2012 at 6:00 PM, Jerry Hill wrote: > On Wed, Feb 8, 2012 at 5:21 PM, Joel Goldstick > wrote: >> >> The else clause runs if the loop breaks for some reason. ?So you would >> use it only to do some processing if the loop completes completely. >> > > No.? The else clause only runs if the loop does NOT break out early.? The > else clause only runs if the loop runs to completion without breaking. > > For what it's worth, I loathe for/else loops, and will probably never use > them in my code.? They confuse me every time I see them, and I have to go > look up the behavior.? My brain always jumps to the conclusion that the > "else" clause should run when we do hit a break, which is the exact opposite > of how it actually works.? Maybe if they had been written into the language > as for/then loops I would remember it correctly. > > Jerry > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > oops.. sorry.. yes else runs if the loop completes without a break.. duh! -- Joel Goldstick From steve at pearwood.info Thu Feb 9 01:32:15 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 09 Feb 2012 11:32:15 +1100 Subject: [Tutor] general basic question In-Reply-To: <1328736506.18576.YahooMailNeo@web39304.mail.mud.yahoo.com> References: <1328736506.18576.YahooMailNeo@web39304.mail.mud.yahoo.com> Message-ID: <4F33140F.5020207@pearwood.info> ken brockman wrote: > Really close to it Robert. No delete but an error msg. Something akin to file dosen't exist, not found , or words to that effect . Something "akin to"? How about if you copy and paste the actual error message, instead of asking us to guess? That means the full traceback, starting at the line "Traceback (most recent call last)" all the way to the end. It may also help if you show us the code that you are running, again instead of making us guess. But before you do, please read this document: http://sscce.org/ -- Steven From hothottrott at gmail.com Thu Feb 9 01:43:17 2012 From: hothottrott at gmail.com (Nathaniel Trujillo) Date: Wed, 8 Feb 2012 17:43:17 -0700 Subject: [Tutor] This program has worked for me before. Message-ID: Hello, I stopped using python for about 4 months but now I am back. I tried running my pizza_panic_game.py program again thinking nothing had changed since a last ran it but boy was I wrong. Are we allowed to send the program as an attachment? Here is the program # Pizza Panic # Player must catch falling pizzas before they hit the ground from livewires import games, color import random games.init(screen_width = 640, screen_height = 480, fps =50) class Pan(games.Sprite): """ A pan controlled by player to catch falling pizzas. """ image = games.load_image("pan.bmp") def __init__(self): """ Initializing Pan object and create Text object for score. """ super(Pan, self).__init__(image = Pan.image, x = games.mouse.x, bottom = games.screen.height) self.score = games.Text(value = 0, size = 25, color = color.black, top = 5, right = games.screen.width - 10) games.screen.add(self.score) def update(self): """ Move to mouse x position. """ self.x = games.mouse.x if self.left < 0: self.left = 0 if self.right > games.screen.width: self.right = games.screen.width self.check_catch() def check_catch(self): """ Check if catch pizzas. """ for pizza in self.overlapping_sprites: self.score.value += 10 self.score.right = games.screen.width - 10 pizza.handle_caught() class Pizza(games.Sprite): """ A pizza which falls to the ground. """ image = games.load_image("pizza.bmp") speed = 1 def __init__(self, x, y = 90): """ Initialize a Pizza object. """ super(Pizza, self).__init__(image = Pizza.image, x = x, y = y, dy = Pizza.speed) def update(self): """ Check if bottom edge has reached screen bottom. """ if self.bottom > games.screen.height: self.end_game() self.destroy() def handle_caught(self): """ Destroy self if caught. """ self.destroy() def end_game(self): """ End the game. """ end_message = games.Message(value = "Game Over", size = 90, color = color.red, x = games.screen.width/2, y = games.screen.height/2, lifetime = 5 * games.screen.fps, after_death = games.screen.quit) games.screen.add(end_message) class Chef(games.Sprite): """ A chef which moves left and right, dropping pizzas. """ image = games.load_image("chef.bmp") def __init__(self, y = 55, speed = 2, odds_change = 200): """ Initialize the Chef object. """ super(Chef, self).__init__(image = Chef.image, x = games.screen.width / 2, y = y, dx = speed) self.odds_change = odds_change self.time_til_drop = 0 def update(self): """ Determined if direction needs to be reversed. """ if self.left < 0 or self.right > games.screen.width: self.dx = -self.dx elif random.randrange(self.odds_change) == 0: self.dx = -self.dx self.check_drop() def check_drop(self): """ Decrease countdown or drop pizza and reset countdown. """ if self.time_til_drop > 0: self.time_til_drop -= 1 else: new_pizza = Pizza(x = self.x) games.screen.add(new_pizza) # set buffer to approx 30% of pizza height, regardless of pizza speed self.time_til_drop = int(new_pizza.height * 1.3 / Pizza.speed) + 1 def main(): """ Play the game. """ wall_image = games.load_image("wall.jpg", transparent = False) games.screen.background = wall_image the_chef = Chef() games.screen.add(the_chef) the_pan = Pan() games.screen.add(the_pan) games.mouse.is_visible = False games.screen.event_grab = True games.screen.mainloop() # start it up! main() and it keeps giving me this error message which I then googled to no avail Traceback (most recent call last): File "C:\Python31\pizza_panic_game.py", line 4, in from livewires import games, color File "C:\Python31\lib\site-packages\livewires\games.py", line 57, in import pygame, pygame.image, pygame.mixer, pygame.font, pygame.transform File "C:\Python31\lib\site-packages\pygame\__init__.py", line 95, in from pygame.base import * ImportError: DLL load failed: The specified module could not be found. thanks for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From garry.willgoose at newcastle.edu.au Thu Feb 9 02:46:45 2012 From: garry.willgoose at newcastle.edu.au (Garry Willgoose) Date: Thu, 9 Feb 2012 12:46:45 +1100 Subject: [Tutor] bogus characters in a windows file Message-ID: <418AB33F-8998-47CE-8F83-E6DD40A2F572@newcastle.edu.au> I'm reading a file output by the system utility WMIC in windows (so I can track CPU usage by process ID) and the text file WMIC outputs seems to have extra characters in I've not seen before. I use os.system('WMIC /OUTPUT:c:\cpu.txt PROCESS GET ProcessId') to output the file and parse file c:\cpu.txt The first few lines of the file look like this in notepad ProcessId 0 4 568 624 648 I input the data with the lines infile = open('c:\cpu.txt','r') infile.readline() infile.readline() infile.readline() the readline()s yield the following output '\xff\xfeP\x00r\x00o\x00c\x00e\x00s\x00s\x00I\x00d\x00 \x00 \x00\r\x00\n' '\x000\x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00\r\x00\n' '\x004\x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00\r\x00\n' Now for the first line the title 'ProcessId' is in this string but the individual characters are separated by '\x00' and at least for the first line of the file there is an extra '\xff\xfe'. For subsequent its just '\x00. Now I can just replace the '\x**' with '' but that seems a bit inelegant. I've tried various options on the open 'rU' and 'rb' but no effect. Does anybody know what the rubbish characters are and what has caused the. I'm using the latest Enthought python if that matters. From marc.tompkins at gmail.com Thu Feb 9 03:09:25 2012 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 8 Feb 2012 18:09:25 -0800 Subject: [Tutor] bogus characters in a windows file In-Reply-To: <418AB33F-8998-47CE-8F83-E6DD40A2F572@newcastle.edu.au> References: <418AB33F-8998-47CE-8F83-E6DD40A2F572@newcastle.edu.au> Message-ID: On Wed, Feb 8, 2012 at 5:46 PM, Garry Willgoose < garry.willgoose at newcastle.edu.au> wrote: > I'm reading a file output by the system utility WMIC in windows (so I can > track CPU usage by process ID) and the text file WMIC outputs seems to have > extra characters in I've not seen before. > > I use os.system('WMIC /OUTPUT:c:\cpu.txt PROCESS GET ProcessId') to output > the file and parse file c:\cpu.txt > > The first few lines of the file look like this in notepad > > ProcessId > 0 > 4 > 568 > 624 > 648 > > > I input the data with the lines > > infile = open('c:\cpu.txt','r') > infile.readline() > infile.readline() > infile.readline() > > the readline()s yield the following output > > '\xff\xfeP\x00r\x00o\x00c\x00e\x00s\x00s\x00I\x00d\x00 \x00 \x00\r\x00\n' > '\x000\x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00\r\x00\n' > '\x004\x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00\r\x00\n' > > Now for the first line the title 'ProcessId' is in this string but the > individual characters are separated by '\x00' and at least for the first > line of the file there is an extra '\xff\xfe'. For subsequent its just > '\x00. Now I can just replace the '\x**' with '' but that seems a bit > inelegant. I've tried various options on the open 'rU' and 'rb' but no > effect. > > Does anybody know what the rubbish characters are and what has caused the. > I'm using the latest Enthought python if that matters. > > You're trying to read a Unicode text file byte-by-byte. It'll end in tears... The "\xff\xfe" at the beginning is the Byte Order Marker or BOM. Here's a quick primer on Unicode: http://www.joelonsoftware.com/articles/Unicode.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Thu Feb 9 03:17:34 2012 From: d at davea.name (Dave Angel) Date: Wed, 08 Feb 2012 21:17:34 -0500 Subject: [Tutor] bogus characters in a windows file In-Reply-To: <418AB33F-8998-47CE-8F83-E6DD40A2F572@newcastle.edu.au> References: <418AB33F-8998-47CE-8F83-E6DD40A2F572@newcastle.edu.au> Message-ID: <4F332CBE.4080704@davea.name> On 02/08/2012 08:46 PM, Garry Willgoose wrote: > I'm reading a file output by the system utility WMIC in windows (so I can track CPU usage by process ID) and the text file WMIC outputs seems to have extra characters in I've not seen before. > > I use os.system('WMIC /OUTPUT:c:\cpu.txt PROCESS GET ProcessId') to output the file and parse file c:\cpu.txt First mistake. If you use backslash inside a python literal string, you need to do one of two things: 1) use a raw string 2) double the backslash It so happens that \c is not a python escape sequence, so you escaped this particular bug. > The first few lines of the file look like this in notepad > > ProcessId > 0 > 4 > 568 > 624 > 648 > > > I input the data with the lines > > infile = open('c:\cpu.txt','r') Same thing. You should either make it r'c:\cpu.txt' or 'c:\\cpu.txt' or even 'c:/cpu.txt' > infile.readline() > infile.readline() > infile.readline() > OK, so you throw away the first 3 lines of the file. > the readline()s yield the following output > > '\xff\xfeP\x00r\x00o\x00c\x00e\x00s\x00s\x00I\x00d\x00 \x00 \x00\r\x00\n' > '\x000\x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00\r\x00\n' > '\x004\x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00\r\x00\n' > Now, how did you get those bytes displayed; they've already been thrown out. > Now for the first line the title 'ProcessId' is in this string but the individual characters are separated by '\x00' and at least for the first line of the file there is an extra '\xff\xfe'. For subsequent its just '\x00. Now I can just replace the '\x**' with '' but that seems a bit inelegant. I've tried various options on the open 'rU' and 'rb' but no effect. > > Does anybody know what the rubbish characters are and what has caused the. I'm using the latest Enthought python if that matters. It matters, but it'd save each of us lots of trouble if you told us what version that was; especially which version of Python. The latest Enthought I see is called EPD 7.2. But after 10 minutes on the site, I can't see whether there actually is a Python on there or not. it seems to be just a bunch of libraries for Python. But whether they're for CPython, IronPython, or something else, who knows? I don't see any rubbish characters. What I see is some unicode strings, displayed as though they were byte strings. the first two bytes are the BOM code, commonly put at the beginning of a file encoded in UTF-16. The remaining pairs of bytes are UTF-16 encodings for ordinary characters. Notepad would recognize the UTF-16 encoding, and display the characters correctly. Perhaps you need to do the same. You showed us a fragment of code which would throw away the first 3 lines of the file. You don't show us any code indicating what you mean by "yield the following output." So you want us to read your mind, and tell you what's there? -- DaveA From marc.tompkins at gmail.com Thu Feb 9 03:54:11 2012 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 8 Feb 2012 18:54:11 -0800 Subject: [Tutor] bogus characters in a windows file In-Reply-To: References: <418AB33F-8998-47CE-8F83-E6DD40A2F572@newcastle.edu.au> Message-ID: On Wed, Feb 8, 2012 at 6:09 PM, Marc Tompkins wrote: > On Wed, Feb 8, 2012 at 5:46 PM, Garry Willgoose < > garry.willgoose at newcastle.edu.au> wrote: > >> I'm reading a file output by the system utility WMIC in windows (so I can >> track CPU usage by process ID) and the text file WMIC outputs seems to have >> extra characters in I've not seen before. >> >> I use os.system('WMIC /OUTPUT:c:\cpu.txt PROCESS GET ProcessId') to >> output the file and parse file c:\cpu.txt >> >> The first few lines of the file look like this in notepad >> >> ProcessId >> 0 >> 4 >> 568 >> 624 >> 648 >> >> >> I input the data with the lines >> >> infile = open('c:\cpu.txt','r') >> infile.readline() >> infile.readline() >> infile.readline() >> >> the readline()s yield the following output >> >> '\xff\xfeP\x00r\x00o\x00c\x00e\x00s\x00s\x00I\x00d\x00 \x00 \x00\r\x00\n' >> '\x000\x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00\r\x00\n' >> '\x004\x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00\r\x00\n' >> >> Now for the first line the title 'ProcessId' is in this string but the >> individual characters are separated by '\x00' and at least for the first >> line of the file there is an extra '\xff\xfe'. For subsequent its just >> '\x00. Now I can just replace the '\x**' with '' but that seems a bit >> inelegant. I've tried various options on the open 'rU' and 'rb' but no >> effect. >> >> Does anybody know what the rubbish characters are and what has caused >> the. I'm using the latest Enthought python if that matters. >> >> You're trying to read a Unicode text file byte-by-byte. It'll end in > tears... > The "\xff\xfe" at the beginning is the Byte Order Marker or BOM. > > Here's a quick primer on Unicode: > http://www.joelonsoftware.com/articles/Unicode.html > > In particular, this phrase: > "we decided to do everything internally in UCS-2 (two byte) Unicode, which > is what Visual Basic, COM, and Windows NT/2000/XP use as their native > string type." > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Feb 9 06:12:08 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 09 Feb 2012 05:12:08 +0000 Subject: [Tutor] This program has worked for me before. In-Reply-To: References: Message-ID: On 09/02/12 00:43, Nathaniel Trujillo wrote: > Hello, I stopped using python for about 4 months but now I am back. I .... > and it keeps giving me this error message which I then googled to no avail > Traceback (most recent call last): > File "C:\Python31\pizza_panic_game.py", line 4, in > from livewires import games, color > File "C:\Python31\lib\site-packages\livewires\games.py", line 57, in > > import pygame, pygame.image, pygame.mixer, pygame.font, > pygame.transform > File "C:\Python31\lib\site-packages\pygame\__init__.py", line 95, in > > from pygame.base import * > ImportError: DLL load failed: The specified module could not be found. > thanks for the help. Looks like a problem with your Livewires installation. Have you upgraded either Python or Livewires? Or deleted either? I'd start by reinstalling the correct matching version of Livewires. ie the one that matches your version of Python. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From daedae11 at 126.com Thu Feb 9 07:15:04 2012 From: daedae11 at 126.com (daedae11) Date: Thu, 9 Feb 2012 14:15:04 +0800 Subject: [Tutor] What the difference between the two RE? Message-ID: <201202091415049115699@126.com> import re re.match("^hello", "hello") re.match("hello", "hello") Please give a string that matches RE "^hello" but does not match RE "hello", or matches RE "hello" but does not match RE "^hello". daedae11 -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Thu Feb 9 08:16:48 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 09 Feb 2012 09:16:48 +0200 Subject: [Tutor] What the difference between the two RE? In-Reply-To: <201202091415049115699@126.com> References: <201202091415049115699@126.com> Message-ID: <4F3372E0.8020304@compuscan.co.za> On 2012/02/09 08:15 AM, daedae11 wrote: > import re > re.match("^hello", "hello") > re.match("hello", "hello") > Please give a string that matches RE "^hello" but does not match RE > "hello", or matches RE "hello" but does not match RE "^hello". > ------------------------------------------------------------------------ > daedae11 > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor The caret ^ means "At the beginning of the line" so 'And they said hello' will not be matched by the regex pattern '^hello'. The docs are pretty good on the module http://docs.python.org/library/re.html http://docs.python.org/howto/regex.html -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From goran at usertime.se Thu Feb 9 08:21:08 2012 From: goran at usertime.se (=?ISO-8859-1?Q?G=F6ran_T=F6rnquist?=) Date: Thu, 09 Feb 2012 08:21:08 +0100 Subject: [Tutor] What the difference between the two RE? In-Reply-To: <4F3372E0.8020304@compuscan.co.za> References: <201202091415049115699@126.com> <4F3372E0.8020304@compuscan.co.za> Message-ID: <4F3373E4.3080802@usertime.se> On 2012-02-09 08.16, Christian Witts wrote: > On 2012/02/09 08:15 AM, daedae11 wrote: >> import re >> re.match("^hello", "hello") >> re.match("hello", "hello") >> Please give a string that matches RE "^hello" but does not match RE >> "hello", or matches RE "hello" but does not match RE "^hello". >> ------------------------------------------------------------------------ >> daedae11 >> >> >> _______________________________________________ >> Tutor maillist -Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > The caret ^ means "At the beginning of the line" so 'And they said > hello' will not be matched by the regex pattern '^hello'. > > The docs are pretty good on the module > http://docs.python.org/library/re.html > http://docs.python.org/howto/regex.html > -- > > Christian Witts > Python Developer > This is also a good source of information for regexp patterns in general: http://www.regular-expressions.info/ G?ran T?rnquist Usertime -------------- next part -------------- An HTML attachment was scrubbed... URL: From krush1954 at yahoo.com Thu Feb 9 08:22:34 2012 From: krush1954 at yahoo.com (ken brockman) Date: Wed, 8 Feb 2012 23:22:34 -0800 (PST) Subject: [Tutor] (no subject) Message-ID: <1328772154.22880.YahooMailNeo@web39301.mail.mud.yahoo.com> ?Really close to it Robert. No delete but an error msg. Something akin to file dosen't exist, not found , or words to that effect . Something "akin to"? How about if you copy and paste the actual error message, instead of asking us to guess? Have?been?all afternoon' That means the full traceback, starting at the line "Traceback (most recent call last)" all the way to the end. I have been trying to post all?afternoon?to no avail. I keep getting bounced back...As per instructions from the list i have resubmitted my original request 20 times. Not sure of this one will get through either but here goes. As i had written 20 times before, the issue is resolved, as such no error msgs,?but?will try to?replicated?it, I seem pretty good at generating error msg.: Take 15: sigh,, def General_info(): file4 = open("Genfacts.p", "rb") Ginfo = pickle.load(file4) file4.close() print('General Information: ') GinfoKey = input('CatKey: ') GinfoFact = input('Info: ') Ginfo[GinfoKey] = GinfoFact # add new key:fact file4 = open("Genfacts.p", "wb") pickle.dump(Ginfo, file4) file4.close() return(Ginfo) thanks for the good folks who have tried to help. Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From krush1954 at yahoo.com Thu Feb 9 08:54:58 2012 From: krush1954 at yahoo.com (ken brockman) Date: Wed, 8 Feb 2012 23:54:58 -0800 (PST) Subject: [Tutor] general basic question Message-ID: <1328774098.2121.YahooMailNeo@web39302.mail.mud.yahoo.com> Really close to it Robert. No delete but an error msg. Something akin to file dosen't exist, not found , or words to that effect . Something "akin to"? I'm back on the list again, and if not too late, here is the asked for trace. ?i've managed to replicate the original error msg, by removing the pickled file Genfacts.p, from the directory. Traceback (most recent call last): File "/home/bob/Ninja/ArtyNOW2.py", line 120, in Ginfo = General_info() File "/home/bob/Ninja/ArtyNOW2.py", line 69, in General_info file4 = open("Genfacts.p", "rb") IOError: [Errno 2] No such file or directory: 'Genfacts.p' elif choice == "g": Ginfo = General_info() print('General Info is: ',Ginfo) # espeak routine General info text = 'General Info is ', Ginfo cmd = 'espeak -v en+f3 "{0}" 2>/dev/null'.format(text) os.system(cmd) elif choice == "p": # Alt. choice != "q": incase anything uexpectd inputed Thanks again Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Thu Feb 9 09:05:46 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 09 Feb 2012 10:05:46 +0200 Subject: [Tutor] What the difference between the two RE? In-Reply-To: <2012020915442644600514@126.com> References: <201202091415049115699@126.com>, <4F3372E0.8020304@compuscan.co.za> <2012020915442644600514@126.com> Message-ID: <4F337E5A.9080606@compuscan.co.za> On 2012/02/09 09:44 AM, daedae11 wrote: > However, re.match("hello", "And they said hello" ) will also return > None. So "And they said hello" also won't be matched by the regex > pattern "hello". > ------------------------------------------------------------------------ > daedae11 > *From:* Christian Witts > *Date:* 2012-02-09 15:16 > *To:* daedae11 > *CC:* turor_python > *Subject:* Re: [Tutor] What the difference between the two RE? > On 2012/02/09 08:15 AM, daedae11 wrote: >> import re >> re.match("^hello", "hello") >> re.match("hello", "hello") >> Please give a string that matches RE "^hello" but does not match RE >> "hello", or matches RE "hello" but does not match RE "^hello". >> ------------------------------------------------------------------------ >> daedae11 >> >> >> _______________________________________________ >> Tutor maillist -Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > The caret ^ means "At the beginning of the line" so 'And they said > hello' will not be matched by the regex pattern '^hello'. > > The docs are pretty good on the module > http://docs.python.org/library/re.html > http://docs.python.org/howto/regex.html > -- > > Christian Witts > Python Developer > // > > -- From the docs http://docs.python.org/library/re.html#re.match Note: If you want to locate a match anywhere in string, use search() instead. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From krush1954 at yahoo.com Thu Feb 9 09:07:44 2012 From: krush1954 at yahoo.com (ken brockman) Date: Thu, 9 Feb 2012 00:07:44 -0800 (PST) Subject: [Tutor] general simply question Message-ID: <1328774864.46965.YahooMailNeo@web39304.mail.mud.yahoo.com> Without sight of code it's only a guess but are you creating the file with the 'wb' mode - ie. write binary? :- myPickleFile = open("somefilename.dat", "wb") oops. Not as in object orientated?programming,?just?as in oops, i messed up.?pasted?wrong bit?of code. Here is the?relative?bit. def General_info(): file4 = open("Genfacts.p", "rb") Ginfo = pickle.load(file4) file4.close() print('General Information: ') GinfoKey = input('CatKey: ') GinfoFact = input('Info: ') Ginfo[GinfoKey] = GinfoFact # add new key:fact file4 = open("Genfacts.p", "wb") pickle.dump(Ginfo, file4) file4.close() return(Ginfo) Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Thu Feb 9 09:34:40 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 09 Feb 2012 10:34:40 +0200 Subject: [Tutor] =?gbk?q?=BB=D8=B8=B4=3A_Re=3A__What_the_difference_betwee?= =?gbk?q?n_the_two_RE=3F?= In-Reply-To: <2012020916175263163420@126.com> References: <201202091415049115699@126.com>, <4F3372E0.8020304@compuscan.co.za> <2012020915442644600514@126.com>, <4F337E5A.9080606@compuscan.co.za> <2012020916175263163420@126.com> Message-ID: <4F338520.1030002@compuscan.co.za> On 2012/02/09 10:17 AM, daedae11 wrote: > So doesn't it means the follow two sentences can achieve the same goal? > re.match("^hello", "hello") > re.match("hello", "hello") > ------------------------------------------------------------------------ > daedae11 > *????* Christian Witts > *?????* 2012-02-09 16:05 > *????* daedae11 ; tutor at python.org > > *???* Re: [Tutor] What the difference between the two RE? > On 2012/02/09 09:44 AM, daedae11 wrote: >> However, re.match("hello", "And they said hello" ) will also return >> None. So "And they said hello" also won't be matched by the regex >> pattern "hello". >> ------------------------------------------------------------------------ >> daedae11 >> *From:* Christian Witts >> *Date:* 2012-02-09 15:16 >> *To:* daedae11 >> *CC:* turor_python >> *Subject:* Re: [Tutor] What the difference between the two RE? >> On 2012/02/09 08:15 AM, daedae11 wrote: >>> import re >>> re.match("^hello", "hello") >>> re.match("hello", "hello") >>> Please give a string that matches RE "^hello" but does not match RE >>> "hello", or matches RE "hello" but does not match RE "^hello". >>> ------------------------------------------------------------------------ >>> daedae11 >>> >>> >>> _______________________________________________ >>> Tutor maillist -Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >> The caret ^ means "At the beginning of the line" so 'And they said >> hello' will not be matched by the regex pattern '^hello'. >> >> The docs are pretty good on the module >> http://docs.python.org/library/re.html >> http://docs.python.org/howto/regex.html >> -- >> >> Christian Witts >> Python Developer >> // >> >> -- > From the docs http://docs.python.org/library/re.html#re.match > Note: If you want to locate a match anywhere in string, use search() > instead. > -- > > Christian Witts > Python Developer > // > If your use case is that simple the caret is not needed as .match only searches from the start of the string to see if the pattern is there. If you need to look anywhere in your string for your pattern you should be using .search instead which if you do you can put the caret in if you just want to match if it's at the start. >>> import re >>> re.match('hello', 'hello there') <_sre.SRE_Match object at 0x02324528> >>> re.match('^hello', 'hello there') <_sre.SRE_Match object at 0x023243D8> >>> re.match('^hello', 'hi, hello there') >>> re.match('hello', 'hi, hello there') >>> re.search('hello', 'hi, hello there') <_sre.SRE_Match object at 0x02324528> >>> re.search('^hello', 'hi, hello there') >>> -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Feb 9 10:15:22 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 09 Feb 2012 10:15:22 +0100 Subject: [Tutor] bogus characters in a windows file References: <418AB33F-8998-47CE-8F83-E6DD40A2F572@newcastle.edu.au> Message-ID: Garry Willgoose wrote: > I input the data with the lines > > infile = open('c:\cpu.txt','r') > infile.readline() > infile.readline() > infile.readline() > > the readline()s yield the following output > > '\xff\xfeP\x00r\x00o\x00c\x00e\x00s\x00s\x00I\x00d\x00 \x00 \x00\r\x00\n' > '\x000\x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00\r\x00\n' > '\x004\x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00\r\x00\n' You were already told that you are trying to read a UTF-16-encoded file. Here's how to deal with that: >>> import codecs >>> with codecs.open("cpu.txt", "rU", encoding="UTF-16") as f: ... for line in f: ... print line.rstrip("\n") ... ProcessId 0 4 From andipersti at gmail.com Thu Feb 9 10:46:54 2012 From: andipersti at gmail.com (Andreas Perstinger) Date: Thu, 9 Feb 2012 10:46:54 +0100 Subject: [Tutor] general basic question In-Reply-To: <1328774098.2121.YahooMailNeo@web39302.mail.mud.yahoo.com> References: <1328774098.2121.YahooMailNeo@web39302.mail.mud.yahoo.com> Message-ID: <20120209104654.ccc91e00ea101add76ce445a@gmail.com> On Wed, 8 Feb 2012 23:54:58 -0800 (PST) ken brockman wrote: > I'm back on the list again, and if not too late, here is the asked > for trace. i've managed to replicate the original error msg, by > removing the pickled file Genfacts.p, from the directory. > Traceback (most recent call last): > File "/home/bob/Ninja/ArtyNOW2.py", line 120, in Ginfo = > General_info() > File "/home/bob/Ninja/ArtyNOW2.py", line 69, in General_info file4 = > open("Genfacts.p", "rb") > IOError: [Errno 2] No such file or directory: 'Genfacts.p' Because you have deleted "Genfacts.p" you are trying to open an non-existing file. So check if the file exists before opening it. Bye, Andreas From steve at pearwood.info Thu Feb 9 12:28:32 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 09 Feb 2012 22:28:32 +1100 Subject: [Tutor] (no subject) In-Reply-To: <1328772154.22880.YahooMailNeo@web39301.mail.mud.yahoo.com> References: <1328772154.22880.YahooMailNeo@web39301.mail.mud.yahoo.com> Message-ID: <4F33ADE0.4050402@pearwood.info> ken brockman wrote: > I have been trying to post all afternoon to no avail. I keep getting > bounced back... Ken, I don't suppose you have another email address that you sometimes use? Because if you do, that may be the problem. If you are subscribed to this list as krush1954 at yahoo.com, and you try to send to it using another email address, you will get bounced. The list software can only recognize you by your email address. > def General_info(): > file4 = open("Genfacts.p", "rb") This line above is the problem: it tries to open a file which may not exist. > Ginfo = pickle.load(file4) > file4.close() > print('General Information: ') > GinfoKey = input('CatKey: ') > GinfoFact = input('Info: ') > Ginfo[GinfoKey] = GinfoFact # add new key:fact > file4 = open("Genfacts.p", "wb") > pickle.dump(Ginfo, file4) > file4.close() > return(Ginfo) Try this instead: def General_info(): try: file4 = open("Genfacts.p", "rb") Ginfo = pickle.load(file4) file4.close() except IOError: # Either the file doesn't exist, or something more serious. # Assume the file doesn't exist. Ginfo = {} # Start with an empty dict. print('General Information: ') GinfoKey = input('CatKey: ') GinfoFact = input('Info: ') Ginfo[GinfoKey] = GinfoFact # add new key:fact file4 = open("Genfacts.p", "wb") pickle.dump(Ginfo, file4) file4.close() return Ginfo Note: Python experts will probably point out a whole bunch of things I did wrong in the above. That's deliberate: I didn't want to overload you with too many changes all at once. By the way, the shelve module is specifically designed to solve the problem you are trying to solve here: how to store key:value pairs on disk. Here's a version using shelve: import shelve def get_facts(): facts = shelve.open('facts.db', writeback=True) print('Please enter a fact: ') key = input('CatKey: ') value = input('Info: ') facts[key] = value # Make a copy for later use. d = {} d.update(facts) # Copy from facts --> d facts.close() return d Good luck! -- Steven From dcdavemail at gmail.com Thu Feb 9 12:31:47 2012 From: dcdavemail at gmail.com (David Craig) Date: Thu, 09 Feb 2012 11:31:47 +0000 Subject: [Tutor] How to make def where arguments are either stated when called or entered via raw_input Message-ID: <4F33AEA3.7000609@ucdconnect.ie> Hi, I'm trying to write a function that will either take arguments when the function is called, such as myFunc(x,y,z) or if the user does not enter any arguments, myFunc() the raw_input function will ask for them. But I dont know how to check how many arguments have been entered. My code is below. Anyone know how?? Thanks D def NoiseCorr(file1,file2,500,0.25,0.35): ####################################################################################### ### Check number of arguments ?????????????????? ####################################################################################### ### User inputs. if numArgs == 0: file1 = raw_input('Path to Station 1: ') file2 = raw_input('Path to Station 2: ') shift_length = raw_input('Length of Correlation: ') freqMin = raw_input('Min. Frequency: ') freqMax = raw_input('Max. Frequency: ') From steve at pearwood.info Thu Feb 9 12:36:40 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 09 Feb 2012 22:36:40 +1100 Subject: [Tutor] What the difference between the two RE? In-Reply-To: <201202091415049115699@126.com> References: <201202091415049115699@126.com> Message-ID: <4F33AFC8.3030001@pearwood.info> daedae11 wrote: > import re > re.match("^hello", "hello") > re.match("hello", "hello") > > Please give a string that matches RE "^hello" but does not match RE > "hello", or matches RE "hello" but does not match RE "^hello". re.match always matches the beginning of the string, so re.match("^hello", something) re.match("hello", something) are identical. re.search will search anywhere in the string, not just the beginning, so: re.search("^hello", something) means "find the beginning of the string followed by h e l l o" while re.search("hello", something) means "find h e l l o anywhere in the string". -- Steven From steve at pearwood.info Thu Feb 9 12:41:14 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 09 Feb 2012 22:41:14 +1100 Subject: [Tutor] How to make def where arguments are either stated when called or entered via raw_input In-Reply-To: <4F33AEA3.7000609@ucdconnect.ie> References: <4F33AEA3.7000609@ucdconnect.ie> Message-ID: <4F33B0DA.2020803@pearwood.info> David Craig wrote: > Hi, > I'm trying to write a function that will either take arguments when the > function is called, such as myFunc(x,y,z) or if the user does not enter > any arguments, myFunc() the raw_input function will ask for them. But I > dont know how to check how many arguments have been entered. My code is > below. Anyone know how?? Does this suit your requirements? def myFunc(x=None, y=None, z=None): if x is None: x = float( raw_input("Please enter a value for x: ") ) if y is None: y = float( raw_input("Please enter a value for y: ") ) if z is None: z = float( raw_input("Please enter a value for z: ") ) # do something with x, y, z I've assumed that you want float arguments. If not, change the calls to float to something else, or to leave them as strings, remove them altogether. -- Steven From __peter__ at web.de Thu Feb 9 12:51:01 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 09 Feb 2012 12:51:01 +0100 Subject: [Tutor] How to make def where arguments are either stated when called or entered via raw_input References: <4F33AEA3.7000609@ucdconnect.ie> Message-ID: David Craig wrote: > I'm trying to write a function that will either take arguments when the > function is called, such as myFunc(x,y,z) or if the user does not enter > any arguments, myFunc() the raw_input function will ask for them. But I > dont know how to check how many arguments have been entered. My code is > below. Anyone know how?? You either can use a star argument that causes the function to accept an arbitrary number of arguments which are put into a tuple >>> def f(*args): ... if not args: ... x = raw_input("x? ") ... y = raw_input("y? ") ... z = raw_input("z? ") ... else: ... x, y, z = args ... print "x=%r, y=%r, z=%r" % (x, y, z) ... >>> f() x? alpha y? beta z? gamma x='alpha', y='beta', z='gamma' >>> f(1, 2, 3) x=1, y=2, z=3 >>> f(1) Traceback (most recent call last): File "", line 1, in File "", line 7, in f ValueError: need more than 1 value to unpack or provide default values that cannot occur as normal input: >>> def f(x=None, y=None, z=None): ... if x is None: x = raw_input("x? ") ... if y is None: y = raw_input("y? ") ... if z is None: z = raw_input("z? ") ... print "x=%r, y=%r, z=%r" % (x, y, z) ... >>> f() x? one y? two z? three x='one', y='two', z='three' >>> f("ONE", z="THREE") y? two x='ONE', y='two', z='THREE' > def NoiseCorr(file1,file2,500,0.25,0.35): That's a syntax error. Try to be more careful about the code you are posting here. From brian.van.den.broek at gmail.com Thu Feb 9 12:55:03 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Thu, 9 Feb 2012 13:55:03 +0200 Subject: [Tutor] How to make def where arguments are either stated when called or entered via raw_input In-Reply-To: <4F33AEA3.7000609@ucdconnect.ie> References: <4F33AEA3.7000609@ucdconnect.ie> Message-ID: On 9 Feb 2012 13:34, "David Craig" wrote: > > Hi, > I'm trying to write a function that will either take arguments when the function is called, such as myFunc(x,y,z) or if the user does not enter any arguments, myFunc() the raw_input function will ask for them. But I dont know how to check how many arguments have been entered. My code is below. Anyone know how?? > Thanks > D > > > def NoiseCorr(file1,file2,500,0.25,0.35): > > ####################################################################################### > ### Check number of arguments > ?????????????????? > > ####################################################################################### > ### User inputs. > if numArgs == 0: > file1 = raw_input('Path to Station 1: ') > file2 = raw_input('Path to Station 2: ') > shift_length = raw_input('Length of Correlation: ') > freqMin = raw_input('Min. Frequency: ') > freqMax = raw_input('Max. Frequency: ') Hi David, >From your description, it doesn't sound as though you do need the number of arguments. Are you familiar with keyword args and default values? I would do it like so: def myfunc(x=None): if x is None: x=raw_input(a_prompt) expanding the arg list as needed. This also allows for callers to specify only some of the values. HTH, Brian vdB -------------- next part -------------- An HTML attachment was scrubbed... URL: From swiftone at swiftone.org Thu Feb 9 14:01:05 2012 From: swiftone at swiftone.org (Brett Ritter) Date: Thu, 9 Feb 2012 08:01:05 -0500 Subject: [Tutor] What the difference between the two RE? In-Reply-To: <201202091415049115699@126.com> References: <201202091415049115699@126.com> Message-ID: On Thu, Feb 9, 2012 at 1:15 AM, daedae11 wrote: > import re > re.match("^hello", "hello") > re.match("hello", "hello") > > Please give a string that matches RE "^hello"?but does not match RE "hello", > or matches RE "hello"?but does not match RE "^hello". In addition to the other answers, it's important to note that nothing in these REs require it to be a "word". So both of the above will match the "hello" in "hellonwheels" for example. -- Brett Ritter / SwiftOne swiftone at swiftone.org From ljmamoreira at gmail.com Thu Feb 9 16:36:15 2012 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Thu, 09 Feb 2012 15:36:15 +0000 Subject: [Tutor] two-dimensional color map Message-ID: <2793427.xWu8BiQvXH@mu.site> Hello I'm trying to plot a false-color map of a two dimensional function. My main problem is that the function I want to plot depends also on time, and I wish to show the plot as the function evolves, in real time. My first (and only, so far) idea on how to achieve this was to iterate the computation and the plot of the values of the function on a 2-D mesh for different times. Regarding the plot, I tried some options and the one that came closer to what I pretend is based on pylab (numpy and matplotlib, I guess), using the matshow() method. However, I found that the display of successive frames takes longer and longer. The following simple script shows this behaviour: -------------------- from matplotlib.pylab import * # Display a random matrix with a specified figure number for i in range(20): mymatrix = rand(864,864) fig = matshow(mymatrix,fignum=0) draw() quit = raw_input() #wait for user input before closing graphics window --------------------- So my questions are 1. Is matshow() appropriate for what I have in mind? 2. Am I using it correctly? 3. Are there better tools for plotting time-dependent 2D data using python? Thank you very much Ze Amoreira -------------- next part -------------- An HTML attachment was scrubbed... URL: From ljmamoreira at gmail.com Thu Feb 9 16:40:36 2012 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Thu, 09 Feb 2012 15:40:36 +0000 Subject: [Tutor] two-dimensional color map Message-ID: <1430646.GFZZCCiaJT@mu.site> I'm so, so sorry! When editing my script before posting it, I accidently deleted a line activating matplotlib interactive mode. The correct listing is the one below. Hello I'm trying to plot a false-color map of a two dimensional function. My main problem is that the function I want to plot depends also on time, and I wish to show the plot as the function evolves, in real time. My first (and only, so far) idea on how to achieve this was to iterate the computation and the plot of the values of the function on a 2-D mesh for different times. Regarding the plot, I tried some options and the one that came closer to what I pretend is based on pylab (numpy and matplotlib, I guess), using the matshow() method. However, I found that the display of successive frames takes longer and longer. The following simple script shows this behaviour: -------------------- from matplotlib.pylab import * ion() # Display a random matrix with a specified figure number for i in range(20): mymatrix = rand(864,864) fig = matshow(mymatrix,fignum=0) draw() quit = raw_input() #wait for user input before closing graphics window --------------------- So my questions are 1. Is matshow() appropriate for what I have in mind? 2. Am I using it correctly? 3. Are there better tools for plotting time-dependent 2D data using python? Thank you very much Ze Amoreira -------------- next part -------------- An HTML attachment was scrubbed... URL: From defensoft at gmail.com Thu Feb 9 16:45:35 2012 From: defensoft at gmail.com (Nate Lastname) Date: Thu, 9 Feb 2012 10:45:35 -0500 Subject: [Tutor] two-dimensional color map In-Reply-To: <1430646.GFZZCCiaJT@mu.site> References: <1430646.GFZZCCiaJT@mu.site> Message-ID: Have you considered pygame and its surfarray module? -------------- next part -------------- An HTML attachment was scrubbed... URL: From ljmamoreira at gmail.com Thu Feb 9 17:14:45 2012 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Thu, 09 Feb 2012 16:14:45 +0000 Subject: [Tutor] two-dimensional color map In-Reply-To: References: <1430646.GFZZCCiaJT@mu.site> Message-ID: <1589406.CMRSLW7O30@mu.site> On Thursday, February 09, 2012 10:45:35 AM Nate Lastname wrote: > Have you considered pygame and its surfarray module? Thanks, Nate. I haven't, but I will. Ze -------------- next part -------------- An HTML attachment was scrubbed... URL: From thudfoo at gmail.com Thu Feb 9 20:36:11 2012 From: thudfoo at gmail.com (xDog Walker) Date: Thu, 9 Feb 2012 11:36:11 -0800 Subject: [Tutor] PyQT GUI Threading example In-Reply-To: References: Message-ID: <201202091136.11640.thudfoo@gmail.com> On Wednesday 2012 February 08 06:46, R.S. wrote: > I can't find any full example of threading with many threads working and > updating GUI (precisely i need QTreeWidget). I can only find: not updating > GUI examples, updating GUI examples with one thread. But i just can't find > what i need. Could anyone share working example with many threads updating > GUI like for example connecting to several www sites and adding the > response in a list on QTreeWidget? You might have better luck asking on pyGUI's mailing list: http://mail.python.org/mailman/listinfo/pygui -- I have seen the future and I am not in it. From tmikk at umn.edu Thu Feb 9 20:23:43 2012 From: tmikk at umn.edu (Tonu Mikk) Date: Thu, 9 Feb 2012 13:23:43 -0600 Subject: [Tutor] exercise with classes In-Reply-To: <4F3022BE.2000608@davea.name> References: <4F3022BE.2000608@davea.name> Message-ID: On Mon, Feb 6, 2012 at 12:58 PM, Dave Angel wrote: > On 02/06/2012 01:24 PM, Tonu Mikk wrote: > >> Now I get an error: NameError: global name 'self' is not define. >> >> Tonu >> >> >> Put your remarks after the stuff you quote. You're top-posting, which > makes the reply difficult to follow. > > Use copy/paste to describe an error message. You retyped the one above, > and added a typo. Include the whole error, which includes the stack trace. > > If you had followed Nate's advice, you couldn't have gotten that error at > all, so you'll also need to post the code that actually triggers the error. Let's try this one more time. I thought that I would try to make Alan's code work. Here is the version what I have now: class Printer: def __init__(self,number=0): self.value = number def sayIt(self): print self.value class MyApp: def __init__(self, aPrinter = None): if aPrinter == None: # if no object passed create one aPrinter = Printer() self.obj = aPrinter # assign object def doIt(): self.obj.sayIt() # use object def test(): p = Printer(42) a1 = MyApp() a2 = MyApp(p) # pass p object into a2 a1.doIt(self) # prints default value = 0 a2.doIt(self) # prints 42, the value of p test() When I run it, I get an error: Traceback (most recent call last): File "alan_class.py", line 22, in test() File "alan_class.py", line 19, in test a1.doIt(self) # prints default value = 0 NameError: global name 'self' is not defined > > > > > > > -- > > DaveA > > -- Tonu Mikk Disability Services, Office for Equity and Diversity 612 625-3307 tmikk at umn.edu -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Thu Feb 9 20:53:10 2012 From: d at davea.name (Dave Angel) Date: Thu, 09 Feb 2012 14:53:10 -0500 Subject: [Tutor] exercise with classes In-Reply-To: References: <4F3022BE.2000608@davea.name> Message-ID: <4F342426.9070802@davea.name> On 02/09/2012 02:23 PM, Tonu Mikk wrote: > On Mon, Feb 6, 2012 at 12:58 PM, Dave Angel wrote: > >> On 02/06/2012 01:24 PM, Tonu Mikk wrote: >> >>> Now I get an error: NameError: global name 'self' is not define. >>> >>> Tonu >>> >>> >>> Put your remarks after the stuff you quote. You're top-posting, which >> makes the reply difficult to follow. >> >> Use copy/paste to describe an error message. You retyped the one above, >> and added a typo. Include the whole error, which includes the stack trace. >> >> If you had followed Nate's advice, you couldn't have gotten that error at >> all, so you'll also need to post the code that actually triggers the error. > > > Let's try this one more time. I thought that I would try to make Alan's > code work. Here is the version what I have now: > > class Printer: > def __init__(self,number=0): > self.value = number > def sayIt(self): > print self.value > > class MyApp: > def __init__(self, aPrinter = None): > if aPrinter == None: # if no object passed create one > aPrinter = Printer() > self.obj = aPrinter # assign object > def doIt(): > self.obj.sayIt() # use object > > def test(): > p = Printer(42) > a1 = MyApp() > a2 = MyApp(p) # pass p object into a2 > a1.doIt(self) # prints default value = 0 > a2.doIt(self) # prints 42, the value of p > > test() > > When I run it, I get an error: > Traceback (most recent call last): > File "alan_class.py", line 22, in > test() > File "alan_class.py", line 19, in test > a1.doIt(self) # prints default value = 0 > NameError: global name 'self' is not defined > > Very good. Now I can see the problem(s). The immediate problem is that inside function test() (which is an ordinary function, not a method), you refer to self, which is not defined there. just omit it there (both times), since the "self" value will automatically be supplied when you use the a1.doIt() syntax. Which takes me to the next problem. You've defined a method inside class MyApp, without supplying the self parameter. All methods of a class will have a 'self' parameter as the first argument (until you get to classmethod and staticmethod, which come much later in your learning). You have it everywhere else, but not here. This is admittedly a confusing aspect of class programming in Python. When you call a method, you do not supply an explicit self, it's implied by the object you used to get that method. And in the method, you do have to declare an explicit self as the first parameter. Thus when you get error messages, the compiler's concept of how many arguments there are, and how many there should be, is confusing. Trust me when I say there are reasons why this should be, having to do with passing bound methods around. But at this point of your learning, it's a confusion with no obvious benefit. Without trying it, here's what I think those two portions of coee should look like: class MyApp: ..... def doIt(self): self.obj.sayIt() # use object def test(): p = Printer(42) a1 = MyApp() a2 = MyApp(p) # pass p object into a2 a1.doIt() # prints default value = 0 a2.doIt() # prints 42, the value of p -- DaveA From joel.goldstick at gmail.com Thu Feb 9 20:59:53 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 9 Feb 2012 14:59:53 -0500 Subject: [Tutor] exercise with classes In-Reply-To: References: <4F3022BE.2000608@davea.name> Message-ID: On Thu, Feb 9, 2012 at 2:23 PM, Tonu Mikk wrote: > > > On Mon, Feb 6, 2012 at 12:58 PM, Dave Angel wrote: >> >> On 02/06/2012 01:24 PM, Tonu Mikk wrote: >>> >>> Now I get an error: ?NameError: global name 'self' is not define. >>> >>> Tonu >>> >>> >> Put your remarks after the stuff you quote. ?You're top-posting, which >> makes the reply difficult to follow. >> >> Use copy/paste to describe an error message. ?You retyped the one above, >> and added a typo. ?Include the whole error, which includes the stack trace. >> >> If you had followed Nate's advice, you couldn't have gotten that error at >> all, so you'll also need to post the code that actually triggers the error. > > > Let's try this one more time. ?I thought that I would try to make Alan's > code work. ?Here is the version what I have now: > > class Printer: > ? def __init__(self,number=0): > ? ? ?self.value = number > ? def sayIt(self): > ? ? ?print self.value > > class MyApp: > ? def __init__(self, aPrinter = None): > ? ? ? if aPrinter == None: ? ? # if no object passed create one > ? ? ? ? ?aPrinter = Printer() > ? ? ? self.obj = aPrinter ? ? ?# assign object > ? def doIt(): > ? ? ? self.obj.sayIt() ? ? ? ? # use object > > def test(): > ? p = Printer(42) > ? a1 = MyApp() > ? a2 = MyApp(p) ? # pass p object into a2 > ? a1.doIt(self) ? # prints default value = 0 > ? a2.doIt(self) ? # prints 42, the value of p I haven't run this, but I think this is what is going on here: When you make the call to the method you don't include self. You have no self variable in your namespace, so it throws the error. However, when you write a method in a class, you need to declare the first argument self (its a convention to call it self. You could call it 'me', or anything -- but don't). self is the object itself. So do this: a1.doIt() a2.doIt() Alternately you could do this: MyApp.doIt(a1) In this case you are saying use the object a1 which is of the MyApp Class. But this looks weird > > test() > > When I run it, I get an error: > Traceback (most recent call last): > ? File "alan_class.py", line 22, in > ? ? test() > ? File "alan_class.py", line 19, in test > ? ? a1.doIt(self) ? # prints default value = 0 > NameError: global name 'self' is not defined > > >> >> >> >> >> >> >> >> -- >> >> DaveA >> > > > > -- > Tonu Mikk > Disability Services, Office for Equity and Diversity > 612 625-3307 > tmikk at umn.edu > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick From Garry.Willgoose at newcastle.edu.au Thu Feb 9 21:57:40 2012 From: Garry.Willgoose at newcastle.edu.au (Garry Willgoose) Date: Fri, 10 Feb 2012 07:57:40 +1100 Subject: [Tutor] bogus characters in a windows file In-Reply-To: <4F332CBE.4080704@davea.name> References: <418AB33F-8998-47CE-8F83-E6DD40A2F572@newcastle.edu.au> <4F332CBE.4080704@davea.name> Message-ID: <4374C86B-0CBE-49EB-BFB3-29304E99B762@newcastle.edu.au> > >> I'm reading a file output by the system utility WMIC in windows (so I can track CPU usage by process ID) and the text file WMIC outputs seems to have extra characters in I've not seen before. >> >> I use os.system('WMIC /OUTPUT:c:\cpu.txt PROCESS GET ProcessId') to output the file and parse file c:\cpu.txt > > First mistake. If you use backslash inside a python literal string, you need to do one of two things: > 1) use a raw string > 2) double the backslash > It so happens that \c is not a python escape sequence, so you escaped this particular bug. Lucked out on that one ... slipped under my radar. I was just cutting and pasting some code from the documentation to WMIC ;-) > >> The first few lines of the file look like this in notepad >> >> ProcessId >> 0 >> 4 >> 568 >> 624 >> 648 >> >> >> I input the data with the lines >> >> infile = open('c:\cpu.txt','r') > Same thing. You should either make it r'c:\cpu.txt' or 'c:\\cpu.txt' or even 'c:/cpu.txt' >> infile.readline() >> infile.readline() >> infile.readline() >> > OK, so you throw away the first 3 lines of the file. > >> the readline()s yield the following output >> >> '\xff\xfeP\x00r\x00o\x00c\x00e\x00s\x00s\x00I\x00d\x00 \x00 \x00\r\x00\n' >> '\x000\x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00\r\x00\n' >> '\x004\x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00\r\x00\n' >> > Now, how did you get those bytes displayed; they've already been thrown out. Simple run the readline() commands at the command line and python interpreter prompt (or IDLE if you like). The results are not thrown away ... they are echoed to the screen. >> Now for the first line the title 'ProcessId' is in this string but the individual characters are separated by '\x00' and at least for the first line of the file there is an extra '\xff\xfe'. For subsequent its just '\x00. Now I can just replace the '\x**' with '' but that seems a bit inelegant. I've tried various options on the open 'rU' and 'rb' but no effect. >> >> Does anybody know what the rubbish characters are and what has caused the. I'm using the latest Enthought python if that matters. > It matters, but it'd save each of us lots of trouble if you told us what version that was; especially which version of Python. The latest Enthought I see is called EPD 7.2. But after 10 minutes on the site, I can't see whether there actually is a Python on there or not. it seems to be just a bunch of libraries for Python. But whether they're for CPython, IronPython, or something else, who knows? My fault. Its Python 2.7.1 ... Ipython interpreter. > > > I don't see any rubbish characters. What I see is some unicode strings, displayed as though they were byte strings. the first two bytes are the BOM code, commonly put at the beginning of a file encoded in UTF-16. The remaining pairs of bytes are UTF-16 encodings for ordinary characters. Notepad would recognize the UTF-16 encoding, and display the characters correctly. Perhaps you need to do the same. Yes well this was the insight I was after. At one stage I was using a distribution compiled for Unicode (so I'm guessing I would have never seen this problem then) but it seems like the last distribution from Enthought is non-Unicode (I've sent them an email to confirm this ... but thats what it looks like). This is the first time I've explicitly faced Unicode input from a text file so the \x00 stuff was unfamiliar with the details of how it works and displays itself in a normal string. Mostly I've seen them in python as u'string' and never paid much attention (unless I passed them as a file name to open() ... when they caused all sorts of grief until I realised I needed to change their type to str with str()) Since this is one-off to get one of my PhD students out of hole I might just filter out the \x** characters explicitly since the remainder looks OK. As background the reason for this is to manage a stand-alone science code developed elsewhere to ensure that CPU usage doesn't go out of control. We're doing thousands of runs with this code (monte-carlo simulation), launching the code for each simulation with os.system() and occasionally a simulation goes into an infinite loop, which stalls the monte-carlo so we just want to be able to kill that simulation and go to the next one. WE do this sort of stuff on *NIX all the time using the unix command 'ps' but because the executable we need to use is somebody else's we are stuck on Windows ... and WMIC looks the easiest, quickest way to achieve this sort of process control on Windows. If anybody has any other ideas how to do this direct from python that might be platform independent (being able to set some CPU limits on a popen call for instance) I'd be interested but looking on the web most of the solutions look rather difficult. ==================================================================== Prof Garry Willgoose, Director, Centre for Climate Impact Management (C2IM), Head of Discipline, Discipline of Civil Surveying and Environmental Engineering, School of Engineering, The University of Newcastle, Callaghan, 2308 Australia. C2IM webpage: www.c2im.org.au Phone: (International) +61 2 4921 6050 (Tues-Thurs); +61 2 6545 9574 (Mon, Fri) FAX: (International) +61 2 4921 6991 Env. Engg. Secretary: (International) +61 2 4921 6042 email: garry.willgoose at newcastle.edu.au (uni); g.willgoose at telluricresearch.com (personal, consulting) email-for-life: garry.willgoose at alum.mit.edu personal webpage: www.telluricresearch.com/garry ==================================================================== "Do not go where the path may lead, go instead where there is no path and leave a trail" Ralph Waldo Emerson ==================================================================== From bgailer at gmail.com Thu Feb 9 23:32:03 2012 From: bgailer at gmail.com (bob gailer) Date: Thu, 09 Feb 2012 17:32:03 -0500 Subject: [Tutor] Ongoing problems with Pam's new computer Message-ID: <4F344963.7020000@gmail.com> Today is the third time Pam (connecting to the web site for event publication) has run into an inexplicable Access error. Error 430 Class does not support Automation or does not support expected interface. H have googled this error. None of the explanations I found relate in any way to what I see in the code. Twice now I have "repaired the program" (by removing perfectly valid code that runs fine on other computers). I won't do that again. I deem there is a problem with her computer or the Access installation. Therefore I bring this to Sarai's attention. I recommend Pam use another computer to publish events. -- Bob Gailer 919-636-4239 Chapel Hill NC From bgailer at gmail.com Thu Feb 9 23:43:23 2012 From: bgailer at gmail.com (bob gailer) Date: Thu, 09 Feb 2012 17:43:23 -0500 Subject: [Tutor] Character Buffer Object Error In-Reply-To: References: <4F3280F4.1040709@gmail.com> Message-ID: <4F344C0B.5050904@gmail.com> Always reply-all so a copy goes to the tutor list. On 2/8/2012 11:04 PM, Michael Lewis wrote: > Thanks Bob, Thanks for what if you did not follow my suggestions? Your code is still pretty buggy. Please test it by running it, seeing that the result is not correct, then try the desk checking. > > The below code is what I came up with without using your suggestion. > On a scale, how novice is mine compared to what you offered? I am > curious because I want to know if I should have come up with your > solution instead of what I did come up with. > > def AlterInput(user_input): > '''search for nums in str and increment/append, return new string''' > new_output = [] > for num in user_input: > if not num.isdigit(): > new_output.append(num) > else: > num.isdigit() > new_num = int(num) > new_num += 1 > new_output.append(str(new_num)) > return ' '.join(new_output) > > def GetUserInput(): > '''Get a string from the user and pass it''' > user_input = '''I * got 432 when I counted, but Jim got 433 which > is a lot for only 6 cats, or were there 12 cats?''' > return AlterInput(user_input.split()) > > > Your code: > > return ' '.join(str(int(num)+1) if num.isdigit() else num for num in > user_input) > > On Wed, Feb 8, 2012 at 6:04 AM, bob gailer > wrote: > > On 2/8/2012 12:56 AM, Michael Lewis wrote: > > I want to find all digits in a string and then increment those > digits by 1 and then return the same string with the > incremented digits. > > [snip] > > You got lots of good advice from others and some not-so-good advice. > > > Michael said: > 2. The following line appears wrong. > new_output = ' '.join(user_input) > He did not say why! > > > I add: > > Master the art of "Desk Checking". > > Take pencil & paper. > > Write down the input and output of each statement as though you > were the computer. > > > Also learn to read the & understand the Python Manuals: > > str.replace(old, new[, count]) > Return a copy of the string with all occurrences of substring old > replaced by new. If the optional argument count is given, only the > first count occurrences are replaced. > > Notice "return a copy". It does NOT say that this will convert old > in place. > > No one else caught this problem! > > Since this is homework we we probably should not be offering > alternative solutions. > > However I can't resist offering the one-line solution: > > ''.join(str(int(x)+1) if x.isdigit() else x for x in 'user_input) > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Feb 9 23:49:33 2012 From: bgailer at gmail.com (bob gailer) Date: Thu, 09 Feb 2012 17:49:33 -0500 Subject: [Tutor] Character Buffer Object Error OOPS In-Reply-To: References: <4F3280F4.1040709@gmail.com> Message-ID: <4F344D7D.8000304@gmail.com> On 2/8/2012 11:04 PM, Michael Lewis wrote: > Thanks Bob, My Bad - I did not examine all your code - I broke my own rule. Your code is still a little buggy. > The below code is what I came up with without using your suggestion. > On a scale, how novice is mine compared to what you offered? I am > curious because I want to know if I should have come up with your > solution instead of what I did come up with. Since you are studying Python you do well to apply what you learn. The first objective is to get something that works. As you learn more you then apply new techniques. When you have learned conditional expressions, list comprehensions and generator expressions then you will be able to write the code I did. That code is just an alternative to what you wrote, "flattening it" as it were. [snip] -- Bob Gailer 919-636-4239 Chapel Hill NC From mjolewis at gmail.com Thu Feb 9 23:59:07 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Thu, 9 Feb 2012 14:59:07 -0800 Subject: [Tutor] Character Buffer Object Error In-Reply-To: <4F344C0B.5050904@gmail.com> References: <4F3280F4.1040709@gmail.com> <4F344C0B.5050904@gmail.com> Message-ID: On Thu, Feb 9, 2012 at 2:43 PM, bob gailer wrote: > Always reply-all so a copy goes to the tutor list. > > On 2/8/2012 11:04 PM, Michael Lewis wrote: > > Thanks Bob, > > Thanks for what if you did not follow my suggestions? > I partially followed your suggestions by getting rid of str.replace(old, new[, count]) and new_output = ' '.join(user_input). But I also wanted to try to get this to work without simply copying your code. > > Your code is still pretty buggy. > I don't think I made my intentions clear. I don't wont to increment each digit. I want to find each number (for example, if the str contains 436, I don't want to interpret that as 4, 3, 6 - I instead want to interpret that as 436, which is why I created a list and then joined back into a string afterwards. > > Please test it by running it, seeing that the result is not correct, then > try the desk checking. > I don't see how this is not correct, because my input was > > I got 432 when I counted, but Jim got 433 which > is a lot for only 6 cats, or were there 12 cats? > And my output was: I got 433 when I counted, but Jim got 434 which is a lot for only 7 cats, or were there 13 cats? > The below code is what I came up with without using your suggestion. > On a scale, how novice is mine compared to what you offered? I am curious > because I want to know if I should have come up with your solution instead > of what I did come up with. > > def AlterInput(user_input): > '''search for nums in str and increment/append, return new string''' > new_output = [] > for num in user_input: > if not num.isdigit(): > new_output.append(num) > else: > num.isdigit() > new_num = int(num) > new_num += 1 > new_output.append(str(new_num)) > return ' '.join(new_output) > > def GetUserInput(): > '''Get a string from the user and pass it''' > user_input = '''I * got 432 when I counted, but Jim got 433 which > is a lot for only 6 cats, or were there 12 cats?''' > return AlterInput(user_input.split()) > > > Your code: > > return ' '.join(str(int(num)+1) if num.isdigit() else num for num in > user_input) > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Feb 10 00:56:42 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 10 Feb 2012 10:56:42 +1100 Subject: [Tutor] Ongoing problems with Pam's new computer In-Reply-To: <4F344963.7020000@gmail.com> References: <4F344963.7020000@gmail.com> Message-ID: <4F345D3A.1050101@pearwood.info> bob gailer wrote: > Today is the third time Pam (connecting to the web site for event > publication) has run into an inexplicable Access error. I don't think this has anything to do with learning Python. -- Steven From bgailer at gmail.com Fri Feb 10 01:48:21 2012 From: bgailer at gmail.com (bob gailer) Date: Thu, 09 Feb 2012 19:48:21 -0500 Subject: [Tutor] Ongoing problems with Pam's new computer In-Reply-To: <4F345D3A.1050101@pearwood.info> References: <4F344963.7020000@gmail.com> <4F345D3A.1050101@pearwood.info> Message-ID: <4F346955.6010505@gmail.com> On 2/9/2012 6:56 PM, Steven D'Aprano wrote: > bob gailer wrote: >> Today is the third time Pam (connecting to the web site for event >> publication) has run into an inexplicable Access error. > > > I don't think this has anything to do with learning Python. > > You are right. I was surprised to discover I had entered the wrong email address. Sorry for any confusion or pollution. -- Bob Gailer 919-636-4239 Chapel Hill NC From lowelltackett at yahoo.com Fri Feb 10 06:14:58 2012 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Thu, 9 Feb 2012 21:14:58 -0800 (PST) Subject: [Tutor] Ongoing problems with Pam's new computer In-Reply-To: <4F346955.6010505@gmail.com> References: <4F344963.7020000@gmail.com> <4F345D3A.1050101@pearwood.info> <4F346955.6010505@gmail.com> Message-ID: <1328850898.90839.YahooMailNeo@web110103.mail.gq1.yahoo.com> Doggonit!? I was half-way thru a really cool Python solution, too! From the virtual desk of Lowell Tackett? ________________________________ From: bob gailer To: tutor at python.org Sent: Thursday, February 9, 2012 7:48 PM Subject: Re: [Tutor] Ongoing problems with Pam's new computer On 2/9/2012 6:56 PM, Steven D'Aprano wrote: > bob gailer wrote: >> Today is the third time Pam (connecting to the web site for event publication) has run into an inexplicable Access error. > > > I don't think this has anything to do with learning Python. > > You are right. I was surprised to discover I had entered the wrong email address. Sorry for any confusion or pollution. -- Bob Gailer 919-636-4239 Chapel Hill NC _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From daedae11 at 126.com Fri Feb 10 13:48:03 2012 From: daedae11 at 126.com (daedae11) Date: Fri, 10 Feb 2012 20:48:03 +0800 Subject: [Tutor] Where can I download the document for twisted? Message-ID: <201202102048031399952@126.com> Where can I download the document for twisted? I could't find it on twistedmatrix.com . daedae11 -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Fri Feb 10 14:01:59 2012 From: wprins at gmail.com (Walter Prins) Date: Fri, 10 Feb 2012 13:01:59 +0000 Subject: [Tutor] Where can I download the document for twisted? In-Reply-To: <201202102048031399952@126.com> References: <201202102048031399952@126.com> Message-ID: On 10 February 2012 12:48, daedae11 wrote: > Where?can?I?download?the?document?for?twisted? I could't find it on > twistedmatrix.com . Umm, click on the "Doc" link, top right of the page you listed? (The page includes a link to a PDF version of the developer guide...) Walter From cwitts at compuscan.co.za Fri Feb 10 14:10:02 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 10 Feb 2012 15:10:02 +0200 Subject: [Tutor] Where can I download the document for twisted? In-Reply-To: <201202102048031399952@126.com> References: <201202102048031399952@126.com> Message-ID: <4F35172A.1090801@compuscan.co.za> On 2012/02/10 02:48 PM, daedae11 wrote: > Where can I download the document for twisted? I could't find it on > twistedmatrix.com . > ------------------------------------------------------------------------ > daedae11 > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor There a link to "The complete developer guide in PDF Format" on http://twistedmatrix.com/trac/wiki/Documentation -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From daedae11 at 126.com Fri Feb 10 15:12:49 2012 From: daedae11 at 126.com (daedae11) Date: Fri, 10 Feb 2012 22:12:49 +0800 Subject: [Tutor] Question about an example in Python doc Message-ID: <2012021022124912487013@126.com> The example is the third example in (Python2.7's doc)->(Python Library Reference)->17.2.2. The code of the example is: import socket # the public network interface HOST = socket.gethostbyname(socket.gethostname()) # create a raw socket and bind it to the public interface s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) s.bind((HOST, 0)) # Include IP headers s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # receive all packages s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) # receive a package print s.recvfrom(65565) # disabled promiscuous mode s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) However, when I run it, the interpreter show the following error: Traceback (most recent call last): File "E:\c language\Eclipse\example\src\sniffer.py", line 12, in s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) File "D:\Python27\lib\socket.py", line 187, in __init__ _sock = _realsocket(family, type, proto) socket.error: [Errno 10013] What's the matter? daedae11 -------------- next part -------------- An HTML attachment was scrubbed... URL: From mylesbroomes at hotmail.co.uk Fri Feb 10 15:13:52 2012 From: mylesbroomes at hotmail.co.uk (myles broomes) Date: Fri, 10 Feb 2012 14:13:52 +0000 Subject: [Tutor] Dictionaries Message-ID: Ive been given a challenge in the book im learning Python from and its basically create a program with a dictionary of father - son pairs and allow the user to add, replace and delete pairs. Ive done that without any problems but ive been giving another challenge where I have to improve the previous program by adding a choice that lets the user enter a name and get back a grandfather. The program should still only use one dictionary of father-son pairs and finally I have to make sure to include several generations in your dictionary so that a match can be found. Im not sure I fully understand the task because surely its only possible to have one key and one value per pair but the challenge seems to want me to have a key (for the father), a value (for the son) and then something else (for the grandfather). Is this actually possible? Or am I just misinterpreting the challenge? Myles Broomes -------------- next part -------------- An HTML attachment was scrubbed... URL: From tvssarma.omega9 at gmail.com Fri Feb 10 15:31:31 2012 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Fri, 10 Feb 2012 20:01:31 +0530 Subject: [Tutor] Dictionaries In-Reply-To: References: Message-ID: On 10 Feb 2012 19:45, "myles broomes" wrote: > > Ive been given a challenge in the book im learning Python from and its basically create a program with a dictionary of father - son pairs and allow the user to add, replace and delete pairs. Ive done that without any problems but ive been giving another challenge where I have to improve the previous program by adding a choice that lets the user enter a name and get back a grandfather. The program should still only use one dictionary of father-son pairs and finally I have to make sure to include several generations in your dictionary so that a match can be found. Im not sure I fully understand the task because surely its only possible to have one key and one value per pair but the challenge seems to want me to have a key (for the father), a value (for the son) and then something else (for the grandfather). Is this actually possible? Or am I just misinterpreting the challenge? > > > Myles Broomes > I don't think the task is asking you to modify the exisiting dictionary and that its aim is to have you modify the way you search the dictionary. -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Fri Feb 10 15:33:07 2012 From: d at davea.name (Dave Angel) Date: Fri, 10 Feb 2012 09:33:07 -0500 Subject: [Tutor] Dictionaries In-Reply-To: References: Message-ID: <4F352AA3.1040906@davea.name> On 02/10/2012 09:13 AM, myles broomes wrote: > Ive been given a challenge in the book im learning Python from and its basically create a program with a dictionary of father - son pairs and allow the user to add, replace and delete pairs. Ive done that without any problems but ive been giving another challenge where I have to improve the previous program by adding a choice that lets the user enter a name and get back a grandfather. The program should still only use one dictionary of father-son pairs and finally I have to make sure to include several generations in your dictionary so that a match can be found. Im not sure I fully understand the task because surely its only possible to have one key and one value per pair but the challenge seems to want me to have a key (for the father), a value (for the son) and then something else (for the grandfather). Is this actually possible? Or am I just misinterpreting the challenge? > > Myles Broomes > > Some sample code would be good. Can I assume that in your dictionary, the key is the son's name, and the value is the father's name? if so, then a grandfather is simply a father's father. So your challenge is to see how you might get that by doing multiple lookups in the dictionary, not by changing it at all. -- DaveA From wprins at gmail.com Fri Feb 10 15:33:37 2012 From: wprins at gmail.com (Walter Prins) Date: Fri, 10 Feb 2012 14:33:37 +0000 Subject: [Tutor] Question about an example in Python doc In-Reply-To: <2012021022124912487013@126.com> References: <2012021022124912487013@126.com> Message-ID: Hi, On 10 February 2012 14:12, daedae11 wrote: > Traceback?(most?recent?call?last): > ??File?"E:\c?language\Eclipse\example\src\sniffer.py",?line?12,?in? > ????s?=?socket.socket(socket.AF_INET,?socket.SOCK_RAW,?socket.IPPROTO_IP) > ??File?"D:\Python27\lib\socket.py",?line?187,?in?__init__ > ????_sock?=?_realsocket(family,?type,?proto) > socket.error:?[Errno?10013] A bit of googling suggests that "ErrNo 10013" means "Access denied". The error therefore presumably results because raw sockets require elevated (Administrator) privileges. The documentation you're referring to actually states as much: "The last example shows how to write a very simple network sniffer with raw sockets on Windows. The example requires administrator privileges to modify the interface:" So I conclude you need to run your script as administrator (and apparently have not done so above.) Walter From hugo.yoshi at gmail.com Fri Feb 10 15:37:21 2012 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 10 Feb 2012 15:37:21 +0100 Subject: [Tutor] Question about an example in Python doc In-Reply-To: <2012021022124912487013@126.com> References: <2012021022124912487013@126.com> Message-ID: On Fri, Feb 10, 2012 at 3:12 PM, daedae11 wrote: > The example is the third example in (Python2.7's doc)->(Python Library > Reference)->17.2.2. > The code of the example is: > > import?socket > > #?the?public?network?interface > HOST?=?socket.gethostbyname(socket.gethostname()) > > #?create?a?raw?socket?and?bind?it?to?the?public?interface > s?=?socket.socket(socket.AF_INET,?socket.SOCK_RAW,?socket.IPPROTO_IP) > s.bind((HOST,?0)) > > #?Include?IP?headers > s.setsockopt(socket.IPPROTO_IP,?socket.IP_HDRINCL,?1) > > #?receive?all?packages > s.ioctl(socket.SIO_RCVALL,?socket.RCVALL_ON) > > #?receive?a?package > print?s.recvfrom(65565) > > #?disabled?promiscuous?mode > s.ioctl(socket.SIO_RCVALL,?socket.RCVALL_OFF) > > > However, when I run it, the interpreter show the following error: > > Traceback?(most?recent?call?last): > ??File?"E:\c?language\Eclipse\example\src\sniffer.py",?line?12,?in? > ????s?=?socket.socket(socket.AF_INET,?socket.SOCK_RAW,?socket.IPPROTO_IP) > ??File?"D:\Python27\lib\socket.py",?line?187,?in?__init__ > ????_sock?=?_realsocket(family,?type,?proto) > socket.error:?[Errno?10013] > That's very strange, because when I run it, the interpreter shows the following error: Traceback (most recent call last): File "C:/Users/hugo/Downloads/test.py", line 7, in s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) File "C:\Python27\lib\socket.py", line 187, in __init__ _sock = _realsocket(family, type, proto) error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions >>> Which is identical to yours, but includes a helpful message telling you what is wrong. Did you not get that message, or did you just paste it wrong? In any case, Walter got you the solution. HTH, Hugo From wprins at gmail.com Fri Feb 10 15:38:27 2012 From: wprins at gmail.com (Walter Prins) Date: Fri, 10 Feb 2012 14:38:27 +0000 Subject: [Tutor] Dictionaries In-Reply-To: References: Message-ID: Hi Myles, On 10 February 2012 14:13, myles broomes wrote: > Ive been given a challenge in the book im learning Python from and its > basically create a program with a dictionary of father - son pairs and allow > the user to add, replace and delete pairs. Ive done that without any > problems but ive been giving another challenge where I have to improve the > previous program by adding a choice that lets the user enter?a name and get > back a grandfather. The program should still only use one dictionary of > father-son pairs and finally I have to make sure to include several > generations in your dictionary so that a match can be found. Im not sure I > fully understand the task because surely its only possible to have one key > and one value per pair but the challenge seems to want me to have a key (for > the father), a value (for the son) and then something else (for the > grandfather). Is this actually possible? Or am I just misinterpreting the > challenge? Sarma is correct. I'd like to add: Suppose you had a table with 2 columns, the first listing sons, the second their fathers. And suppose someone asked you to find the grandfather of someone. How would *you* go about finding the answer to this question, using the table? What steps would you execute? If you can come up with an explanation to my question, then your job is to translate this solution into Python, but using your existing dictionary instead of the table. HTH, Walter From breamoreboy at yahoo.co.uk Fri Feb 10 15:42:46 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 10 Feb 2012 14:42:46 +0000 Subject: [Tutor] Dictionaries In-Reply-To: References: Message-ID: On 10/02/2012 14:13, myles broomes wrote: > > Ive been given a challenge in the book im learning Python from and its basically create a program with a dictionary of father - son pairs and allow the user to add, replace and delete pairs. Ive done that without any problems but ive been giving another challenge where I have to improve the previous program by adding a choice that lets the user enter a name and get back a grandfather. The program should still only use one dictionary of father-son pairs and finally I have to make sure to include several generations in your dictionary so that a match can be found. Im not sure I fully understand the task because surely its only possible to have one key and one value per pair but the challenge seems to want me to have a key (for the father), a value (for the son) and then something else (for the grandfather). Is this actually possible? Or am I just misinterpreting the challenge? > > Myles Broomes > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Take a look at this http://www.daniweb.com/software-development/python/code/217019 and think about it in relation to the replies you've already had. -- Cheers. Mark Lawrence. From s.charonis at gmail.com Fri Feb 10 17:38:22 2012 From: s.charonis at gmail.com (Spyros Charonis) Date: Fri, 10 Feb 2012 16:38:22 +0000 Subject: [Tutor] Concatenating multiple lines into one Message-ID: Dear python community, I have a file where I store sequences that each have a header. The structure of the file is as such: >sp|(some code) =>1st header ATTTTGGCGG MNKPLOI ..... ..... >sp|(some code) => 2nd header AAAAAA GGGG ... ......... ...... I am looking to implement a logical structure that would allow me to group each of the sequences (spread on multiple lines) into a single string. So instead of having the letters spread on multiple lines I would be able to have 'ATTTTGGCGGMNKP....' as a single string that could be indexed. This snipped is good for isolating the sequences (=stripping headers and skipping blank lines) but how could I concatenate each sequence in order to get one string per sequence? >>> for line in align_file: ... if line.startswith('>sp'): ... continue ... elif not line.strip(): ... continue ... else: ... print line (... is just OS X terminal notation, nothing programmatic) Many thanks in advance. S. -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Fri Feb 10 18:00:32 2012 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 10 Feb 2012 18:00:32 +0100 Subject: [Tutor] Concatenating multiple lines into one In-Reply-To: References: Message-ID: On Fri, Feb 10, 2012 at 5:38 PM, Spyros Charonis wrote: > Dear python community, > > I have a file where I store sequences that each have a header. The structure > of the file is as such: > >>sp|(some code) =>1st header > ATTTTGGCGG > MNKPLOI > ..... > ..... > >>sp|(some code) => 2nd header > AAAAAA > GGGG ... > ......... > > ...... > > I am looking to implement a logical structure that would allow me to group > each of the sequences (spread on multiple lines) into a single string. So > instead of having the letters spread on multiple lines I would be able to > have 'ATTTTGGCGGMNKP....' as a single string that could be indexed. > > This snipped is good for isolating the sequences (=stripping headers and > skipping blank lines) but how could I concatenate each sequence in order to > get one string per sequence? > >>>> for line in align_file: > ... ? ? if line.startswith('>sp'): > ... ? ? ? ? ? ? continue > ... ? ? elif not line.strip(): > ... ? ? ? ? ? ? continue > ... ? ? else: > ... ? ? ? ? ? ? print line > > (... is just OS X terminal notation, nothing programmatic) > > Many thanks in advance. > > S. > python has a simple method to do that, str.join. Let me demonstrate it: >>> a = ['a', 'b', 'c', 'd', 'e'] >>> ''.join(a) 'abcde' >>> ' '.join(a) # with a space 'a b c d e' >>> ' hello '.join(a) # go crazy if you want 'a hello b hello c hello d hello e' so, it takes a list as an argument and joins the elements together in a string. the string that you call join on is used as a separator between the arguments. Pretty simple. HTH, Hugo From __peter__ at web.de Fri Feb 10 18:08:28 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 10 Feb 2012 18:08:28 +0100 Subject: [Tutor] Concatenating multiple lines into one References: Message-ID: Spyros Charonis wrote: > Dear python community, > > I have a file where I store sequences that each have a header. The > structure of the file is as such: > >>sp|(some code) =>1st header > ATTTTGGCGG > MNKPLOI > ..... > ..... > >>sp|(some code) => 2nd header > AAAAAA > GGGG ... > ......... > > ...... > > I am looking to implement a logical structure that would allow me to group > each of the sequences (spread on multiple lines) into a single string. So > instead of having the letters spread on multiple lines I would be able to > have 'ATTTTGGCGGMNKP....' as a single string that could be indexed. > > This snipped is good for isolating the sequences (=stripping headers and > skipping blank lines) but how could I concatenate each sequence in order > to get one string per sequence? > >>>> for line in align_file: > ... if line.startswith('>sp'): > ... continue > ... elif not line.strip(): > ... continue > ... else: > ... print line > > (... is just OS X terminal notation, nothing programmatic) > > Many thanks in advance. Instead of printing the line directly collect it in a list (without trailing "\n"). When you encounter a line starting with ">sp" check if that list is non-empty, and if so print "".join(parts), assuming the list is called parts, and start with a fresh list. Don't forget to print any leftover data in the list once the for loop has terminated. From breamoreboy at yahoo.co.uk Fri Feb 10 18:30:27 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 10 Feb 2012 17:30:27 +0000 Subject: [Tutor] Concatenating multiple lines into one In-Reply-To: References: Message-ID: On 10/02/2012 17:08, Peter Otten wrote: > Spyros Charonis wrote: > >> Dear python community, >> >> I have a file where I store sequences that each have a header. The >> structure of the file is as such: >> >>> sp|(some code) =>1st header >> ATTTTGGCGG >> MNKPLOI >> ..... >> ..... >> >>> sp|(some code) => 2nd header >> AAAAAA >> GGGG ... >> ......... >> >> ...... >> >> I am looking to implement a logical structure that would allow me to group >> each of the sequences (spread on multiple lines) into a single string. So >> instead of having the letters spread on multiple lines I would be able to >> have 'ATTTTGGCGGMNKP....' as a single string that could be indexed. >> >> This snipped is good for isolating the sequences (=stripping headers and >> skipping blank lines) but how could I concatenate each sequence in order >> to get one string per sequence? >> >>>>> for line in align_file: >> ... if line.startswith('>sp'): >> ... continue >> ... elif not line.strip(): >> ... continue >> ... else: >> ... print line >> >> (... is just OS X terminal notation, nothing programmatic) >> >> Many thanks in advance. > > Instead of printing the line directly collect it in a list (without trailing > "\n"). When you encounter a line starting with">sp" check if that list is > non-empty, and if so print "".join(parts), assuming the list is called > parts, and start with a fresh list. Don't forget to print any leftover data > in the list once the for loop has terminated. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > The advice from Peter is sound if the strings could grow very large but you can simply concatenate the parts if they are not. For the indexing simply store your data in a dict. -- Cheers. Mark Lawrence. From dave at hansonforensics.co.uk Sat Feb 11 11:06:47 2012 From: dave at hansonforensics.co.uk (Dave Hanson) Date: Sat, 11 Feb 2012 10:06:47 +0000 Subject: [Tutor] Cmd Advice In-Reply-To: References: Message-ID: Hi Walter, I can't thank you enough for taking the time to explain all of this in such level of detail. :) also apologies for taking so long to respond, I have to do this on my work machine and we are so busy at the minute I just haven't the time to do anything - I will not be deterred though! I followed your instructions and now have no errors, but all that seems to happen is either the dos window or python window (not sure which - it's black and only appears for a millisecond) pops up and then.... nothing. I maybe incorrectly assumed that I would have a terminal like window with a blinking cursor and that would accept my commands to the "t" program? Thanks again for all your help. Best Regards, Dave Hanson On Wed, Feb 8, 2012 at 1:29 AM, Walter Prins wrote: > HI Dave, > > > On 7 February 2012 16:55, Dave Hanson wrote: > >> I tried what you said, many attempts result in this message: >> >> >>> *C:\Documents and Settings\dhanson2\Desktop>"C:\Python27\python.exe" >>> "C:\t.py"* >>> * * >>> *C:\Python27\python.exe: can't open file 'C:\t.py': [Errno 2] No such >>> file or directory* >>> >> >> I've tried moving t.py around but still no joy? >> >> Here is what I put in my bat file with and without the quotes: >> >> >>> *"C:\Python27\python.exe" "C:\t.py" %1 %2 %3 %4 %5 %6 %7 %8 %9 >>> * >> >> >> > The error message implies that the program "t.py" is in the root of your > C:\ drive? I'd have thought this would not be the case -- you need to give > the correct path to the "t.py" file for Python to load it. (And as an > aside, you need to quote paths if theycontains spaces, otherwise the > command prompt will interpret the first part up to a space in the path as > the path/command and the remainder of the path as a command line argument! > (One subtlety of command lines...) The "Documents and Settings" folder on > Windows XP was therefore very unfortunately chosen since the spaces causes > endless problems with people not realising this and trying to use files > located inside Documents and Settings. You'll notice on Windows 7 > Microsoft has wisely (at last) decided to shorten and remove spaces as much > as possible from paths to avoid gotchas with people forgetting to quote > paths, and similarly Python itself does not uses spaces in any of its > folder names. But I digress. > > Anyway, I've had a quick further look at this program and got it working > the way you want on my machine. The precise steps I followed was: > 1.) Install Mercurial for Windows (to be able to checkout the source). I > got it here: http://tortoisehg.bitbucket.org/download/index.html > 2.) Retrieved the source code. On my machine I opened a command prompt, > and: > cd "C:\Users\walterp\Documents\Python" > hg clone https://bitbucket.org/sjl/t > > This creates a folder called "t" inside of my Python source folder. > Adjust folders as required for your machine and/or where you keep your > Python source. > > 3) Create a batch file called "t.bat" in > "C:\Users\walterp\Documents\Python\t", so the full filename is > "C:\Users\walterp\Documents\Python\t\t.bat", containing these lines: > > @echo off > c: > cd C:\Users\walterp\Documents\Python\t > c:\python27\python.exe "C:\Users\walterp\Documents\Python\t\t.py" %1 %2 %3 > %4 %5 %6 %7 %8 %9 > > The effect of these commands is to stop the command interpreter from > displaying the commands issues by the batch file (which is unwanted here) > via the "@echo off" line, and then setting up the environment prior to > running the t.py program such that it will always run having the "current > working folder" be the same folder that the t.py program is located in. > > This is important since the t.py program currently assumes that it will > always be run from the same starting location, which is not the case if you > go and put the program on the command line search path so that you can use > it from any other working folder. (Without this, if you run the program > from another location, then the t.py program will create a new task list in > the new location -- basically the t.py command will create and manage a > task list in whatever folder you happen to be in, so in order to ensure it > always updates the same task list, the lines above therefore ensures it > always effectively runs from the same place, regardless of where the batch > file t.bat might have been run from, thereby effectively ensuring it to > always uses the same task list file.) > > Also, note that in order to in fact use the t.bat file from any other > folder, you'll have to add the bat files location to you system (or user) > PATH variable. Do you know how to do this, and are you allowed to do so, > or are you blocked by your IT policies? If so you should also be able to > do this via e.g. another batch file, perhaps the same one you use to > circumvent the cmd.exe blocks on your system, by simply adding it to the > PATH variable there, e.g. a line like this ought to do it: > PATH=%PATH%;C:\Users\walterp\Documents\Python\t > > Lastly a minor observation: I note this source code includes a setup.py > script. This implies you can install t.py into your Python environment > such that an .exe file will be created for it (really copy of the t.py file > and the python interpreter [I think, or a launcher of some sort] combined) > in the Python\Scripts folder. Some Python distributions (e.g. Activestate > IIRC) puts this folder onto the system Path thereby making "system wide" > installed Python packages/commands (where appropriate) instantly usable > from the command prompt, others (e.g. standard Python on Windows) do not > and leaves this step for you to complete. Anyway, I've obviously not gone > the route of installin via setup.py, since installing this program in this > way will make it difficult/impossible for you to tinker/edit the program > easily, and I'm assuming you want to actually be able to edit the program > (and possibly submit patches back to the author?) while using it etc. So, > for this to be possible you actually need the t.py to "run from source" and > don't want to embedded in your Python environment, which is what not using > setup.py and doing the above effectively enables you to do easily. (Aside: > when I noticed the program isn't location/working directory independent I > immediately thought this might be a useful patch/enhancement to make -- > make it get the folder location of itself and use that for the location of > the tasks list etc.) > > Let me know if you have further problems. > > Walter > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sat Feb 11 12:35:07 2012 From: d at davea.name (Dave Angel) Date: Sat, 11 Feb 2012 06:35:07 -0500 Subject: [Tutor] Cmd Advice In-Reply-To: References: Message-ID: <4F36526B.7050204@davea.name> (Please don't top-post. Please put your comments after whatever parts you're quoting (replying to) ) On 02/11/2012 05:06 AM, Dave Hanson wrote: > Hi Walter, > > I can't thank you enough for taking the time to explain all of this in such > level of detail. :) also apologies for taking so long to respond, I have to > do this on my work machine and we are so busy at the minute I just haven't > the time to do anything - I will not be deterred though! > > I followed your instructions and now have no errors, but all that seems to > happen is either the dos window or python window (not sure which - it's > black and only appears for a millisecond) pops up and then.... nothing. I > maybe incorrectly assumed that I would have a terminal like window with a > blinking cursor and that would accept my commands to the "t" program? > > Thanks again for all your help. You need to learn how to create a DOS window (or cmd window, just another name for same thing) in Windows. One way is to use the RUN prompt in the Start menu, and run the program CMD. Another is to go to the Start Menu->Accessories->DOS box. it's been a long time since I ran Windows, so it may have some different name, but it should be in your accessories somewhere. Since I use such a shell constantly, I created a shortcut key to open one. Once you do that, you should see a "box" with a C: prompt. It is indeed black, but you can customize it in many ways. From there you can type all the commands that Walter was telling you about. And it normally won't go away when a program finishes running, so you don't have the "black and appears for a millisecond" syndrome. Windows will create one of these if you run console things from the GUI, but it also destroys them as soon as the program ends. -- DaveA From dave at hansonforensics.co.uk Sat Feb 11 12:46:24 2012 From: dave at hansonforensics.co.uk (Dave Hanson) Date: Sat, 11 Feb 2012 11:46:24 +0000 Subject: [Tutor] Cmd Advice In-Reply-To: <4F36526B.7050204@davea.name> References: <4F36526B.7050204@davea.name> Message-ID: On Sat, Feb 11, 2012 at 11:35 AM, Dave Angel wrote: > (Please don't top-post. Please put your comments after whatever parts > you're quoting (replying to) ) > Apologies Dave. > You need to learn how to create a DOS window (or cmd window, just another > name for same thing) in Windows. One way is to use the RUN prompt in the > Start menu, and run the program CMD. Another is to go to the Start > Menu->Accessories->DOS box. it's been a long time since I ran Windows, so > it may have some different name, but it should be in your accessories > somewhere. Since I use such a shell constantly, I created a shortcut key > to open one. > > Once you do that, you should see a "box" with a C: prompt. It is indeed > black, but you can customize it in many ways. From there you can type all > the commands that Walter was telling you about. And it normally won't go > away when a program finishes running, so you don't have the "black and > appears for a millisecond" syndrome. > > Windows will create one of these if you run console things from the GUI, > but it also destroys them as soon as the program ends. > > -- > > DaveA > > I did mention very early on in my query that I had restricted access to the Dos CMD prompt, hence why I asked if anyone knew how to create a self contained prompt within the Python program. I was under the impression that the .bat file Walter described would fill that gap. Thanks for your comments too, but your solution unfortunately is not one I can use as I cannot do all the usual methods to run the Dos prompt, .bat files are not a problem, I have used several in the past. My issue is that I cannot give commands directly to the Dos prompt and in turn not "operate" the python program as I can on my Ubuntu machine. Thanks Guys, Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sat Feb 11 13:14:32 2012 From: d at davea.name (Dave Angel) Date: Sat, 11 Feb 2012 07:14:32 -0500 Subject: [Tutor] Cmd Advice In-Reply-To: References: <4F36526B.7050204@davea.name> Message-ID: <4F365BA8.407@davea.name> On 02/11/2012 06:46 AM, Dave Hanson wrote: > On Sat, Feb 11, 2012 at 11:35 AM, Dave Angel wrote: > >> (Please don't top-post. Please put your comments after whatever parts >> you're quoting (replying to) ) >> > Apologies Dave. > > >> You need to learn how to create a DOS window (or cmd window, just another >> name for same thing) in Windows. One way is to use the RUN prompt in the >> Start menu, and run the program CMD. Another is to go to the Start >> Menu->Accessories->DOS box. it's been a long time since I ran Windows, so >> it may have some different name, but it should be in your accessories >> somewhere. Since I use such a shell constantly, I created a shortcut key >> to open one. >> >> Once you do that, you should see a "box" with a C: prompt. It is indeed >> black, but you can customize it in many ways. From there you can type all >> the commands that Walter was telling you about. And it normally won't go >> away when a program finishes running, so you don't have the "black and >> appears for a millisecond" syndrome. >> >> Windows will create one of these if you run console things from the GUI, >> but it also destroys them as soon as the program ends. >> >> -- >> >> DaveA >> >> I did mention very early on in my query that I had restricted access to > the Dos CMD prompt, hence why I asked if anyone knew how to create a self > contained prompt within the Python program. I was under the impression that > the .bat file Walter described would fill that gap. > > Thanks for your comments too, but your solution unfortunately is not one I > can use as I cannot do all the usual methods to run the Dos prompt, .bat > files are not a problem, I have used several in the past. My issue is that > I cannot give commands directly to the Dos prompt and in turn not "operate" > the python program as I can on my Ubuntu machine. > You still don't say "why" you can't get a traditional DOS prompt. If your Windows is somehow constrained (e.g. company rules) or broken (e.g. somebody deleted some of the dll's in Windows/system32), then it's unclear how we're supposed to guess just which things are going to work in it. it's also unclear whether it's the programmer's machine (yours) that's constrained or only the end user. In Windows, whenever a console program is launched without a console, one is created for that program. It goes away when the program ends, so it's not real useful for learning and experimentation. However, it does last as long as the program does, so you can just use raw_input to print your "prompt" and accept commands. Just remember you may want to add another one at the end so the user gets a chance to read the last stuff you printed. CMD is the cononical way to launch such a window, and batch files use CMD by default. So a batch file is one back-door. But you can write your own shell in any programming language you like, and if don't mark it as a GUI app, it'll get a DOS box as well. You can launch programs, including Python programs, from your own shell. And they'll normally continue to use the same shell as your launcher. Perhaps you didn't realize that CMD takes some command switches of its own. One of them tells it to stick around even when the current batch file ends. Random thoughts for an incompletely specified set of constraints. -- DaveA From d at davea.name Sat Feb 11 13:43:46 2012 From: d at davea.name (Dave Angel) Date: Sat, 11 Feb 2012 07:43:46 -0500 Subject: [Tutor] Cmd Advice In-Reply-To: <4F365BA8.407@davea.name> References: <4F36526B.7050204@davea.name> <4F365BA8.407@davea.name> Message-ID: <4F366282.6060505@davea.name> On 02/11/2012 07:14 AM, Dave Angel wrote: > On 02/11/2012 06:46 AM, Dave Hanson wrote: >> On Sat, Feb 11, 2012 at 11:35 AM, Dave Angel wrote: >> >>> (Please don't top-post. Please put your comments after whatever parts >>> you're quoting (replying to) ) >>> >> Apologies Dave. >> >> >>> You need to learn how to create a DOS window (or cmd window, just >>> another >>> name for same thing) in Windows. One way is to use the RUN prompt >>> in the >>> Start menu, and run the program CMD. Another is to go to the Start >>> Menu->Accessories->DOS box. it's been a long time since I ran >>> Windows, so >>> it may have some different name, but it should be in your accessories >>> somewhere. Since I use such a shell constantly, I created a >>> shortcut key >>> to open one. >>> >>> Once you do that, you should see a "box" with a C: prompt. It is >>> indeed >>> black, but you can customize it in many ways. From there you can >>> type all >>> the commands that Walter was telling you about. And it normally >>> won't go >>> away when a program finishes running, so you don't have the "black and >>> appears for a millisecond" syndrome. >>> >>> Windows will create one of these if you run console things from the >>> GUI, >>> but it also destroys them as soon as the program ends. >>> >>> -- >>> >>> DaveA >>> >>> I did mention very early on in my query that I had restricted >>> access to >> the Dos CMD prompt, hence why I asked if anyone knew how to create a >> self >> contained prompt within the Python program. I was under the >> impression that >> the .bat file Walter described would fill that gap. >> >> Thanks for your comments too, but your solution unfortunately is not >> one I >> can use as I cannot do all the usual methods to run the Dos prompt, .bat >> files are not a problem, I have used several in the past. My issue is >> that >> I cannot give commands directly to the Dos prompt and in turn not >> "operate" >> the python program as I can on my Ubuntu machine. >> > > You still don't say "why" you can't get a traditional DOS prompt. If > your Windows is somehow constrained (e.g. company rules) or broken > (e.g. somebody deleted some of the dll's in Windows/system32), then > it's unclear how we're supposed to guess just which things are going > to work in it. it's also unclear whether it's the programmer's > machine (yours) that's constrained or only the end user. > > In Windows, whenever a console program is launched without a console, > one is created for that program. It goes away when the program ends, > so it's not real useful for learning and experimentation. However, it > does last as long as the program does, so you can just use raw_input > to print your "prompt" and accept commands. Just remember you may > want to add another one at the end so the user gets a chance to read > the last stuff you printed. > > CMD is the cononical way to launch such a window, and batch files use > CMD by default. So a batch file is one back-door. But you can write > your own shell in any programming language you like, and if don't mark > it as a GUI app, it'll get a DOS box as well. You can launch > programs, including Python programs, from your own shell. And they'll > normally continue to use the same shell as your launcher. > > Perhaps you didn't realize that CMD takes some command switches of its > own. One of them tells it to stick around even when the current batch > file ends. > > Random thoughts for an incompletely specified set of constraints. > > My apologies. You gave lots more detail earlier in the thread, but I didn't make the connection till just now. I only saw the message from Walter and your response and thought I could help. Some tests. Try a batch file with a PAUSE in it. Do you get to hit enter at that point? If that works, then try making a batch file that runs CMD.EXE. Again, put a PAUSE at the end of the batch file so you can see any errors you might get. If those don't pan out, write a simple python program that does raw_input() in a loop (or input(), if you're on Python 3.x), and does something trivial with the stuff you type in. while True indata = raw_input("prompt:") print indata It's not much harder to exec a program based on the contents of indata. In Windows, you don't usually even have to separate out which part is the command, and which part is the parameters like -l When they eliminated cmd, they may have actually removed the file (or moved it to someplace inaccessible to your account), or they may have just eliminated the more obvious ways of running it. -- DaveA From dave at hansonforensics.co.uk Sat Feb 11 13:53:48 2012 From: dave at hansonforensics.co.uk (Dave Hanson) Date: Sat, 11 Feb 2012 12:53:48 +0000 Subject: [Tutor] Cmd Advice In-Reply-To: <4F366282.6060505@davea.name> References: <4F36526B.7050204@davea.name> <4F365BA8.407@davea.name> <4F366282.6060505@davea.name> Message-ID: On Sat, Feb 11, 2012 at 12:43 PM, Dave Angel wrote: > On 02/11/2012 07:14 AM, Dave Angel wrote: > >> On 02/11/2012 06:46 AM, Dave Hanson wrote: >> >>> On Sat, Feb 11, 2012 at 11:35 AM, Dave Angel wrote: >>> >>> (Please don't top-post. Please put your comments after whatever parts >>>> you're quoting (replying to) ) >>>> >>>> Apologies Dave. >>> >>> >>> You need to learn how to create a DOS window (or cmd window, just >>>> another >>>> name for same thing) in Windows. One way is to use the RUN prompt in >>>> the >>>> Start menu, and run the program CMD. Another is to go to the Start >>>> Menu->Accessories->DOS box. it's been a long time since I ran Windows, >>>> so >>>> it may have some different name, but it should be in your accessories >>>> somewhere. Since I use such a shell constantly, I created a shortcut >>>> key >>>> to open one. >>>> >>>> Once you do that, you should see a "box" with a C: prompt. It is indeed >>>> black, but you can customize it in many ways. From there you can type >>>> all >>>> the commands that Walter was telling you about. And it normally won't >>>> go >>>> away when a program finishes running, so you don't have the "black and >>>> appears for a millisecond" syndrome. >>>> >>>> Windows will create one of these if you run console things from the GUI, >>>> but it also destroys them as soon as the program ends. >>>> >>>> -- >>>> >>>> DaveA >>>> >>>> I did mention very early on in my query that I had restricted access to >>>> >>> the Dos CMD prompt, hence why I asked if anyone knew how to create a self >>> contained prompt within the Python program. I was under the impression >>> that >>> the .bat file Walter described would fill that gap. >>> >>> Thanks for your comments too, but your solution unfortunately is not one >>> I >>> can use as I cannot do all the usual methods to run the Dos prompt, .bat >>> files are not a problem, I have used several in the past. My issue is >>> that >>> I cannot give commands directly to the Dos prompt and in turn not >>> "operate" >>> the python program as I can on my Ubuntu machine. >>> >>> >> You still don't say "why" you can't get a traditional DOS prompt. If >> your Windows is somehow constrained (e.g. company rules) or broken (e.g. >> somebody deleted some of the dll's in Windows/system32), then it's unclear >> how we're supposed to guess just which things are going to work in it. >> it's also unclear whether it's the programmer's machine (yours) that's >> constrained or only the end user. >> >> In Windows, whenever a console program is launched without a console, one >> is created for that program. It goes away when the program ends, so it's >> not real useful for learning and experimentation. However, it does last as >> long as the program does, so you can just use raw_input to print your >> "prompt" and accept commands. Just remember you may want to add another >> one at the end so the user gets a chance to read the last stuff you printed. >> >> CMD is the cononical way to launch such a window, and batch files use CMD >> by default. So a batch file is one back-door. But you can write your own >> shell in any programming language you like, and if don't mark it as a GUI >> app, it'll get a DOS box as well. You can launch programs, including >> Python programs, from your own shell. And they'll normally continue to use >> the same shell as your launcher. >> >> Perhaps you didn't realize that CMD takes some command switches of its >> own. One of them tells it to stick around even when the current batch file >> ends. >> >> Random thoughts for an incompletely specified set of constraints. >> >> >> My apologies. You gave lots more detail earlier in the thread, but I > didn't make the connection till just now. I only saw the message from > Walter and your response and thought I could help. > > Some tests. Try a batch file with a PAUSE in it. Do you get to hit enter > at that point? If that works, then try making a batch file that runs > CMD.EXE. Again, put a PAUSE at the end of the batch file so you can see > any errors you might get. > > If those don't pan out, write a simple python program that does > raw_input() in a loop (or input(), if you're on Python 3.x), and does > something trivial with the stuff you type in. > > while True > indata = raw_input("prompt:") > print indata > > > It's not much harder to exec a program based on the contents of indata. > In Windows, you don't usually even have to separate out which part is the > command, and which part is the parameters like -l > > When they eliminated cmd, they may have actually removed the file (or > moved it to someplace inaccessible to your account), or they may have just > eliminated the more obvious ways of running it. > > > > -- > > DaveA > > No worries Dave, I did try with pause during my previous attempts to get the .bat file running and when it ran with no errors I tried the pause again, pressed Enter and the window just closes and nothing happens. Cmd.exe does still exist, it's just that when you run it the message is displayed saying I can't use it, I have a degree in computer forensics and so know the registry key to remove the restricted access, this only lasts until a reboot occurs then I have to do it again - and if I'm honest it's not very professional of me to be 'buggering about' with my work machine's registry. If I understand your proposed 'loop' method correctly, could I use that to pass commands to my "t" program then do you think? or have the loop built into the "t.py" script? Have to nip out, so I'll have to respond tomorrow now. Thanks, Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sat Feb 11 14:04:49 2012 From: d at davea.name (Dave Angel) Date: Sat, 11 Feb 2012 08:04:49 -0500 Subject: [Tutor] Cmd Advice In-Reply-To: References: <4F36526B.7050204@davea.name> <4F365BA8.407@davea.name> <4F366282.6060505@davea.name> Message-ID: <4F366771.30508@davea.name> On 02/11/2012 07:53 AM, Dave Hanson wrote: > > I did try with pause during my previous attempts to get the .bat file > running and when it ran with no errors I tried the pause again, pressed > Enter and the window just closes and nothing happens. > > Cmd.exe does still exist, it's just that when you run it the message is > displayed saying I can't use it, I have a degree in computer forensics and > so know the registry key to remove the restricted access, this only lasts > until a reboot occurs then I have to do it again - and if I'm honest it's > not very professional of me to be 'buggering about' with my work machine's > registry. > > If I understand your proposed 'loop' method correctly, could I use that to > pass commands to my "t" program then do you think? or have the loop built > into the "t.py" script? > PAUSE in a batch file is run by CMD.EXE. So there is such a program, and it is, at least to some degree, available. How about a 3 line batch file :labletop cmd pause goto labeltop If that cmd works, you'll have an unrestricted cmd window. if it doesn't , you should write your own, more restricted, shell. And replace cmd above with python myshell (with appropriate cd's and suchlike) The shell doesn't have to be too complex, just a raw_input() followed by perhaps a split and some subprocess command. But one of the advantages of having a standard shell running when you start python is that if it crashes, you don't lose the window. The pause would do that for you. -- DaveA From wprins at gmail.com Sat Feb 11 14:54:30 2012 From: wprins at gmail.com (Walter Prins) Date: Sat, 11 Feb 2012 13:54:30 +0000 Subject: [Tutor] Cmd Advice In-Reply-To: References: <4F36526B.7050204@davea.name> Message-ID: Hi Dave, >> You need to learn how to create a DOS window (or cmd window, just another >> name for same thing) in Windows. ?One way is to use the RUN prompt in the >> Start menu, and run the program ?CMD. ?Another is to go to the Start >> Menu->Accessories->DOS box. ?it's been a long time since I ran Windows, so >> it may have some different name, but it should be in your accessories >> somewhere. ?Since I use such a shell constantly, I created a shortcut key to >> open one. > ?I did mention very early on in my query that I had restricted access to the > Dos CMD prompt, hence why I asked if anyone knew how to create a self > contained prompt within the Python program. I was under the impression that > the .bat file Walter described would fill that gap. OK, I thought you said you already knew how to get a cmd.exe shell despite the blocks in place (via a batch file) yourself. The batch file I suggested was not meant to work around your cmd.exe issues, it was meant to smooth out the calling of the python program so that, once having a command prompt, you could use the t.py program identically to how you would use it on Linux, while still allowing you to tinker with the code as well. As an aside, the least desireable idea would be to modify t.py, or write another python program, to simulate cmd.exe in order to work around the cmd.exe block. As Dave has posted, if you can create batch files, then cmd.exe is available to some extent, the goal is to trick the system into running cmd.exe interactively, possibly via a batch file as intermediary, without blocking it and thus allowing you to continue to use it. So, regarding getting a working command prompt, several options have been mentioned already but I'll just chip in and suggest the following: 1) Create a batch file (call it, say, "shell.bat") and put in it: c:\windows\system32\cmd.exe Double clicking this should run cmd.exe and present a normal command prompt. If this works, then create a shortcut on your desktop to this batch file and you're done. (You would probably want to add a line to add the location of the t.py program into the PATH environment variable into this batch file, to allow you to run the program from any working folder. If you don't know what I'm on about post back and I'll explain.) 2.) If no.1 fails, then the next idea is to try making a copy of cmd.exe from c:\windows\system32\cmd.exe into your own home folder, and call it something else, say "shell.exe". This should evade the cmd.exe blocks in place (depending on how thorough they are.) Try directly running this by double clicking. This should open up a normal command prompt as well. Let me know if either of those options work for you. Cheers, Walter From wprins at gmail.com Sat Feb 11 15:03:17 2012 From: wprins at gmail.com (Walter Prins) Date: Sat, 11 Feb 2012 14:03:17 +0000 Subject: [Tutor] Cmd Advice In-Reply-To: References: Message-ID: Hi all, Below is an *earlier* (note the date) private response by myself that at the time accidentally didn't get sent to the list and only to Dave (as he privately replied to me only and not to the list.) Given that the thread on the list has resumed, I thought I'd forward this to the thread for completeness sake as otherwise a bit of context might be lost. Regards, Walter ---------- Forwarded message ---------- From: Walter Prins Date: 8 February 2012 01:29 Subject: Re: [Tutor] Cmd Advice To: Dave Hanson HI Dave, On 7 February 2012 16:55, Dave Hanson wrote: > > I tried what you said, many attempts result in this message: > >> >> C:\Documents and Settings\dhanson2\Desktop>"C:\Python27\python.exe" "C:\t.py" >> >> C:\Python27\python.exe: can't open file 'C:\t.py': [Errno 2] No such file or directory > > > I've tried moving t.py around but still no joy? > > Here is what I put in my bat file with and without the quotes: > >> >> "C:\Python27\python.exe" "C:\t.py" %1 %2 %3 %4 %5 %6 %7 %8 %9 > > The error message implies that the program "t.py" is in the root of your C:\ drive?? I'd have thought this would not be the case -- you need to give the correct path to the "t.py" file for Python to load it. (And as an aside, you need to quote paths if theycontains spaces, otherwise the command prompt will interpret the first part up to a space in the path as the path/command and the remainder of the path as a command line argument!? (One subtlety of command lines...)? The "Documents and Settings" folder on Windows XP was therefore very unfortunately chosen since the spaces causes endless problems with people not realising this and trying to use files located inside Documents and Settings.? You'll notice on Windows 7 Microsoft has wisely (at last) decided to shorten and remove spaces as much as possible from paths to avoid gotchas with people forgetting to quote paths, and similarly Python itself does not uses spaces in any of its folder names.? But I digress. Anyway, I've had a quick further look at this program and got it working the way you want on my machine.? The precise steps I followed was: 1.) Install Mercurial for Windows (to be able to checkout the source). I got it here: http://tortoisehg.bitbucket.org/download/index.html 2.) Retrieved the source code.? On my machine I opened a command prompt, and: cd "C:\Users\walterp\Documents\Python" hg clone https://bitbucket.org/sjl/t This creates a folder called "t" inside of my Python source folder. Adjust folders as required for your machine and/or where you keep your Python source. 3) Create a batch file called "t.bat" in "C:\Users\walterp\Documents\Python\t", so the full filename is "C:\Users\walterp\Documents\Python\t\t.bat", containing these lines: @echo off c: cd C:\Users\walterp\Documents\Python\t c:\python27\python.exe "C:\Users\walterp\Documents\Python\t\t.py" %1 %2 %3 %4 %5 %6 %7 %8 %9 The effect of these commands is to stop the command interpreter from displaying the commands issues by the batch file (which is unwanted here) via the "@echo off" line, and then setting up the environment prior to running the t.py program such that it will always run having the "current working folder" be the same folder that the t.py program is located in. This is important since the t.py program currently assumes that it will always be run from the same starting location, which is not the case if you go and put the program on the command line search path so that you can use it from any other working folder.? (Without this, if you run the program from another location, then the t.py program will create a new task list in the new location -- basically the t.py command will create and manage a task list in whatever folder you happen to be in, so in order to ensure it always updates the same task list, the lines above therefore ensures it always effectively runs from the same place, regardless of where the batch file t.bat might have been run from, thereby effectively ensuring it to always uses the same task list file.) Also, note that in order to in fact use the t.bat file from any other folder, you'll have to add the bat files location to you system (or user) PATH variable.? Do you know how to do this, and are you allowed to do so, or are you blocked by your IT policies?? If so you should also be able to do this via e.g. another batch file, perhaps the same one you use to circumvent the cmd.exe blocks on your system, by simply adding it to the PATH variable there, e.g. a line like this ought to do it: PATH=%PATH%;C:\Users\walterp\Documents\Python\t Lastly a minor observation:? I note this source code includes a setup.py script.? This implies you can install t.py into your Python environment such that an .exe file will be created for it (really copy of the t.py file and the python interpreter [I think, or a launcher of some sort] combined) in the Python\Scripts folder.? Some Python distributions (e.g. Activestate IIRC) puts this folder onto the system Path thereby making "system wide" installed Python packages/commands (where appropriate) instantly usable from the command prompt, others (e.g. standard Python on Windows) do not and leaves this step for you to complete.? Anyway, I've obviously not gone the route of installin via setup.py, since installing this program in this way will make it difficult/impossible for you to tinker/edit the program easily, and I'm assuming you want to actually be able to edit the program (and possibly submit patches back to the author?) while using it etc.? So, for this to be possible you actually need the t.py to "run from source" and don't want to embedded in your Python environment, which is what not using setup.py and doing the above effectively enables you to do easily. (Aside: when I noticed the program isn't location/working directory independent I immediately thought this might be a useful patch/enhancement to make -- make it get the folder location of itself and use that for the location of the tasks list etc.) Let me know if you have further problems. Walter From 0101amt at gmail.com Sat Feb 11 23:26:58 2012 From: 0101amt at gmail.com (amt) Date: Sun, 12 Feb 2012 00:26:58 +0200 Subject: [Tutor] Learn Python The Hard Way, Ex19-3 Message-ID: Hello! I'm currently stuck at the Extra Credit 3 from LPTHW. Link to the actual exercise:http://learnpythonthehardway.org/book/ex19.html The exercise: Write at least one more function of your own design, and run it 10 different ways. Code from the book: def cheese_and_crackers(cheese_count, boxes_of_crackers): print "You have %d cheeses!" % cheese_count print "You have %d boxes of crackers!" % boxes_of_crackers print "Man that's enough for a party!" print "Get a blanket.\n" print "We can just give the function numbers directly:" cheese_and_crackers(20, 30) print "OR, we can use variables from our script:" amount_of_cheese = 10 amount_of_crackers = 50 cheese_and_crackers(amount_of_cheese, amount_of_crackers) print "We can even do math inside too:" cheese_and_crackers(10 + 20, 5 + 6) print "And we can combine the two, variables and math:" cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) I wrote a function similar to cheese_and_crackers and it works just fine but I can't figure out more ways of calling a function other than the ones presented in the code(with integers as arguments,variables as arguments, two integer additions as arguments and with arguments in the form of variable+integer). The author states that there are 10 different ways to run it.(in a comment he states that: "You can run it a lot of different ways, far too many to enumerate.). So, what other ways are there aside the ones already presented in the above code? Thanks in advance, amt. From d at davea.name Sat Feb 11 23:47:20 2012 From: d at davea.name (Dave Angel) Date: Sat, 11 Feb 2012 17:47:20 -0500 Subject: [Tutor] Learn Python The Hard Way, Ex19-3 In-Reply-To: References: Message-ID: <4F36EFF8.4010304@davea.name> On 02/11/2012 05:26 PM, amt wrote: > Hello! I'm currently stuck at the Extra Credit 3 from LPTHW. > > Link to the actual exercise:http://learnpythonthehardway.org/book/ex19.html > The exercise: > Write at least one more function of your own design, and run it 10 > different ways. > > > Code from the book: > def cheese_and_crackers(cheese_count, boxes_of_crackers): > print "You have %d cheeses!" % cheese_count > print "You have %d boxes of crackers!" % boxes_of_crackers > print "Man that's enough for a party!" > print "Get a blanket.\n" > > > print "We can just give the function numbers directly:" > cheese_and_crackers(20, 30) > > > print "OR, we can use variables from our script:" > amount_of_cheese = 10 > amount_of_crackers = 50 > > cheese_and_crackers(amount_of_cheese, amount_of_crackers) > > > print "We can even do math inside too:" > cheese_and_crackers(10 + 20, 5 + 6) > > > print "And we can combine the two, variables and math:" > cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) > > > > > > I wrote a function similar to cheese_and_crackers and it works just > fine but I can't figure out more ways of calling a function other than > the ones presented in the code(with integers as arguments,variables as > arguments, two integer additions as arguments and with arguments in > the form of variable+integer). The author states that there are 10 > different ways to run it.(in a comment he states that: "You can run it > a lot of different ways, far too many to enumerate.). > > > So, what other ways are there aside the ones already presented in the > above code? > I don't have time to get the book and figure out how much of Python you've covered, but let me give it a shot: food = (3, 9) cheese_and_crackers(*food) Since they say you can use a function of your own design, how about giving it default values for one or more arguments? if the function is def cheese_and_crackers(cheese_count, boxes_of_crackers=1): You can now call it as cheese_and_crackers(5) You can call it using named arguments: cheese_and_crackers(boxes_of_crackers=5, cheese_count=12) If you're allowed to use the library, import functools aaa = functools.partial(cheese_and_crackers, 3) then call aaa(19) That's all I've got right now, but we could really go crazy... -- DaveA From alan.gauld at btinternet.com Sun Feb 12 00:11:55 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 11 Feb 2012 23:11:55 +0000 Subject: [Tutor] Learn Python The Hard Way, Ex19-3 In-Reply-To: References: Message-ID: On 11/02/12 22:26, amt wrote: > Write at least one more function of your own design, > and run it 10 different ways. It's hard to know without reading the book what the author has in mind but I'll add yet another option to the mix. Create a new function that takes your function as an argument and calls it... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mjolewis at gmail.com Sun Feb 12 00:22:54 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Sat, 11 Feb 2012 15:22:54 -0800 Subject: [Tutor] repeat a sequence in range Message-ID: I am trying to repeat a certain sequence in a range if a certain even occurs. Forgive me for not pasting my code; but I am not at the machine where it's saved. Basically, I want to get user input and append that input to a list only if the input is not already in the list. I want to do this x amount of times, but if the user input is already in the list, then I want to repeat that step in range(x). At the prompt, I want to ask the user for: Name 1: Name 2: Name 3: etc.... but if the user input for Name 3 was the same as the user input for Name 2, then I want to ask the user again for Name 3 instead of continuing to Name 4. How can I do this? -- Michael J. Lewis mjolewis at gmail.com 415.815.7257 -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sun Feb 12 00:31:15 2012 From: d at davea.name (Dave Angel) Date: Sat, 11 Feb 2012 18:31:15 -0500 Subject: [Tutor] repeat a sequence in range In-Reply-To: References: Message-ID: <4F36FA43.8070104@davea.name> On 02/11/2012 06:22 PM, Michael Lewis wrote: > I am trying to repeat a certain sequence in a range if a certain even > occurs. Forgive me for not pasting my code; but I am not at the machine > where it's saved. > > Basically, I want to get user input and append that input to a list only if > the input is not already in the list. I want to do this x amount of times, > but if the user input is already in the list, then I want to repeat that > step in range(x). > > At the prompt, I want to ask the user for: > > Name 1: > Name 2: > Name 3: > etc.... > but if the user input for Name 3 was the same as the user input for Name > 2, then I want to ask the user again for Name 3 instead of continuing to > Name 4. > > How can I do this? > You imply that you're using a range, and I suspect you're writing the loop as for elem in range(10): But since you don't know how many times you want to loop, why not switch to a different loop construct? while len(mylist) < 10: then you do your input and if the answer is not in the list, append it and loop around. If it is in the list, tell the user that it's a duplicate and loop around without appending. -- DaveA From brian.van.den.broek at gmail.com Sun Feb 12 01:29:35 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Sun, 12 Feb 2012 02:29:35 +0200 Subject: [Tutor] Learn Python The Hard Way, Ex19-3 In-Reply-To: References: Message-ID: On 12 Feb 2012 00:29, "amt" <0101amt at gmail.com> wrote: > > Hello! I'm currently stuck at the Extra Credit 3 from LPTHW. > > Link to the actual exercise: http://learnpythonthehardway.org/book/ex19.html > The exercise: > Write at least one more function of your own design, and run it 10 > different ways. > > > Code from the book: > def cheese_and_crackers(cheese_count, boxes_of_crackers): > print "You have %d cheeses!" % cheese_count > print "You have %d boxes of crackers!" % boxes_of_crackers > print "Man that's enough for a party!" > print "Get a blanket.\n" > > > print "We can just give the function numbers directly:" > cheese_and_crackers(20, 30) > I wrote a function similar to cheese_and_crackers and it works just > fine but I can't figure out more ways of calling a function other than > the ones presented in the code(with integers as arguments,variables as > arguments, two integer additions as arguments and with arguments in > the form of variable+integer). The author states that there are 10 > different ways to run it.(in a comment he states that: "You can run it > a lot of different ways, far too many to enumerate.). > > > So, what other ways are there aside the ones already presented in the > above code? > > Hi, Subject to the same caveats as your other replies: How about for (cheesecount, crackercount) in [(3,5), (7,42)]: cheese_and_crackers(cheesecount, crackercount) Best, Brian vdB -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Feb 12 01:54:35 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 12 Feb 2012 00:54:35 +0000 Subject: [Tutor] Learn Python The Hard Way, Ex19-3 In-Reply-To: References: Message-ID: On 11/02/12 22:26, amt wrote: > Write at least one more function of your own design, and run it 10 > different ways. Put it in a dictionary and call it by name... Put it in a list of functions and call it as part of a loop. Create a lambda with it as expression and then call the lambda Just 3 more... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From tmikk at umn.edu Sun Feb 12 04:19:50 2012 From: tmikk at umn.edu (Tonu Mikk) Date: Sat, 11 Feb 2012 21:19:50 -0600 Subject: [Tutor] exercise with classes 2nd attempt Message-ID: I am learning Python using the "Learn Python the Hard Way" book by Zed Shaw. I reached exercise 42 where we learn about Python classes. The exercise shows a game with one class that includes all the definitions for playing the game. For extra credit we are asked to create another version of this game where we use two classes - one for the room definitions and the other for the playing the game. May attempt at creating two classes is here http://codepad.org/963vUgSt . I get the following error which I have been un-able to resolve. Any suggestions are welcome. Traceback (most recent call last): File "ex42_3.py", line 233, in run() File "ex42_3.py", line 231, in run room1.doIt() # plays the game File "ex42_3.py", line 32, in doIt self.obj.play() # use object File "ex42_3.py", line 20, in play room = getattr(self, next) AttributeError: 'Engine' object has no attribute 'central_corridor' Tonu -------------- next part -------------- An HTML attachment was scrubbed... URL: From talmidim at live.com Sun Feb 12 08:21:19 2012 From: talmidim at live.com (Yony Torres) Date: Sun, 12 Feb 2012 02:21:19 -0500 Subject: [Tutor] Running Files with Command Lines Message-ID: Hello buddies I'm trying to learn Python from a well known book, and i'm stuck with something that i know that might seem surprisingly easy for you and i would like to humbly request your help: i created a script in a file named script1.py and i saved it in the folder named python journey located in this path c:\users\myusername\documents\varios 2\python journey\ i tested the script1.py file via the GUI and it works fine...BUT!...i have been trying to run it via the Python command line and the Windows CMD... UNSUCCESSFULLY :( the instructions given in the book are these as follows: "Once you?ve saved this text file, you can ask Python to run it by listing its full filename as the first argument to a python command, typed at the system shell prompt:" % python script1.py "Again, you can type such a system shell command in whatever your system provides for command-line entry?a Windows Command Prompt window, an xterm window,or similar. Remember to replace ?python? with a full directory path, as before, if your PATH setting is not configured." what i did was this: I typed all this options: c:\users\myusername\documents\varios 2\python journey> script1.py c:\users\myusername\documents\varios 2\python journey\ script1.py c:\users\myusername\documents\varios 2\python journey\script1.py what am i doing wrong? can somebody please help me? -------------- next part -------------- An HTML attachment was scrubbed... URL: From talmidim at live.com Sun Feb 12 08:24:58 2012 From: talmidim at live.com (Yony Torres) Date: Sun, 12 Feb 2012 02:24:58 -0500 Subject: [Tutor] Running Files with Command Lines Message-ID: Hello buddies I'm trying to learn Python from a well known book, and i'm stuck with something that i know that might seem surprisingly easy for you and i would like to humbly request your help: i created a script in a file named script1.py and i saved it in the folder named python journey located in this path c:\users\myusername\documents\varios 2\python journey\ i tested the script1.py file via the GUI and it works fine...BUT!...i have been trying to run it via the Python command line and the Windows CMD... UNSUCCESSFULLY :( the instructions given in the book are these as follows: "Once you?ve saved this text file, you can ask Python to run it by listing its full filename?as the first argument to a python command, typed at the system shell prompt:" % python script1.py "Again, you can type such a system shell command in whatever your system provides?for command-line entry?a Windows Command Prompt window, an xterm window,or similar. Remember to replace ?python? with a full directory path, as before, if your?PATH setting is not configured." what i did was this:? I typed all this options: c:\users\myusername\documents\varios 2\python journey> script1.py c:\users\myusername\documents\varios 2\python journey\ script1.py c:\users\myusername\documents\varios 2\python journey\script1.py what am i doing wrong? can somebody please help me? From silideba at gmail.com Sun Feb 12 08:26:37 2012 From: silideba at gmail.com (Debashish Saha) Date: Sun, 12 Feb 2012 12:56:37 +0530 Subject: [Tutor] (no subject) Message-ID: import numpy as np import matplotlib.pyplot as plt E=[81.97400737666324, 322.0939978589591, 694.5766491226185] V0=1000 a=0.1 def V(x): if x > -a and x < a: return 0 return V0 V=np.vectorize(V) #psi=np.vectorize(psi) x= np.linspace(-1.5*a,1.5*a,100) plt.plot(x,V(x)) plt.xlim(-5*a,5*a) plt.ylim(-.001*V0,1.01*V0) for m in E: x1=np.linspace(-a,+a,100) #y=m #plt.xlim(-5*a,5*a) #plt.axhline(m) #y=np.vectorize(y) plt.plot(x1,m) #plt.show() print m Error: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) C:\Python27\lib\site-packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc) 166 else: 167 filename = fname --> 168 exec compile(scripttext, filename, 'exec') in glob, loc 169 else: 170 def execfile(fname, *where): C:\Users\as\uy.py in () 23 #plt.axhline(m) 24 #y=np.vectorize(y) ---> 25 plt.plot(x1,m) 26 #plt.show() 27 print m C:\Python27\lib\site-packages\matplotlib\pyplot.pyc in plot(*args, **kwargs) 2456 ax.hold(hold) 2457 try: -> 2458 ret = ax.plot(*args, **kwargs) 2459 draw_if_interactive() 2460 finally: C:\Python27\lib\site-packages\matplotlib\axes.pyc in plot(self, *args, **kwargs) 3846 lines = [] 3847 -> 3848 for line in self._get_lines(*args, **kwargs): 3849 self.add_line(line) 3850 lines.append(line) C:\Python27\lib\site-packages\matplotlib\axes.pyc in _grab_next_args(self, *args, **kwargs) 321 return 322 if len(remaining) <= 3: --> 323 for seg in self._plot_args(remaining, kwargs): 324 yield seg 325 return C:\Python27\lib\site-packages\matplotlib\axes.pyc in _plot_args(self, tup, kwargs) 298 x = np.arange(y.shape[0], dtype=float) 299 --> 300 x, y = self._xy_from_xy(x, y) 301 302 if self.command == 'plot': C:\Python27\lib\site-packages\matplotlib\axes.pyc in _xy_from_xy(self, x, y) 238 y = np.atleast_1d(y) 239 if x.shape[0] != y.shape[0]: --> 240 raise ValueError("x and y must have same first dimension") 241 if x.ndim > 2 or y.ndim > 2: 242 raise ValueError("x and y can be no greater than 2-D") ValueError: x and y must have same first dimension Question: then how to plot those specific component of E within the square well omly? From d at davea.name Sun Feb 12 08:45:33 2012 From: d at davea.name (Dave Angel) Date: Sun, 12 Feb 2012 02:45:33 -0500 Subject: [Tutor] Running Files with Command Lines In-Reply-To: References: Message-ID: <4F376E1D.60205@davea.name> On 02/12/2012 02:24 AM, Yony Torres wrote: > Hello buddies > > I'm trying to learn Python from a well known book, and i'm stuck with something that i know that might seem surprisingly easy for you and i would like to humbly request your help: > i created a script in a file named script1.py and i saved it in the folder named python journey located in this path c:\users\myusername\documents\varios 2\python journey\ > i tested the script1.py file via the GUI and it works fine...BUT!...i have been trying to run it via the Python command line and the Windows CMD... UNSUCCESSFULLY :( > the instructions given in the book are these as follows: > "Once you?ve saved this text file, you can ask Python to run it by listing its full filename as the first argument to a python command, typed at the system shell prompt:" > % python script1.py > "Again, you can type such a system shell command in whatever your system provides for command-line entry?a Windows Command Prompt window, an xterm window,or similar. Remember to replace ?python? with a full directory path, as before, if your PATH setting is not configured." > what i did was this: > I typed all this options: > c:\users\myusername\documents\varios 2\python journey> script1.py > c:\users\myusername\documents\varios 2\python journey\ script1.py > c:\users\myusername\documents\varios 2\python journey\script1.py > > what am i doing wrong? can somebody please help me? > _______________________________________________ The first command may have wiped out the script1.py, so maybe that's why it stopped working. I could also point out that making directories with spaces in them (on Windows) is a recipe for disaster, and if you're stuck with it, then get used to using quotes around things. Now, it'd be much more useful to show us the full stuff you typed, and the error you received, complete with traceback if it got that far. You can copy/paste from (or to) a DOS box; if you don't know how, ask. Still, I'll make a guess. I'd guess that you didn't install python in the c:\users\myusername\docu,ents\varios 2\ directory. And yet, that's what you're telling the cmd processor to run. Everything up to the first space is the program to run. Try just typing python, and see if your installation has it on your path. if it doesn't, perhaps that's something you'd like to fix while you're working on the problem. Go change your environment variable PATH to include the installation location of python.exe You can fix that permanently in the control panel, or edit the path in a particular DOS box. If that doesn't show the python interpreter starting up, and you get something like "command not found", then do as the book said, only use the path that you actuallly installed to, which is probably something like c:\python35\python I'd also recommend while you're playing, to change the current directory to be the location of the script. That way any assumptions the script may make about current directory will make sense. -- DaveA From alan.gauld at btinternet.com Sun Feb 12 10:06:41 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 12 Feb 2012 09:06:41 +0000 Subject: [Tutor] Running Files with Command Lines In-Reply-To: References: Message-ID: On 12/02/12 07:24, Yony Torres wrote: > "Once you?ve saved this text file, you can ask Python to run it > by listing its full filename as the first argument to a > python command, typed at the system shell prompt:" > % python script1.py Lets break down what this line is saying. It comprises three parts: 1) the operating system command prompt, shown as '%' 2) the python interpreter shown as 'python' 3) the python script to be interpreted, shown as script1.py You only need to type the last two since your OS will provide the first one. On Windows that will usually look like C:\WINDOWS> or similar. The path to the interpreter normally looks like C:\python31\python And the path to your script we know is: c:\users\myusername\documents\varios 2\python journey\script1.py And because you have a space in there we must put quotes aroundd it: "c:\users\myusername\documents\varios 2\python journey\script1.py" So the command that you type in your CMD shell window should look like: C:\python31\python "c:\users\myusername\documents\varios 2\python journey\script1.py" all on one line. Now we can shorten that significantly by setting Python to be in the PATH. That way you don't need to provide the full path to Python. (To set the path follow the instructions in my tutor in the "Windows Command prompt" box in the "Getting started" topic.) Next, you can change into the folder with your script using CD "c:\users\myusername\documents\varios 2\python journey" (The prompt should now show the path to your script) Now you only need to type: python script1.py HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From evert.rol at gmail.com Sun Feb 12 11:59:57 2012 From: evert.rol at gmail.com (Evert Rol) Date: Sun, 12 Feb 2012 11:59:57 +0100 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: Hi, Tip: use a meaningful subject line; attracts more/better attention and makes it easier to trace your email in the archives. Continued at the bottom. > import numpy as np > import matplotlib.pyplot as plt > E=[81.97400737666324, 322.0939978589591, 694.5766491226185] > V0=1000 > a=0.1 > def V(x): > if x > -a and x < a: > return 0 > return V0 > > V=np.vectorize(V) > #psi=np.vectorize(psi) > x= np.linspace(-1.5*a,1.5*a,100) > > plt.plot(x,V(x)) > plt.xlim(-5*a,5*a) > plt.ylim(-.001*V0,1.01*V0) > for m in E: > x1=np.linspace(-a,+a,100) > #y=m > #plt.xlim(-5*a,5*a) > #plt.axhline(m) > #y=np.vectorize(y) > plt.plot(x1,m) > #plt.show() > print m > > Error: > --------------------------------------------------------------------------- > ValueError Traceback (most recent call last) > C:\Python27\lib\site-packages\IPython\utils\py3compat.pyc in > execfile(fname, glob, loc) > 166 else: > 167 filename = fname > --> 168 exec compile(scripttext, filename, 'exec') in glob, loc > 169 else: > 170 def execfile(fname, *where): > > C:\Users\as\uy.py in () > 23 #plt.axhline(m) > > 24 #y=np.vectorize(y) > > ---> 25 plt.plot(x1,m) > 26 #plt.show() > > 27 print m > > C:\Python27\lib\site-packages\matplotlib\pyplot.pyc in plot(*args, **kwargs) > 2456 ax.hold(hold) > 2457 try: > -> 2458 ret = ax.plot(*args, **kwargs) > 2459 draw_if_interactive() > 2460 finally: > > C:\Python27\lib\site-packages\matplotlib\axes.pyc in plot(self, *args, **kwargs) > 3846 lines = [] > 3847 > -> 3848 for line in self._get_lines(*args, **kwargs): > 3849 self.add_line(line) > 3850 lines.append(line) > > C:\Python27\lib\site-packages\matplotlib\axes.pyc in > _grab_next_args(self, *args, **kwargs) > 321 return > 322 if len(remaining) <= 3: > --> 323 for seg in self._plot_args(remaining, kwargs): > 324 yield seg > 325 return > > C:\Python27\lib\site-packages\matplotlib\axes.pyc in _plot_args(self, > tup, kwargs) > 298 x = np.arange(y.shape[0], dtype=float) > 299 > --> 300 x, y = self._xy_from_xy(x, y) > 301 > 302 if self.command == 'plot': > > C:\Python27\lib\site-packages\matplotlib\axes.pyc in _xy_from_xy(self, x, y) > 238 y = np.atleast_1d(y) > 239 if x.shape[0] != y.shape[0]: > --> 240 raise ValueError("x and y must have same first dimension") > 241 if x.ndim > 2 or y.ndim > 2: > 242 raise ValueError("x and y can be no greater than 2-D") > > ValueError: x and y must have same first dimension Read the error message: *same (first) dimension* Then search where in your program the exception occurred: C:\Users\as\uy.py in () 23 #plt.axhline(m) 24 #y=np.vectorize(y) ---> 25 plt.plot(x1,m) 26 #plt.show() 27 print m So, x1 and m don't have the same first dimension. Try printing x1 and m before this statement (not after, like you did for m); just as a debug line. Then see if you can figure out why m isn't what probably you want it to be. Good luck, Evert > > > Question: > then how to plot those specific component of E within the square well omly? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From __peter__ at web.de Sun Feb 12 12:01:18 2012 From: __peter__ at web.de (Peter Otten) Date: Sun, 12 Feb 2012 12:01:18 +0100 Subject: [Tutor] repeat a sequence in range References: Message-ID: Michael Lewis wrote: > I am trying to repeat a certain sequence in a range if a certain even > occurs. Forgive me for not pasting my code; but I am not at the machine > where it's saved. > > Basically, I want to get user input and append that input to a list only > if the input is not already in the list. I want to do this x amount of > times, but if the user input is already in the list, then I want to repeat > that step in range(x). > > At the prompt, I want to ask the user for: > > Name 1: > Name 2: > Name 3: > etc.... > but if the user input for Name 3 was the same as the user input for Name > 2, then I want to ask the user again for Name 3 instead of continuing to > Name 4. > > How can I do this? Well, you are describing the algorithm pretty clearly: keep asking for a name until the user enters a name that is not in the list of names already. Here's a straightforward implementation: >>> names = [] >>> for i in range(1, 4): ... while True: ... name = raw_input("Name %d: " % i) ... if name not in names: ... names.append(name) ... break ... print "Name %r already taken" % name ... Name 1: Jack Name 2: Jack Name 'Jack' already taken Name 2: Jack Name 'Jack' already taken Name 2: Jim Name 3: Jack Name 'Jack' already taken Name 3: Jim Name 'Jim' already taken Name 3: Joe >>> names ['Jack', 'Jim', 'Joe'] From bgailer at gmail.com Sun Feb 12 12:06:22 2012 From: bgailer at gmail.com (bob gailer) Date: Sun, 12 Feb 2012 06:06:22 -0500 Subject: [Tutor] Running Files with Command Lines In-Reply-To: References: Message-ID: <4F379D2E.8000606@gmail.com> On 2/12/2012 2:21 AM, Yony Torres wrote: > Hello buddies > > > I'm trying to learn Python from a well known book, and i'm stuck with > something that i know that might seem surprisingly easy for you and i > would like to humbly request your help: > > i created a script in a file named script1.py and i saved it in the > folder named python journey located in this path > c:\users\myusername\documents\varios 2\python journey\ > > i tested the script1.py file via the GUI and it works fine...BUT!...i > have been trying to run it via the Python command line and the Windows > CMD... UNSUCCESSFULLY :( > > the instructions given in the book are these as follows: > > "Once you've saved this text file, you can ask Python to run it by > listing its full filename as the first argument to a python command, > typed at the system shell prompt:" > > % python script1.py > > "Again, you can type such a system shell command in whatever your > system provides for command-line entry---a Windows Command Prompt > window, an xterm window, > or similar. Remember to replace "python" with a full directory path, > as before, if your PATH setting is not configured." > > what i did was this: > > I typed all this options: > > c:\users\myusername\documents\varios 2\python journey> script1.py > > c:\users\myusername\documents\varios 2\python journey\ script1.py > > c:\users\myusername\documents\varios 2\python journey\script1.py > > > what am i doing wrong? can somebody please help me? Thanks for asking. When you ask for help please tell us which version of Python and what OS you are running, and what (if any) errors or unexpected results you are getting. The more info you give us the easier it is for us to help. Also be sure to reply-all so a copy goes to the list. The directions you were given are hard to follow, and a lot depends on how your system is configured. Once we see the error you are getting we can better help. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From silideba at gmail.com Sun Feb 12 12:54:13 2012 From: silideba at gmail.com (Debashish Saha) Date: Sun, 12 Feb 2012 17:24:13 +0530 Subject: [Tutor] how to stop a running program in python without closing python interface? Message-ID: actually a i ran a progam in python which is sufficiently large . so i want to stop the execution of the program now . how can i do this? From das.mm.mm at gmail.com Sun Feb 12 13:06:57 2012 From: das.mm.mm at gmail.com (David Smith) Date: Sun, 12 Feb 2012 12:06:57 +0000 Subject: [Tutor] how to stop a running program in python without closing python interface? In-Reply-To: References: Message-ID: <15B3EF92-4283-468F-A9FE-B2D19DE80BC1@gmail.com> On 12 Feb 2012, at 11:54, Debashish Saha wrote: > actually a i ran a progam in python which is sufficiently large . so i > want to stop the execution of the program now . how can i do this? This will depend on your operating system. On a Mac you press alt + command + esc and the choose the program you want to Force Quit. I have no idea what you do on Windows or Unix. Dax From silideba at gmail.com Sun Feb 12 13:47:34 2012 From: silideba at gmail.com (Debashish Saha) Date: Sun, 12 Feb 2012 18:17:34 +0530 Subject: [Tutor] how to print a string in desired colour Message-ID: suppose i want to print 'hello world' in color blue.so what to do? i tried print 'hello world','blue' From evert.rol at gmail.com Sun Feb 12 13:55:26 2012 From: evert.rol at gmail.com (Evert Rol) Date: Sun, 12 Feb 2012 13:55:26 +0100 Subject: [Tutor] how to stop a running program in python without closing python interface? In-Reply-To: <15B3EF92-4283-468F-A9FE-B2D19DE80BC1@gmail.com> References: <15B3EF92-4283-468F-A9FE-B2D19DE80BC1@gmail.com> Message-ID: <66E77F5B-38B8-457B-BA6C-FB15D32DDCD2@gmail.com> >> actually a i ran a progam in python which is sufficiently large . so i >> want to stop the execution of the program now . how can i do this? > > This will depend on your operating system. > > On a Mac you press alt + command + esc and the choose the program you want to Force Quit. I have no idea what you do on Windows or Unix. Going by the subject line, and assuming you're running the python shell (I don't know about Python IDEs etc), you may want to try control-C instead. That will stop the currently running function or similar, while leaving you in the shell: >>> while True: ... pass ... ^CTraceback (most recent call last): File "", line 2, in KeyboardInterrupt >>> Evert From sirgnip at gmail.com Sun Feb 12 14:02:35 2012 From: sirgnip at gmail.com (Scott Nelson) Date: Sun, 12 Feb 2012 07:02:35 -0600 Subject: [Tutor] how to print a string in desired colour In-Reply-To: References: Message-ID: On Sun, Feb 12, 2012 at 6:47 AM, Debashish Saha wrote: > suppose i want to print 'hello world' in color blue.so what to do? > > There was a similar thread awhile ago. Unfortunately the answer isn't an easy one. It depends on what operating system you use. Here's a link to the old thread: http://comments.gmane.org/gmane.comp.python.tutor/67743 -------------- next part -------------- An HTML attachment was scrubbed... URL: From williamjstewart at rogers.com Sun Feb 12 14:25:31 2012 From: williamjstewart at rogers.com (William Stewart) Date: Sun, 12 Feb 2012 05:25:31 -0800 (PST) Subject: [Tutor] string integers? Message-ID: <1329053131.44653.YahooMailClassic@web88614.mail.bf1.yahoo.com> I am trying to get 2 string variables and 2 integer variables to be able to be multiplied can anyone tell me what I did wrong ? str1 = raw_input("Type in a String: ") str2 = raw_input("Type in a String: ") int1 = raw_input("Type in a integer variable: ") int2 = raw_input("Type in a integer variable: ") print str1 + str2 + int1 + int2 import math print str1, "*", str2, "*", int1, "*"int2 ?"=", str1, * str2, * int1 * int 2 ? ? and it wont let me write int2 I know this may look stupid to most people? but I am just new at this so dont laugh? :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Feb 12 14:19:07 2012 From: bgailer at gmail.com (bob gailer) Date: Sun, 12 Feb 2012 08:19:07 -0500 Subject: [Tutor] how to print a string in desired colour In-Reply-To: References: Message-ID: <4F37BC4B.9020900@gmail.com> Please always tell us which OS you are using, which version of Python. When something you try does not give you the result you want, please tell us what you got. In a case like this also tell us where you want the colored text to appear. It may be obvious to you but it is not to us. Given how long you've been on this list I'd think you'd know all that by now. On 2/12/2012 7:47 AM, Debashish Saha wrote: > suppose i want to print 'hello world' in color blue.so what to do? Ths stupid answer is "take a blue marker and write 'hello world'" > > i tried > print 'hello world','blue' Where did you get the idea that that would do what you want????? Did you read the documentation regarding print? Please do not post stuff that is obviously wrong! No one can tell you how to create colored output until we know where you are trying to get it to display. -- Bob Gailer 919-636-4239 Chapel Hill NC From hugo.yoshi at gmail.com Sun Feb 12 14:51:45 2012 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 12 Feb 2012 14:51:45 +0100 Subject: [Tutor] string integers? In-Reply-To: <1329053131.44653.YahooMailClassic@web88614.mail.bf1.yahoo.com> References: <1329053131.44653.YahooMailClassic@web88614.mail.bf1.yahoo.com> Message-ID: On Sun, Feb 12, 2012 at 2:25 PM, William Stewart wrote: > I am trying to get 2 string variables and 2 integer variables to be able > to be multiplied > can anyone tell me what I did wrong > > str1 = raw_input("Type in a String: ") > str2 = raw_input("Type in a String: ") > int1 = raw_input("Type in a integer variable: ") > int2 = raw_input("Type in a integer variable: ") > print str1 + str2 + int1 + int2 > import math > print str1, "*", str2, "*", int1, "*"int2 "=", str1, * str2, * int1 * int > 2 > > > > and it wont let me write int2 > I know this may look stupid to most people but I am just new at this so > dont laugh :) > > No worries, this list is aimed toward new people. No one asking questions here looks stupid. Now, when you post to places like this, make sure you mention 1) what you thought would happen or what you're trying to do (you've got this one decently covered) 2) what happened instead (if an error message happened, paste it!!! It's almost always useful to us). Your first problem is the commas in the print statement. You have commas in places where they shouldn't be, and no commas in places where they should. I'm not gonna give everything away, but look real close at it again. If you have to put a lot of variables inside a string, all these commas do end up being fairly confusing. You might want to have a look at the format method, I'll give you a sample: print "{0} * {1} * {2} * {3} = {4}".format(str1, str2, int1, int2, str1 * str2 * int1 * int2) The curly brackets are replaced by an argument of the format call. The number indicates which argument. This way, you don't get commas all over the place and you keep things nice and organized. You should also know that you really can't multiply strings. You'll get a TypeError if you try. HTH, Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From brian.van.den.broek at gmail.com Sun Feb 12 14:53:22 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Sun, 12 Feb 2012 15:53:22 +0200 Subject: [Tutor] string integers? In-Reply-To: <1329053131.44653.YahooMailClassic@web88614.mail.bf1.yahoo.com> References: <1329053131.44653.YahooMailClassic@web88614.mail.bf1.yahoo.com> Message-ID: On 12 Feb 2012 15:28, "William Stewart" wrote: > > I am trying to get 2 string variables and 2 integer variables to be able to be multiplied > can anyone tell me what I did wrong > > str1 = raw_input("Type in a String: ") > str2 = raw_input("Type in a String: ") > int1 = raw_input("Type in a integer variable: ") > int2 = raw_input("Type in a integer variable: ") > print str1 + str2 + int1 + int2 > import math > print str1, "*", str2, "*", int1, "*"int2 "=", str1, * str2, * int1 * int 2 > > > > and it wont let me write int2 > I know this may look stupid to most people but I am just new at this so dont laugh :) > Hi, It is a bit unclear what you mean by "it wont let me write int2". Try running this function and see if it helps: def test(): data = raw_input("give me an integer") print type(data) print "a string" * "another" Best, Brian vdB -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanpierreda at gmail.com Sun Feb 12 14:55:22 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 12 Feb 2012 08:55:22 -0500 Subject: [Tutor] how to print a string in desired colour In-Reply-To: References: Message-ID: On Sun, Feb 12, 2012 at 8:02 AM, Scott Nelson wrote: > On Sun, Feb 12, 2012 at 6:47 AM, Debashish Saha wrote: >> >> suppose i want to print 'hello world' in color blue.so what to do? >> > > There was a similar thread awhile ago. ?Unfortunately the answer isn't an > easy one. ?It depends on what operating system you use. ?Here's a link to > the old thread:?http://comments.gmane.org/gmane.comp.python.tutor/67743 Colorama works on every major desktop platform. http://pypi.python.org/pypi/colorama -- Devin From daedae11 at 126.com Sun Feb 12 14:31:57 2012 From: daedae11 at 126.com (daedae11) Date: Sun, 12 Feb 2012 21:31:57 +0800 Subject: [Tutor] Same code has different result Message-ID: <201202122131571930448@126.com> The code is: from nntplib import NNTP s = NNTP('news.gmane.org') resp, count, first, last, name = s.group('gmane.comp.python.committers') print 'Group', name, 'has', count, 'articles, range', first, 'to', last resp, subs = s.xhdr('subject', first + '-' + last) for id, sub in subs[-10:]: print id, sub s.quit() When I write it into a script, it can execute normally. However, when I input it in interpreter line by line, I got the follow error when I execute the third sentence. What's the matter? >>> s = NNTP('news.gmane.org') >>> resp, count, first, last, name = s.group('gmane.comp.python.committers') Traceback (most recent call last): File "", line 1, in File "D:\Python27\lib\nntplib.py", line 345, in group resp = self.shortcmd('GROUP ' + name) File "D:\Python27\lib\nntplib.py", line 259, in shortcmd return self.getresp() File "D:\Python27\lib\nntplib.py", line 214, in getresp resp = self.getline() File "D:\Python27\lib\nntplib.py", line 206, in getline if not line: raise EOFError EOFError daedae11 -------------- next part -------------- An HTML attachment was scrubbed... URL: From brian.van.den.broek at gmail.com Sun Feb 12 15:16:39 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Sun, 12 Feb 2012 16:16:39 +0200 Subject: [Tutor] exercise with classes 2nd attempt In-Reply-To: References: Message-ID: On 12 Feb 2012 05:23, "Tonu Mikk" wrote: > > I am learning Python using the "Learn Python the Hard Way" book by Zed Shaw. I reached exercise 42 where we learn about Python classes. The exercise shows a game with one class that includes all the definitions for playing the game. For extra credit we are asked to create another version of this game where we use two classes - one for the room definitions and the other for the playing the game. > > May attempt at creating two classes is here http://codepad.org/963vUgSt . I get the following error which I have been un-able to resolve. Any suggestions are welcome. > > Traceback (most recent call last): > File "ex42_3.py", line 233, in > run() > File "ex42_3.py", line 231, in run > room1.doIt() # plays the game > File "ex42_3.py", line 32, in doIt > self.obj.play() # use object > File "ex42_3.py", line 20, in play > room = getattr(self, next) > AttributeError: 'Engine' object has no attribute 'central_corridor' Hi, Your code is longer than I feel like reading carefully. (Not a complaint; just cautioning you about how closely I looked.) Also, the line numbers of your code sample do not agree with those of your traceback. (That is a mild complaint; it makes it harder to help you.) Notice that you defined central_corridor as a method of Room. The last line of your traceback is (it seems) in Engine.play; the code there looks for central_corridor in Engine and doesn't find it. If that help, great. If not, try to trim down your code to a smaller version that exhibits the problem and post again, this time making sure the posted code and the code that generate the traceback are the same. Best, Brian vdB -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sun Feb 12 15:51:59 2012 From: d at davea.name (Dave Angel) Date: Sun, 12 Feb 2012 09:51:59 -0500 Subject: [Tutor] string integers? In-Reply-To: <1329053131.44653.YahooMailClassic@web88614.mail.bf1.yahoo.com> References: <1329053131.44653.YahooMailClassic@web88614.mail.bf1.yahoo.com> Message-ID: <4F37D20F.1020707@davea.name> On 02/12/2012 08:25 AM, William Stewart wrote: > I am trying to get 2 string variables and 2 integer variables to be able to be multiplied > can anyone tell me what I did wrong > > str1 = raw_input("Type in a String: ") > str2 = raw_input("Type in a String: ") > int1 = raw_input("Type in a integer variable: ") > int2 = raw_input("Type in a integer variable: ") > print str1 + str2 + int1 + int2 > import math > print str1, "*", str2, "*", int1, "*"int2 "=", str1, * str2, * int1 * int 2 > > > > and it wont let me write int2 > I know this may look stupid to most people but I am just new at this so dont laugh :) > That's who this list is targeted at, people who are just learning Python. Are you new to programming, or just to Python? Anyway, welcome to Python-Tutor list. If these 7 lines are in a file, and you try to run them, you get a specific error, pointing to a specific line. When asking questions about Python error messages, please post the actual message, as it generally contains lots of clues as to what's wrong. davea at think:~/temppython$ python william.py File "william.py", line 7 print str1, "*", str2, "*", int1, "*"int2 "=", str1, * str2, * int1 * int 2 ^ SyntaxError: invalid syntax So now we both know the error is a syntax error, and it occurs on line 7, which is conveniently redisplayed with a caret pointing at where the error was discovered (notice that in many email systems a proportional font may hide the correct column. So trust what you saw on your own terminal window). Sometimes the actual syntax error is a few characters earlier, but this is as fine-tuned as most compilers can manage. That print line has 4 errors that I can immediately spot, and the compiler told you about the first one. That error was in omitting the comma before the first occurrence of the variable int2. You butted a string literal right up to a variable name, with no operator between. My usual advice when seeing a beginner with a complex line that gives a syntax error is to see if you can replace it by a few simpler lines. Then the error might be more obvious. So use several print lines. So what if the output isn't quite right; you have some more debugging to do before you'll even see that output. Now let me ask you, how is str1 any different from int1 ? Python does not have typed variables, and it certainly pays no attention to the spelling of a name to guess what it's intended to hold. The same name str1 can hold a string one time, an integer another time, a list yet another. The only way you're going to get those 3rd and 4th lines to make integer objects is to convert the string that raw_input() returns into an integer. So use int1 = int(raw_input("xxxxx")) The next problem will probably be easier for you to spot, but if not, remember to post the full error message, not some summary of it. -- DaveA From andipersti at gmail.com Sun Feb 12 16:13:01 2012 From: andipersti at gmail.com (Andreas Perstinger) Date: Sun, 12 Feb 2012 16:13:01 +0100 Subject: [Tutor] Same code has different result In-Reply-To: <201202122131571930448@126.com> References: <201202122131571930448@126.com> Message-ID: <20120212161301.90c32b90ffcfa0a990a6be35@gmail.com> On Sun, 12 Feb 2012 21:31:57 +0800 daedae11 wrote: > The code is: > from nntplib import NNTP > s = NNTP('news.gmane.org') > resp, count, first, last, name = s.group > ('gmane.comp.python.committers') print 'Group', name, 'has', count, > 'articles, range', first, 'to', last resp, subs = s.xhdr('subject', > first + '-' + last) for id, sub in subs[-10:]: > print id, sub > s.quit() > > When I write it into a script, it can execute normally. However, when > I input it in interpreter line by line, I got the follow error when I > execute the third sentence. What's the matter? It seems that the connection is closed if you need more than about 6-7 seconds (on my computer) to type the third line. >From the source of "nntplib.py": def getline(self): """Internal: return one line from the server, stripping CRLF. Raise EOFError if the connection is closed.""" Bye, Andreas From breamoreboy at yahoo.co.uk Sun Feb 12 16:22:19 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 12 Feb 2012 15:22:19 +0000 Subject: [Tutor] string integers? In-Reply-To: <4F37D20F.1020707@davea.name> References: <1329053131.44653.YahooMailClassic@web88614.mail.bf1.yahoo.com> <4F37D20F.1020707@davea.name> Message-ID: On 12/02/2012 14:51, Dave Angel wrote: > On 02/12/2012 08:25 AM, William Stewart wrote: [snipped] > My usual advice when seeing a beginner with a complex line that gives a > syntax error is to see if you can replace it by a few simpler lines. > Then the error might be more obvious. So use several print lines. So > what if the output isn't quite right; you have some more debugging to do > before you'll even see that output. > For the OP. print str1, "*", str2, "*", int1, "*"int2 "=", str1, * str2, * int1 * int 2 To print all of this on one line you can use print str1, print "*", etc See http://docs.python.org/tutorial/inputoutput.html -- Cheers. Mark Lawrence. From talmidim at live.com Sun Feb 12 16:50:36 2012 From: talmidim at live.com (Yony Torres) Date: Sun, 12 Feb 2012 10:50:36 -0500 Subject: [Tutor] Running Files with Command Lines In-Reply-To: <4F379D2E.8000606@gmail.com> References: , <4F379D2E.8000606@gmail.com> Message-ID: hello there :) ima try it one more time, ima pasting the previous email content i sent previously so here it goes ;P I'm working in a windows vista home premium system i installed python 3.2.2 I'm trying to learn Python from a well known book, and i'm stuck with? > something that i know that might seem surprisingly easy for you and i? > would like to humbly request your help:? >? > i created a script in a file named script1.py and i saved it in the? > folder named python journey located in this path? > c:\users\myusername\documents\varios2\pythonjourney\? (as you can see i?suppressed?the spaces in the folder's names) >? > i tested the script1.py file via the GUI and it works fine...BUT!...i? > have been trying to run it via the Python command line and the Windows? > CMD... UNSUCCESSFULLY :(? >? > the instructions given in the book are these as follows:? >? > "Once you?ve saved this text file, you can ask Python to run it by? > listing its full filename as the first argument to a python command,? > typed at the system shell prompt:"? >? > % python script1.py? >? > "Again, you can type such a system shell command in whatever your? > system provides for command-line entry?a Windows Command Prompt window,? > an xterm window,? > or similar. Remember to replace ?python? with a full directory path, as? > before, if your PATH setting is not configured."? >? > what i did was this:? while i was working with the windows CMD i made sure i was working on python by entering this "code" cd c:\python32pyhton ---so, it successfully showed me this c:\Python32>pythonPython 3.2.2 (default, Sep ?4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> ----then, i tried this: >>> c:\Users\myusername\Documents\varios2\pythonjourney\ script1.py ----(please note that i put no indentation), i pressed enter and it returned this: ? File "", line 1? ? c:\Users\myusername\Documents\varios2\pythonjourney\ script1.py? ? ?^SyntaxError: invalid syntax ----then i tried what's next: >>> c:\Users\myusername\Documents\varios2\pythonjourney> script1.py----and returned this: ??File "", line 1? ? c:\Users\Talmidim\Documents\varios2\pythonjourney> script1.py? ? ?^SyntaxError: invalid syntax ----my guess was that is something wrong with writing the the ":", so i tried: >>> \Users\Talmidim\Documents\varios2\pythonjourney> script1.pyand it returned this: ??File "", line 1? ? \Users\myusername\Documents\varios2\pythonjourney> script1.py? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ^SyntaxError: unexpected character after line continuation character Can somebody please help me? thanks in advance!!! ;) ? ________________________________ > Date: Sun, 12 Feb 2012 06:06:22 -0500 > From: bgailer at gmail.com > To: talmidim at live.com > CC: tutor at python.org > Subject: Re: [Tutor] Running Files with Command Lines > > On 2/12/2012 2:21 AM, Yony Torres wrote: > Hello buddies > > > I'm trying to learn Python from a well known book, and i'm stuck with > something that i know that might seem surprisingly easy for you and i > would like to humbly request your help: > > i created a script in a file named script1.py and i saved it in the > folder named python journey located in this path > c:\users\myusername\documents\varios 2\python journey\ > > i tested the script1.py file via the GUI and it works fine...BUT!...i > have been trying to run it via the Python command line and the Windows > CMD... UNSUCCESSFULLY :( > > the instructions given in the book are these as follows: > > "Once you?ve saved this text file, you can ask Python to run it by > listing its full filename as the first argument to a python command, > typed at the system shell prompt:" > > % python script1.py > > "Again, you can type such a system shell command in whatever your > system provides for command-line entry?a Windows Command Prompt window, > an xterm window, > or similar. Remember to replace ?python? with a full directory path, as > before, if your PATH setting is not configured." > > what i did was this: > > I typed all this options: > > c:\users\myusername\documents\varios 2\python journey> script1.py > > c:\users\myusername\documents\varios 2\python journey\ script1.py > > c:\users\myusername\documents\varios 2\python journey\script1.py > > > what am i doing wrong? can somebody please help me? > > Thanks for asking. When you ask for help please tell us which version > of Python and what OS you are running, and what (if any) errors or > unexpected results you are getting. The more info you give us the > easier it is for us to help. > > Also be sure to reply-all so a copy goes to the list. > > The directions you were given are hard to follow, and a lot depends on > how your system is configured. Once we see the error you are getting we > can better help. > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC From alan.gauld at btinternet.com Sun Feb 12 17:16:47 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 12 Feb 2012 16:16:47 +0000 Subject: [Tutor] Running Files with Command Lines In-Reply-To: References: , <4F379D2E.8000606@gmail.com> Message-ID: On 12/02/12 15:50, Yony Torres wrote: > I'm trying to learn Python from a well known book, Do0n;t make us guess, tell us the name of the book, well known or not. There is just a chance somebody else may have read it too! > while i was working with the windows CMD > c:\Python32>python This is where you are going wrong. You should not run python on its own, that gets you into the Python interpreter with its own >>> prompt. For this exercise you want to run your script directly from the OS prompt (on Windows usually ending in a single >) > Can somebody please help me? See the other posted replies about typing the command. It will likely look like this(but all on a single line) C:\Python32> python c:\Users\myusername\Documents\varios2\pythonjourney\script1.py Don't put spaces in your paths, that will confuse Windows... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From talmidim at live.com Sun Feb 12 17:57:57 2012 From: talmidim at live.com (Yony Torres) Date: Sun, 12 Feb 2012 11:57:57 -0500 Subject: [Tutor] Running Files with Command Lines In-Reply-To: References: , , <4F379D2E.8000606@gmail.com>, , Message-ID: 1. i tried this morning and it worked in the CMD check it out: copied and pasted from the CMD C:\Users\myusername>cd documents C:\Users\myusername\Documents>cd varios2 C:\Users\myusername\Documents\varios2>cd pythonjourney C:\Users\myusername\Documents\varios2\pythonjourney>script.py ? ?<------- i did not write the name the file properly, my mistake!'script.py' is not recognized as an internal or external command,operable program or batch file. C:\Users\myusername\Documents\varios2\pythonjourney>script1.py ? ?<----- now i did it properlywin321267650600228229401496703205376spam!spam!spam!spam!spam!spam!spam!spam! --- i must say that previously i added C:\python32 to the environment path ;) yay! now im trying it from the python command line, with no success yet :( ---------------------------------------- > To: tutor at python.org > From: alan.gauld at btinternet.com > Date: Sun, 12 Feb 2012 16:16:47 +0000 > Subject: Re: [Tutor] Running Files with Command Lines > > On 12/02/12 15:50, Yony Torres wrote: > > > I'm trying to learn Python from a well known book, > > > Do0n;t make us guess, tell us the name of the book, well known or not. > There is just a chance somebody else may have read it too! > > > while i was working with the windows CMD > > c:\Python32>python > > This is where you are going wrong. > You should not run python on its own, that gets you into the Python > interpreter with its own >>> prompt. For this exercise you want to run > your script directly from the OS prompt (on Windows usually ending in a > single >) > > > Can somebody please help me? > > See the other posted replies about typing the command. > It will likely look like this(but all on a single line) > > C:\Python32> python > c:\Users\myusername\Documents\varios2\pythonjourney\script1.py > > Don't put spaces in your paths, that will confuse Windows... > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From andipersti at gmail.com Sun Feb 12 18:02:35 2012 From: andipersti at gmail.com (Andreas Perstinger) Date: Sun, 12 Feb 2012 18:02:35 +0100 Subject: [Tutor] Same code has different result In-Reply-To: <2012021300045417884616@126.com> References: <201202122131571930448@126.com> <20120212161301.90c32b90ffcfa0a990a6be35@gmail.com> <2012021300045417884616@126.com> Message-ID: <20120212180235.96d4477d3e4409410e8d920d@gmail.com> [You've forgot to include the list in your reply] On Mon, 13 Feb 2012 00:04:54 +0800 daedae11 wrote: > Sorry, I'm not sure I know your viewpoint. Could you give me a > detailed explanation about "you need more than about 6-7 seconds (on > my computer) to type the third line."? Thank you very much. The comment in "nntplib.py" says that if the connection is closed, an "EOFError" will be raised (that's the error you get). In the interpreter you type in first the line "s = NNTP('news.gmane.org')" which opens the connection. Then you type in the "s.group"-line which is rather long and you are probably not typing fast enough. Meanwhile the connection to the gmane-Server is closed and that's why you get the "EOFError". In your script there is no problem because there is no delay between those two lines. Try to copy the lines of your script into your interpreter shell and you shouldn't get the error (don't type them manually, use copy & paste!). HTH, Andreas From talmidim at live.com Sun Feb 12 18:17:12 2012 From: talmidim at live.com (Yony Torres) Date: Sun, 12 Feb 2012 12:17:12 -0500 Subject: [Tutor] Running Files with Command Lines In-Reply-To: References: , , , <4F379D2E.8000606@gmail.com>, , , , , Message-ID: oh i forgot this: The book i bought and which im reading from is Learning Python - Mark Lutz - O'reilly ---------------------------------------- > From: talmidim at live.com > To: alan.gauld at btinternet.com; tutor at python.org > Date: Sun, 12 Feb 2012 11:57:57 -0500 > Subject: Re: [Tutor] Running Files with Command Lines > > > 1. i tried this morning and it worked in the CMD check it out: > > copied and pasted from the CMD > C:\Users\myusername>cd documents > C:\Users\myusername\Documents>cd varios2 > C:\Users\myusername\Documents\varios2>cd pythonjourney > C:\Users\myusername\Documents\varios2\pythonjourney>script.py <------- i did not write the name the file properly, my mistake!'script.py' is not recognized as an internal or external command,operable program or batch file. > C:\Users\myusername\Documents\varios2\pythonjourney>script1.py <----- now i did it properlywin321267650600228229401496703205376spam!spam!spam!spam!spam!spam!spam!spam! > --- i must say that previously i added C:\python32 to the environment path ;) > yay! > now im trying it from the python command line, with no success yet :( > > > ---------------------------------------- > > To: tutor at python.org > > From: alan.gauld at btinternet.com > > Date: Sun, 12 Feb 2012 16:16:47 +0000 > > Subject: Re: [Tutor] Running Files with Command Lines > > > > On 12/02/12 15:50, Yony Torres wrote: > > > > > I'm trying to learn Python from a well known book, > > > > > > Do0n;t make us guess, tell us the name of the book, well known or not. > > There is just a chance somebody else may have read it too! > > > > > while i was working with the windows CMD > > > c:\Python32>python > > > > This is where you are going wrong. > > You should not run python on its own, that gets you into the Python > > interpreter with its own >>> prompt. For this exercise you want to run > > your script directly from the OS prompt (on Windows usually ending in a > > single >) > > > > > Can somebody please help me? > > > > See the other posted replies about typing the command. > > It will likely look like this(but all on a single line) > > > > C:\Python32> python > > c:\Users\myusername\Documents\varios2\pythonjourney\script1.py > > > > Don't put spaces in your paths, that will confuse Windows... > > > > -- > > Alan G > > Author of the Learn to Program web site > > http://www.alan-g.me.uk/ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From d at davea.name Sun Feb 12 18:28:17 2012 From: d at davea.name (Dave Angel) Date: Sun, 12 Feb 2012 12:28:17 -0500 Subject: [Tutor] Same code has different result In-Reply-To: <20120212180235.96d4477d3e4409410e8d920d@gmail.com> References: <201202122131571930448@126.com> <20120212161301.90c32b90ffcfa0a990a6be35@gmail.com> <2012021300045417884616@126.com> <20120212180235.96d4477d3e4409410e8d920d@gmail.com> Message-ID: <4F37F6B1.4010908@davea.name> On 02/12/2012 12:02 PM, Andreas Perstinger wrote: > [You've forgot to include the list in your reply] > > On Mon, 13 Feb 2012 00:04:54 +0800 daedae11 wrote: > >> Sorry, I'm not sure I know your viewpoint. Could you give me a >> detailed explanation about "you need more than about 6-7 seconds (on >> my computer) to type the third line."? Thank you very much. > The comment in "nntplib.py" says that if the connection is closed, an "EOFError" will be raised (that's the error you get). > > In the interpreter you type in first the line "s = NNTP('news.gmane.org')" which opens the connection. Then you type in the "s.group"-line which is rather long and you are probably not typing fast enough. Meanwhile the connection to the gmane-Server is closed and that's why you get the "EOFError". > > In your script there is no problem because there is no delay between those two lines. > > Try to copy the lines of your script into your interpreter shell and you shouldn't get the error (don't type them manually, use copy& paste!). > > HTH, Andreas > Or write them in a function, so it doesn't get run at all till you call it. -- DaveA From d at davea.name Sun Feb 12 18:40:24 2012 From: d at davea.name (Dave Angel) Date: Sun, 12 Feb 2012 12:40:24 -0500 Subject: [Tutor] Running Files with Command Lines In-Reply-To: References: , , <4F379D2E.8000606@gmail.com>, , Message-ID: <4F37F988.6060403@davea.name> On 02/12/2012 11:57 AM, Yony Torres wrote: > 1. i tried this morning and it worked in the CMD check it out: > > copied and pasted from the CMD > C:\Users\myusername>cd documents > C:\Users\myusername\Documents>cd varios2 > C:\Users\myusername\Documents\varios2>cd pythonjourney > C:\Users\myusername\Documents\varios2\pythonjourney>script.py<------- i did not write the name the file properly, my mistake!'script.py' is not recognized as an internal or external command,operable program or batch file. > C:\Users\myusername\Documents\varios2\pythonjourney>script1.py<----- now i did it properlywin321267650600228229401496703205376spam!spam!spam!spam!spam!spam!spam!spam! > --- i must say that previously i added C:\python32 to the environment path ;) > yay! > now im trying it from the python command line, with no success yet :( Still some things you haven't caught onto yet. 1) please don't top-post 2) Please do use copy/paste, rather than laboriously (and inaccurately) retyping what you did & saw 3) Use more definite wording than with no success yet 4) the syntax inside the python interpreter is different than in a Windows cmd prompt. Once you get that prompt, you can type simple expressions like 3*4, or you can define and execute functions. But if you want to "run" another script, that script needs to be a valid module, and you import it with the "import" statement. So if you want to start python, and then run your script/module from the python prompt, you'd do something like: davea at think:~/temppython$ python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import myscript Traceback (most recent call last): File "", line 1, in File "myscript.py", line 16 assert w = -1 ^ SyntaxError: invalid syntax >>> Note that a number of things are significant, and different than the command line: 1) the script must be in the current directory, or it must be in the sys.path string, which you probably haven't learned about yet. 2) you import the script by its module name, which does not include the .py In fact, other extensions are possible and common. 3) when the module exits to the python prompt, any variables it defined are in the module's space, not the "global" space. So if you defined a variable w, you'd reference it by myscript.w -- DaveA From s.charonis at gmail.com Sun Feb 12 20:38:51 2012 From: s.charonis at gmail.com (Spyros Charonis) Date: Sun, 12 Feb 2012 19:38:51 +0000 Subject: [Tutor] Concatenating multiple lines into one In-Reply-To: References: Message-ID: Thanks for all the help, Peter's and Hugo's methods worked well in concatenating multiple lines into a single data structure! S On Fri, Feb 10, 2012 at 5:30 PM, Mark Lawrence wrote: > On 10/02/2012 17:08, Peter Otten wrote: > >> Spyros Charonis wrote: >> >> Dear python community, >>> >>> I have a file where I store sequences that each have a header. The >>> structure of the file is as such: >>> >>> sp|(some code) =>1st header >>>> >>> ATTTTGGCGG >>> MNKPLOI >>> ..... >>> ..... >>> >>> sp|(some code) => 2nd header >>>> >>> AAAAAA >>> GGGG ... >>> ......... >>> >>> ...... >>> >>> I am looking to implement a logical structure that would allow me to >>> group >>> each of the sequences (spread on multiple lines) into a single string. So >>> instead of having the letters spread on multiple lines I would be able to >>> have 'ATTTTGGCGGMNKP....' as a single string that could be indexed. >>> >>> This snipped is good for isolating the sequences (=stripping headers and >>> skipping blank lines) but how could I concatenate each sequence in order >>> to get one string per sequence? >>> >>> for line in align_file: >>>>>> >>>>> ... if line.startswith('>sp'): >>> ... continue >>> ... elif not line.strip(): >>> ... continue >>> ... else: >>> ... print line >>> >>> (... is just OS X terminal notation, nothing programmatic) >>> >>> Many thanks in advance. >>> >> >> Instead of printing the line directly collect it in a list (without >> trailing >> "\n"). When you encounter a line starting with">sp" check if that list is >> non-empty, and if so print "".join(parts), assuming the list is called >> parts, and start with a fresh list. Don't forget to print any leftover >> data >> in the list once the for loop has terminated. >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> >> > The advice from Peter is sound if the strings could grow very large but > you can simply concatenate the parts if they are not. For the indexing > simply store your data in a dict. > > -- > Cheers. > > Mark Lawrence. > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Feb 12 23:19:40 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 13 Feb 2012 09:19:40 +1100 Subject: [Tutor] how to stop a running program in python without closing python interface? In-Reply-To: References: Message-ID: <4F383AFC.10604@pearwood.info> Debashish Saha wrote: > actually a i ran a progam in python which is sufficiently large . so i > want to stop the execution of the program now . how can i do this? Control-C should work on every operating system. Obviously you have send the Ctrl-C to the Python process, not some other application. E.g. if you are running your program in a terminal window, bring the terminal window to the front so it captures keystrokes and type Ctrl-C. If you have to kill the Python process from outside, use your operating system's standard method for killing processes. E.g. on Windows you would type ctrl-alt-del and then select which process to kill from the dialog box. On Linux you would use the ps and kill commands. -- Steven From brian.van.den.broek at gmail.com Sun Feb 12 23:44:47 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Mon, 13 Feb 2012 00:44:47 +0200 Subject: [Tutor] string integers? In-Reply-To: <1329074855.45144.YahooMailClassic@web88608.mail.bf1.yahoo.com> References: <1329074855.45144.YahooMailClassic@web88608.mail.bf1.yahoo.com> Message-ID: On 12 February 2012 21:27, William Stewart wrote: > > thanks i tried the code and it doesnt make anydiffference what I need is it to multiply now I fixed the error message but how do I get the 2 numbers that the person enters?to multiply > > --- On Sun, 2/12/12, Brian van den Broek wrote: > > > From: Brian van den Broek > Subject: Re: [Tutor] string integers? > To: "William Stewart" > Cc: tutor at python.org > Date: Sunday, February 12, 2012, 8:53 AM > > > > On 12 Feb 2012 15:28, "William Stewart" wrote: > > > > I am trying to get 2 string variables and 2 integer variables to be able to be multiplied > > can anyone tell me what I did wrong > > > > str1 = raw_input("Type in a String: ") > > str2 = raw_input("Type in a String: ") > > int1 = raw_input("Type in a integer variable: ") > > int2 = raw_input("Type in a integer variable: ") > > print str1 + str2 + int1 + int2 > > import math > > print str1, "*", str2, "*", int1, "*"int2 ?"=", str1, * str2, * int1 * int 2 > > > > > > > > and it wont let me write int2 > > I know this may look stupid to most people? but I am just new at this so dont laugh? :) > > > Hi, > It is a bit unclear what you mean by "it wont let me write int2". > Try running this function and see if it helps: > def test(): > ??? data = raw_input("give me an integer") > ??? print type(data) > ??? print "a string" * "another" > Best, > Brian vdB Hi William and list, To the list: I have only recently reappeared here on the Tutor list, but years back, I learned a great deal from various patient people, some of whom are still here. (Grateful waves to those folk!) I feel fairly confident that the message below is still in the spirit and cultural norms of the list. However, if I am wrong in that, I would welcome any Tutor veterans calling me out, in public (preferred) or in private. To William: I have a few observations that, if you take them to heart, will help you make better use of the Tutor mailing list. They may seem picky, but I assure you that there are reasons behind each thing I say and following these observations will give you a much more rewarding experience with the list. 1) Please don't top post. It bothers geeks and as you want geeks to help you, even if that preference seems silly (it isn't), grit your teeth and do as those who you are asking to help you would prefer. ('Geek' is, of course, a term of praise.) 2) Please be sure to hit Reply-to-All in your mail client. If it lacks such a button, be sure to add a to:tutor at python.org. If you don't your response will go only to the person to whom you are replying. This is what happened to your response to me. If I'd lost the time, interest, or ability to reply to you, your message to me would never get you any further help. Sent to both me and to the list, you can get help from others even if help from me is not forthcoming for whatever reason. 3) Please put more effort in to asking your question in a clear manner. In all honesty, I have no idea what it is you hope "thanks i tried the code and it doesnt make anydiffference what I need is it to multiply now I fixed the error message but how do I get the 2 numbers that the person enters to multiply" to produce by way of further help. What code? What difference were you expecting? Different from what? What error message? I am quite sure I spent longer typing up my first message to you than you did typing your reply. You will generally find that people here will respond positively to effort you expend to make your question clear as it makes it easy for them to help you. If you are not willing to spend much effort, in general, people are not likely to spend more effort than you are. To help see the importance of including your code, your output or backtrace, and a clear statement of your expectations and intentions, consider what happened with your first message. I said "It is a bit unclear what you mean by "it wont let me write int2"." I noticed a problem with your code and, as you'd not been clear about what problem you were having, I said something about that. I didn't read carefully enough to see the problems that others pointed out to you. (If you didn't care to clearly state your problem, I didn't care to work it out for you.) While your code did have multiple issues (that's fine; we were all beginners once), the way you asked it made it hard for me to focus on the issue you were having at the time. Another benefit of taking the time to compose a clear email with a clear statement of your problem (including a *copy and paste* of the smallest chunk of code that exhibits the problem, a description of the expected output, and a *copy and paste* of the output or generate traceback) is that very often, the process of generating such a message will help you solve your own problem. I cannot begin to guess how many times I've started writing a question to this or some other technical mailinglist or newsgroup only to find that the process of asking well forced me to think clearly enough that I came to the solution myself. I have hit you with a lot, and if you feel a bit scolded, well, that was part of my intent. It is, however, intended as a friendly scolding. If you take it to heart, I will have helped you MUCH more than I would have had I spent hours answering the kinds of questions that you have been posting. I can tell you that if you don't seem to have tried to take any of this to heart, I won't be spending more time in an effort to help you. I suspect that I am not alone in this view amongst those who read this list. This also helps explain the apparent contradiction: I have spent a lot of time and effort to explain to you that in general, people won't spend more time and effort on your problem than you will. While it might not seem to you on first reading this email, you have just received a gift---the gift of someone taking the time to help explain how to benefit from the community here even though your efforts in our exchange above have not been promising. (Much of what I have said is on the list website or in the list welcome message and thus is something about which you ought already to have read.) Rather than letting your message go without an answer, I picked it as one of those cases where I'd try to give the sort of gift I have myself been given by others in the past. You will not very often find someone willing to put so much effort into answering a question that exhibits as little effort as did yours. As for your actual programming problem, I suspect I see what is going on, but I don't want to play another round of guessing games. I suggest that you start a new thread with a question written in light of my remarks above. I am confident that if you do, you will find plenty of friendly help on this list. Best, Brian vdB PS Reviewing this email and the upthread posts, I see that you received much of this advice in other replies. Did you read those other replies? The message you sent to me "thanks i tried the code and it doesnt make anydiffference what I need is it to multiply now I fixed the error message but how do I get the 2 numbers that the person enters to multiply" betrays *absolutely no effort whatsoever* to follow the given advice. You will, I think, soon find your prospects of help here are dim if you ignore the advice about how to seek help that you do get. From williamjstewart at rogers.com Mon Feb 13 00:34:28 2012 From: williamjstewart at rogers.com (William Stewart) Date: Sun, 12 Feb 2012 15:34:28 -0800 (PST) Subject: [Tutor] string integers? In-Reply-To: <4F383825.5080904@davea.name> Message-ID: <1329089668.23933.YahooMailClassic@web88608.mail.bf1.yahoo.com> this is the code I have ? str1 = raw_input("Type in a String: ") str2 = raw_input("Type in a String: ") int1 = raw_input("Type in a integer variable: ") int2 = raw_input("Type in a integer variable: ") print str1 + str2 + int1 + int2 import math int1 = int(raw_input("")) print str1, print str2, print int1, "*", int2 print "=" and it does not give me an error message when I run it, the program runs fine except its did not multiply the 2 integer variables i entered ? it looks like this ? Type in a String: hello Type in a String: hi Type in a integer variable: 4 Type in a integer variable: 5 hellohi45 ? This part is exactly what I want it to look like except I want it to multply the 2 numbers I inputed (4 & 5 in this example) ? thanks again for your time and sorry if I seem rude I just dont have alot of time these days I know you all dont have alot of time either and thats why I am extremely appreciative of everyones help ? ? --- On Sun, 2/12/12, Dave Angel wrote: From: Dave Angel Subject: Re: [Tutor] string integers? To: "William Stewart" Date: Sunday, February 12, 2012, 5:07 PM On 02/12/2012 02:41 PM, William Stewart wrote: > hello thank you for your reply That was a post to the list;? you replied privately,? but I'm going to just elaborate my earlier points.? Try again, but use reply-all to one of the messages in the thread. You've got a new version of stuff, but no indication what the code now looks like, or what is "not working". Be explicit when requesting help.? I and others pointed out a few things wrong;? there are others. So don't make us guess what state you're in. Hopefully you're here to learn, and that happens best when you make clear questions, and get good responses. Show your code, show the error,and use cut&paste for the error you get. "It's not working" is not an error message. You either get an error message:? quote the entire traceback Or it doesn't do what you expect:???tell what you expected, and show what you got instead. > I fixed the error the only problem now is how do i get the 2 spereate integers to multiply? but I still need the 2 strings to print > > I tried > > print str1, > print str2, > print int1, "*", int2 > print "=" > > I think I am missing something > I know the * is to multiply but its not working > thank you > > > > --- On Sun, 2/12/12, Dave Angel? wrote: > > > From: Dave Angel > Subject: Re: [Tutor] string integers? > To: "William Stewart" > Cc: tutor at python.org > Date: Sunday, February 12, 2012, 9:51 AM > > > On 02/12/2012 08:25 AM, William Stewart wrote: >> I am trying to get 2 string variables and 2 integer variables to be able to be multiplied >> can anyone tell me what I did wrong >>? ???str1 = raw_input("Type in a String: ") >> str2 = raw_input("Type in a String: ") >> int1 = raw_input("Type in a integer variable: ") >> int2 = raw_input("Type in a integer variable: ") >> print str1 + str2 + int1 + int2 >> import math >> print str1, "*", str2, "*", int1, "*"int2? "=", str1, * str2, * int1 * int 2 >> >> and it wont let me write int2 >> I know this may look stupid to most people? but I am just new at this so dont laugh? :) >> > > That's who this list is targeted at, people who are just learning Python.? Are you new to programming, or just to Python?? Anyway, welcome to Python-Tutor list. > > If these 7 lines are in a file, and you try to run them, you get a specific error, pointing to a specific line.? When asking questions about Python error messages, please post the actual message, as it generally contains lots of clues as to what's wrong. > > davea at think:~/temppython$ python william.py >? ? File "william.py", line 7 >? ? ? print str1, "*", str2, "*", int1, "*"int2? "=", str1, * str2, * int1 * int 2 >? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ^ > SyntaxError: invalid syntax > > So now we both know the error is a syntax error, and it occurs on line 7, which is conveniently redisplayed with a caret pointing at where the error was discovered (notice that in many email systems a proportional font may hide the correct column.? So trust what you saw on your own terminal window).? Sometimes the actual syntax error is a few characters earlier, but this is as fine-tuned as most compilers can manage. > > That print line has 4 errors that I can immediately spot, and the compiler told you about the first one.? That error was in omitting the comma? before the first occurrence of the variable int2.? You butted a string literal right up to a variable name, with no operator between. > > My usual advice when seeing a beginner with a complex line that gives a syntax error is to see if you can replace it by a few simpler lines.? Then the error might be more obvious.? So use several print lines.? So what if the output isn't quite right;? you have some more debugging to do before you'll even see that output. > > > Now let me ask you, how is str1 any different from int1 ?? Python does not have typed variables, and it certainly pays no attention to the spelling of a name to guess what it's intended to hold.? The same name str1 can hold a string one time, an integer another time, a list yet another.? The only way you're going to get those 3rd and 4th lines to make integer objects is to convert the string that raw_input() returns into an integer.? So use >? ? ???int1 = int(raw_input("xxxxx")) > > The next problem will probably be easier for you to spot, but if not, remember to post the full error message, not some summary of it. > > > > > -- DaveA -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Feb 13 00:50:03 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 13 Feb 2012 10:50:03 +1100 Subject: [Tutor] string integers? In-Reply-To: <1329089668.23933.YahooMailClassic@web88608.mail.bf1.yahoo.com> References: <1329089668.23933.YahooMailClassic@web88608.mail.bf1.yahoo.com> Message-ID: <4F38502B.3000702@pearwood.info> William Stewart wrote: > this is the code I have > > str1 = raw_input("Type in a String: ") > str2 = raw_input("Type in a String: ") > int1 = raw_input("Type in a integer variable: ") > int2 = raw_input("Type in a integer variable: ") > print str1 + str2 + int1 + int2 > import math > int1 = int(raw_input("")) > print str1, > print str2, > print int1, "*", int2 > print "=" > > and it does not give me an error message when I run it, the program runs fine > except its did not multiply the 2 integer variables i entered But you haven't asked it to multiply anything. You asked it to PRINT the two variables with an asterisk between them. And further more, you don't have two integers. You have two strings that merely happen to contain digits. Before you can do maths on them, you have to tell Python to treat them as integers, not strings. You use the int() function (int being short for integer, in case it isn't obvious) for that: py> x = raw_input("Enter a number: ") Enter a number: 42 py> type(x) py> x * 10 '42424242424242424242' py> py> x + 1 Traceback (most recent call last): File "", line 1, in TypeError: cannot concatenate 'str' and 'int' objects Before you can do maths on x, you have to turn it into a number: py> x = int(x) py> x * 10 420 py> x + 1 43 P.S. Does your computer have a Delete or Backspace key? Please trim your replies, there is no need to quote page after page after page of old conversation that you don't directly address. -- Steven From 0101amt at gmail.com Mon Feb 13 01:04:41 2012 From: 0101amt at gmail.com (amt) Date: Mon, 13 Feb 2012 02:04:41 +0200 Subject: [Tutor] string integers? In-Reply-To: <4F38502B.3000702@pearwood.info> References: <1329089668.23933.YahooMailClassic@web88608.mail.bf1.yahoo.com> <4F38502B.3000702@pearwood.info> Message-ID: Hello William and welcome to the Python list. I'm a beginner but I'll give it a shot. Problem is, you use raw_input and it returns a string, not an int. Try this code: str1 = raw_input("Type in a String: ") str2 = raw_input("Type in a String: ") int1 = int(raw_input("Type in a integer variable: ")) int2 = int(raw_input("Type in a integer variable: ")) print "{0}{1}{2}".format(str1, str2, int1*int2) From brian.van.den.broek at gmail.com Mon Feb 13 01:16:43 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Mon, 13 Feb 2012 02:16:43 +0200 Subject: [Tutor] string integers? In-Reply-To: <1329089668.23933.YahooMailClassic@web88608.mail.bf1.yahoo.com> References: <4F383825.5080904@davea.name> <1329089668.23933.YahooMailClassic@web88608.mail.bf1.yahoo.com> Message-ID: On 13 February 2012 01:34, William Stewart wrote: > > this is the code I have > > str1 = raw_input("Type in a String: ") > str2 = raw_input("Type in a String: ") > int1 = raw_input("Type in a integer variable: ") > int2 = raw_input("Type in a integer variable: ") > print str1 + str2 + int1 + int2 > import math > int1 = int(raw_input("")) > print str1, > print str2, > print int1, "*", int2 > print "=" > and it does not give me an error message when I run it, the program runs fine except its did not multiply the 2 integer variables i entered > > it looks like this > > Type in a String: hello > Type in a String: hi > Type in a integer variable: 4 > Type in a integer variable: 5 > hellohi45 > > This part is exactly what I want it to look like > except I want it to multply the 2 numbers I inputed (4 & 5 in this example) > Hi William, That is a much better starting point from which to get help. It looks to me as though you took the responses concerning form that I and other gave you seriously; I'm glad. (I sympathize about the difficulty to find time to ask well. It does, however, take less time in the long run than asking several rounds of quick to compose questions.) Steven D'Aprano has given you enough that you should be able to make progress and ask again if needed. I did, however, want to point out that in my first message to you, when I suggested a function for you to run, it was with an eye to helping you to discover the problem. Here's the function and the results of running it in idle: IDLE 2.6.6 >>> def test(): data = raw_input("give me an integer") print type(data) print "a string" * "another" >>> test() give me an integer42 Traceback (most recent call last): File "", line 1, in test() File "", line 4, in test print "a string" * "another" TypeError: can't multiply sequence by non-int of type 'str' >>> (Here, 42 is my input.) You can see that the type of data (the value returned by the raw_input call) is str---a string. The TypeError is telling you that the code I gave tries to multiply by a string and that caused a TypeError as multiplication isn't an operation defined for strings as the right-hand multiplier. Steven's email shows you how to surmount that problem; you must use int() to turn the returned value of raw_input into an integer. Compare: >>> def test2(): data = int(raw_input("give me an integer")) print type(data) print data * data >>> test2() give me an integer4 16 of course, there are still things that can go wrong: >>> test2() give me an integer3.1415 Traceback (most recent call last): File "", line 1, in test2() File "", line 2, in test2 data = int(raw_input("give me an integer")) ValueError: invalid literal for int() with base 10: '3.1415' >>> test2() give me an integerFourtyTwo Traceback (most recent call last): File "", line 1, in test2() File "", line 2, in test2 data = int(raw_input("give me an integer")) ValueError: invalid literal for int() with base 10: 'FourtyTwo' >>> In both cases, I entered some string that int() cannot turn into an integer. If you get the basic idea working for the case where the user enters sane values, we can talk about how to deal with such cases if need be. Best, Brian vdB From williamjstewart at rogers.com Mon Feb 13 01:35:14 2012 From: williamjstewart at rogers.com (William Stewart) Date: Sun, 12 Feb 2012 16:35:14 -0800 (PST) Subject: [Tutor] string integers? In-Reply-To: <4F38502B.3000702@pearwood.info> Message-ID: <1329093314.42820.YahooMailClassic@web88601.mail.bf1.yahoo.com> Thank you for the reply It worked fine ! --- On Sun, 2/12/12, Steven D'Aprano wrote: From: Steven D'Aprano Subject: Re: [Tutor] string integers? To: tutor at python.org Date: Sunday, February 12, 2012, 6:50 PM William Stewart wrote: > this is the code I have >? str1 = raw_input("Type in a String: ") > str2 = raw_input("Type in a String: ") > int1 = raw_input("Type in a integer variable: ") > int2 = raw_input("Type in a integer variable: ") > print str1 + str2 + int1 + int2 > import math > int1 = int(raw_input("")) > print str1, > print str2, > print int1, "*", int2 > print "=" > > and it does not give me an error message when I run it, the program runs fine >? except its did not multiply the 2 integer variables i entered But you haven't asked it to multiply anything. You asked it to PRINT the two variables with an asterisk between them. And further more, you don't have two integers. You have two strings that merely happen to contain digits. Before you can do maths on them, you have to tell Python to treat them as integers, not strings. You use the int() function (int being short for integer, in case it isn't obvious) for that: py> x = raw_input("Enter a number: ") Enter a number: 42 py> type(x) py> x * 10 '42424242424242424242' py> py> x + 1 Traceback (most recent call last): ? File "", line 1, in TypeError: cannot concatenate 'str' and 'int' objects Before you can do maths on x, you have to turn it into a number: py> x = int(x) py> x * 10 420 py> x + 1 43 P.S. Does your computer have a Delete or Backspace key? Please trim your replies, there is no need to quote page after page after page of old conversation that you don't directly address. -- Steven _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From mjolewis at gmail.com Mon Feb 13 01:52:30 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Sun, 12 Feb 2012 16:52:30 -0800 Subject: [Tutor] tabbed output Message-ID: I am having a weird issue. I have a print statement that will give me multiple outputs separated by a tab; however, sometimes there is a tab between the output and sometimes there is not. It seems sort of sporadic. My code is below and two sample outputs are below that (one that works how I expect, and the other showing the issue (tab separation not occurring between all pieces of the output) What is going on? def CheckNames(): names = [] for loop in range(1,4): while True: name = raw_input('''Name #%s: ''' %(loop)) if name not in names: names.append(name) break print '%s is already in the data. Try again.' %(name) sorted_names = sorted(names) for element in list(sorted_names): print 'Hurray for %s!\t' %(element), Sample Output1: Name #1: mike Name #2: bret Name #3: adam Hurray for adam! Hurray for bret! Hurray for mike! Sample Output2(there is a tab between output 2 & 3, but not 1 & 2): Name #1: abe Name #2: alan Name #3: adam Hurray for abe! Hurray for adam! Hurray for alan! -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Feb 13 02:00:02 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 13 Feb 2012 01:00:02 +0000 Subject: [Tutor] how to stop a running program in python without closing python interface? In-Reply-To: <4F383AFC.10604@pearwood.info> References: <4F383AFC.10604@pearwood.info> Message-ID: On 12/02/2012 22:19, Steven D'Aprano wrote: > Debashish Saha wrote: >> actually a i ran a progam in python which is sufficiently large . so i >> want to stop the execution of the program now . how can i do this? > > Control-C should work on every operating system. Obviously you have send > the Ctrl-C to the Python process, not some other application. E.g. if > you are running your program in a terminal window, bring the terminal > window to the front so it captures keystrokes and type Ctrl-C. > > If you have to kill the Python process from outside, use your operating > system's standard method for killing processes. E.g. on Windows you > would type ctrl-alt-del and then select which process to kill from the > dialog box. On Linux you would use the ps and kill commands. > > At least on Windows Vista ctrl-alt-del brings up a list of options, one of which lets you bring up the Task Manager to kill the process and/or application. ctrl-shift-esc brings up the Task Manager directly. -- Cheers. Mark Lawrence. From hugo.yoshi at gmail.com Mon Feb 13 02:11:51 2012 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 13 Feb 2012 02:11:51 +0100 Subject: [Tutor] tabbed output In-Reply-To: References: Message-ID: On Mon, Feb 13, 2012 at 1:52 AM, Michael Lewis wrote: > I am having a weird issue. I have a print statement that will give me > multiple outputs separated by a tab; however, sometimes there is a tab > between the output and sometimes there is not. It seems sort of sporadic. My > code is below and two sample outputs are below that (one that works how I > expect, and the other showing the issue (tab separation not occurring > between all pieces of the output) What is going on? > > def CheckNames(): > ? ? names = [] > ? ? for loop in range(1,4): > ? ? ? ? while True: > ? ? ? ? ? ? name = raw_input('''Name #%s: ''' %(loop)) > ? ? ? ? ? ? if name not in names: > ? ? ? ? ? ? ? ? names.append(name) > ? ? ? ? ? ? ? ? break > ? ? ? ? ? ? print '%s is already in the data. Try again.' %(name) > ? ? sorted_names = sorted(names) > ? ? for element in list(sorted_names): > ? ? ? ? print 'Hurray for %s!\t' %(element), > > Sample Output1: > > Name #1: mike > Name #2: bret > Name #3: adam > Hurray for adam! ? ? ? ? ? ?Hurray for bret! ??Hurray for mike! > > Sample Output2(there is a tab between output 2 & 3, but not 1 & 2): > Yes there is, and I'll show you by modifying your method just a little: >>> def CheckNames(): names = [] for loop in range(1,4): while True: name = raw_input('''Name #%s: ''' %(loop)) if name not in names: names.append(name) break print '%s is already in the data. Try again.' %(name) sorted_names = sorted(names) lst = [] for element in list(sorted_names): lst.append('Hurray for %s!\t' %(element)) return ''.join(lst) The juicy bit is at the end. Instead of printing, we make a list, append everything we were going to print to it, join it into one big string, and return it. This way we can look at the string better. Now for the demonstration: >>> CheckNames() Name #1: abe Name #2: alan Name #3: adam 'Hurray for abe!\tHurray for adam!\tHurray for alan!\t' >>> print _ # btw, _ is short for last value in the interpreter Hurray for abe! Hurray for adam! Hurray for alan! >>> You see that? in the string returned, there is most definitely a tab. And in fact, that little space between abe and adam, that is also a tab. You see, if you insert a tab, the cursor is moved up to the next tab stop. Choosing a short name #1, like abe, means that the next tab stop is right after the exclamation mark. If you use a slightly longer name though, like adam, the exclamation mark will be past that tab stop, and the tab character afterward will put name #2 all the way at the next tabstop. tab characters are lame like that. They are generally only used to make sure output lines up at a tabstop, it's not a reliable way to put a certain amount of space between two pieces of text. HTH, Hugo From modulok at gmail.com Mon Feb 13 03:20:17 2012 From: modulok at gmail.com (Modulok) Date: Sun, 12 Feb 2012 19:20:17 -0700 Subject: [Tutor] tabbed output In-Reply-To: References: Message-ID: On 2/12/12, Michael Lewis wrote: > I am having a weird issue. I have a print statement that will give me > multiple outputs separated by a tab; however, sometimes there is a tab > between the output and sometimes there is not. It seems sort of sporadic. > My code is below and two sample outputs are below that (one that works how > I expect, and the other showing the issue (tab separation not occurring > between all pieces of the output) What is going on? > > def CheckNames(): > names = [] > for loop in range(1,4): > while True: > name = raw_input('''Name #%s: ''' %(loop)) > if name not in names: > names.append(name) > break > print '%s is already in the data. Try again.' %(name) > sorted_names = sorted(names) > for element in list(sorted_names): > print 'Hurray for %s!\t' %(element), > > Sample Output1: > > Name #1: mike > Name #2: bret > Name #3: adam > Hurray for adam! Hurray for bret! Hurray for mike! > > Sample Output2(there is a tab between output 2 & 3, but not 1 & 2): > > Name #1: abe > Name #2: alan > Name #3: adam > Hurray for abe! Hurray for adam! Hurray for alan! > You should use spaces, not tabs. Tabs only align with tab stops, which will depend on the length of the words (names). To make it easy to use spaces instead, use the 'format()' method available on string objects. A one-line modification of your could would look like this:: def CheckNames(): names = [] for loop in range(1,4): while True: name = raw_input('''Name #%s: ''' %(loop)) if name not in names: names.append(name) break print '%s is already in the data. Try again.' %(name) sorted_names = sorted(names) for element in list(sorted_names): print "{value:<30}".format(value="Hurray for %s!" % element), # The line above is all that was changed. The result, is that 'value' will be output as left-aligned '<', and a minimum of 30 characters wide '30'. The 'value' is specified as a keyword argument to the format() method. In the example above, 'value' is also making use of python's older string formatting method. Using a monospaced font, your output will always be lined up, as long as the 'value' string never exceeds 30 characters wide. You can optionally *not* specify the 'value' variable and instead use a positional argument to the format method like this, but it makes it less clear what you're doing:: print "{0:<30}".format("Hurray for %s!" % element), As a final note, if 'CheckNames' is a function and not a method, it should be all lowercase, or use_underscores rather than camelCase. This is not enforced by python, but is kind of the de-facto standard. Read more about the format method here: http://docs.python.org/library/string.html#formatspec http://docs.python.org/library/string.html#formatstrings -Modulok- From dcdavemail at gmail.com Mon Feb 13 14:35:21 2012 From: dcdavemail at gmail.com (David Craig) Date: Mon, 13 Feb 2012 13:35:21 +0000 Subject: [Tutor] ipython trouble with editor Message-ID: <4F391199.6030201@gmail.com> Hi, I use emacs with ipython (or I would like to) on a GNU/linux machine. To be able to use it from the ipython shell through %ed I added the following lines to my .bashrc file, export LESS="-R" export EDITOR=emacs this seemed to work as when I try %ed filename it opens and is editable in the ipython shell. However I cant quit out of emacs to run my changes. I've tried Control-x Control-c but it doesnt work. Anyone know how I can exit????? Thanks D -------------- next part -------------- An HTML attachment was scrubbed... URL: From daedae11 at 126.com Mon Feb 13 15:43:13 2012 From: daedae11 at 126.com (daedae11) Date: Mon, 13 Feb 2012 22:43:13 +0800 Subject: [Tutor] What's the difference between Queue(in module Queue) and list(build_in class)? Message-ID: <201202132243132981989@126.com> What's the difference between Queue(in module Queue) and list(build_in class)? I think that when I pass a same queue object to two different threads, the change in each thread will affect each other as same as Queue. So why don't we use list or other variable object? daedae11 -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Feb 13 17:05:22 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 14 Feb 2012 03:05:22 +1100 Subject: [Tutor] What's the difference between Queue(in module Queue) and list(build_in class)? In-Reply-To: <201202132243132981989@126.com> References: <201202132243132981989@126.com> Message-ID: <4F3934C2.6010203@pearwood.info> daedae11 wrote: > What's the difference between Queue(in module Queue) and list(build_in class)? > I think that when I pass a same queue object to two different threads, the change in each thread will affect each other as same as Queue. So why don't we use list or other variable object? Have you read the Fine Manual? Queue has a much more powerful and richer interface designed for use as a queue, while list is a general purpose sequence that can only be used for the most primitive queue-like data structures. For example, Queue can be set to have a maximum size, while list will always grow until you run out of memory. Queue.get() by default will wait as long as necessary for a value to be available, while list.pop() will fail immediately if the list is empty. Queue is also carefully written to be thread-safe, unlike most other data structures written in pure Python. (I expect that the built-in list is also thread-safe, but I don't know for sure.) By thread-safe I mean that two threads cannot accidentally delete or write to the same item at the same time. Thread safety is very hard to get right, so you should always use Queue with threads. -- Steven From steve at pearwood.info Mon Feb 13 17:07:19 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 14 Feb 2012 03:07:19 +1100 Subject: [Tutor] ipython trouble with editor In-Reply-To: <4F391199.6030201@gmail.com> References: <4F391199.6030201@gmail.com> Message-ID: <4F393537.7050805@pearwood.info> David Craig wrote: > Hi, > I use emacs with ipython (or I would like to) on a GNU/linux machine. To > be able to use it from the ipython shell through %ed I added the > following lines to my .bashrc file, > > export LESS="-R" > export EDITOR=emacs > > this seemed to work as when I try %ed filename it opens and is editable > in the ipython shell. However I cant quit out of emacs to run my > changes. I've tried Control-x Control-c but it doesnt work. Anyone know > how I can exit????? This is not a mailing list for solving emacs problems, although we'll help you if we can. It's not even for solving ipython problems, since that's a fairly specialist area of Python (although I must admit I keep intending to try it out). This is for learning Python the programming language itself, not necessarily every tool vaguely associated with Python. You might be better off asking your question on a dedicated ipython support forum. While waiting for somebody who knows more about ipython/emacs to show up, I'll start with a basic question: when you run emacs in ipython, do you get emacs running in the terminal, or in a GUI window? If you get a GUI window, what happens if you select the Quit menu item or close the window? -- Steven From breamoreboy at yahoo.co.uk Mon Feb 13 17:46:14 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 13 Feb 2012 16:46:14 +0000 Subject: [Tutor] ipython trouble with editor In-Reply-To: <4F393537.7050805@pearwood.info> References: <4F391199.6030201@gmail.com> <4F393537.7050805@pearwood.info> Message-ID: On 13/02/2012 16:07, Steven D'Aprano wrote: [snipped] > You might be better off asking your question on a dedicated > ipython support forum. Like http://news.gmane.org/gmane.comp.python.ipython.user -- Cheers. Mark Lawrence. From dave at hansonforensics.co.uk Mon Feb 13 18:00:25 2012 From: dave at hansonforensics.co.uk (Dave Hanson) Date: Mon, 13 Feb 2012 17:00:25 +0000 Subject: [Tutor] Cmd Advice In-Reply-To: References: Message-ID: On Sat, Feb 11, 2012 at 2:03 PM, Walter Prins wrote: > Hi all, > > Below is an *earlier* (note the date) private response by myself that > at the time accidentally didn't get sent to the list and only to Dave > (as he privately replied to me only and not to the list.) Given that > the thread on the list has resumed, I thought I'd forward this to the > thread for completeness sake as otherwise a bit of context might be > lost. > > Regards, > > Walter > > > ---------- Forwarded message ---------- > From: Walter Prins > Date: 8 February 2012 01:29 > Subject: Re: [Tutor] Cmd Advice > To: Dave Hanson > > > HI Dave, > > > On 7 February 2012 16:55, Dave Hanson wrote: > > > > I tried what you said, many attempts result in this message: > > > >> > >> C:\Documents and Settings\dhanson2\Desktop>"C:\Python27\python.exe" > "C:\t.py" > >> > >> C:\Python27\python.exe: can't open file 'C:\t.py': [Errno 2] No such > file or directory > > > > > > I've tried moving t.py around but still no joy? > > > > Here is what I put in my bat file with and without the quotes: > > > >> > >> "C:\Python27\python.exe" "C:\t.py" %1 %2 %3 %4 %5 %6 %7 %8 %9 > > > > > > The error message implies that the program "t.py" is in the root of > your C:\ drive? I'd have thought this would not be the case -- you > need to give the correct path to the "t.py" file for Python to load > it. (And as an aside, you need to quote paths if theycontains spaces, > otherwise the command prompt will interpret the first part up to a > space in the path as the path/command and the remainder of the path as > a command line argument! (One subtlety of command lines...) The > "Documents and Settings" folder on Windows XP was therefore very > unfortunately chosen since the spaces causes endless problems with > people not realising this and trying to use files located inside > Documents and Settings. You'll notice on Windows 7 Microsoft has > wisely (at last) decided to shorten and remove spaces as much as > possible from paths to avoid gotchas with people forgetting to quote > paths, and similarly Python itself does not uses spaces in any of its > folder names. But I digress. > > Anyway, I've had a quick further look at this program and got it > working the way you want on my machine. The precise steps I followed > was: > 1.) Install Mercurial for Windows (to be able to checkout the source). > I got it here: http://tortoisehg.bitbucket.org/download/index.html > 2.) Retrieved the source code. On my machine I opened a command prompt, > and: > cd "C:\Users\walterp\Documents\Python" > hg clone https://bitbucket.org/sjl/t > > This creates a folder called "t" inside of my Python source folder. > Adjust folders as required for your machine and/or where you keep your > Python source. > > 3) Create a batch file called "t.bat" in > "C:\Users\walterp\Documents\Python\t", so the full filename is > "C:\Users\walterp\Documents\Python\t\t.bat", containing these lines: > > @echo off > c: > cd C:\Users\walterp\Documents\Python\t > c:\python27\python.exe "C:\Users\walterp\Documents\Python\t\t.py" %1 > %2 %3 %4 %5 %6 %7 %8 %9 > > The effect of these commands is to stop the command interpreter from > displaying the commands issues by the batch file (which is unwanted > here) via the "@echo off" line, and then setting up the environment > prior to running the t.py program such that it will always run having > the "current working folder" be the same folder that the t.py program > is located in. > > This is important since the t.py program currently assumes that it > will always be run from the same starting location, which is not the > case if you go and put the program on the command line search path so > that you can use it from any other working folder. (Without this, if > you run the program from another location, then the t.py program will > create a new task list in the new location -- basically the t.py > command will create and manage a task list in whatever folder you > happen to be in, so in order to ensure it always updates the same task > list, the lines above therefore ensures it always effectively runs > from the same place, regardless of where the batch file t.bat might > have been run from, thereby effectively ensuring it to always uses the > same task list file.) > > Also, note that in order to in fact use the t.bat file from any other > folder, you'll have to add the bat files location to you system (or > user) PATH variable. Do you know how to do this, and are you allowed > to do so, or are you blocked by your IT policies? If so you should > also be able to do this via e.g. another batch file, perhaps the same > one you use to circumvent the cmd.exe blocks on your system, by simply > adding it to the PATH variable there, e.g. a line like this ought to > do it: > PATH=%PATH%;C:\Users\walterp\Documents\Python\t > > Lastly a minor observation: I note this source code includes a > setup.py script. This implies you can install t.py into your Python > environment such that an .exe file will be created for it (really copy > of the t.py file and the python interpreter [I think, or a launcher of > some sort] combined) in the Python\Scripts folder. Some Python > distributions (e.g. Activestate IIRC) puts this folder onto the system > Path thereby making "system wide" installed Python packages/commands > (where appropriate) instantly usable from the command prompt, others > (e.g. standard Python on Windows) do not and leaves this step for you > to complete. Anyway, I've obviously not gone the route of installin > via setup.py, since installing this program in this way will make it > difficult/impossible for you to tinker/edit the program easily, and > I'm assuming you want to actually be able to edit the program (and > possibly submit patches back to the author?) while using it etc. So, > for this to be possible you actually need the t.py to "run from > source" and don't want to embedded in your Python environment, which > is what not using setup.py and doing the above effectively enables you > to do easily. (Aside: when I noticed the program isn't > location/working directory independent I immediately thought this > might be a useful patch/enhancement to make -- make it get the folder > location of itself and use that for the location of the tasks list > etc.) > > Let me know if you have further problems. > > Walter > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Hi Guys, > Apologies again for my slow response. I tried Dave's method to create a 'fake shell' and also Walters methods - All result in: The command prompt has been disabled by your administrator. I think I'll just have to do some restructuring to the program and just use raw_input() with some kind of loop to keep the window open. I'll post what I come up with (If I'm able to come up with something) somewhere incase it's helps someone out. [For future reference - should I have snipped the previous message out of this email or trimmed it down a bit? Just thinking about my top posting telling off from DaveA during the weekend!] (only kidding Dave) :) Best Regards, Dave Hanson -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 13 19:55:17 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 13 Feb 2012 18:55:17 +0000 Subject: [Tutor] Cmd Advice In-Reply-To: References: Message-ID: On 13/02/12 17:00, Dave Hanson wrote: > [For future reference - should I have snipped the previous message out > of this email or trimmed it down a bit? Always snip out as much as possible that is not needed for context. Anything irrelevant just adds to the confusion and the byte count. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From elainahyde at gmail.com Tue Feb 14 00:50:46 2012 From: elainahyde at gmail.com (Elaina Ann Hyde) Date: Tue, 14 Feb 2012 10:50:46 +1100 Subject: [Tutor] Request for advice on Python code Message-ID: Hi, I'm working on a routine for reading in the Schlegel dustmaps. I have an ascii table with values, Ra-Dec and I'm trying to convert 2 columns to l,b and get the dust values out, this is a 2 part problem as I need to first convert to l,b, keep those values for other uses (calculating VLSR), and get extinctions for each l,b value, I have: import astropysics from astropysics.coords import ICRSCoordinates,GalacticCoordinates import asciitable x='Core_rod_name.list' dat=asciitable.read(x,Reader=asciitable.CommentedHeader, fill_values=['','-999.99']) Radeg=dat['ra-drad']*180./math.pi Decdeg=dat['dec-drad']*180./math.pi plot(Radeg,Decdeg,'o') xlabel('Radeg') ylabel('Decdeg') gcoords=ICRSCoordinates(dat['ra-drad'],dat['dec-drad'],radians=True).convert(GalacticCoordinates) l=gcoords.l.degrees b=gcoords.b.degrees VLSR=dat['Vhel_f'] + 9*np.cos(l)*np.cos(b) + 12*np.sin(l)*np.cos(b) + 7*np.sin(b) VGSR=VLSR + 220*np.sin(l)*np.cos(b) dustmap='SFD_dust_4096_ngp.fits' EB_V=astropysics.obstools.get_SFD_dust(l,b,dustmap,interpolate=True) ------- this gives the error 'Only length-1 arrays can be converted to Python scalars' ... however, I cannot do: for row in dat: gcoords=ICRSCoordinates(dat['ra-drad'],dat['dec-drad'],radians=True).convert(GalacticCoordinates) without the same error. Any ideas would be apreciated, thanks! ~Elaina -- PhD Candidate Department of Physics and Astronomy Faculty of Science Macquarie University North Ryde, NSW 2109, Australia -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Feb 14 01:52:04 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 14 Feb 2012 00:52:04 +0000 Subject: [Tutor] Request for advice on Python code In-Reply-To: References: Message-ID: On 13/02/12 23:50, Elaina Ann Hyde wrote: > Hi, I'm working on a routine for reading in the Schlegel dustmaps. I > have an ascii table with values, Ra-Dec and I'm trying to convert 2 > columns to l,b and get the dust values out, this is a 2 part problem as > I need to first convert to l,b, keep those values for other uses > (calculating VLSR), and get extinctions for each l,b value, That sounds very interesting but almost totally meaningless to most of us on this list I suspect! :-) > import astropysics > from astropysics.coords import ICRSCoordinates,GalacticCoordinates > import asciitable From those lines alone I suspect you might have more luck on either a specialised forum or on the general Python mailing list/newsgroup. It looks like a much more specialised query than is usual on this list which is for beginning Python programmers. However.... > dustmap='SFD_dust_4096_ngp.fits' > EB_V=astropysics.obstools.get_SFD_dust(l,b,dustmap,interpolate=True) > ------- > this gives the error 'Only length-1 arrays can be converted to Python > scalars' ... however, I cannot do: Always post the full error text not just the last line or a summary. It usually contains a lot of useful information, especially what code Python actually saw when it tried to execute your code. > gcoords=ICRSCoordinates(dat['ra-drad'],dat['dec-drad'],radians=True).convert(GalacticCoordinates) > > without the same error. Any ideas would be appreciated, thanks! On the surface I have no idea because that looks like an issue related to the use of the astrophysics module. But the error message may reveal a more fundamental issue underneath. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From elainahyde at gmail.com Tue Feb 14 02:09:07 2012 From: elainahyde at gmail.com (Elaina Ann Hyde) Date: Tue, 14 Feb 2012 12:09:07 +1100 Subject: [Tutor] Request for advice on Python code In-Reply-To: References: Message-ID: On Tue, Feb 14, 2012 at 11:52 AM, Alan Gauld wrote: > On 13/02/12 23:50, Elaina Ann Hyde wrote: > >> Hi, I'm working on a routine for reading in the Schlegel dustmaps. I >> have an ascii table with values, Ra-Dec and I'm trying to convert 2 >> columns to l,b and get the dust values out, this is a 2 part problem as >> I need to first convert to l,b, keep those values for other uses >> (calculating VLSR), and get extinctions for each l,b value, >> > > That sounds very interesting but almost totally meaningless to most of us > on this list I suspect! :-) > > > import astropysics >> from astropysics.coords import ICRSCoordinates,**GalacticCoordinates >> import asciitable >> > > From those lines alone I suspect you might have more luck on either a > specialised forum or on the general Python mailing list/newsgroup. > It looks like a much more specialised query than is usual on this list > which is for beginning Python programmers. > > However.... > > > dustmap='SFD_dust_4096_ngp.**fits' >> EB_V=astropysics.obstools.get_**SFD_dust(l,b,dustmap,**interpolate=True) >> ------- >> this gives the error 'Only length-1 arrays can be converted to Python >> scalars' ... however, I cannot do: >> > > Always post the full error text not just the last line or a summary. > It usually contains a lot of useful information, especially what code > Python actually saw when it tried to execute your code. > > gcoords=ICRSCoordinates(dat['**ra-drad'],dat['dec-drad'],** >> radians=True).convert(**GalacticCoordinates) >> >> without the same error. Any ideas would be appreciated, thanks! >> > > On the surface I have no idea because that looks like an issue > related to the use of the astrophysics module. But the error > message may reveal a more fundamental issue underneath. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > Thanks Alan, I'm pretty sure that the problem is that the module expects a scalar and I want it to read and return a vector from a table. This is a general-ish problem since I haven't had any real experience operating vectors, although the code I'm working on now should give me that. I had a moment of puzzelment earlier when I realized that .math doesn't operate on vectors either so you have to do np.sin() instead of math.sin(). I am thinking/hoping this might be a similarly easy problem.... Anyone performing a module operation on a column from a file would encounter a similar message (I have in other instances as well, some tasks don't seem to care, other's do...). If I do figure it out and it's a general thing shall I post the solution here? The entire error is: Traceback (most recent call last): File "read_plot.py", line 63, in gcoords=ICRSCoordinates(dat['ra-drad'],dat['dec-drad'], radians=True).convert(GalacticCoordinates) File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/Astropysics-0.1.dev_r1142-py2.7.egg/astropysics/coords/coordsys.py", line 1845, in __init__ EpochalLatLongCoordinates.__init__(self,kwargs['ra'],kwargs['dec'],kwargs['raerr'],kwargs['decerr']) File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/Astropysics-0.1.dev_r1142-py2.7.egg/astropysics/coords/coordsys.py", line 1730, in __init__ LatLongCoordinates.__init__(self,long,lat,longerr,laterr,distancepc) File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/Astropysics-0.1.dev_r1142-py2.7.egg/astropysics/coords/coordsys.py", line 1307, in __init__ self.lat = lat File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/Astropysics-0.1.dev_r1142-py2.7.egg/astropysics/coords/coordsys.py", line 1375, in _setLat rads = AngularCoordinate(val).radians%_twopi File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/Astropysics-0.1.dev_r1142-py2.7.egg/astropysics/coords/coordsys.py", line 254, in __init__ self._decval = radians(inpt) File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/numpy/ma/core.py", line 3782, in __float__ raise TypeError("Only length-1 arrays can be converted "\ TypeError: Only length-1 arrays can be converted to Python scalars -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at linux-ip.net Tue Feb 14 03:08:50 2012 From: martin at linux-ip.net (Martin A. Brown) Date: Mon, 13 Feb 2012 21:08:50 -0500 Subject: [Tutor] Request for advice on Python code In-Reply-To: References: Message-ID: Greetings Elaina, I will echo Alan's remarks--it sounds like you are using a quite specialized (specialised?) module. It is certainly not a module with which I am familiar, not in the standard library, and not a commonly encountered problem. I would classify this module as domain-specific. It is for this reason, that Alan (and possibly others on this list) would recommend finding a domain-specific mailing list on which to ask the question--IFF that question is really domain specific. If the question is more general (and part of your question is general), then this is an appropriate forum. With that, said, though, you have asked the question quite reasonably, and I have one other observation to make, based on the traceback and comments you have provided. : I'm pretty sure that the problem is that the module expects a : scalar and I want it to read and return a vector from a table. : This is a general-ish problem since I haven't had any real : experience operating vectors, although the code I'm working on : now should give me that. I had a moment of puzzelment earlier : when I realized that .math doesn't operate on vectors either so : you have to do np.sin() instead of math.sin(). I note that you say 'np' here. I will make an educated guess that this means numpy. There is a package, numpy [0], which operates on arrays/vectors rather than the Python standard library math, which operates on individual values. So, yes, you can use the standard library for calculating a sine: >>> import math >>> math.sin(0) 0.0 But, the numpy library lets you operate on an array. >>> import numpy >>> l = [ x/1000.0 for x in range(1,1001) ] >>> len(numpy.sin(l)) 1000 It is up to you whether you treat the data as an array or a vector. Now...going back to your original posting, I see: : dustmap='SFD_dust_4096_ngp.fits' : EB_V=astropysics.obstools.get_SFD_dust(l,b,dustmap,interpolate=True) : ------- : this gives the error 'Only length-1 arrays can be converted to : Python scalars' ... however, I cannot do: First, I have no idea what a dustmap is. Second thing, it seems that the error you are seeing is 'Only length-1 arrays [...]', which suggests that you are treating an array (a numpy thing) as a scalar (a native Python data type) without knowing how you wish to summarize your data into a single value. Who is responsible for the namespace 'astrophysics' here? The documentation there may be able to help you.....maybe. : I am thinking/hoping this might be a similarly easy problem.... : Anyone performing a module operation on a column from a file : would encounter a similar message (I have in other instances as : well, some tasks don't seem to care, other's do...). If I do : figure it out and it's a general thing shall I post the solution : here? The entire error is: Traceback (most recent call last): It is good form to post the traceback, so thank you for posting that. I snipped your traceback, because the error message suggested to me exactly what you observed--that some part of that operates only on values, not arrays/vectors. Good luck sorting this out! -Martin [0] http://numpy.scipy.org/ From walksloud at gmail.com Tue Feb 14 03:38:28 2012 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Mon, 13 Feb 2012 18:38:28 -0800 Subject: [Tutor] Request for advice on Python code In-Reply-To: References: Message-ID: Hi Elaina, just reading your question (and responses). There is an issue with what you wrote in the email, which may help. > for row in dat: > gcoords=ICRSCoordinates(dat['ra-drad'],dat['dec-drad'],radians=True).convert(GalacticCoordinates) This line is identical to the one that broke before, and now you are just looping over it, so it is not surprising to fail in the same way. If a loop will work, you would need the following instead """ for row in dat: gcoords = ICRSCoordinates(row['ra-drad'],row['dec-drad'],radians=True).convert(GalacticCoordinates) """ notice the "dat" --> "row" inside the loop. Now if that works, you can get it to work along the following lines Example: suppose the output (gcoords) is a scalar float, and you would like to store these data in an array. Then you can do """ import numpy as np #just copying the style from a previous reply gcoords = np.zeros([len(dat)]) #this creates a numpy array of the length of dat, and fills it with all zeros for i,row in enumerate(dat): gcoords[i] = ICRSCoordinates(row['ra-drad'],row['dec-drad'],radians=True).convert(GalacticCoordinates) """ If the loop doesn't work, then you need to investigate the astrophysics library you are using, as previously mentioned, and hopefully there is someone who is familiar with it you can ask questions to. Actually, even if the loop does work, you want to be more familiar with the astrophysics library. You certainly would not want to produce results with it (and base some conclusions on them/publish them) without being 100% sure you know what it is doing. Good luck, Andre From breamoreboy at yahoo.co.uk Tue Feb 14 03:45:46 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 14 Feb 2012 02:45:46 +0000 Subject: [Tutor] Request for advice on Python code In-Reply-To: References: Message-ID: On 13/02/2012 23:50, Elaina Ann Hyde wrote: > Hi, I'm working on a routine for reading in the Schlegel dustmaps. I have > an ascii table with values, Ra-Dec and I'm trying to convert 2 columns to > l,b and get the dust values out, this is a 2 part problem as I need to > first convert to l,b, keep those values for other uses (calculating VLSR), > and get extinctions for each l,b value, I have: > > import astropysics > from astropysics.coords import ICRSCoordinates,GalacticCoordinates > import asciitable > > x='Core_rod_name.list' > dat=asciitable.read(x,Reader=asciitable.CommentedHeader, > fill_values=['','-999.99']) > Radeg=dat['ra-drad']*180./math.pi > Decdeg=dat['dec-drad']*180./math.pi > > plot(Radeg,Decdeg,'o') > xlabel('Radeg') > ylabel('Decdeg') > > gcoords=ICRSCoordinates(dat['ra-drad'],dat['dec-drad'],radians=True).convert(GalacticCoordinates) > l=gcoords.l.degrees > b=gcoords.b.degrees > > VLSR=dat['Vhel_f'] + 9*np.cos(l)*np.cos(b) + 12*np.sin(l)*np.cos(b) + > 7*np.sin(b) > VGSR=VLSR + 220*np.sin(l)*np.cos(b) > > dustmap='SFD_dust_4096_ngp.fits' > EB_V=astropysics.obstools.get_SFD_dust(l,b,dustmap,interpolate=True) > ------- > this gives the error 'Only length-1 arrays can be converted to Python > scalars' ... however, I cannot do: > > for row in dat: > > gcoords=ICRSCoordinates(dat['ra-drad'],dat['dec-drad'],radians=True).convert(GalacticCoordinates) > > without the same error. Any ideas would be apreciated, thanks! > > ~Elaina > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Well it's as clear as dust to me :) Unlike others who have already responded I don't believe that this will be too difficult to sort as the astropysics package is available on Pypi and there it states that it requires scipy and numpy. Did you or someone else install the package, if the latter can you ask them about this problem? Best of British/Australian/Whatever luck with this. -- Cheers. Mark Lawrence. From elainahyde at gmail.com Tue Feb 14 06:12:36 2012 From: elainahyde at gmail.com (Elaina Ann Hyde) Date: Tue, 14 Feb 2012 16:12:36 +1100 Subject: [Tutor] Request for advice on Python code In-Reply-To: References: Message-ID: On Tue, Feb 14, 2012 at 1:38 PM, Andre' Walker-Loud wrote: > Hi Elaina, > > just reading your question (and responses). There is an issue with what > you wrote in the email, which may help. > > > for row in dat: > > > gcoords=ICRSCoordinates(dat['ra-drad'],dat['dec-drad'],radians=True).convert(GalacticCoordinates) > > This line is identical to the one that broke before, and now you are just > looping over it, so it is not surprising to fail in the same way. If a > loop will work, you would need the following instead > > """ > for row in dat: > gcoords = > ICRSCoordinates(row['ra-drad'],row['dec-drad'],radians=True).convert(GalacticCoordinates) > """ > > notice the "dat" --> "row" inside the loop. Now if that works, you can > get it to work along the following lines > > Example: suppose the output (gcoords) is a scalar float, and you would > like to store these data in an array. Then you can do > > """ > import numpy as np #just copying the style from a previous reply > > gcoords = np.zeros([len(dat)]) #this creates a numpy array of the length > of dat, and fills it with all zeros > for i,row in enumerate(dat): > gcoords[i] = > ICRSCoordinates(row['ra-drad'],row['dec-drad'],radians=True).convert(GalacticCoordinates) > """ > > If the loop doesn't work, then you need to investigate the astrophysics > library you are using, as previously mentioned, and hopefully there is > someone who is familiar with it you can ask questions to. > > Actually, even if the loop does work, you want to be more familiar with > the astrophysics library. You certainly would not want to produce results > with it (and base some conclusions on them/publish them) without being 100% > sure you know what it is doing. > > > Good luck, > > Andre Thanks to everyone who replied, Andre's idea was very good and led to the following solution: l=[] b=[] for i in xrange(len(Radeg)): gcoords=ICRSCoordinates(Radeg[i],Decdeg[i]).convert(GalacticCoordinates) l.append(gcoords.l.degrees) b.append(gcoords.b.degrees) .... you know, just in case anyone ever wants to convert to galactic coordinates in the future. Thanks again ~Elaina -------------- next part -------------- An HTML attachment was scrubbed... URL: From silideba at gmail.com Tue Feb 14 14:13:49 2012 From: silideba at gmail.com (Debashish Saha) Date: Tue, 14 Feb 2012 18:43:49 +0530 Subject: [Tutor] problem in ploting cylinders with different colour. Message-ID: import numpy from enthought.mayavi import mlab #def test_mesh(): #"""A very pretty picture of spherical harmonics translated from #the octaviz example.""" for r in range (1,5): print r pi = numpy.pi cos = numpy.cos sin = numpy.sin dphi, dtheta, dz = pi/250.0, pi/250.0, 0.01 #[phi,theta] = numpy.mgrid[0:pi+dphi*1.5:dphi,0:2*pi+dtheta*1.5:dtheta] [phi,z] = numpy.mgrid[0:2*pi+dphi*1.5:dphi,0:2+dz*1.5:dz] m0 = 4; m1 = 3; m2 = 2; m3 = 3; m4 = 6; m5 = 2; m6 = 6; m7 = 4; # r = sin(m0*phi)**m1 + cos(m2*phi)**m3 + 5*sin(m4*theta)**m5 + cos(m6*theta)**m7 #x = 1*sin(phi)*cos(theta) #y = 1*sin(phi)*sin(theta) #z = 1*cos(phi); x=r*cos(phi) y=r*sin(phi) z=z i=['Reds','greens','autumn','purples'] print i[r-1] e=i[r-1] mlab.mesh(x, y, z,colormap='e') #print i[r-1] Error: TypeError Traceback (most recent call last) C:\Python27\lib\site-packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc) 166 else: 167 filename = fname --> 168 exec compile(scripttext, filename, 'exec') in glob, loc 169 else: 170 def execfile(fname, *where): C:\Users\as\jhgf.py in () 24 print i[r-1] 25 e=i[r-1] ---> 26 mlab.mesh(x, y, z,'e') 27 #print i[r-1] 28 C:\Python27\lib\site-packages\mayavi\tools\helper_functions.pyc in the_function(*args, **kwargs) 32 def document_pipeline(pipeline): 33 def the_function(*args, **kwargs): ---> 34 return pipeline(*args, **kwargs) 35 36 if hasattr(pipeline, 'doc'): C:\Python27\lib\site-packages\mayavi\tools\helper_functions.pyc in __call__(self, *args, **kwargs) 77 scene.disable_render = True 78 # Then call the real logic ---> 79 output = self.__call_internal__(*args, **kwargs) 80 # And re-enable the rendering, if needed. 81 if scene is not None: C:\Python27\lib\site-packages\mayavi\tools\helper_functions.pyc in __call_internal__(self, *args, **kwargs) 830 filters. 831 """ --> 832 self.source = self._source_function(*args, **kwargs) 833 kwargs.pop('name', None) 834 self.store_kwargs(kwargs) TypeError: grid_source() takes exactly 3 arguments (4 given) From silideba at gmail.com Tue Feb 14 14:56:26 2012 From: silideba at gmail.com (Debashish Saha) Date: Tue, 14 Feb 2012 19:26:26 +0530 Subject: [Tutor] problem in plotting circular plates at regular separation Message-ID: from __future__ import division import numpy from enthought.mayavi import mlab for r in range (1,5): print r pi = numpy.pi cos = numpy.cos sin = numpy.sin dphi, dtheta, dz = pi/250.0, pi/250.0, 0.01 [s,theta]=numpy.mgrid[0.01:r+0.015:.01,0:2*pi+dtheta*1.5:dtheta] x=s*cos(theta) y=s*sin(theta) z=r mlab.mesh(x, y,z, colormap='Greens') error: AssertionError Traceback (most recent call last) C:\Users\as\ in () 13 y=s*sin(theta) 14 z=r ---> 15 mlab.mesh(x, y,z, colormap='Greens') C:\Python27\lib\site-packages\mayavi\tools\helper_functions.pyc in the_function(*args, **kwargs) 32 def document_pipeline(pipeline): 33 def the_function(*args, **kwargs): ---> 34 return pipeline(*args, **kwargs) 35 36 if hasattr(pipeline, 'doc'): C:\Python27\lib\site-packages\mayavi\tools\helper_functions.pyc in __call__(self, *args, **kwargs) 77 scene.disable_render = True 78 # Then call the real logic ---> 79 output = self.__call_internal__(*args, **kwargs) 80 # And re-enable the rendering, if needed. 81 if scene is not None: C:\Python27\lib\site-packages\mayavi\tools\helper_functions.pyc in __call_internal__(self, *args, **kwargs) 830 filters. 831 """ --> 832 self.source = self._source_function(*args, **kwargs) 833 kwargs.pop('name', None) 834 self.store_kwargs(kwargs) C:\Python27\lib\site-packages\mayavi\tools\sources.pyc in grid_source(x, y, z, **kwargs) 1259 x, y, z, scalars = convert_to_arrays((x, y, z, scalars)) 1260 data_source = MGridSource() -> 1261 data_source.reset(x=x, y=y, z=z, scalars=scalars) 1262 1263 name = kwargs.pop('name', 'GridSource') C:\Python27\lib\site-packages\mayavi\tools\sources.pyc in reset(self, **traits) 689 assert len(x.shape) == 2, "Array x must be 2 dimensional." 690 assert len(y.shape) == 2, "Array y must be 2 dimensional." --> 691 assert len(z.shape) == 2, "Array z must be 2 dimensional." 692 assert x.shape == y.shape, "Arrays x and y must have same shape." 693 assert y.shape == z.shape, "Arrays y and z must have same shape." AssertionError: Array z must be 2 dimensional. From alan.gauld at btinternet.com Tue Feb 14 15:07:26 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 14 Feb 2012 14:07:26 +0000 Subject: [Tutor] problem in plotting circular plates at regular separation In-Reply-To: References: Message-ID: On 14/02/12 13:56, Debashish Saha wrote: > for r in range (1,5): ... > z=r > mlab.mesh(x, y,z, colormap='Greens') ... > AssertionError: Array z must be 2 dimensional. And your question is? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Tue Feb 14 15:43:47 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 15 Feb 2012 01:43:47 +1100 Subject: [Tutor] problem in ploting cylinders with different colour. In-Reply-To: References: Message-ID: <4F3A7323.9060308@pearwood.info> Debashish Saha wrote: > TypeError: grid_source() takes exactly 3 arguments (4 given) Is this error not clear enough? The function expects 3 arguments, you have given it 4. You need to give one fewer. The only tricky thing to remember is that when you have a method, one argument is the automatically provided "self" argument: function(a, b, c, d) # This is FOUR arguments. instance.method(a, b, c) # So is this, because there is also a "self" arg. -- Steven From breamoreboy at yahoo.co.uk Tue Feb 14 15:55:26 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 14 Feb 2012 14:55:26 +0000 Subject: [Tutor] problem in plotting circular plates at regular separation In-Reply-To: References: Message-ID: On 14/02/2012 14:07, Alan Gauld wrote: > On 14/02/12 13:56, Debashish Saha wrote: > >> for r in range (1,5): > ... >> z=r >> mlab.mesh(x, y,z, colormap='Greens') > ... >> AssertionError: Array z must be 2 dimensional. > > > And your question is? > It's implied, please do my work for me because I can't be bothered to phrase a question. -- Cheers. Mark Lawrence. From kliateni at gmail.com Tue Feb 14 16:12:42 2012 From: kliateni at gmail.com (Karim) Date: Tue, 14 Feb 2012 16:12:42 +0100 Subject: [Tutor] Using __ini__.py for common fonctions Message-ID: <4F3A79EA.4040004@gmail.com> Hello All, I have 3 functions, common utilities which I use several times in many modules of a main package. I don't want to create an utilies.py module in the package. Instead I declare it in the __init__.py of the package. Then to use it inside my package I do the following: from package import my_common_utility_fonction. Is it ok to do this? Is it a common practise? Advices are welcome! Cheers Karim From kliateni at gmail.com Tue Feb 14 20:08:18 2012 From: kliateni at gmail.com (Karim) Date: Tue, 14 Feb 2012 20:08:18 +0100 Subject: [Tutor] Using __ini__.py for common fonctions Message-ID: <4F3AB122.8080706@gmail.com> Hello All, I have 3 functions, common utilities which I use several times in many modules of a main package. I don't want to create an utilies.py module in the package. Instead I declare it in the __init__.py of the package. Then to use it I do the following: from packe Is it ok to do this? Is it a common practise? Advices are welcome! From alan.gauld at btinternet.com Tue Feb 14 20:25:33 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 14 Feb 2012 19:25:33 +0000 Subject: [Tutor] Using __ini__.py for common fonctions In-Reply-To: <4F3AB122.8080706@gmail.com> References: <4F3AB122.8080706@gmail.com> Message-ID: On 14/02/12 19:08, Karim wrote: > Advices are welcome! Asking the same question twice does not double your chances of getting a reply. It may even reduce them. As to your question, it's not the most common way to do it, it's not even the way I'd recommend since what it does is hide your code by putting it somewhere a user is not likely to guess. In Python explicit beats implicit. Put it in a module where we can see where it lives. It makes maintenance much easier later. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kliateni at gmail.com Tue Feb 14 21:12:18 2012 From: kliateni at gmail.com (Karim) Date: Tue, 14 Feb 2012 21:12:18 +0100 Subject: [Tutor] Using __ini__.py for common fonctions In-Reply-To: References: <4F3AB122.8080706@gmail.com> Message-ID: <4F3AC022.6000309@gmail.com> Le 14/02/2012 20:25, Alan Gauld a ?crit : > On 14/02/12 19:08, Karim wrote: > >> Advices are welcome! > > Asking the same question twice does not double your chances of getting > a reply. It may even reduce them. > > As to your question, it's not the most common way to do it, it's not > even the way I'd recommend since what it does is hide your code by > putting it somewhere a user is not likely to guess. > > In Python explicit beats implicit. Put it in a module where we can see > where it lives. It makes maintenance much easier later. > Sorry Alan, I have an issue w/ thunderbird and I found my first email in the Trash bin ! I did not know if my email was sent or not as I don't receive my email back (Don't know why). Thanks for your prompt answer. Cheers karim From 0101amt at gmail.com Tue Feb 14 22:04:30 2012 From: 0101amt at gmail.com (amt) Date: Tue, 14 Feb 2012 23:04:30 +0200 Subject: [Tutor] Learn Python The Hard Way, Ex19-3 In-Reply-To: References: Message-ID: Hello! I managed in the end to have more than 10 ways of doing it, moving now to Exercise 20. Thank you so much for helping me out every time. Regards, amt From emeraldoffice at hotmail.com Wed Feb 15 03:16:16 2012 From: emeraldoffice at hotmail.com (Tamar Osher) Date: Tue, 14 Feb 2012 20:16:16 -0600 Subject: [Tutor] specific recommendation for a Python book, to move from baby-level to intermediate-level Message-ID: Hello! I have finished reading some Python tutorials. My favorite tutorial is the official tutorial at Python.org. I am hoping to find a professionally designed, serious, university level book (with exercises, with a learning disc, and answers, and an elaborately helpful website) that will carefully and surely guide me through learning computer programming with Python version 3. I want to be lifted up from a baby-level to an intermediate level. I don't want to spend a lot of time casually browsing through the websites, trying out different things. I am in a rush to become a Python expert, I need a job! I enjoy computer programming. Python is my only programming language. A note to Python Teachers: I downloaded Python version 3.2.2 on my computer. Most Python books and tutorials are several years old, for older, outdated versions. My learning Python got off to a slow start: Initially, I had spent over a week trying to figure out the (version 2) tutorial for "Hello, World!", and the print/print() situation. Today, there is a huge and growing number of online Python tutorials and websites. My request is that the list of recommended tutorials be revised and updated. There is a sizable amount of learning and tutorial info at Python.org that seems to be valuable historical information rather than urgent-read-now-tutorials for new beginning programmers. For instance, there are some very well written Python tutorials from years 2009, 2007, and 2005. An idea: Delete all references to tutorials that are not version 2 or 3. And clearly label all the well-written version 2 tutorials, as being outdated version 2. For me, learning computer programming is easy, so far. What is difficult is finding the proper tutorials, and learning how to manage the difference between version 3.2.2 and older versions. For someone new to programming, the difference between version 3.2.2 and the older versions is enormous. (I have a background as a professional classroom teacher.) I am very eager to get kind help and wise counsel from others. If I need to install install Python version 2, buy a version 2 university-level book, read some version 2 tutorials, and do some version 2 exercises, please let me know. I want to quickly move myself from a baby-level to a capable, intermediate-level Python programmer. Please contact me when you have time. I am eager to connect with everyone and hear each person's comments. Have a GREAT day! >From Your Friend: Tamar Osher Skype: tamarosher Email: EmeraldOffice at hotmail.com Message Phone: 011- 1- 513-252-2936 www.HowToBeGifted.com - marketing communication, web design, and much more -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Feb 15 10:28:30 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 15 Feb 2012 09:28:30 +0000 Subject: [Tutor] specific recommendation for a Python book, to move from baby-level to intermediate-level In-Reply-To: References: Message-ID: On 15/02/12 02:16, Tamar Osher wrote: > I am hoping to find a professionally designed, serious, university level > book (with exercises, with a learning disc, and answers, and an > elaborately helpful website) that will carefully and surely guide me > through learning computer programming with Python version 3. I want to > be lifted up from a baby-level to an intermediate level. I don;t know about a CD etc but its a good book: Programming in Python 3 by Summerfield. And as a general intermediate book I like Programming Python by Lutz (not in v3 yet but as an intermediate programmer that won't make any difference to you, your past worrying about that) > I don't want to spend a lot of time casually browsing through the > websites, trying out different things. A pity, its the best way to learn. > I am in a rush to become a Python expert, I need a job! Go write lots of code. > I enjoy computer programming. Python is my only programming language. To get and keep a job you will need more than one. As a minimum you will probably need SQL and nowadays at least some JavaScript will be useful. And an OS shell language would be useful too. As a minimum. > A note to Python Teachers: > I downloaded Python version 3.2.2 on my computer. Most Python books and > tutorials are several years old, for older, outdated versions. Yes, because to produce them takes a lot of time. And most online tutorials are done by volunteers with another lifew - the one that earns them money. So they can't write tutorials as fast as the language evolves. Or they only have time to write a tutorial once, not to update it. The good news is that Python is fairly stable and most things still work even from version 1. > learning Python got off to a slow start: Initially, I had spent over a > week trying to figure out the (version 2) tutorial for "Hello, World!", > and the print/print() situation. Really? If you had asked here. or even read the v3 documentation you would have had print() explained in great detail. > Today, there is a huge and growing number of online Python tutorials and > websites. My request is that the list of recommended tutorials be > revised and updated. There is a sizable amount of learning and tutorial > info at Python.org that seems to be valuable historical information > rather than urgent-read-now-tutorials for new beginning programmers. Remember that many - most? - professional Python programmers are still using Python v2 not v3. There are still some critical third party libraries to be ported to v3. It is getting better but we are not there yet. At the very least they are maintaining v2 code. I use both versions but only about 20-25% of my time is spent in v3. v2 is not only of "historical" interest, its what the majority of Python code is written in, even today. > instance, there are some very well written Python tutorials from years > 2009, 2007, and 2005. An idea: Delete all references to tutorials that > are not version 2 or 3. v1 Python is possibly a valid point. But most v1 tutorials are still valid in v2, there was much less change from v1 to v2. > And clearly label all the well-written version 2 tutorials, as > being outdated version 2. Who determines what is "well written"? And if a tutorial is based on v2.7 is it really outdated? > For me, learning computer programming is easy, so far. That's good, so you will have realized that the language, and especially the language version is largely irrelevant. What is important is structure, algorithm, data and I/O. > What is difficult is ...learning how to manage the > difference between version 3.2.2 and older versions. No, that's trivially easy. If you think that's difficult then you haven't begun to understand computer science. I strongly suggest you search for and read the classic paper by Fred Brooks called "No silver bullet" There he describes the "essential" problems at the heart of programming and why there are no easy answers. Languages included. > For someone new to programming, the difference between version 3.2.2 > and the older versions is enormous. I agree and thats why I still tend to recommend a newcomer stick to v2 for now. There are more tutorials and they are more mature and there are more practitioners using it than v3. All of which makes it easier to get answers for v2 than for v3. The situation is changing but v3 is not mainstream yet. > please let me know. I want to quickly move myself from a baby-level to a > capable, intermediate-level Python programmer. It depends on your expectations but the quickest way to get competent in any programming language is through use. Once you have written several tens of thousands of lines of code you will be well on your way. But that will take quite a few months and that may not align with your expectations. Reading books will teach you the theory (but for that you would be better off reading books like The Structure and Interpretation of Computer Programs (aka SICP) by Sussman and How to Design Programs (HTDP). But both are in Scheme not Python. But they will transform your understanding of how programs work. And if you really want to understand the theory find books on relational data theory, state automata theory, algorithm development, and Lambda calculus. Then finally you might want to look at some of the books on system design, especially as you get involved in bigger projects. Its hard to organise code over several hundred files unless you have an underlying architecture and that needs to be based on good design principles more than good coding principles. But none of that is essential to becoming a working programmer, just get out and write lots of code for real world problems. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From wescpy at gmail.com Wed Feb 15 11:43:36 2012 From: wescpy at gmail.com (wesley chun) Date: Wed, 15 Feb 2012 02:43:36 -0800 Subject: [Tutor] specific recommendation for a Python book, to move from baby-level to intermediate-level In-Reply-To: References: Message-ID: tooting my own horn, http://corepython.com gets good reviews too. however, it does target existing programmers who want to learn Python as quickly and as comprehensively as possible. it's not a good book if you're a beginner to programming or are looking for a pure reference like PER or Nutshell. if you really need a learning disc, a subset of my book and the slides i use to teach with can be found in the Python Fundamentals DVD that i authored as well, however it is *not* a "showmedo" video of Python hacking. rather, it's a subset of my lectures that come from my Python courses. i'm also book-agnostic but am concerned that readers get the right book for their needs, so i would be glad to recommend other books outside of my own. cheers, --wesley On Wed, Feb 15, 2012 at 1:28 AM, Alan Gauld wrote: > On 15/02/12 02:16, Tamar Osher wrote: > > I am hoping to find a professionally designed, serious, university level >> book (with exercises, with a learning disc, and answers, and an >> elaborately helpful website) that will carefully and surely guide me >> through learning computer programming with Python version 3. I want to >> be lifted up from a baby-level to an intermediate level. >> > > I don;t know about a CD etc but its a good book: > > Programming in Python 3 by Summerfield. > > And as a general intermediate book I like > > Programming Python by Lutz (not in v3 yet but as an > intermediate programmer that won't make any difference > to you, your past worrying about that) > > > I don't want to spend a lot of time casually browsing through the >> websites, trying out different things. >> > > A pity, its the best way to learn. > > > > I am in a rush to become a Python expert, I need a job! > > Go write lots of code. > > > I enjoy computer programming. Python is my only programming language. >> > > To get and keep a job you will need more than one. > As a minimum you will probably need SQL and nowadays > at least some JavaScript will be useful. And an OS shell > language would be useful too. As a minimum. > > > A note to Python Teachers: >> I downloaded Python version 3.2.2 on my computer. Most Python books and >> tutorials are several years old, for older, outdated versions. >> > > Yes, because to produce them takes a lot of time. And most online > tutorials are done by volunteers with another lifew - the one that earns > them money. So they can't write tutorials as fast as the language evolves. > Or they only have time to write a tutorial once, not to update it. The good > news is that Python is fairly stable and most things still work even from > version 1. > > > learning Python got off to a slow start: Initially, I had spent over a >> week trying to figure out the (version 2) tutorial for "Hello, World!", >> and the print/print() situation. >> > > Really? If you had asked here. or even read the v3 documentation you would > have had print() explained in great detail. > > > Today, there is a huge and growing number of online Python tutorials and >> websites. My request is that the list of recommended tutorials be >> revised and updated. There is a sizable amount of learning and tutorial >> info at Python.org that seems to be valuable historical information >> rather than urgent-read-now-tutorials for new beginning programmers. >> > > Remember that many - most? - professional Python programmers are still > using Python v2 not v3. There are still some critical third party libraries > to be ported to v3. It is getting better but we are not there yet. At the > very least they are maintaining v2 code. I use both versions but only about > 20-25% of my time is spent in v3. v2 is not only of "historical" interest, > its what the majority of Python code is written in, even today. > > > instance, there are some very well written Python tutorials from years >> 2009, 2007, and 2005. An idea: Delete all references to tutorials that >> are not version 2 or 3. >> > > v1 Python is possibly a valid point. But most v1 tutorials are still valid > in v2, there was much less change from v1 to v2. > > > And clearly label all the well-written version 2 tutorials, as >> > > being outdated version 2. > > Who determines what is "well written"? And if a tutorial is based on v2.7 > is it really outdated? > > > For me, learning computer programming is easy, so far. >> > > That's good, so you will have realized that the language, and especially > the language version is largely irrelevant. What is important is structure, > algorithm, data and I/O. > > What is difficult is ...learning how to manage the >> >> difference between version 3.2.2 and older versions. >> > > No, that's trivially easy. If you think that's difficult then you haven't > begun to understand computer science. I strongly suggest you search for and > read the classic paper by Fred Brooks called "No silver bullet" > There he describes the "essential" problems at the heart of programming > and why there are no easy answers. Languages included. > > > For someone new to programming, the difference between version 3.2.2 >> > > and the older versions is enormous. > > I agree and thats why I still tend to recommend a newcomer stick to v2 for > now. There are more tutorials and they are more mature and there are more > practitioners using it than v3. All of which makes it easier to get answers > for v2 than for v3. The situation is changing but v3 is not mainstream yet. > > > please let me know. I want to quickly move myself from a baby-level to a >> capable, intermediate-level Python programmer. >> > > It depends on your expectations but the quickest way to get competent in > any programming language is through use. Once you have written several tens > of thousands of lines of code you will be well on your way. But that will > take quite a few months and that may not align with your expectations. > > Reading books will teach you the theory (but for that you would be better > off reading books like The Structure and Interpretation of Computer > Programs (aka SICP) by Sussman and How to Design Programs (HTDP). But both > are in Scheme not Python. But they will transform your understanding of how > programs work. And if you really want to understand the theory find books > on relational data theory, state automata theory, algorithm development, > and Lambda calculus. > > Then finally you might want to look at some of the books on system design, > especially as you get involved in bigger projects. Its hard to organise > code over several hundred files unless you have an underlying architecture > and that needs to be based on good design principles more than good coding > principles. > > But none of that is essential to becoming a working programmer, just get > out and write lots of code for real world problems. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.chun : wescpy-gmail.com : @wescpy/+wescpy python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From leamhall at gmail.com Wed Feb 15 13:35:33 2012 From: leamhall at gmail.com (leam hall) Date: Wed, 15 Feb 2012 07:35:33 -0500 Subject: [Tutor] specific recommendation for a Python book, to move from baby-level to intermediate-level In-Reply-To: References: Message-ID: I will have to agree with both Wes and Alan, they provide great resources. However, the issue you will face is three-fold. You need to: 1. Write lots of good code. 2. Write lots more good code. 3. Show a whole lot of good code you've written. If you want to program professionally I suggest getting a job in computers that is near where you want to be. Develop your programming skills and your work reputation at the same time. Your porfolio of lots of good code will require more than one language, software lifecycle and version control, specification writing, etc...etc...etc... To write good code you need books, experience, and lots of critical review. Otherwise you'll be writing lots of bad code that won't get you anywhere. Feedback is critical to growth. Leam -- Mind on a Mission From joel.goldstick at gmail.com Wed Feb 15 13:46:48 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 15 Feb 2012 07:46:48 -0500 Subject: [Tutor] specific recommendation for a Python book, to move from baby-level to intermediate-level In-Reply-To: References: Message-ID: On Wed, Feb 15, 2012 at 7:35 AM, leam hall wrote: > I will have to agree with both Wes and Alan, they provide great > resources. However, the issue you will face is three-fold. You need > to: > > 1. Write lots of good code. > 2. Write lots more good code. > 3. Show a whole lot of good code you've written. > > If you want to program professionally I suggest getting a job in > computers that is near where you want to be. Develop your programming > skills and your work reputation at the same time. Your porfolio of > lots of good code will require more than one language, software > lifecycle and version control, specification writing, > etc...etc...etc... > > To write good code you need books, experience, and lots of critical > review. Otherwise you'll be writing lots of bad code that won't get > you anywhere. Feedback is critical to growth. > > Leam > > -- > Mind on a Mission > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Programming is all about doing it -- over and over. I think Malcolm Gladwell proposed that it takes 10,000 hours to get good at anything. Its great to be smitten, but there is no shortcut. Aside from Brooks, I really loved reading a two volume set called Programming Practice by Henry Ledgard. It was published in 1987, but its timeless. These authors don't write 'how to' books on coding, but they get to the core of the software engineering profession. -- Joel Goldstick From josempalaka at gmail.com Wed Feb 15 15:17:36 2012 From: josempalaka at gmail.com (JOSEPH MARTIN MPALAKA) Date: Wed, 15 Feb 2012 17:17:36 +0300 Subject: [Tutor] Some help Please Message-ID: take an example of updating Bank Accounts, gaving the following table: acc_id acc_name standing_Balance mn0001 computer 20000 my problem is how can i credit the standing balance from user data,as in making a deposit onto the computer account, using the code below:- import MySQLdb as mdb import sys con = mdb.connect('localhost', 'joseph', 'jmm20600', 'savings'); dep = input('Enter Amount: ') cur.execute("UPDATE accounts SET Standing_Amount = (Standing_Amount + dep) WHERE Acc_ID = 'MN0001'") conn.commit() HOw do i format "dep" in order to be added onto the standing_Amount,to make an increment? Please, is it the same thing with the withdrawing format, in case i want to decrement the account as in withdrawing?? joseph -- MY BEING was HIS BEING. Of what is magnificent and liked of me, this was him too. In VAIN, I will always miss u,thou i live with YOU in vain. Lt.Col.Sam .E. Lukakamwa (DADDY) -- MY BEING was HIS BEING. Of what is magnificent and liked of me, this was him too. In VAIN, I will always miss u,thou i live with YOU in vain. Lt.Col.Sam .E. Lukakamwa (DADDY) -- MY BEING was HIS BEING. Of what is magnificent and liked of me, this was him too. In VAIN, I will always miss u,thou i live with YOU in vain. Lt.Col.Sam .E. Lukakamwa (DADDY) From evert.rol at gmail.com Wed Feb 15 16:42:45 2012 From: evert.rol at gmail.com (Evert Rol) Date: Wed, 15 Feb 2012 16:42:45 +0100 Subject: [Tutor] Some help Please In-Reply-To: References: Message-ID: <417E6284-61C8-42F7-B899-D1DDA374AB36@gmail.com> Hi Joseph, > take an example of updating Bank Accounts, > gaving the following table: > > acc_id acc_name standing_Balance > mn0001 computer 20000 > > my problem is how can i credit the standing balance from user data,as > in making a deposit onto the computer account, using the code below:- > > > > import MySQLdb as mdb > import sys > > con = mdb.connect('localhost', 'joseph', 'jmm20600', 'savings'); > > dep = input('Enter Amount: ') > > cur.execute("UPDATE accounts SET Standing_Amount = > (Standing_Amount + dep) WHERE Acc_ID = 'MN0001'") > > conn.commit() > > HOw do i format "dep" in order to be added onto the standing_Amount,to > make an increment? First of all, what have you tried? And what problems or errors are you getting? Then people on the list know better how to reply, and what details you may need to know. For example, the above code is not code that will run: the cur and conn variables are undefined, and the indentation appears to be messed up. So it would appear you have not tried things out yet. If I understand your question correctly, however, it is probably fairly straightforward: you need to replace the 'dep' variable inside the string with a %-sequence, and add the dep inside a tuple as the second argument of the execute statement. An example is probably better: cur.execute("UPDATE accounts SET Standing_Amount = (Standing_Amount + %s) WHERE Acc_ID = 'MN0001'", (dep,)) That will take the value of the variable dep and put it at the %s. Note that trailing ',', to make the second argument a tuple. Note that you may want to first validate that dep is actually a number, not some string like "a lot of money"? But, in fact, this should all be reasonably clear with the help of the MySQLdb documentation. From a quick search, I can find: http://mysql-python.sourceforge.net/MySQLdb.html#some-examples , which explains the above. For some other details, there is the Python DB API description: http://www.python.org/dev/peps/pep-0249/ Evert > Please, is it the same thing with the withdrawing format, in case i > want to decrement the account as in withdrawing?? > > > joseph From swiftone at swiftone.org Wed Feb 15 16:50:42 2012 From: swiftone at swiftone.org (Brett Ritter) Date: Wed, 15 Feb 2012 10:50:42 -0500 Subject: [Tutor] specific recommendation for a Python book, to move from baby-level to intermediate-level In-Reply-To: References: Message-ID: On Wed, Feb 15, 2012 at 7:46 AM, Joel Goldstick wrote: > Programming is all about doing it -- over and over. ?I think Malcolm > Gladwell proposed that it takes 10,000 hours to get good at anything. > Its great to be smitten, but there is no shortcut. Jumping in because this is a favorite topic of mine. The 10,000 hours has been followed-up on a lot, and as a I recall (I'm no expert) it varies considerably. Experts (meaning that they have an intuitive approach to problems) can arise in much less time, while others (with a rule-based understanding only) can put in far more than 10,000 hours and still not become experts. What I've found works for me personally is to combine _doing_ (which is essential and unavoidable) with _variety_ in the tasks and also to google the heck out of "best practices", "anti-patterns", and "tips" on the topic. Make sure to get a feel for the reliability of the source of these tips, and don't trust them blindly, instead try to understand them. For example, there are three levels of progression in handling how Python uses "self" in objects: 1) This is stupid, other languages are smarter than this. 2) I do it without worrying about it because I'm used to it, but I don't really get why it works that way. 3) I understand how "obvious" alternatives won't work as Python is modeled and have come to appreciate the way it works. You can't jump straight to #3, but if you know it's there you can regularly poke at the issue as you're otherwise learning (via doing) and get closer to a higher understanding more quickly than writing 10,000 hours of "To Do" lists will get you there. Other common enlightenments to strive for: * I grok list comprehensions * I understand generators * I understand decorators (where understand is more than "can use") -- Brett Ritter / SwiftOne swiftone at swiftone.org From breamoreboy at yahoo.co.uk Wed Feb 15 17:14:26 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 15 Feb 2012 16:14:26 +0000 Subject: [Tutor] specific recommendation for a Python book, to move from baby-level to intermediate-level In-Reply-To: References: Message-ID: On 15/02/2012 02:16, Tamar Osher wrote: > > Hello! I have finished reading some Python tutorials. My favorite tutorial is the official tutorial at Python.org. > > I > am hoping to find a professionally designed, serious, university level book (with exercises, with > a learning disc, and answers, and an elaborately helpful website) that will carefully and surely guide me through > learning computer programming with Python version 3. I want to be lifted up from a baby-level to an intermediate > level. > > I > don't want to spend a lot of time casually browsing through the > websites, trying out different things. I am in a rush to become a > Python expert, I need a job! I enjoy computer programming. Python is my only programming language. > > A note to Python Teachers: > I downloaded Python version 3.2.2 on my computer. Most Python books and tutorials are several years old, for older, outdated versions. My learning Python got off to a slow start: Initially, I had spent over a week trying to figure out the (version 2) tutorial for "Hello, World!", and the print/print() situation. > Today, there is a huge and growing number of online Python tutorials and websites. My request is that the list of recommended tutorials be revised and updated. There is a sizable amount of learning and tutorial info at Python.org that seems to be valuable historical information rather than urgent-read-now-tutorials for new beginning programmers. For instance, there are some very well written Python tutorials from years 2009, 2007, and 2005. An idea: Delete all references to tutorials that are not version 2 or 3. And clearly label all the well-written version 2 tutorials, as being outdated version 2. > For me, learning computer programming is easy, so far. What is difficult is finding the proper tutorials, and learning how to manage the difference between version 3.2.2 and older versions. For someone new to programming, the difference between version 3.2.2 and the older versions is enormous. (I have a background as a professional classroom teacher.) > > I am very eager to get kind help and wise counsel from others. If I need to install install Python version 2, buy a version 2 university-level book, read some version 2 tutorials, and do some version 2 exercises, please let me know. I want to quickly move myself from a baby-level to a capable, intermediate-level Python programmer. > > Please contact me when you have time. I am eager to connect with everyone and hear each person's comments. Have a GREAT day! > >> From Your Friend: Tamar Osher > Skype: tamarosher > Email: EmeraldOffice at hotmail.com > Message Phone: 011- 1- 513-252-2936 > www.HowToBeGifted.com - marketing communication, web design, and much more > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor For an unbiased set of book reviews search the book reviews here http://accu.org/index.php?module=bookreviews&func=search -- Cheers. Mark Lawrence. From bgailer at gmail.com Wed Feb 15 18:13:23 2012 From: bgailer at gmail.com (bob gailer) Date: Wed, 15 Feb 2012 12:13:23 -0500 Subject: [Tutor] formatting sql Was: Some help Please In-Reply-To: References: Message-ID: <4F3BE7B3.7080609@gmail.com> Welcome to python help. We are a few volunteers who donate time to assist. To assist you better: 1 - provide a meaningful subject line - such as "formatting sql" 2 - tell us what OS and Python version you are using. 3 - what is your prior Python experience? On 2/15/2012 9:17 AM, JOSEPH MARTIN MPALAKA wrote: > take an example of updating Bank Accounts, > gaving the following table: > > acc_id acc_name standing_Balance > mn0001 computer 20000 > > my problem is how can i credit the standing balance from user data,as > in making a deposit onto the computer account, using the code below:- > > > > import MySQLdb as mdb > import sys > > con = mdb.connect('localhost', 'joseph', 'jmm20600', 'savings'); > > dep = input('Enter Amount: ') > > cur.execute("UPDATE accounts SET Standing_Amount = > (Standing_Amount + dep) WHERE Acc_ID = 'MN0001'") In you table the acc_id is 'mn0001' In your sql Acc_ID = 'MN0001' Why the difference in case? Why the () around Standing_Amount + dep? > > conn.commit() > > HOw do i format "dep" in order to be added onto the standing_Amount,to > make an increment? > > Please, is it the same thing with the withdrawing format, in case i > want to decrement the account as in withdrawing?? > > > joseph > > > > > > > > > -- Bob Gailer 919-636-4239 Chapel Hill NC From eire1130 at gmail.com Wed Feb 15 19:03:20 2012 From: eire1130 at gmail.com (James Reynolds) Date: Wed, 15 Feb 2012 13:03:20 -0500 Subject: [Tutor] formatting sql Was: Some help Please In-Reply-To: <4F3BE7B3.7080609@gmail.com> References: <4F3BE7B3.7080609@gmail.com> Message-ID: On Wed, Feb 15, 2012 at 12:13 PM, bob gailer wrote: > Welcome to python help. We are a few volunteers who donate time to assist. > > To assist you better: > 1 - provide a meaningful subject line - such as "formatting sql" > 2 - tell us what OS and Python version you are using. > 3 - what is your prior Python experience? > > > On 2/15/2012 9:17 AM, JOSEPH MARTIN MPALAKA wrote: > >> take an example of updating Bank Accounts, >> gaving the following table: >> >> acc_id acc_name standing_Balance >> mn0001 computer 20000 >> >> my problem is how can i credit the standing balance from user data,as >> in making a deposit onto the computer account, using the code below:- >> >> >> >> import MySQLdb as mdb >> import sys >> >> con = mdb.connect('localhost', 'joseph', 'jmm20600', 'savings'); >> >> dep = input('Enter Amount: ') >> >> cur.execute("UPDATE accounts SET Standing_Amount = >> (Standing_Amount + dep) WHERE Acc_ID = 'MN0001'") >> > In you table the acc_id is 'mn0001' > In your sql Acc_ID = 'MN0001' > Why the difference in case? > Why the () around Standing_Amount + dep? > > >> conn.commit() >> >> HOw do i format "dep" in order to be added onto the standing_Amount,to >> make an increment? >> >> Please, is it the same thing with the withdrawing format, in case i >> want to decrement the account as in withdrawing?? >> >> >> joseph >> >> >> >> >> >> >> >> >> >> > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > Normally, sql doesn't care about case with respect to table names. I believe in certain implementations they are always lower case, even if you pass an upper. The problem, as Bob pointed out above, cur.execute("UPDATE accounts SET Standing_Amount = (Standing_Amount + dep) WHERE Acc_ID = 'MN0001'") here, specifically, (Standing_Amount + dep) Sql isn't going to have any idea what "dep" is when passed, because it is going to see a string called "Dep". Well, it will know what it is, it will be a string and will through an error that it can't add a string and integer. When i want to update a value in sql, normally i extract to python, do the math there, and then update. You can do this in sql if you prefer and I'm sure there are good reasons for doing it, I'm just more comfortable working in python than I am sql. Also, when passing variables to SQL, if you are doing raw queries and not using some ORM, I would get used to using the "?" within the sql string and then passing your variables in the following list. Otherwise, you are going to leave yourself open to injection attacks (provided you are doing direct string manipulations). To do this in sql, you need to run a select statement first, saving the results to a @variable. use that @variable later (after passing in an integer) to add the two numbers. To do this in python, also run a select statement, save it to some python variable. Add your new result to it, and send that new result along to the DB using your update query. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Feb 15 19:04:57 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 15 Feb 2012 18:04:57 +0000 Subject: [Tutor] Some help Please In-Reply-To: References: Message-ID: On 15/02/12 14:17, JOSEPH MARTIN MPALAKA wrote: > take an example of updating Bank Accounts, > gaving the following table: > > acc_id acc_name standing_Balance > mn0001 computer 20000 > > cur.execute("UPDATE accounts SET Standing_Amount = > (Standing_Amount + dep) WHERE Acc_ID = 'MN0001'") Note that in programming consistency is critically important. In your table description you have standing_Balance. In your SQL query you have Standing_Amount Which is it? Also the ID is mn0001 and MN0001 which is it? You also use Acc_ID and acc_id but I believe SQL is universally case agnostic so you probably get away with that. But its better to be consistent. How to format the dep will depend on the data format of your database. If we assume it's an integer then you have several options: 1) Calculate the total and insert it into the SQL statement (may require a select first to retrieve the current value) 2) Replace dep with the value using a MySql format operation. This allows you to validate the value before inserting it. 3) Replace dep with the input string as is (slightly harder to do validation) There are probably more... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From nsivaram.net at gmail.com Wed Feb 15 19:14:19 2012 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Wed, 15 Feb 2012 23:44:19 +0530 Subject: [Tutor] Class definition confusion Message-ID: <82haysrmkk.fsf@gmail.com> I was under the impression that you have to define the attributes of the class before using it in an instance. Following the book 'thinking in Python', >>> class Point: ... """pts in 2d space""" ... >>> print Point __main__.Point >>> b = Point() >>> b.x =3 >>> b.y =4 >>> print b.y 4 >>> Why is it not throwing an error? This is confusing me a bit. sivaram -- From cranky.frankie at gmail.com Wed Feb 15 19:24:10 2012 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Wed, 15 Feb 2012 13:24:10 -0500 Subject: [Tutor] specific recommendation for a Python book, to move Message-ID: The book I recommend is Python Programming, Third Edition, for the Absolute Beginner, by Michael Dawson. It's Python 3 based. You go from knowing nothing to writing video games. I think it's great. -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?How you do anything is how you do everything.? - from Alabama Crimson Tide training room From alan.gauld at btinternet.com Wed Feb 15 19:30:28 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 15 Feb 2012 18:30:28 +0000 Subject: [Tutor] formatting sql Was: Some help Please In-Reply-To: References: <4F3BE7B3.7080609@gmail.com> Message-ID: On 15/02/12 18:03, James Reynolds wrote: > > In you table the acc_id is 'mn0001' > > In your sql Acc_ID = 'MN0001' > > Why the difference in case? > > Normally, sql doesn't care about case with respect to table names. I > believe in certain implementations they are always lower case, even if > you pass an upper. The issue is not the table (or even column name) its the value within it. Comparing 'mn0001' to 'MN0001' will fail. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Feb 15 19:33:10 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 15 Feb 2012 18:33:10 +0000 Subject: [Tutor] Class definition confusion In-Reply-To: <82haysrmkk.fsf@gmail.com> References: <82haysrmkk.fsf@gmail.com> Message-ID: On 15/02/12 18:14, Sivaram Neelakantan wrote: > > I was under the impression that you have to define the attributes of > the class before using it in an instance. Only in some languages. Python is not one of those. >>>> class Point: > ... """pts in 2d space""" > ... >>>> b = Point() >>>> b.x =3 >>>> b.y =4 >>>> print b.y > 4 >>>> > > Why is it not throwing an error? This is confusing me a bit. Python allows instance attributes to be added at runtime. In general this is a bad idea IMHO, a dictionary would probably be more appropriate, but there can, very occasionally, be valid uses for it. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From hugo.yoshi at gmail.com Wed Feb 15 19:35:41 2012 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 15 Feb 2012 19:35:41 +0100 Subject: [Tutor] Class definition confusion In-Reply-To: <82haysrmkk.fsf@gmail.com> References: <82haysrmkk.fsf@gmail.com> Message-ID: On Wed, Feb 15, 2012 at 7:14 PM, Sivaram Neelakantan wrote: > > I was under the impression that you have to define the attributes of > the class before using it in an instance. ?Following the book > 'thinking in Python', > >>>> class Point: > ... ? ? """pts in 2d space""" > ... >>>> print Point > __main__.Point >>>> b = Point() >>>> b.x =3 >>>> b.y =4 >>>> print b.y > 4 >>>> > > Why is it not throwing an error? ?This is confusing me a bit. > Python is different from static languages like C++. You can add and remove attributes from objects at any time. You do not have to declare, in your class, what kind of attributes it has. An __init__ might seem like it's special in some way, declaring attributes. But it's not, really, it's just another method that gets passed the object it is called on (that would be "self"). It's only special because it gets called when an object is created, so generally an object is initialized there and attributes are assigned (hence the name "init").' HTH, Hugo From nsivaram.net at gmail.com Wed Feb 15 19:39:52 2012 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Thu, 16 Feb 2012 00:09:52 +0530 Subject: [Tutor] Class definition confusion References: <82haysrmkk.fsf@gmail.com> Message-ID: <82d39grldz.fsf@gmail.com> On Thu, Feb 16 2012,Alan Gauld wrote: [snipped 19 lines] > Python allows instance attributes to be added at runtime. > In general this is a bad idea IMHO, a dictionary would probably > be more appropriate, but there can, very occasionally, be valid > uses for it. Thanks for that, I kept thinking that the author had made some typos in the book and was getting progressively confused, till I tried it at the prompt. sivaram -- From breamoreboy at yahoo.co.uk Wed Feb 15 19:43:53 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 15 Feb 2012 18:43:53 +0000 Subject: [Tutor] Class definition confusion In-Reply-To: <82haysrmkk.fsf@gmail.com> References: <82haysrmkk.fsf@gmail.com> Message-ID: On 15/02/2012 18:14, Sivaram Neelakantan wrote: > > I was under the impression that you have to define the attributes of > the class before using it in an instance. Following the book > 'thinking in Python', > >>>> class Point: > ... """pts in 2d space""" > ... >>>> print Point > __main__.Point >>>> b = Point() >>>> b.x =3 >>>> b.y =4 >>>> print b.y > 4 >>>> > > Why is it not throwing an error? This is confusing me a bit. > > sivaram > -- > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Your impression is incorrect. This type of behaviour is allowed because of Python's dynamic nature, so the following is fine. >>> class Point: ... """pts in 2d space""" ... >>> b = Point() >>> b.x = 3 >>> b.y = 4 >>> del b.x >>> del b.y >>> b.l = 5 >>> b.m = 6 >>> print b, b.l, b.m <__main__.Point instance at 0x02FB89B8> 5 6 Also be careful of your terminology. Here we are discussing instance attributes. Class attributes are different in that they are are shared at the class level so. >>> class Point: ... """pts in 2d space""" ... x = 3 ... y = 4 ... >>> a = Point() >>> b = Point() >>> a.x 3 >>> b.y 4 HTH. -- Cheers. Mark Lawrence. From eire1130 at gmail.com Wed Feb 15 19:51:00 2012 From: eire1130 at gmail.com (James Reynolds) Date: Wed, 15 Feb 2012 13:51:00 -0500 Subject: [Tutor] formatting sql Was: Some help Please In-Reply-To: References: <4F3BE7B3.7080609@gmail.com> Message-ID: On Wed, Feb 15, 2012 at 1:30 PM, Alan Gauld wrote: > On 15/02/12 18:03, James Reynolds wrote: > > > In you table the acc_id is 'mn0001' >> > In your sql Acc_ID = 'MN0001' >> > Why the difference in case? >> >> Normally, sql doesn't care about case with respect to table names. I >> believe in certain implementations they are always lower case, even if >> you pass an upper. >> > > The issue is not the table (or even column name) its the value within it. > Comparing 'mn0001' to 'MN0001' will fail. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > I think this depends on the settings of the column and what you have set in your sql statement. Example: if ('j' = 'J') select 'True' else select 'False' This comes out True if ('j' = 'k') select 'True' else select 'False' This comes out False I suppose this could be by implementation, but at least in sql server, I think Oracle, and maybe some others, you have to set the database (or column) to case sensitive by changing it through a collation statement. -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Wed Feb 15 20:01:04 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 15 Feb 2012 19:01:04 +0000 Subject: [Tutor] Class definition confusion In-Reply-To: References: <82haysrmkk.fsf@gmail.com> Message-ID: On 15/02/2012 18:35, Hugo Arts wrote: [snip] > An __init__ might seem like it's special in some way, declaring > attributes. But it's not, really, it's just another method that gets > passed the object it is called on (that would be "self"). It's only > special because it gets called when an object is created, so generally > an object is initialized there and attributes are assigned (hence the > name "init").' > > HTH, > Hugo > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor To the OP. Note that __init__ is an initialiser and not a constructor which is __new__, see e.g. http://mail.python.org/pipermail/tutor/2008-April/061426.html -- Cheers. Mark Lawrence. From lmergner at gmail.com Thu Feb 16 05:57:08 2012 From: lmergner at gmail.com (Luke Thomas Mergner) Date: Wed, 15 Feb 2012 23:57:08 -0500 Subject: [Tutor] Debugging While Loops for Control Message-ID: Hi, I've been translating and extending the Blackjack project from codeacademy.com into Python. My efforts so far are here: https://gist.github.com/1842131 My problem is that I am using two functions that return True or False to determine whether the player receives another card. Because of the way it evaluates the while condition, it either prints too little information or previously called the hitMe() function too many times. I am assuming that I am misusing the while loop in this case. If so, is there an elegant alternative still running the functions at least once. e.g. while ask_for_raw_input() AND is_the_score_over_21(): hitMe(hand) Any advice or observations are appreciated, but please don't solve the whole puzzle for me at once! And no, not all the functionality of a real game is implemented. The code is pretty raw. I'm just a hobbyist trying to learn a few things in my spare time. Thanks in advance. Luke From alan.gauld at btinternet.com Thu Feb 16 10:05:39 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 16 Feb 2012 09:05:39 +0000 Subject: [Tutor] Debugging While Loops for Control In-Reply-To: References: Message-ID: On 16/02/12 04:57, Luke Thomas Mergner wrote: > My problem is that I am using two functions that return True or False > to determine whether the player receives another card. > Because of the way it evaluates the while condition, it either > prints too little information or previously called the hitMe() > function too many times. > I am assuming that I am misusing the while loop in this case. > while ask_for_raw_input() AND is_the_score_over_21(): > hitMe(hand) I haven't looked at the code for the functions but going by their names I'd suggest you need to reverse their order to while is_the_score_over_21() and ask_for_raw_input(): hitMe(hand) The reason is that the first function will always get called but you (I think) only want to ask for, and give out, another card if the score is over 21 (or should that maybe be *under* 21?). Personally I would never combine a test function with an input one. Its kind of the other side of the rule that says don't don;t put print statements inside logic functions. In both cases its about separating himan interaction/display from program logic. So I'd make the ask_for_raw_input jusat return a value(or set of values) and create a new funtion to test the result and use that one in the while loop. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From racgomi at yahoo.com Thu Feb 16 22:46:14 2012 From: racgomi at yahoo.com (alain Delon) Date: Thu, 16 Feb 2012 13:46:14 -0800 (PST) Subject: [Tutor] How to convert seconds to hh:mm:ss format Message-ID: <1329428774.82131.YahooMailNeo@web114617.mail.gq1.yahoo.com> userName = raw_input("Enter your name ") ? ? ?print "hi " + userName + ". \n " ? ? ?seconds = input("Enter the number of seconds since midnight:") ? ? ?hours = seconds/3600 ? ? ?hoursRemain = hours%60 ? ? ?minutes = hoursReamain/60 ? ? ?secondsRemain = minutes%60 ? ? ?print "hours: " + "minutes: " + "seconds" I'm going to be crazy. Please give me a hand. Thank you very much. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Thu Feb 16 23:05:49 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 16 Feb 2012 22:05:49 +0000 Subject: [Tutor] How to convert seconds to hh:mm:ss format In-Reply-To: <1329428774.82131.YahooMailNeo@web114617.mail.gq1.yahoo.com> References: <1329428774.82131.YahooMailNeo@web114617.mail.gq1.yahoo.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474150326@SCACMX008.exchad.jpmchase.net> >userName = raw_input("Enter your name ") > print "hi " + userName + ". \n " > seconds = input("Enter the number of seconds since midnight:") > hours = seconds/3600 > hoursRemain = hours%60 > minutes = hoursReamain/60 > secondsRemain = minutes%60 > print "hours: " + "minutes: " + "seconds" I avoid any kind of manual date/time calculation unless I am forced to. Here is how I would do it: >>> midnight = datetime.datetime.combine( datetime.date.today(), datetime.time() ) >>> seconds = datetime.timedelta( seconds=234 ) >>> time = midnight + seconds >>> time.strftime( '%H:%M:%S' ) '00:03:54' >>> time.strftime( 'Hours:%H minutes:%M seconds:%S' ) 'Hours:00 minutes:03 seconds:54' Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From d at davea.name Thu Feb 16 23:21:52 2012 From: d at davea.name (Dave Angel) Date: Thu, 16 Feb 2012 17:21:52 -0500 Subject: [Tutor] How to convert seconds to hh:mm:ss format In-Reply-To: <1329428774.82131.YahooMailNeo@web114617.mail.gq1.yahoo.com> References: <1329428774.82131.YahooMailNeo@web114617.mail.gq1.yahoo.com> Message-ID: <4F3D8180.5000203@davea.name> On 02/16/2012 04:46 PM, alain Delon wrote: > userName = raw_input("Enter your name ") > print "hi " + userName + ". \n " > seconds = input("Enter the number of seconds since midnight:") > hours = seconds/3600 > hoursRemain = hours%60 > minutes = hoursReamain/60 > secondsRemain = minutes%60 > print "hours: " + "minutes: " + "seconds" > > > I'm going to be crazy. Please give me a hand. Thank you very much. > Welcome to the list. Are you new to programming, or just to Python, or just to this list? Did you copy/paste this from somewhere? Or retype it? Have you tried running it? What happens? Is it a learning exercise, or something where you want the results with the least effort? There are library functions in datetime that'll practically do it for you, but you don't already know about integer division and remainders, it's a good exercise to do by hand. Why do you need help going crazy? When I try running it, I get indentation errors first, because the code doesn't line up. next, I get an error because you spelled hoursRemain two different ways. Then I get output that doesn't print out any of the results you calculated. that's because you never print out any of the variables, only literal strings. There also, you could use formatting functions, but if you just want to see the results, print them out with three separate print statements. Only when you decide they're correct should you worry about making it pretty, with leading zeroes, colons, and such. -- DaveA From martin at linux-ip.net Thu Feb 16 23:21:29 2012 From: martin at linux-ip.net (Martin A. Brown) Date: Thu, 16 Feb 2012 17:21:29 -0500 Subject: [Tutor] How to convert seconds to hh:mm:ss format In-Reply-To: <1329428774.82131.YahooMailNeo@web114617.mail.gq1.yahoo.com> References: <1329428774.82131.YahooMailNeo@web114617.mail.gq1.yahoo.com> Message-ID: Welcome to the joys of time and date handling. : userName = raw_input("Enter your name ") : ? ? ?print "hi " + userName + ". \n " : ? ? ?seconds = input("Enter the number of seconds since midnight:") : ? ? ?hours = seconds/3600 : ? ? ?hoursRemain = hours%60 : ? ? ?minutes = hoursReamain/60 : ? ? ?secondsRemain = minutes%60 : ? ? ?print "hours: " + "minutes: " + "seconds" : : I'm going to be crazy. In fact, yes, you probably will. This is one of those wonderful places where you probably really want to look into what a library can do for you. There are many, but I'll just start with the standard library called time. Read the documenation on the time module: http://docs.python.org/library/time.html Here's a simple example of getting the time right now, and presenting in in a variety of ways. I give '%T' as the example you asked for, and then, I make up a nonstandard example to show how rich the format operators are when using strftime(). >>> import time >>> time.gmtime() time.struct_time(tm_year=2012, tm_mon=2, tm_mday=16, tm_hour=22, tm_min=2, tm_sec=26, tm_wday=3, tm_yday=47, tm_isdst=0) >>> time.strftime('%T',time.gmtime()) '22:02:28' >>> time.strftime('%R %A %B %d, %Y',time.gmtime()) '22:02 Thursday February 16, 2012' >>> time.strftime('%R %A %B %d, %Y',time.localtime()) '17:02 Thursday February 16, 2012' Now, you will probably need to think carefully about whether you want localtime() or gmtime(). You will probably need to consider whether you need to do any date math. : Please give me a hand. Thank you very much. Play with strftime(). This is a feature of many languages and programming environments. It should be able to produce most (if not all) output formats you probably need. Now, you specifically asked about how to deal with adding and subtracting dates and times. For this, consider the datetime module/library. Yes, there's a small bit of overlap...notably that you can also use strftime() on datetime objects. http://docs.python.org/library/datetime.html >>> import datetime >>> now = datetime.datetime.now() >>> twohrsago = datetime.timedelta(minutes=120) >>> now datetime.datetime(2012, 2, 16, 17, 15, 46, 655472) >>> now + twohrsago datetime.datetime(2012, 2, 16, 19, 15, 46, 655472) >>> then = now + twohrsago >>> then.strftime('%F-%T') '2012-02-16-19:15:46' I would add my voice to Ramit Prasad's voice and strongly suggest using the date and time handling tools available in libraries, rather than try to build your own. Good luck, -Martin -- Martin A. Brown http://linux-ip.net/ From njpalmer15 at gmail.com Fri Feb 17 00:45:41 2012 From: njpalmer15 at gmail.com (Nicholas Palmer) Date: Thu, 16 Feb 2012 18:45:41 -0500 Subject: [Tutor] Tutor Digest, Vol 96, Issue 69 In-Reply-To: References: Message-ID: I am fairly experienced in java and I was wondering how to use java in python code, if you could give me any tips.\ On Thu, Feb 16, 2012 at 6:00 AM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Debugging While Loops for Control (Luke Thomas Mergner) > 2. Re: Debugging While Loops for Control (Alan Gauld) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Wed, 15 Feb 2012 23:57:08 -0500 > From: Luke Thomas Mergner > To: tutor at python.org > Subject: [Tutor] Debugging While Loops for Control > Message-ID: > Content-Type: text/plain; charset=us-ascii > > Hi, > > I've been translating and extending the Blackjack project from > codeacademy.com into Python. My efforts so far are here: > https://gist.github.com/1842131 > > My problem is that I am using two functions that return True or False to > determine whether the player receives another card. Because of the way it > evaluates the while condition, it either prints too little information or > previously called the hitMe() function too many times. I am assuming that > I am misusing the while loop in this case. If so, is there an elegant > alternative still running the functions at least once. > > e.g. > while ask_for_raw_input() AND is_the_score_over_21(): > hitMe(hand) > > > Any advice or observations are appreciated, but please don't solve the > whole puzzle for me at once! And no, not all the functionality of a real > game is implemented. The code is pretty raw. I'm just a hobbyist trying to > learn a few things in my spare time. > > Thanks in advance. > > Luke > > ------------------------------ > > Message: 2 > Date: Thu, 16 Feb 2012 09:05:39 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Debugging While Loops for Control > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 16/02/12 04:57, Luke Thomas Mergner wrote: > > > My problem is that I am using two functions that return True or False > > to determine whether the player receives another card. > > > Because of the way it evaluates the while condition, it either > > prints too little information or previously called the hitMe() > > function too many times. > > > I am assuming that I am misusing the while loop in this case. > > > while ask_for_raw_input() AND is_the_score_over_21(): > > hitMe(hand) > > I haven't looked at the code for the functions but going > by their names I'd suggest you need to reverse their order to > > while is_the_score_over_21() and ask_for_raw_input(): > hitMe(hand) > > The reason is that the first function will always get called > but you (I think) only want to ask for, and give out, another > card if the score is over 21 (or should that maybe be > *under* 21?). > > Personally I would never combine a test function with > an input one. Its kind of the other side of the rule that > says don't don;t put print statements inside logic functions. > In both cases its about separating himan interaction/display from > program logic. So I'd make the ask_for_raw_input jusat return a value(or > set of values) and create a new funtion to test > the result and use that one in the while loop. > > HTH, > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 96, Issue 69 > ************************************* > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Fri Feb 17 00:57:26 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 16 Feb 2012 23:57:26 +0000 Subject: [Tutor] Using Java from Python was RE: Tutor Digest, Vol 96, Issue 69 In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474150502@SCACMX008.exchad.jpmchase.net> >I am fairly experienced in java and I was wondering how to use java in python code, if you could give me any tips.\ Hi, Please remove any irrelevant sections of the digest if you are replying to it (which in this case is everything) and change the subject to be more descriptive. Also, top posting (replying above relevant text) is considered bad form. Now getting down to your question, what exactly do you mean by "using" java "in" python? 1. Call a java program from Python? 2. Using Python code with a Java virtual machine? 3. Use actual Java code in Python? My answers: 1. Look at Subprocess.call (preferred) or os.system functions. 2. Take a look at Jython. 3. I have no idea. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Fri Feb 17 01:19:20 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Feb 2012 00:19:20 +0000 Subject: [Tutor] Tutor Digest, Vol 96, Issue 69 In-Reply-To: References: Message-ID: On 16/02/12 23:45, Nicholas Palmer wrote: > I am fairly experienced in java and I was wondering how to use java in > python code, if you could give me any tips.\ In general you don't you use Python instead of Java. But if you really must you can use Jython which is an implementation of python in Java. This allows you to use Java classes in Python and Python(Jython) classes in Java. Of course nothing is free so you get a performance hit and a resource hit (you have to embed the interpreter in your app). But you get a big development efficiency boon. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Fri Feb 17 01:28:18 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 17 Feb 2012 11:28:18 +1100 Subject: [Tutor] Python in Java [was Re: Tutor Digest, Vol 96, Issue 69] In-Reply-To: References: Message-ID: <4F3D9F22.10303@pearwood.info> Nicholas Palmer wrote: > I am fairly experienced in java and I was wondering how to use java in > python code, if you could give me any tips.\ My first tip is to learn how to use email effectively. Doing so will increase the chances that volunteers on mailing lists will answer your questions with respect instead of dismissing you as rude or incompetent or both. (1) Please do not hijack existing threads for a new question, because your question may be missed or ignored by others. Always use your mail program's "Write Email" command (or equivalent) to ask a new question, not Reply or Reply All. (2) That includes replying to message digests. Never use Reply unless you are actually *replying*. (3) Always use Reply All to ensure a copy of your reply goes to the list, unless you wish to make a private (personal) comment to the person you are replying to. (4) Always choose a sensible, meaningful subject line, such as "How to use Python with Java", and not "Re: [Tutor] Tutor Digest, Vol 96, Issue 69" or "Help". (5) When replying, trim the irrelevant parts of the previous message. There is no need to include quotes of quotes of quotes of quotes going back through fifteen messages. To answer your question about running Python in Java, there is an implementation of Python written in Java which has very high integration with the Java virtual machine and runtime libraries: http://www.jython.org/ You might also try JPype, which promises Java to Python integration: http://jpype.sourceforge.net/ or Jepp: http://jepp.sourceforge.net/ or basically google for "python in java" or similar: https://duckduckgo.com/html/?q=python%20in%20java -- Steven From elainahyde at gmail.com Fri Feb 17 02:04:12 2012 From: elainahyde at gmail.com (Elaina Ann Hyde) Date: Fri, 17 Feb 2012 12:04:12 +1100 Subject: [Tutor] finding a maximum between the absolute difference of several columns Message-ID: Hello all, I am still scripting away and have reached my next quandry, this one is much simpler than the last, basically I read in a file with several columns. Vmatch3_1=dat[col1] Vmatch3_2=dat[col2] Vmatch3_3=dat[col3] Vdav=5.0 Vhel_fdiff3=max(abs(Vmatch3_1 - Vmatch3_2),abs(Vmatch3_1 - Vmatch3_3),abs(Vmatch3_3 - Vmatch3_2)) ---------------- What I would like this to return is the maximum difference in each case, so I end up with one column which contains only the largest differences. now I use this to write the condition: with_v1_3=(Vhel_fdiff3 >= Vdav) I know the condition works and plots if Vhel_fdiff3=(Vmatch3_1 - Vmatch3_2) for example, and I know this syntax would work if it was numbers instead of columns. >>max(abs(1-2),abs(3-7),abs(2-4)) >>4 The error is: ----------------------- Traceback (most recent call last): File "double_plot.py", line 109, in Vhel_fdiff3=max(abs(Vmatch3_1 - Vmatch3_2),abs(Vmatch3_1 - Vmatch3_3),abs(Vmatch3_3 - Vmatch3_2)) ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() ----------------- So it can't handle the fact that it's columns of numbers and not single numbers, so my question is, can I solve this without doing a loop around it... use numpy, or some other function instead? I've been searching around and haven't found any good ways forward so I thought one of you might know. Thanks ~Elaina -- PhD Candidate Department of Physics and Astronomy Faculty of Science Macquarie University North Ryde, NSW 2109, Australia -------------- next part -------------- An HTML attachment was scrubbed... URL: From vandyke.geospatial at gmail.com Fri Feb 17 02:29:46 2012 From: vandyke.geospatial at gmail.com (Daryl V) Date: Thu, 16 Feb 2012 17:29:46 -0800 Subject: [Tutor] How to convert seconds to hh:mm:ss format Message-ID: You've gotten some really excellent advice about how to approach working with the time format. Here's a chunk of code I use quite a bit. It's probably sub-optimal, but playing with it might help you come up with a solution that works for your application. def Int2Digit(integer): if integer < 9: strInteger = "0"+str(integer) else: strInteger = str(integer) return strInteger def TimeStampMaker(): import datetime t = datetime.datetime.now() strTmonth = Int2Digit(t.month) strTday = Int2Digit(t.day) strThour = Int2Digit(t.hour) strTminute = Int2Digit(t.minute) timeStamp = str(t.year)+strTmonth+strTday+strThour+strTminute return timeStamp Good Luck - D -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Fri Feb 17 03:11:06 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 17 Feb 2012 02:11:06 +0000 Subject: [Tutor] finding a maximum between the absolute difference of several columns In-Reply-To: References: Message-ID: On 17/02/2012 01:04, Elaina Ann Hyde wrote: > Hello all, > I am still scripting away and have reached my next quandry, this one is > much simpler than the last, basically I read in a file with several > columns. > Vmatch3_1=dat[col1] > Vmatch3_2=dat[col2] > Vmatch3_3=dat[col3] > Vdav=5.0 > Vhel_fdiff3=max(abs(Vmatch3_1 - Vmatch3_2),abs(Vmatch3_1 - > Vmatch3_3),abs(Vmatch3_3 - Vmatch3_2)) > ---------------- > What I would like this to return is the maximum difference in each case, so > I end up with one column which contains only the largest differences. > now I use this to write the condition: > > with_v1_3=(Vhel_fdiff3>= Vdav) > > I know the condition works and plots if > > Vhel_fdiff3=(Vmatch3_1 - Vmatch3_2) > > for example, and I know this syntax would work if it was numbers instead of > columns. >>> max(abs(1-2),abs(3-7),abs(2-4)) >>> 4 > > The error is: > ----------------------- > Traceback (most recent call last): > File "double_plot.py", line 109, in > Vhel_fdiff3=max(abs(Vmatch3_1 - Vmatch3_2),abs(Vmatch3_1 - > Vmatch3_3),abs(Vmatch3_3 - Vmatch3_2)) > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() > ----------------- > So it can't handle the fact that it's columns of numbers and not single > numbers, so my question is, can I solve this without doing a loop around > it... use numpy, or some other function instead? > I've been searching around and haven't found any good ways forward so I > thought one of you might know. Thanks > ~Elaina > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Throwing the error message into google gave a pile of hits from stackoverflow.com, which indicate that the error message is from numpy. See if this can get you going http://stackoverflow.com/questions/1322380/gotchas-where-numpy-differs-from-straight-python. The fourth answer down states "this is a horrible problem" so I'll duck out here, sorry :) -- Cheers. Mark Lawrence. From elainahyde at gmail.com Fri Feb 17 03:53:57 2012 From: elainahyde at gmail.com (Elaina Ann Hyde) Date: Fri, 17 Feb 2012 13:53:57 +1100 Subject: [Tutor] finding a maximum between the absolute difference of several columns In-Reply-To: References: Message-ID: On Fri, Feb 17, 2012 at 1:41 PM, Rohan Sachdeva wrote: > The way I would do this is to put all of the differences in a list then > take the maximum of the list. So.. > > a = Vmatch3_1 - Vmatch3_2 > b = Vmatch3_1 - Vmatch3_3 > c = Vmatch3_3 - Vmatch3_2 > > Vhel_fdiff3=max([a,b,c]) > > That should work. a,b,c are pretty bad variable names... > > Rohan > > On Thu, Feb 16, 2012 at 5:04 PM, Elaina Ann Hyde wrote: > >> Hello all, >> I am still scripting away and have reached my next quandry, this one >> is much simpler than the last, basically I read in a file with several >> columns. >> Vmatch3_1=dat[col1] >> Vmatch3_2=dat[col2] >> Vmatch3_3=dat[col3] >> Vdav=5.0 >> Vhel_fdiff3=max(abs(Vmatch3_1 - Vmatch3_2),abs(Vmatch3_1 - >> Vmatch3_3),abs(Vmatch3_3 - Vmatch3_2)) >> ---------------- >> What I would like this to return is the maximum difference in each case, >> so I end up with one column which contains only the largest differences. >> now I use this to write the condition: >> >> with_v1_3=(Vhel_fdiff3 >= Vdav) >> >> I know the condition works and plots if >> >> Vhel_fdiff3=(Vmatch3_1 - Vmatch3_2) >> >> for example, and I know this syntax would work if it was numbers instead >> of columns. >> >>max(abs(1-2),abs(3-7),abs(2-4)) >> >>4 >> >> The error is: >> ----------------------- >> Traceback (most recent call last): >> File "double_plot.py", line 109, in >> Vhel_fdiff3=max(abs(Vmatch3_1 - Vmatch3_2),abs(Vmatch3_1 - >> Vmatch3_3),abs(Vmatch3_3 - Vmatch3_2)) >> ValueError: The truth value of an array with more than one element is >> ambiguous. Use a.any() or a.all() >> ----------------- >> So it can't handle the fact that it's columns of numbers and not single >> numbers, so my question is, can I solve this without doing a loop around >> it... use numpy, or some other function instead? >> I've been searching around and haven't found any good ways forward so I >> thought one of you might know. Thanks >> ~Elaina >> >> -- >> PhD Candidate >> Department of Physics and Astronomy >> Faculty of Science >> Macquarie University >> North Ryde, NSW 2109, Australia >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > ------------------ Thanks for the replies so far. I don't think that Rohan's idea solves the numbers versus columns issue. If I run it I get ------------------- Traceback (most recent call last): File "double_plot.py", line 112, in Vhel_fdiff3=max(a,b,c) ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() --------------------- which is just the same error, I looked at the forums and the link suggested and I guess maybe my problem is trickier than I first thought! ~Elaina -- PhD Candidate Department of Physics and Astronomy Faculty of Science Macquarie University North Ryde, NSW 2109, Australia -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Fri Feb 17 04:27:19 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 17 Feb 2012 03:27:19 +0000 Subject: [Tutor] finding a maximum between the absolute difference of several columns In-Reply-To: References: Message-ID: On 17/02/2012 02:53, Elaina Ann Hyde wrote: > On Fri, Feb 17, 2012 at 1:41 PM, Rohan Sachdeva wrote: > >> The way I would do this is to put all of the differences in a list then >> take the maximum of the list. So.. >> >> a = Vmatch3_1 - Vmatch3_2 >> b = Vmatch3_1 - Vmatch3_3 >> c = Vmatch3_3 - Vmatch3_2 >> >> Vhel_fdiff3=max([a,b,c]) >> >> That should work. a,b,c are pretty bad variable names... >> >> Rohan >> >> On Thu, Feb 16, 2012 at 5:04 PM, Elaina Ann Hydewrote: >> >>> Hello all, >>> I am still scripting away and have reached my next quandry, this one >>> is much simpler than the last, basically I read in a file with several >>> columns. >>> Vmatch3_1=dat[col1] >>> Vmatch3_2=dat[col2] >>> Vmatch3_3=dat[col3] >>> Vdav=5.0 >>> Vhel_fdiff3=max(abs(Vmatch3_1 - Vmatch3_2),abs(Vmatch3_1 - >>> Vmatch3_3),abs(Vmatch3_3 - Vmatch3_2)) >>> ---------------- >>> What I would like this to return is the maximum difference in each case, >>> so I end up with one column which contains only the largest differences. >>> now I use this to write the condition: >>> >>> with_v1_3=(Vhel_fdiff3>= Vdav) >>> >>> I know the condition works and plots if >>> >>> Vhel_fdiff3=(Vmatch3_1 - Vmatch3_2) >>> >>> for example, and I know this syntax would work if it was numbers instead >>> of columns. >>>>> max(abs(1-2),abs(3-7),abs(2-4)) >>>>> 4 >>> >>> The error is: >>> ----------------------- >>> Traceback (most recent call last): >>> File "double_plot.py", line 109, in >>> Vhel_fdiff3=max(abs(Vmatch3_1 - Vmatch3_2),abs(Vmatch3_1 - >>> Vmatch3_3),abs(Vmatch3_3 - Vmatch3_2)) >>> ValueError: The truth value of an array with more than one element is >>> ambiguous. Use a.any() or a.all() >>> ----------------- >>> So it can't handle the fact that it's columns of numbers and not single >>> numbers, so my question is, can I solve this without doing a loop around >>> it... use numpy, or some other function instead? >>> I've been searching around and haven't found any good ways forward so I >>> thought one of you might know. Thanks >>> ~Elaina >>> >>> -- >>> PhD Candidate >>> Department of Physics and Astronomy >>> Faculty of Science >>> Macquarie University >>> North Ryde, NSW 2109, Australia >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> > > ------------------ > Thanks for the replies so far. I don't think that Rohan's idea solves the > numbers versus columns issue. If I run it I get > ------------------- > Traceback (most recent call last): > File "double_plot.py", line 112, in > Vhel_fdiff3=max(a,b,c) > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() > --------------------- > which is just the same error, I looked at the forums and the link suggested > and I guess maybe my problem is trickier than I first thought! > ~Elaina > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor I've found this http://comments.gmane.org/gmane.comp.python.tutor/72882. HTH. -- Cheers. Mark Lawrence. From lmergner at gmail.com Fri Feb 17 04:27:35 2012 From: lmergner at gmail.com (Luke Thomas Mergner) Date: Thu, 16 Feb 2012 22:27:35 -0500 Subject: [Tutor] Debugging While Loops for Control Message-ID: <296068FC-F83C-459A-A7E1-F11B278E166F@gmail.com> > > ---------------------------------------------------------------------- > > Message: 1 > Date: Wed, 15 Feb 2012 23:57:08 -0500 > From: Luke Thomas Mergner > To: tutor at python.org > Subject: [Tutor] Debugging While Loops for Control > Message-ID: > Content-Type: text/plain; charset=us-ascii > > Hi, > > I've been translating and extending the Blackjack project from codeacademy.com into Python. My efforts so far are here: https://gist.github.com/1842131 > > My problem is that I am using two functions that return True or False to determine whether the player receives another card. Because of the way it evaluates the while condition, it either prints too little information or previously called the hitMe() function too many times. I am assuming that I am misusing the while loop in this case. If so, is there an elegant alternative still running the functions at least once. > > e.g. > while ask_for_raw_input() AND is_the_score_over_21(): > hitMe(hand) > > > Any advice or observations are appreciated, but please don't solve the whole puzzle for me at once! And no, not all the functionality of a real game is implemented. The code is pretty raw. I'm just a hobbyist trying to learn a few things in my spare time. > > Thanks in advance. > > Luke > > ------------------------------ > > Message: 2 > Date: Thu, 16 Feb 2012 09:05:39 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Debugging While Loops for Control > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 16/02/12 04:57, Luke Thomas Mergner wrote: > >> My problem is that I am using two functions that return True or False >> to determine whether the player receives another card. > >> Because of the way it evaluates the while condition, it either >> prints too little information or previously called the hitMe() >> function too many times. > >> I am assuming that I am misusing the while loop in this case. > >> while ask_for_raw_input() AND is_the_score_over_21(): >> hitMe(hand) > > I haven't looked at the code for the functions but going > by their names I'd suggest you need to reverse their order to > > while is_the_score_over_21() and ask_for_raw_input(): > hitMe(hand) > > The reason is that the first function will always get called > but you (I think) only want to ask for, and give out, another > card if the score is over 21 (or should that maybe be > *under* 21?). > > Personally I would never combine a test function with > an input one. Its kind of the other side of the rule that > says don't don;t put print statements inside logic functions. > In both cases its about separating himan interaction/display from > program logic. So I'd make the ask_for_raw_input jusat return a value(or > set of values) and create a new funtion to test > the result and use that one in the while loop. > > HTH, > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ Alan (and list), Thanks for the advice. It at least points me to an answer: I'm trying to be too clever for my experience level. I am going to go back and incorporate your suggestions. In the meantime, and continuing my problem of over-cleverness, I was trying to rethink the program in classes. With the caveat that I'm only a few hours into this rethinking, I've added the code below. My question is: when I want to build in a "return self" into the Hand class, which is made up of the card class; how do I force a conversion from card object into integer object which is all the card class is really holding? Should I make the class Card inherit from Integers? or is there a __repr__ def I don't understand yet? Bonus question: when I create a the "def score(self)" in class Hand, should that be an generator? And if so where do I go as a newb to understand generators? I'm really not understanding them yet. The "x for x in y:" syntax makes it harder to follow for learners, even if I appreciate brevity. Thanks in advance, Luke class Card(object): def __init__(self): self.score = self.deal() def deal(self): """deal a card from 1 to 52 and return it's points""" return self.getValue(int(math.floor(random.uniform(1, 52)))) def getValue(self, card): """Converts the values 1 - 52 into a 1 - 13 and returns the correct blackjack score based on remainder.""" if (card % 13 == 0 or card % 13 == 11 or card % 13 == 12): #Face Cards are 10 points return 10 elif (card % 13 == 1): return 11 else: #Regular cards, return their value return card % 13 def showCard(self): return repr(self.score) class Hand: def __init__(self): self.cards = [] #Add cards this way to avoid duplicates. for i in range(2): self.cards.append(Card()) def hit(self): self.cards.append(Card()) def showHand(self): return self def score(self): #how do you sum(objects) ??? From elainahyde at gmail.com Fri Feb 17 07:06:25 2012 From: elainahyde at gmail.com (Elaina Ann Hyde) Date: Fri, 17 Feb 2012 17:06:25 +1100 Subject: [Tutor] finding a maximum between the absolute difference of several columns In-Reply-To: References: Message-ID: On Fri, Feb 17, 2012 at 2:27 PM, Mark Lawrence wrote: > On 17/02/2012 02:53, Elaina Ann Hyde wrote: > >> On Fri, Feb 17, 2012 at 1:41 PM, Rohan Sachdeva wrote: >> >> The way I would do this is to put all of the differences in a list then >>> take the maximum of the list. So.. >>> >>> a = Vmatch3_1 - Vmatch3_2 >>> b = Vmatch3_1 - Vmatch3_3 >>> c = Vmatch3_3 - Vmatch3_2 >>> >>> Vhel_fdiff3=max([a,b,c]) >>> >>> That should work. a,b,c are pretty bad variable names... >>> >>> Rohan >>> >>> On Thu, Feb 16, 2012 at 5:04 PM, Elaina Ann Hyde** >>> wrote: >>> >>> Hello all, >>>> I am still scripting away and have reached my next quandry, this one >>>> is much simpler than the last, basically I read in a file with several >>>> columns. >>>> Vmatch3_1=dat[col1] >>>> Vmatch3_2=dat[col2] >>>> Vmatch3_3=dat[col3] >>>> Vdav=5.0 >>>> Vhel_fdiff3=max(abs(Vmatch3_1 - Vmatch3_2),abs(Vmatch3_1 - >>>> Vmatch3_3),abs(Vmatch3_3 - Vmatch3_2)) >>>> ---------------- >>>> What I would like this to return is the maximum difference in each case, >>>> so I end up with one column which contains only the largest differences. >>>> now I use this to write the condition: >>>> >>>> with_v1_3=(Vhel_fdiff3>= Vdav) >>>> >>>> I know the condition works and plots if >>>> >>>> Vhel_fdiff3=(Vmatch3_1 - Vmatch3_2) >>>> >>>> for example, and I know this syntax would work if it was numbers instead >>>> of columns. >>>> >>>>> max(abs(1-2),abs(3-7),abs(2-4)**) >>>>>> 4 >>>>>> >>>>> >>>> The error is: >>>> ----------------------- >>>> Traceback (most recent call last): >>>> File "double_plot.py", line 109, in >>>> Vhel_fdiff3=max(abs(Vmatch3_1 - Vmatch3_2),abs(Vmatch3_1 - >>>> Vmatch3_3),abs(Vmatch3_3 - Vmatch3_2)) >>>> ValueError: The truth value of an array with more than one element is >>>> ambiguous. Use a.any() or a.all() >>>> ----------------- >>>> So it can't handle the fact that it's columns of numbers and not single >>>> numbers, so my question is, can I solve this without doing a loop around >>>> it... use numpy, or some other function instead? >>>> I've been searching around and haven't found any good ways forward so I >>>> thought one of you might know. Thanks >>>> ~Elaina >>>> >>>> -- >>>> PhD Candidate >>>> Department of Physics and Astronomy >>>> Faculty of Science >>>> Macquarie University >>>> North Ryde, NSW 2109, Australia >>>> >>>> ______________________________**_________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/**mailman/listinfo/tutor >>>> >>>> >>>> >>> >> ------------------ >> Thanks for the replies so far. I don't think that Rohan's idea solves the >> numbers versus columns issue. If I run it I get >> ------------------- >> Traceback (most recent call last): >> File "double_plot.py", line 112, in >> Vhel_fdiff3=max(a,b,c) >> ValueError: The truth value of an array with more than one element is >> ambiguous. Use a.any() or a.all() >> --------------------- >> which is just the same error, I looked at the forums and the link >> suggested >> and I guess maybe my problem is trickier than I first thought! >> ~Elaina >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > I've found this http://comments.gmane.org/**gmane.comp.python.tutor/72882 > . > > HTH. > > -- > Cheers. > > Mark Lawrence. > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > Interesting, thanks for all the ideas everyone.... I did finally get it to work in a loop form. Anyone wanting to save themselves lots of confusion, firstly use .append, and secondly don't forget to convert created lists back to arrays for numpy, here is the working code to look through columns, match them, return and make an array to operate on with numpy: ------------------------------------- Vhel_fdiff3=[] for i in xrange(len(Vmatch3_1)): Vhel_fdiff3.append(max([abs(Vmatch3_1[i] - Vmatch3_2[i]),abs(Vmatch3_1[i] - Vmatch3_3[i]),abs(Vmatch3_3[i] - Vmatch3_2[i])])) #print Vhel_fdiff3 #appending writes a list, but numpy which makes the with_ work needs an array Vhel_fdiff3=array(Vhel_fdiff3) ------------------------------------- ~Elaina -- PhD Candidate Department of Physics and Astronomy Faculty of Science Macquarie University North Ryde, NSW 2109, Australia -------------- next part -------------- An HTML attachment was scrubbed... URL: From walksloud at gmail.com Fri Feb 17 07:38:04 2012 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Thu, 16 Feb 2012 22:38:04 -0800 Subject: [Tutor] finding a maximum between the absolute difference of several columns In-Reply-To: References: Message-ID: Hi Elaina, > Vhel_fdiff3=[] > for i in xrange(len(Vmatch3_1)): > Vhel_fdiff3.append(max([abs(Vmatch3_1[i] - Vmatch3_2[i]),abs(Vmatch3_1[i] - Vmatch3_3[i]),abs(Vmatch3_3[i] - Vmatch3_2[i])])) > > #print Vhel_fdiff3 > #appending writes a list, but numpy which makes the with_ work needs an array > Vhel_fdiff3=array(Vhel_fdiff3) You can skip making the list and directly make a numpy array. """ import numpy as np ... Vhel_fdiff3 = np.zeros_like(Vmatch3_1) for i in xrange(len(Vmatch3_1): Vhel_fdiff3[i] = max(abs(Vmatch3_1[i] - Vmatch3_2[i]),abs(Vmatch3_1[i] - Vmatch3_3[i]),abs(Vmatch3_3[i] - Vmatch3_2[i])) """ But, more importantly, you can do it all in numpy - have a read about the "max" function http://scipy.org/Numpy_Example_List#head-7918c09eea00e59ec399064e7d5e1e672d242f60 Given an 2-dimensional array, you can find the max for each row or each column by specifying which axis you want to compare against. Almost surely, the built in numpy function will be faster than your loop - even if you precompile it by importing your functions in another file. You can do something like """ import numpy as np Vhel_fdiff3 = np.array([abs(Vmatch3_1 - Vmatch3_2), abs(Vmatch3_1 - Vmatch3_3), abs(Vmatch3_3 - Vmatch3_2)]) #create an array of the absolute values of the differences of each pair of data # Vhel_fdiff3 is a 2D array # the first index runs over the three pairs of differences # the second index runs over the elements of each pair # to get the maximum difference, you want to compare over the first axis (0) your_answer = Vhel_fdiff3.max(axis=0) """ but you may not want the abs value of the differences, but to actually keep the differences, depending on which one has the maximum abs difference - that would require a little more coding. Andre From alan.gauld at btinternet.com Fri Feb 17 08:50:10 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Feb 2012 07:50:10 +0000 Subject: [Tutor] How to convert seconds to hh:mm:ss format In-Reply-To: References: Message-ID: On 17/02/12 01:29, Daryl V wrote: > def Int2Digit(integer): > if integer < 9: > strInteger = "0"+str(integer) > else: > strInteger = str(integer) > return strInteger Or using format strings: def int2Digit(integer): return "%02d" % integer Although this doesn't behave quite right for negative numbers. But I suspect the function above's handling of negatives is not strictly as intended either... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From pasokan at talentsprint.com Fri Feb 17 09:04:17 2012 From: pasokan at talentsprint.com (Asokan Pichai) Date: Fri, 17 Feb 2012 13:34:17 +0530 Subject: [Tutor] How to convert seconds to hh:mm:ss format In-Reply-To: <1329428774.82131.YahooMailNeo@web114617.mail.gq1.yahoo.com> References: <1329428774.82131.YahooMailNeo@web114617.mail.gq1.yahoo.com> Message-ID: On Fri, Feb 17, 2012 at 3:16 AM, alain Delon wrote: > userName = raw_input("Enter your name ") > ? ? ?print "hi " + userName + ". \n " > ? ? ?seconds = input("Enter the number of seconds since midnight:") > ? ? ?hours = seconds/3600 ******************************** > ? ? ?hoursRemain = hours%60 ******************************** Here is your error > ? ? ?minutes = hoursReamain/60 > ? ? ?secondsRemain = minutes%60 > ? ? ?print "hours: " + "minutes: " + "seconds" > > > I'm going to be crazy. Please give me a hand. Thank you very much. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Fri Feb 17 09:24:15 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Feb 2012 08:24:15 +0000 Subject: [Tutor] Debugging While Loops for Control In-Reply-To: <296068FC-F83C-459A-A7E1-F11B278E166F@gmail.com> References: <296068FC-F83C-459A-A7E1-F11B278E166F@gmail.com> Message-ID: On 17/02/12 03:27, Luke Thomas Mergner wrote: > In the meantime, and continuing my problem of over-cleverness, At least you know what your problem is :-) > Bonus question: when I create a the "def score(self)" in class Hand, > should that be an generator? No. > And if so where do I go as a newb to understand generators? The documentation. Or Google python generator tutorial howto > I'm really not understanding them yet. You don't need to for what you are doing. > The "x for x in y:" syntax makes it harder to follow for learners, Read about list comprehensions first. It helps if you studied sets in math at school. The format is somewhat like the math notation for defining a set. But FWIW it took me a long time to get used to that syntax too. Some thoughts.... > class Card(object): > def __init__(self): > self.score = self.deal() > > def deal(self): > """deal a card from 1 to 52 and return it's points""" > return self.getValue(int(math.floor(random.uniform(1, 52)))) I think you only need random.randint(1,52) here. It simplifies it quite a lot! But you still have the problem that you might wind up with two identical cards! It might be better to create a deck(list) of 52 cards, shuffle() them and then pop the value off of that deck. > def getValue(self, card): > """Converts the values 1 - 52 into a 1 - 13 and returns the correct blackjack score based on remainder.""" > if (card % 13 == 0 or card % 13 == 11 or card % 13 == 12): > #Face Cards are 10 points > return 10 > elif (card % 13 == 1): > return 11 > else: > #Regular cards, return their value > return card % 13 Just calculate the value once rather than doing a mod division each time. Much more efficient and easier to read. > def showCard(self): > return repr(self.score) Why are you using repr? Why not just return the integer value? > class Hand: > def __init__(self): > self.cards = [] > #Add cards this way to avoid duplicates. > for i in range(2): > self.cards.append(Card()) What makes you think it will avoid duplicates? The card values are generated at random. > def hit(self): > self.cards.append(Card()) > def showHand(self): > return self This seems fairly pointless. If i already have a reference to an object why would I call a method that returns what I already have? Maybe returning self.cards would make sense. But really the Hand class should do whatever is needed to cards so even that doesn't make sense. The only thing this could usefully do is pretty print the cards in a formatted string. > def score(self): > #how do you sum(objects) ??? You could define an __add__() method on your cards so that Card()+Card() returns an integer. (Or you could use a generator here if you really, really wanted to. But the __add__ method is cleaner IMHO) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From leamhall at gmail.com Fri Feb 17 10:46:29 2012 From: leamhall at gmail.com (Leam Hall) Date: Fri, 17 Feb 2012 04:46:29 -0500 Subject: [Tutor] dict vs several variables? Message-ID: <4F3E21F5.3010705@gmail.com> I'm building a program that uses one of my own modules for a bunch of formula defs and another module for the tkinter GUI stuff. There are half a dozen input variables and about the same in calculated variables. Is it better/cleaner to just build a global dict and have everything go into it or pass multiple arguments to each function and have it return the calculated value? Thanks! Leam From bbbgggwww at gmail.com Fri Feb 17 12:38:21 2012 From: bbbgggwww at gmail.com (brandon w) Date: Fri, 17 Feb 2012 06:38:21 -0500 Subject: [Tutor] How to hide cursor in Terminal? Message-ID: I made a timer that counts down from five minutes. This code runs fine but I a seeing a cursor blinking on the first number as the code is running. How do I avoid this? I am using gnome-terminal and Python 2.6.6. #!/usr/bin/python import time import sys import os def countd(): seconds = 59 minutes = 4 five_minutes = 0 os.system('clear') while five_minutes != 300: sys.stdout.write("%d:%02.f\r" % (minutes, seconds)) sys.stdout.flush() seconds -= 1 if seconds == -1: minutes -= 1 seconds = 59 five_minutes += 1 time.sleep(1) countd() Brandon -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Feb 17 13:03:36 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 17 Feb 2012 13:03:36 +0100 Subject: [Tutor] finding a maximum between the absolute difference of several columns References: Message-ID: Andre' Walker-Loud wrote: > import numpy as np > Vhel_fdiff3 = np.array([abs(Vmatch3_1 - Vmatch3_2), abs(Vmatch3_1 - > Vmatch3_3), abs(Vmatch3_3 - Vmatch3_2)]) > your_answer = Vhel_fdiff3.max(axis=0) or import numpy as np a = np.array([Vmatch3_1-Vmatch3_2, Vmatch3_1-Vmatch3_3, Vmatch3_3- Vmatch3_2]) print np.max(np.abs(a), axis=0) From __peter__ at web.de Fri Feb 17 13:11:46 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 17 Feb 2012 13:11:46 +0100 Subject: [Tutor] dict vs several variables? References: <4F3E21F5.3010705@gmail.com> Message-ID: Leam Hall wrote: > I'm building a program that uses one of my own modules for a bunch of > formula defs and another module for the tkinter GUI stuff. There are > half a dozen input variables and about the same in calculated variables. > Is it better/cleaner to just build a global dict and have everything go > into it or pass multiple arguments to each function and have it return > the calculated value? The latter. It makes the dependencies explicit to a reader of the function, it simplifies unit tests, allows it to reuse functions in a different context, and it is more likely to work in a multi-threaded environment. From hugo.yoshi at gmail.com Fri Feb 17 13:43:28 2012 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 17 Feb 2012 13:43:28 +0100 Subject: [Tutor] How to hide cursor in Terminal? In-Reply-To: References: Message-ID: On Fri, Feb 17, 2012 at 12:38 PM, brandon w wrote: > I made a timer that counts down from five minutes. This code runs fine but I > a seeing a cursor blinking on the first number as the code is running. How > do I avoid this? > > I am using gnome-terminal and Python 2.6.6. > > > #!/usr/bin/python > > import time > import sys > import os > > def countd(): > > ??? seconds = 59 > ??? minutes = 4 > ??? five_minutes = 0 > > ??? os.system('clear') > > ??? while five_minutes != 300: > ??????? sys.stdout.write("%d:%02.f\r" % (minutes, seconds)) > ??????? sys.stdout.flush() > ??????? seconds -= 1 > ??????? if seconds == -1: > ??????????? minutes -= 1 > ??????????? seconds = 59 > > ??????? five_minutes += 1 > ??????? time.sleep(1) > > countd() > > > > Brandon > I believe that the curses[1] library can do this, though that may be somewhat complex (curses is essentially a GUI toolkit for the terminal). You should probably read up on the tutorial mentioned there. HTH, Hugo [1] http://docs.python.org/library/curses.html From leamhall at gmail.com Fri Feb 17 14:04:53 2012 From: leamhall at gmail.com (leam hall) Date: Fri, 17 Feb 2012 08:04:53 -0500 Subject: [Tutor] dict vs several variables? In-Reply-To: References: <4F3E21F5.3010705@gmail.com> Message-ID: Thanks Peter! My concern with variables is that they have to be passed in specific order to the function, and they may have to have their type set multiple times so that you can perform the right functions on them. In a dict you could set it on insert and not have to worry about it. Thanks! Leam On 2/17/12, Peter Otten <__peter__ at web.de> wrote: > Leam Hall wrote: > >> I'm building a program that uses one of my own modules for a bunch of >> formula defs and another module for the tkinter GUI stuff. There are >> half a dozen input variables and about the same in calculated variables. >> Is it better/cleaner to just build a global dict and have everything go >> into it or pass multiple arguments to each function and have it return >> the calculated value? > > The latter. It makes the dependencies explicit to a reader of the function, > it simplifies unit tests, allows it to reuse functions in a different > context, and it is more likely to work in a multi-threaded environment. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Mind on a Mission From sander.sweers at gmail.com Fri Feb 17 14:33:37 2012 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 17 Feb 2012 14:33:37 +0100 Subject: [Tutor] dict vs several variables? In-Reply-To: References: <4F3E21F5.3010705@gmail.com> Message-ID: On 17 February 2012 14:04, leam hall wrote: > My concern with variables is that they have to be passed in specific > order to the function, and they may have to have their type set > multiple times so that you can perform the right functions on them. In > a dict you could set it on insert and not have to worry about it. There is **kwargs which is behaves like a dict. This is very powerful but comes with the drawback that you have to make sure you get all the variables you need for your function to work properly. I found [1] that is a decent explanation of how these work. Other might have better explanations. Greets Sander [1] http://basicpython.com/understanding-arguments-args-and-kwargs-in-python/ From d at davea.name Fri Feb 17 14:45:02 2012 From: d at davea.name (Dave Angel) Date: Fri, 17 Feb 2012 08:45:02 -0500 Subject: [Tutor] dict vs several variables? In-Reply-To: References: <4F3E21F5.3010705@gmail.com> Message-ID: <4F3E59DE.3090802@davea.name> > On 2/17/12, Peter Otten<__peter__ at web.de> wrote: >> Leam Hall wrote: >> >>> I'm building a program that uses one of my own modules for a bunch of >>> formula defs and another module for the tkinter GUI stuff. There are >>> half a dozen input variables and about the same in calculated variables. >>> Is it better/cleaner to just build a global dict and have everything go >>> into it or pass multiple arguments to each function and have it return >>> the calculated value? >> The latter. It makes the dependencies explicit to a reader of the function, >> it simplifies unit tests, allows it to reuse functions in a different >> context, and it is more likely to work in a multi-threaded environment. >> On 02/17/2012 08:04 AM, leam hall wrote: > Thanks Peter! > > My concern with variables is that they have to be passed in specific > order to the function, and they may have to have their type set > multiple times so that you can perform the right functions on them. In > a dict you could set it on insert and not have to worry about it. > > Thanks! > > Leam Please don't top-post. Put your remarks after the parts you're quoting. You're asking for best-practice, presumably as part of your transition from small snippets to larger scale. First habit that beginners have to break is the tendency to keep things in globals. Can it make things "easier"? Yes, until you try to return to that code and make changes, and discover that one change affects an unknown number of other parts. Yes, until you decide you want to use one of those functions in a multithreaded environment. Yes, until somebody else has to use your code. Variable can't get their type set. They are bound at any moment to an object, and that object has a type. Period. Passed in a specific order? Of course. Very few functions, even binary ones, are commutative on their arguments. Do you expect divide(7, 42) to give the same answer as divide(42, 7) ? You can also use keyword arguments to help disambiguate the order of arguments. That's especially useful when some arguments are optional. Real question is whether some (seldom all) of those variables are in fact part of a larger concept. If so, it makes sense to define a class for them, and pass around objects of that class. Notice it's not global, it's still passed as an argument. This can reduce your parameters from 20 to maybe 6. But make sure that the things the class represents are really related. Dictionaries are a built-in collection class, as are lists, sets, and tuples. But you can write your own. An example of needing a class might be to hold the coordinates of a point in space. You make a Location class, instantiate it with three arguments, and use that instance for functions like move_ship(ship, newlocation) There are times to have arbitrary lists or dictionaries to pass into a function, and Python has added syntax (*args and **kwargs) to make that convenient. But the times that is needed are very specialized. -- DaveA From __peter__ at web.de Fri Feb 17 14:52:31 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 17 Feb 2012 14:52:31 +0100 Subject: [Tutor] dict vs several variables? References: <4F3E21F5.3010705@gmail.com> Message-ID: leam hall wrote: > My concern with variables is that they have to be passed in specific > order to the function, Yes, unless you use keywords. You can invoke def div(x, y): return x // y a = div(3, 2) b = div(y=3, x=2) assert a == b > and they may have to have their type set I have no idea what you mean by "have their type set". Can you give an example? > multiple times so that you can perform the right functions on them. In > a dict you could set it on insert and not have to worry about it. Instead you'll have to worry about the contents of the dict which I suspect will be even harder to verify in a non-trivial script. From leamhall at gmail.com Fri Feb 17 15:06:11 2012 From: leamhall at gmail.com (leam hall) Date: Fri, 17 Feb 2012 09:06:11 -0500 Subject: [Tutor] dict vs several variables? In-Reply-To: <4F3E59DE.3090802@davea.name> References: <4F3E21F5.3010705@gmail.com> <4F3E59DE.3090802@davea.name> Message-ID: On 2/17/12, Dave Angel wrote: > Real question is whether some (seldom all) of those variables are in > fact part of a larger concept. If so, it makes sense to define a class > for them, and pass around objects of that class. Notice it's not > global, it's still passed as an argument. This can reduce your > parameters from 20 to maybe 6. But make sure that the things the class > represents are really related. > > Dictionaries are a built-in collection class, as are lists, sets, and > tuples. But you can write your own. An example of needing a class > might be to hold the coordinates of a point in space. You make a > Location class, instantiate it with three arguments, and use that > instance for functions like > move_ship(ship, newlocation) > > DaveA Understood. In this case, the first half dozen variables are input and the rest are derived from the first ones. A class might make sense and though I understand them a little, not enough to make a good judgement on it. The task is to take parameters for a scuba dive; depth, gas mix, time, air consumption rate, and compute the O2 load, gas required, etc. Leam -- Mind on a Mission From leamhall at gmail.com Fri Feb 17 15:10:05 2012 From: leamhall at gmail.com (leam hall) Date: Fri, 17 Feb 2012 09:10:05 -0500 Subject: [Tutor] dict vs several variables? In-Reply-To: References: <4F3E21F5.3010705@gmail.com> Message-ID: On 2/17/12, Peter Otten <__peter__ at web.de> wrote: > leam hall wrote: >> and they may have to have their type set > > I have no idea what you mean by "have their type set". Can you give an > example? Peter, The variables input seem to be assumed to be strings and I need them to be an integer or a float most of the time. Doing simple math on them. Thanks! Leam -- Mind on a Mission From d at davea.name Fri Feb 17 15:26:43 2012 From: d at davea.name (Dave Angel) Date: Fri, 17 Feb 2012 09:26:43 -0500 Subject: [Tutor] dict vs several variables? In-Reply-To: References: <4F3E21F5.3010705@gmail.com> <4F3E59DE.3090802@davea.name> Message-ID: <4F3E63A3.6070701@davea.name> On 02/17/2012 09:06 AM, leam hall wrote: > On 2/17/12, Dave Angel wrote: > >> Real question is whether some (seldom all) of those variables are in >> fact part of a larger concept. If so, it makes sense to define a class >> for them, and pass around objects of that class. Notice it's not >> global, it's still passed as an argument. This can reduce your >> parameters from 20 to maybe 6. But make sure that the things the class >> represents are really related. >> >> Dictionaries are a built-in collection class, as are lists, sets, and >> tuples. But you can write your own. An example of needing a class >> might be to hold the coordinates of a point in space. You make a >> Location class, instantiate it with three arguments, and use that >> instance for functions like >> move_ship(ship, newlocation) >> >> DaveA > Understood. In this case, the first half dozen variables are input and > the rest are derived from the first ones. A class might make sense and > though I understand them a little, not enough to make a good judgement > on it. > > The task is to take parameters for a scuba dive; depth, gas mix, time, > air consumption rate, and compute the O2 load, gas required, etc. > > Leam > There are two ways to think of a class. One is to hold various related data, and the other is to do operations on that data. If you just consider the first, then you could use a class like a dictionary whose keys are fixed (known at "compile time"). class MyDiver(object): def __init__(self, depth, gasmix, time, rate): self.depth = int(depth) self.gasmix = int(gasmix) self.time = datetime.datetime(time) self.rate = float(rate) Now if you want to use one such: sam = MyDiver(200, 20, "04/14/2011", "3.7") bill = MyDiver(.....) And if you want to fetch various items, you'd do something like: if sam.depth < bill.depth instead of using sam["depth"] and bill["depth"] Next thing is to decide if the functions you're describing are really just methods on the class class MyDiver(object): def __init__( ... as before) def get_load(self): return self.gasmix/self.rate (or whatever) and used as print sam.get_load() that last could be simplified with a decorator @property def load(self): return self.gasmix/self.rate now it's used as though it's a regular data attribute print sam.load -- DaveA From __peter__ at web.de Fri Feb 17 15:43:33 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 17 Feb 2012 15:43:33 +0100 Subject: [Tutor] dict vs several variables? References: <4F3E21F5.3010705@gmail.com> Message-ID: leam hall wrote: > On 2/17/12, Peter Otten <__peter__ at web.de> wrote: >> leam hall wrote: >>> and they may have to have their type set >> >> I have no idea what you mean by "have their type set". Can you give an >> example? > > Peter, > > The variables input seem to be assumed to be strings and I need them > to be an integer or a float most of the time. Doing simple math on > them. If you are processing user input you should convert that once no matter what the structure of your program is. Example: #WRONG, integer conversion in many places in the code def sum(a, b): return int(a) + int(b) def difference(a, b): return int(a) - int(b) a = raw_input("a ") b = raw_input("b ") print "a + b =", sum(a, b) print "a - b =", difference(a, b) #BETTER, integer conversion in a single place def sum(a, b): return a + b def difference(a, b): return a - b def get_int(prompt): return int(raw_input(prompt)) a = get_int("a ") b = get_int("b ") print "a + b =", sum(a, b) print "a - b =", difference(a, b) The second form has the added benefit that you can easily make get_int() more forgiving (allow the user to try again when his input is not a valid integer) or make other changes to the code (e. g. allow floating point input). From walksloud at gmail.com Fri Feb 17 18:29:07 2012 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Fri, 17 Feb 2012 09:29:07 -0800 Subject: [Tutor] finding a maximum between the absolute difference of several columns In-Reply-To: References: Message-ID: > import numpy as np >> Vhel_fdiff3 = np.array([abs(Vmatch3_1 - Vmatch3_2), abs(Vmatch3_1 - >> Vmatch3_3), abs(Vmatch3_3 - Vmatch3_2)]) >> your_answer = Vhel_fdiff3.max(axis=0) > > or > > import numpy as np > a = np.array([Vmatch3_1-Vmatch3_2, Vmatch3_1-Vmatch3_3, Vmatch3_3- > Vmatch3_2]) > print np.max(np.abs(a), axis=0) yes, this one is better than mine. It is more flexible, leaving more options for what you may want to do with it afterwards, andre From robert.sjoblom at gmail.com Fri Feb 17 18:51:49 2012 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Fri, 17 Feb 2012 18:51:49 +0100 Subject: [Tutor] Debugging While Loops for Control In-Reply-To: References: <296068FC-F83C-459A-A7E1-F11B278E166F@gmail.com> Message-ID: >> class Card(object): >> ? ? ? ?def __init__(self): >> ? ? ? ? ? ? ? ?self.score = self.deal() >> >> ? ? ? ?def deal(self): >> ? ? ? ? ? ? ? ?"""deal a card from 1 to 52 and return it's points""" >> ? ? ? ? ? ? ? ?return self.getValue(int(math.floor(random.uniform(1, >> 52)))) > > I think you only need random.randint(1,52) here. It simplifies it quite a > lot! But you still have the problem that you might wind up with two > identical cards! It might be better to create a deck(list) of 52 cards, > shuffle() them and then pop the value off of that deck. I'd suggest using random.sample() instead, but it might just be a matter of style: >>> from random import sample >>> deck = range(1,53) >>> sample(deck, 2) [43, 9] >>> sample(deck, 2) [8, 27] It's a function a lot of people doesn't know about, for some reason. Best part is that it leaves deck (or whatever population you're taking the sample from) alone, so you don't have to rebuild it every time you want to reset the deck. Ah, but I suppose you want to keep track of what cards are available, too. Forgot about that part. I guess you can do: sample(deck, 52) #or instead of deck range(1,53) for each new round, and pop items from the returned sample instead of popping the deck list every time. In the end I suppose it's a matter of style. Oh, and the returned list is in selection order (which might be important but maybe not in Black Jack). Maybe I should have just stayed quiet. -- best regards, Robert S. From __peter__ at web.de Fri Feb 17 19:23:53 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 17 Feb 2012 19:23:53 +0100 Subject: [Tutor] Debugging While Loops for Control References: <296068FC-F83C-459A-A7E1-F11B278E166F@gmail.com> Message-ID: Alan Gauld wrote: >>The "x for x in y:" syntax makes it harder to follow for learners, > > Read about list comprehensions first. > It helps if you studied sets in math at school. The format is > somewhat like the math notation for defining a set. But FWIW it took me > a long time to get used to that syntax too. To grok list comprehensions it helps to write the equivalent for loops first. You can mechanically convert items = [] for x in "abcd": if x < "d": if x != "b": items.append(x) to items = [x for x in "abcd" if x < "d" if x != "b"] The for loops and ifs stay in place, the expression passed to append() in the innermost loop moves to the beginning. Another example: items = [] for x in "abcd": if x < "d": for y in x + x.upper(): if y != "A": items.append(y*2) This becomes items = [y*2 for x in "abcd" if x < "d" for y in x + x.upper() if y != "A"] Real-world list comprehensions tend to be less complicated, but to understand them you just have to reverse the conversion: items = [y*2 for x in "abcd" if x < "d" for y in x + x.upper() if y != "A" # append y*2 ] From alan.gauld at btinternet.com Fri Feb 17 19:55:51 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Feb 2012 18:55:51 +0000 Subject: [Tutor] dict vs several variables? In-Reply-To: References: <4F3E21F5.3010705@gmail.com> Message-ID: On 17/02/12 14:10, leam hall wrote: > The variables input seem to be assumed to be strings They are not assumed to be strings, they *are* strings. Users can only type characters at the keyboard (the usual source of input). Your program has to interpret those characters and convert to the right type. It's good practice to do that as soon as possible which is why you often see code like: numVal = int( raw_input("Type a number: ") ) fltVal = float( raw_input("Type a number: ") ) strVal = raw_input("Type your name: ") This also has the advantage that you can catch user input errors early and request re-input. If you just store whatever the user types ("four" say) and then try to convert during the math you get an error far too late to fix. eg. try print pow(int("four"), 2) You can convert them to strings for display later but usually you don't want to, because you will use string formatting to improve their appearance (especially with floats). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Feb 17 20:00:07 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Feb 2012 19:00:07 +0000 Subject: [Tutor] How to hide cursor in Terminal? In-Reply-To: References: Message-ID: On 17/02/12 11:38, brandon w wrote: > I made a timer that counts down from five minutes. This code runs fine > but I a seeing a cursor blinking on the first number as the code is > running. How do I avoid this? > Try putting the carriage return at the start of the line. You print the line then reset the cursor to the beginning. You want to reset the cursor then print leaving the cursor at the end of the line(I assume?) If you want to get rid of the cursor entirely then I think you might be able to do it via a set tty command or similar - but why would you?! And if you do, don't forget to reset it after you finish! > while five_minutes != 300: > sys.stdout.write("%d:%02.f\r" % (minutes, seconds)) sys.stdout.write("\r%d:%02.f" % (minutes, seconds)) That might do it for you. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bbbgggwww at gmail.com Fri Feb 17 22:28:46 2012 From: bbbgggwww at gmail.com (brandon w) Date: Fri, 17 Feb 2012 16:28:46 -0500 Subject: [Tutor] How to hide cursor in Terminal? In-Reply-To: References: Message-ID: This is what I ended up using: import time import sys import os def countd(): seconds = 59 minutes = 4 five_minutes = 0 os.system('clear') os.system('setterm -cursor off') while five_minutes != 300: sys.stdout.write("\r%d:%02.f\t" % (minutes, seconds)) sys.stdout.flush() seconds -= 1 if seconds == -1: minutes -= 1 seconds = 59 five_minutes += 1 time.sleep(1) countd() os.system('setterm -cursor on') This worked like a charm! Thank you guys for your help! Now I'll have to see if I can get the same thing working on a Windows machine. Brandon On Fri, Feb 17, 2012 at 2:00 PM, Alan Gauld wrote: > On 17/02/12 11:38, brandon w wrote: > >> I made a timer that counts down from five minutes. This code runs fine >> but I a seeing a cursor blinking on the first number as the code is >> running. How do I avoid this? >> >> > Try putting the carriage return at the start of the line. You print the > line then reset the cursor to the beginning. You want to reset the cursor > then print leaving the cursor at the end of the line(I assume?) > If you want to get rid of the cursor entirely then I think you might be > able to do it via a set tty command or similar - but why would you?! > And if you do, don't forget to reset it after you finish! > > > while five_minutes != 300: >> sys.stdout.write("%d:%02.f\r" % (minutes, seconds)) >> > > sys.stdout.write("\r%d:%02.f" % (minutes, seconds)) > > That might do it for you. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From leamhall at gmail.com Sat Feb 18 00:54:18 2012 From: leamhall at gmail.com (Leam Hall) Date: Fri, 17 Feb 2012 18:54:18 -0500 Subject: [Tutor] dict vs several variables? In-Reply-To: <4F3E63A3.6070701@davea.name> References: <4F3E21F5.3010705@gmail.com> <4F3E59DE.3090802@davea.name> <4F3E63A3.6070701@davea.name> Message-ID: <4F3EE8AA.1080804@gmail.com> On 02/17/2012 09:26 AM, Dave Angel wrote: > There are two ways to think of a class. One is to hold various related > data, and the other is to do operations on that data. If you just > consider the first, then you could use a class like a dictionary whose > keys are fixed (known at "compile time"). I think a class is the way to go for a couple reasons. First, of course, is that it pushes me to learn more. It also lets me encapsulate a lot of the work into one thing and keep the methods there. Thanks! Leam From shukla.kapil at gmail.com Sat Feb 18 04:48:17 2012 From: shukla.kapil at gmail.com (Kapil Shukla) Date: Sat, 18 Feb 2012 03:48:17 +0000 Subject: [Tutor] Pyhton editor Message-ID: <191359495-1329536853-cardhu_decombobulator_blackberry.rim.net-55059483-@b13.c5.bise3.blackberry> All Couple of weeks ago I was looking for a nice free IDE for python and got many wonderful suggestion form very helpful people. However I stumbled upon PyScripter and I find it really amazing. I feel once u try it you will hook on to it for ever Thanks Best Regards Kapil From steve at pearwood.info Sat Feb 18 04:59:31 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 18 Feb 2012 14:59:31 +1100 Subject: [Tutor] dict vs several variables? In-Reply-To: <4F3E21F5.3010705@gmail.com> References: <4F3E21F5.3010705@gmail.com> Message-ID: <4F3F2223.50504@pearwood.info> Leam Hall wrote: > I'm building a program that uses one of my own modules for a bunch of > formula defs and another module for the tkinter GUI stuff. There are > half a dozen input variables and about the same in calculated variables. > Is it better/cleaner to just build a global dict and have everything go > into it or pass multiple arguments to each function and have it return > the calculated value? A global dict is like the Dark Side of the Force: easier, quicker, simpler, but it leads to pain and anguish and great suffering. I assume you understand why global variables should be avoided as much as possible? E.g. # Bad! Wrong! Do not do this! x = '' y = '' z = '' def get_user_input(): global x, y x = raw_input("Please enter x: ") y = raw_input("Please enter y: ") def do_calculation(): global z z = "The answer is %s" % (x.upper() + y.lower()) def main() get_user_input() do_calculation() print z If you're not familiar with the reasons to avoid global variables, you should google for "Global variables considered harmful", or start here: http://c2.com/cgi/wiki?GlobalVariablesAreBad Well, using a single global dict is *almost* as bad, and for most of the same reasons: # Do not do this either. values = {'x': '', 'y': '', 'z': ''} def get_user_input(values): values['x'] = raw_input("Please enter x: ") values['y'] = raw_input("Please enter y: ") def do_calculation(values): x = values['x'] y = values['y'] values['z'] = "The answer is %s" % (x.upper() + y.lower()) def main() get_user_input(values) do_calculation(values) print values['z'] This is a mild improvement, at least you can pass in an alternative dict if needed, but it still suffers from failure of encapsulation (all functions that have access to the dict have access to all variables, whether they need them or not) and other problems. Just about the only valid use of this pattern I can think of is for global settings that apply application-wide. Such settings tend to be write-once, which mitigates the disadvantages of global and pseudo-global variables. By the way, in case it isn't obvious, changing from a dict to a instance with named attributes values.x values.y values.z is just a cosmetic change, it doesn't change the basic problems. For a toy problem like the above, it might seem hardly worth the hassle of de-globalising the functions, but for real code this really pays off in fewer bugs and easier maintenance: def get_user_input(): x = raw_input("Please enter x: ") y = raw_input("Please enter y: ") return (x, y) def do_calculation(x, y): return "The answer is %s" % (x.upper() + y.lower()) def main() a, b = get_user_input() result = do_calculation(a, b) print result I assume the problem you are solving is more than just a toy. In that case, passing individual variables to only the functions that need them is a better solution. RELATED variables that MUST stay together can be collected into data structures such as tuples, lists, dicts, or custom classes. But don't be tempted to dump everything into one giant dict -- that's barely better than using globals. -- Steven From bermanrl1 at gmail.com Sat Feb 18 05:23:48 2012 From: bermanrl1 at gmail.com (Robert Berman) Date: Fri, 17 Feb 2012 23:23:48 -0500 Subject: [Tutor] Pyhton editor In-Reply-To: <191359495-1329536853-cardhu_decombobulator_blackberry.rim.net-55059483-@b13.c5.bise3.blackberry> References: <191359495-1329536853-cardhu_decombobulator_blackberry.rim.net-55059483-@b13.c5.bise3.blackberry> Message-ID: On Fri, Feb 17, 2012 at 10:48 PM, Kapil Shukla wrote: > All > > Couple of weeks ago I was looking for a nice free IDE for python and got > many wonderful suggestion form very helpful people. However I stumbled upon > PyScripter and I find it really amazing. > > I feel once u try it you will hook on to it for ever > > Thanks > Best Regards > Kapil > Pity it is only for Windows. -- Robert Berman The Torah says, Love your neighbor as yourself. The Buddha says, There is no self. So, maybe, we're off the hook. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lzantal at gmail.com Sat Feb 18 06:30:47 2012 From: lzantal at gmail.com (Laszlo Antal) Date: Fri, 17 Feb 2012 21:30:47 -0800 Subject: [Tutor] Pyhton editor In-Reply-To: References: <191359495-1329536853-cardhu_decombobulator_blackberry.rim.net-55059483-@b13.c5.bise3.blackberry> Message-ID: <4B260C4D-0822-47E5-B0F6-243028A6C40E@gmail.com> Hi, On Feb 17, 2012, at 20:23, Robert Berman wrote: > > > On Fri, Feb 17, 2012 at 10:48 PM, Kapil Shukla wrote: > All > > Couple of weeks ago I was looking for a nice free IDE for python and got many wonderful suggestion form very helpful people. However I stumbled upon PyScripter and I find it really amazing. > > I feel once u try it you will hook on to it for ever > > Thanks > Best Regards > Kapil > > > Pity it is only for Windows. I can highly recommend Sublime Text 2. Just recently switched to it from Eclipse. lzantal > -- > Robert Berman > > The Torah says, > Love your neighbor as yourself. > The Buddha says, > There is no self. > So, maybe, we're off the hook. > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Feb 18 09:39:55 2012 From: __peter__ at web.de (Peter Otten) Date: Sat, 18 Feb 2012 09:39:55 +0100 Subject: [Tutor] dict vs several variables? References: <4F3E21F5.3010705@gmail.com> <4F3E59DE.3090802@davea.name> <4F3E63A3.6070701@davea.name> <4F3EE8AA.1080804@gmail.com> Message-ID: Leam Hall wrote: > On 02/17/2012 09:26 AM, Dave Angel wrote: >> There are two ways to think of a class. One is to hold various related >> data, and the other is to do operations on that data. If you just >> consider the first, then you could use a class like a dictionary whose >> keys are fixed (known at "compile time"). > > I think a class is the way to go for a couple reasons. First, of course, > is that it pushes me to learn more. It also lets me encapsulate a lot of > the work into one thing and keep the methods there. One word of caution. If you make just one do-it-all class with a single instance and use instance attributes as if they were global variable the improvement over the global dictionary is minimal. You still should strive to make dependencies explicit, e. g. prefer def add(a, b): return a + b over class DoItAll: def add_a_and_b(self): self.c = self.a + self.b From leamhall at gmail.com Sat Feb 18 11:23:28 2012 From: leamhall at gmail.com (Leam Hall) Date: Sat, 18 Feb 2012 05:23:28 -0500 Subject: [Tutor] dict vs several variables? In-Reply-To: References: <4F3E21F5.3010705@gmail.com> <4F3E59DE.3090802@davea.name> <4F3E63A3.6070701@davea.name> <4F3EE8AA.1080804@gmail.com> Message-ID: <4F3F7C20.8000802@gmail.com> On 02/18/2012 03:39 AM, Peter Otten wrote: > Leam Hall wrote: > >> On 02/17/2012 09:26 AM, Dave Angel wrote: >>> There are two ways to think of a class. One is to hold various related >>> data, and the other is to do operations on that data. If you just >>> consider the first, then you could use a class like a dictionary whose >>> keys are fixed (known at "compile time"). >> >> I think a class is the way to go for a couple reasons. First, of course, >> is that it pushes me to learn more. It also lets me encapsulate a lot of >> the work into one thing and keep the methods there. > > One word of caution. If you make just one do-it-all class with a single > instance and use instance attributes as if they were global variable the > improvement over the global dictionary is minimal. You still should strive > to make dependencies explicit, e. g. prefer > > def add(a, b): return a + b > > over > > class DoItAll: > def add_a_and_b(self): > self.c = self.a + self.b Understood. In this case I'm starting the application and there are two separate bits. I'm studying tkinter for the class I'm in so the GUI stuff is one module and the formulas are in another module. The reason I considered a global dict or a class is because all of the data bits are directly related. Dave angel wrote: class MyDiver(object): def __init__(self, depth, gasmix, time, rate): self.depth = int(depth) self.gasmix = int(gasmix) self.time = datetime.datetime(time) self.rate = float(rate) Which is a pretty good start, makes me think he's done scuba before. :) The object in question is a scuba dive. The user types in how deep they want to go, what gas mix they are on, how long they plan on staying, and what they think their air consumption rate will be. The formulas calculate absolute atmospheres which are used in other formulas, O2 concentration (a risk factor), how much of the daily increased O2 exposure the dive will create, and how much gas is needed to make that dive. If the program grew the only thing that might be pulled out is the air consumption rate. That would likely go into a diver object so there was a profile for each diver. However, at the moment the app is just giving you dive profile information so you can plan your bottom time and gas consumption. That's my thinking as of this morning. I need to go back and build unittests; will do so while moving it into a class. Should be fun and good learning! Leam From dknoll66 at hotmail.com Sat Feb 18 19:35:17 2012 From: dknoll66 at hotmail.com (Deborah Knoll) Date: Sat, 18 Feb 2012 12:35:17 -0600 Subject: [Tutor] arrays, while loops Message-ID: Hi I need some help with my program. I need to: Inside a getNumbers() function: Make an array that holds 7 elements - (got that done) make sure the numbers entered are greater than 0 and less than 1001 (can't get this) - is there a way to write a "between" statment or an "or"?? send the array to the aboveAverage () function What I can't get to work is the between 0 and 1001, and also where to make the array entries integer (I get an error saying can't compare string and integer) I also have to answer the three questions I have commented out at the end. I know this should be simple, but the more I read and try things, the more confused I get. Thanks for any suggestions! Here is what I have so far: amount = [0 for index in range (7)] size = len (amount) def getNumbers(): for index in range (size): amount[index] = input ("Enter an amount: ") while amount[index] >0 or < 1001: return (amount[index]) ##getNumbers() ## ##def aboveAverage(): ## total = 0.0 ## ## for value in amount: ## total +=amount[index] ## average = total/len(amount) ## ## ##getNumbers() ##def printData(): ## ##print ("The numbers you entered from lowest to highest are: ") ##print ("The average number is: ") ##print ("You entered this many numbers above average: ") ## -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Sat Feb 18 20:29:57 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 18 Feb 2012 14:29:57 -0500 Subject: [Tutor] arrays, while loops In-Reply-To: References: Message-ID: On Sat, Feb 18, 2012 at 1:35 PM, Deborah Knoll wrote: > Hi > I need some help with my program. I need to: > > Inside a getNumbers() function: > Make an array that holds 7 elements - (got that done) > make sure the numbers entered are greater than 0 and less than 1001 (can't > get this) - is there a way to write a "between" statment or an "or"?? > ?send the array to the aboveAverage () function > > What I can't get to work is the between 0 and 1001, and also where to make > the array entries integer (I get an error saying can't compare string and > integer) > > I also have to answer the three questions I have commented out at the end. I > know this should be simple,? but the more I read and try things, the more > confused I get. > > Thanks for any suggestions! > > > > Here is what I have so far: > > amount = [0 for index in range (7)] > size = len (amount) > def getNumbers(): > ??????? for index in range (size): > ??????????????? amount[index] = input ("Enter an amount: ") > ??????? while amount[index] >0 or < 1001: > ??????????????? return (amount[index]) > > > ##getNumbers() > ## > ##def aboveAverage(): > ##??????? total = 0.0 > ## > ##??????? for value in amount: > ##??????????????? total +=amount[index] > ##??????? average = total/len(amount) > ## > ## > ##getNumbers() > ##def printData(): > ## > ##print ("The numbers you entered from lowest to highest are: ") > ##print ("The average number is: ") > ##print ("You entered this many numbers above average: ") > ## > So, you need to get 7 numbers from the user, make sure they are between 0 and 1001, then report the numbers in sorted order - lowest to highest, report the average, and how many numbers are above the average. Since you are restricting the numbers allowed, you will need to figure out if the number is ok, and if not, tell the user, and ask again for a proper number. You could do something like this: def get_number(n): while 0 < n < 1001: n = input('Enter an number between 0 and 1001") return int(n) That will get you a single good number Now, to get 7 good numbers in your list you could do something like this: def get_numbers(amount): for i, a in enumerate(amount): # this will give you the index and the value in amount[i] amount[i] = get_number(a) return amount # this will return your amount list to the caller Now you just need to write 3 functions: the first to find the average, then one to tell you how many entries are greater than the average, and finally to sort the numbers from lowest to highest. Try working on that and come back with more questions -- Joel Goldstick From breamoreboy at yahoo.co.uk Sat Feb 18 20:32:32 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 18 Feb 2012 19:32:32 +0000 Subject: [Tutor] arrays, while loops In-Reply-To: References: Message-ID: On 18/02/2012 18:35, Deborah Knoll wrote: > > Hi > I need some help with my program. I need to: > > Inside a getNumbers() function: > Make an array that holds 7 elements - (got that done) > make sure the numbers entered are greater than 0 and less than 1001 (can't get this) - is there a way to write a "between" statment or an "or"?? > send the array to the aboveAverage () function > > What I can't get to work is the between 0 and 1001, and also where to make the array entries integer (I get an error saying can't compare string and integer) > > I also have to answer the three questions I have commented out at the end. I know this should be simple, but the more I read and try things, the more confused I get. > > Thanks for any suggestions! > > > > Here is what I have so far: > > amount = [0 for index in range (7)] This is outside getNumbers! Could be written as amount = [0] * 7. Better still amounts, see below. > size = len (amount) You don't need this, because... > def getNumbers(): > for index in range (size): Usually written something like for amount in amounts: amount = ... > amount[index] = input ("Enter an amount: ") Input some strings into your list overwriting the original integers. > while amount[index]>0 or< 1001: Whoops. You'll first need to convert the input numbers with an appropriate function such as int or float, which you can do at the input stage. Python also lets you chain comparisons so this is allowed. while 0 < amount[index] < 1001: > return (amount[index]) No point to this as amount is external to getNumbers. > > > ##getNumbers() > ## > ##def aboveAverage(): > ## total = 0.0 > ## > ## for value in amount: > ## total +=amount[index] You don't need the loop, use the sum built-in function. > ## average = total/len(amount) > ## > ## > ##getNumbers() > ##def printData(): > ## > ##print ("The numbers you entered from lowest to highest are: ") Use built-in functions min and max. > ##print ("The average number is: ") > ##print ("You entered this many numbers above average: ") I'll leave this for you :) > ## > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor HTH. -- Cheers. Mark Lawrence. From d at davea.name Sat Feb 18 23:10:48 2012 From: d at davea.name (Dave Angel) Date: Sat, 18 Feb 2012 17:10:48 -0500 Subject: [Tutor] arrays, while loops In-Reply-To: References: Message-ID: <4F4021E8.2020009@davea.name> On 02/18/2012 01:35 PM, Deborah Knoll wrote: > Hi > I need some help with my program. I need to: > First thing you need to do when asking a question is to establish what version of Python you're running, and on what OS . In this case OS probably doesn't matter, but version does. Mark Lawrence assumed you were running Python 3, while Joel and I are assuming Python 2.x. > Inside a getNumbers() function: > Make an array that holds 7 elements - (got that done) Python has a class array.array. But that's not what you're using. What you're actually using are lists. I almost skipped the query because I'm not that familiar with the array module. > make sure the numbers entered are greater than 0 and less than 1001 (can't get this) - is there a way to write a "between" statment or an "or"?? You can use 'or' or 'and' in an expression, but not the way you did below. Anyway there is what you might call a "between" operation: if 0 < n < 1001: > send the array to the aboveAverage () function > > What I can't get to work is the between 0 and 1001, and also where to make the array entries integer (I get an error saying can't compare string and integer) > > I also have to answer the three questions I have commented out at the end. I know this should be simple, but the more I read and try things, the more confused I get. > > Thanks for any suggestions! > Before you write the code, you need to decide lots more things. But the first one is "what should the program do if the user enters a value that's not within the range? Should it just crash, or should it prompt for a new value? And keep prompting till the user enters an acceptable number. I'll assume the latter. > > > Here is what I have so far: > > amount = [0 for index in range (7)] Start with meaningful names. At the very least, when it's a list of amount values, call it amounts (plural). > size = len (amount) > def getNumbers(): > for index in range (size): > amount[index] = input ("Enter an amount: ") The user may have already entered 7 wrong values. Now what? You want to catch each number as its being input, rather than wait till the end of the loop. This is calling out for another function. For now, pretend you've already written such a function. for index in range(size): amounts[index] = getinput(min, max) Now the function needs to return the list it has built. You weren't really going to use a global there, were you? return amounts knoll > while amount[index]>0 or< 1001: > return (amount[index]) > Now you need to write a function getinput(min, max), that asks the user for input, and returns it if it's between min and max, but asks again if it's not. > > ##getNumbers() > ## > ##def aboveAverage(): You forgot to have the function take a list object. Call it amounts, if you like. Remember to change the references below. > ## total = 0.0 > ## > ## for value in amount: > ## total +=amount[index] > ## average = total/len(amount) > ## now it needs to return average. And in fact, this function should be called average(), since that's what it does. > ## > ##getNumbers() > ##def printData(): > ## > ##print ("The numbers you entered from lowest to highest are: ") Seems that if you sort the amounts list, you could print it pretty easily then. > ##print ("The average number is: ") You already wrote that. > ##print ("You entered this many numbers above average: ") > ## This function should take a parameter called amounts, call average() on it, then loop through comparing each amount to that average: def aboveAverage(amounts): avg = average(amounts) count = 0 for amount in amounts: if xxxx : count += 1 return count > > -- DaveA From alan.gauld at btinternet.com Sat Feb 18 23:35:54 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 18 Feb 2012 22:35:54 +0000 Subject: [Tutor] arrays, while loops In-Reply-To: References: Message-ID: On 18/02/12 18:35, Deborah Knoll wrote: > make sure the numbers entered are greater than 0 and less than 1001 > (can't get this) - is there a way to write a "between" statment or an "or"?? Several replies have shown how to do "between". To use or you would do: if n < 0 or n > 1001: # handle error else: store value > ##def aboveAverage(): > ## total = 0.0 > ## > ## for value in amount: > ## total +=amount[index] > ## average = total/len(amount) An alternative solution here uses a list comprehension def aboveAverage(amounts, ave): return len( [item for item in amounts if item > ave] ) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From wallenpb at gmail.com Sun Feb 19 02:31:49 2012 From: wallenpb at gmail.com (Bill Allen) Date: Sat, 18 Feb 2012 19:31:49 -0600 Subject: [Tutor] list comprehension efficiency Message-ID: Generally speaking, are list comprehensions more efficient that the equivalent for loop with interior conditionals for a given task? Do they compile down to the same Python byte code? Thanks, Bill Allen -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sun Feb 19 02:45:38 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 19 Feb 2012 01:45:38 +0000 Subject: [Tutor] list comprehension efficiency In-Reply-To: References: Message-ID: On 19/02/2012 01:31, Bill Allen wrote: > Generally speaking, are list comprehensions more efficient that the > equivalent for loop with interior conditionals for a given task? Do they > compile down to the same Python byte code? > > Thanks, > Bill Allen > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Use the timeit module to answer Q1 and the dis module to answer Q2. -- Cheers. Mark Lawrence. From steve at pearwood.info Sun Feb 19 03:55:15 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 19 Feb 2012 13:55:15 +1100 Subject: [Tutor] list comprehension efficiency In-Reply-To: References: Message-ID: <4F406493.8090100@pearwood.info> Bill Allen wrote: > Generally speaking, are list comprehensions more efficient that the > equivalent for loop with interior conditionals for a given task? Do they > compile down to the same Python byte code? It depends, and no. For-loops are more general, so there are loops that can't be written as list comprehensions. Consequently, so is the byte code generated. Python makes no attempt to analyse a for-loop and decide that it could be written as a list comp. Nor do list comps generate the exact same code as a for-loop: they can't, because the semantics are slightly different. (Specifically, a list comp is an atomic operation: either the whole thing succeeds, or the resultant list does not persist. That same does not apply to for-loops.) You can inspect the byte code produced by using the dis module. But, for the subset of possible for-loops which can be re-written as list comps, yes, list comps often are more efficient, as building the list can be performed at full C speed instead of at relatively slower Python speed. But don't over-estimate how big a difference that makes in practice. For trivial loops, it makes a big difference: py> with Timer(): ... _ = [None for i in range(10000)] ... time taken: 0.004692 seconds py> py> with Timer(): ... _ = [] ... for i in range(10000): ... _.append(None) ... time taken: 0.020877 seconds but for loops that do actual, significant work, the difference becomes correspondingly less important: py> def func(x): ... y = 2*i**3 - 15*i*i + 17*i + 3 ... z = x**0.5/(2*y**2 - 1) ... return (3*z)/(1+z)**1.25 ... py> with Timer(): ... _ = [func(i) for i in range(10000)] ... time taken: 0.210438 seconds py> py> with Timer(): ... _ = [] ... for i in range(10000): ... _.append(func(i)) ... time taken: 0.250344 seconds If you're interested in using my Timer() code, you can find it here: http://code.activestate.com/recipes/577896-benchmark-code-with-the-with-statement/ Beware though, that you can't exit out of a list comp early. So if you have code like this: collection = [] for x in sorted(sequence): if x > 10: break collection.append(x + 5) versus this: collection = [x+5 for x in sorted(sequence) if x <= 10] Consider what happens if sequence = range(1000000). The for-loop does eleven iterations, the list-comp does a million. Guess which will be faster? :) -- Steven From bgailer at gmail.com Sun Feb 19 04:22:36 2012 From: bgailer at gmail.com (bob gailer) Date: Sat, 18 Feb 2012 22:22:36 -0500 Subject: [Tutor] arrays, while loops In-Reply-To: References: Message-ID: <4F406AFC.6040002@gmail.com> On 2/18/2012 1:35 PM, Deborah Knoll wrote: > Hi [snip] You've received a (perhaps confusing and some incorrect) melange of responses. I hesitate to add to the pile yet feel compelled to put in my comments. 1) thanks for seeking help. 2) this appears to be homework. Our normal policy is to not write programs to solve the assignment. I'm surprised no one else has mentioned this. 3) I assume you are taking a class, yet the amount of struggle you evince indicates that either you did not learn whatever preceded this assignment, or the class is too far advanced for you. Please confirm or explain. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Feb 20 04:00:25 2012 From: d at davea.name (Dave Angel) Date: Sun, 19 Feb 2012 22:00:25 -0500 Subject: [Tutor] arrays, while loops In-Reply-To: References: , <4F4021E8.2020009@davea.name> Message-ID: <4F41B749.5030506@davea.name> On 02/19/2012 07:01 PM, Deborah Knoll wrote: > > Hi You forgot to include the list in your reply, so your message came only to me. That's not the way to keep a discussion going, for several reasons. Normally, you should just do a Reply-All to messages to add to the thread. or you can make sure to add tutor at python.org as a CC to your message. I forwarded this one for you. > First off, my Python version is 3.2.2. This is a beginner class so I'm struggling to understand it. I've redone my code and have a couple more questions. > > 1. I had the input asking for 7 entries working and now it doesn't. Something is out of order? > Yes. you have a return right in the middle of the for loop. You also have the while and else hopelessly confused. > 2. Also, getting the error message: and not sure where to fix this. > Traceback (most recent call last): > File "C:/Users/dknoll/Desktop/amounts8.py", line 50, in > getnumbers() > File "C:/Users/dknoll/Desktop/amounts8.py", line 7, in getnumbers > amtinput = int (amounts) > TypeError: int() argument must be a string or a number, not 'list' This is one reason two of us encouraged you to change names. From the plural name, you can tell it's got multiple numbers in it. So what did you think int() would do for it? Anyway, you already have the int value, no need to convert it again. I don't think you're experienced enough to understand nested loops. That's why i suggested earlier to make a separate function that asks the user for a single value, repeatedly if necessary, until it's a valid value. Joel had the same suggestion, and elaborates a lot more. If you have such a function, then this one gets simpler,and you should be able to figure it out. > > 3. How do I get the variables into my questions in the printData() function? > > > Here is my new code: > amounts = [0 for index in range (7)] > myamt = len(amounts) > def getnumbers(): > for index in range(myamt): > amounts[index] = int (input ("Enter an amount: ")) > amtinput = int (amounts) > > while amtinput< 1 or amtinput> 1001: > print ("Try again") > amounts[index] = int (input ("Enter an amount: ")) > amtinput = int (amounts) > amtinput.sort() > amtinput.reverse() sort() and reverse() work on lists, not on single items. Think about it. And you don't have such a list until you're done with the for loop. > > return amt_input You're defining a function called getnumbers(), so why would you return a single one? The return belongs after the loop finishes, and it should return the whole list. > else: > amtinput.sort() > amtinput.reverse() > return amt_input > > def average(): > listSum = sum(amounts) > listLength = len (amounts) > listAverage = listSum/listLength > return (listAverage) > def aboveAverage(amounts): > avg = average () > count = 0 > for amount in amounts: > if avg< amounts: > count += 1 > return count > ##def printData(): > ## > ## print ("You entered this many numbers above average: " + > #### print ("The numbers you entered from lowest to highest are: "), amounts > ## print ('The average number is: ' > > > > getnumbers() > average() Are you going to actually use the results of these functions? If so, you want to store the return values in some variable, and/or print them. > > > I don't expect anyone to write this for me, just head me in the right direction. I appreciate all the help. Thank you! > All the rest of your post was too confusing, since it's out of order. When replying, you normally want to quote some (usually not all) of earlier messages, and put your responses AFTER the part you're quoting. Your email client will normally handle adding the "<" character (usually displayed as vertical bars) to show which parts were done by which authors. -- DaveA From d at davea.name Mon Feb 20 17:42:08 2012 From: d at davea.name (Dave Angel) Date: Mon, 20 Feb 2012 11:42:08 -0500 Subject: [Tutor] arrays, while loops In-Reply-To: <4F42756F.6080502@gmail.com> References: , <4F4021E8.2020009@davea.name> <4F41B749.5030506@davea.name> <4F42756F.6080502@gmail.com> Message-ID: <4F4277E0.1@davea.name> I'm not sure who you are, but you forgot to include the list. Therefore I'll forward this to the list, and add my comments about your suggestions. On 02/20/2012 11:31 AM, Ricardo Araoz wrote: > El 20/02/12 00:00, Dave Angel escribi?: >> On 02/19/2012 07:01 PM, Deborah Knoll wrote: >> > > A couple of side notes... > >>> Here is my new code: >>> amounts = [0 for index in range (7)] >>> myamt = len(amounts) > > myamt = 7 > amounts = [0 for index in range(myamt)][0 for index in range(myamt)] > or even > amounts = [0] * myamt > > >>> def getnumbers(): >>> for index in range(myamt): >>> amounts[index] = int (input ("Enter an amount: ")) >>> amtinput = int (amounts) > >>> while amtinput< 1 or amtinput> 1001: >>> print ("Try again") > >> amounts[index] = int (input ("Enter an amount: ")) >> amtinput = int (amounts) >> amtinput.sort() >> amtinput.reverse() > Untested : > while True: > try: > amounts[index] = int (input ("Enter an amount: ")) > amtinput = int (amounts) int() won't operate on a list. Probably you meant it to operate on a string, but there are no strings in it, it's a list of ints. > except ValueError: > print ('Not an integer') > if 1<= amtinput<= 1001: > break > else: > print('Value must be between 1 and 1001') > -- DaveA From sunil.techspk at gmail.com Mon Feb 20 17:43:43 2012 From: sunil.techspk at gmail.com (Sunil Tech) Date: Mon, 20 Feb 2012 22:13:43 +0530 Subject: [Tutor] What made Python differ from other Languages? Message-ID: *I am Beginner (very little i know), i want to know what are new things i can find in Python.* -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Feb 20 18:06:29 2012 From: d at davea.name (Dave Angel) Date: Mon, 20 Feb 2012 12:06:29 -0500 Subject: [Tutor] What made Python differ from other Languages? In-Reply-To: References: Message-ID: <4F427D95.3070301@davea.name> On 02/20/2012 11:43 AM, Sunil Tech wrote: > *I am Beginner (very little i know), i want to know what are new things i > can find in Python.* > There are thousands of computer languages out there. Nearly every feature has an analog out there somewhere. So "what's new" really depends on what language you're comparing it with. You said you're a beginner. Is that a beginner at Python, a beginner at programming, a beginner with computers, what? If I assume you're knowledgeable in C++, I'd point to this set of features: 1) No braces. You build program structure simply by proper indentation. 2) No declarations. A "variable" can contain an integer at one moment, and a dictionary of name/value pairs a moment later. The objects have the type, not the name. 3) Built in types for the most useful collections, tuple, list, dictionary, and set. And a large set of operations that can readily be done on them. 4) Duck typing. You can pass anything you like to a function, and the things you pass may not be subclasses of the expected types, but if the right operations (methods) are supported, it'll work. So you can define a "file like" object to a function that's expecting a file, and it doesn't have to be derived from file, it just has to have the right methods, and the equivalent semantics. 5) The kitchen sink. The standard library has an enormous collection of useful stuff, most of it written in python. Most of the time, you don't need to look to third party libraries to accomplish your goal. 6) Easy debugging. There are a number of IDE's available, but it's not hard to debug code without one. And you can run code fragments from a standard interpreter, and examine data and define new functions on the fly. The system also supports introspection, so even the simplest error message tells you a lot about what was happening. And when you need to, you can examine any object in the system, stack frames, types of objects, and so on. 7) Easy testing. You can define some sanity tests in your own source code, in a special string called a docstring. That string can thus have two uses: documentation for the reader of the code, and first line of tests to make sure the code meets those tests. -- DaveA From clsdaniel at gmail.com Mon Feb 20 18:20:59 2012 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Mon, 20 Feb 2012 10:20:59 -0700 Subject: [Tutor] What made Python differ from other Languages? In-Reply-To: <4F427D95.3070301@davea.name> References: <4F427D95.3070301@davea.name> Message-ID: Just to express my opinion on the matter which is cannot stress enough, Python does not only come with the kitchen sink, it comes with a very useful kitchen sink, most of the standard library modules are very useful and not just random additions, I take for example a comparision against C#, I had to process some XML files from email attachments, you cannot do this in C# out of the box (there is no pop3 or imap library, only XML handling), in python there is buildin pop3 module and xml processing, thus the time I invest on looking for a C# pop3 library (or creating my own) I already got it done with python and core modules, plus there is a standard way of searching, getting and installing modules which makes developing with python a bliss. To sum up, python is also different because there is a large amount of libraries and code to harness, making it easy to work with, fast to develop and flexible enough to cover different application types. Regards, Carlos Daniel Ruvalcaba Valenzuela From d at davea.name Mon Feb 20 19:30:43 2012 From: d at davea.name (Dave Angel) Date: Mon, 20 Feb 2012 13:30:43 -0500 Subject: [Tutor] What made Python differ from other Languages? In-Reply-To: References: <4F427D95.3070301@davea.name> Message-ID: <4F429153.2070604@davea.name> On 02/20/2012 12:16 PM, Darin Lawson Hosking wrote: > Sunil > > Here is great way to get started on Python, even though the first few > videos are setting up a Linux virtual machine to develop within, he quickly > moves onto Python. > > http://www.youtube.com/user/RaspberryPiTutorials/videos > > Darin > The above was sent as a private email to me. And I wasn't even the one he apparently was addressing it to. -- DaveA From alan.gauld at btinternet.com Mon Feb 20 19:36:15 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 20 Feb 2012 18:36:15 +0000 Subject: [Tutor] What made Python differ from other Languages? In-Reply-To: References: Message-ID: On 20/02/12 16:43, Sunil Tech wrote: > /I am Beginner (very little i know), i want to know what are new things > i can find in Python./ There is a wealth of detail on this on the Python web site. Try the FAQ for a starter: http://docs.python.org/faq/general.html And the success stories for more concrete evidence: http://www.python.org/about/success/ And for simple advocacy try: http://www.python.org/about/quotes/ HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From joel.goldstick at gmail.com Mon Feb 20 19:37:30 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 20 Feb 2012 13:37:30 -0500 Subject: [Tutor] What made Python differ from other Languages? In-Reply-To: <4F429153.2070604@davea.name> References: <4F427D95.3070301@davea.name> <4F429153.2070604@davea.name> Message-ID: I think python is great because: 1. it is very easy to read other peoples code and understand it 2. without being cryptic, you can do a lot of logic with very little typing because the language was well conceived -- it didn't get added on to in an ad hoc way that (IMO) php has been. 3. there is an active great community so you can learn about what you don't understand here or stack overflow, or meetups, etc. -- Joel Goldstick From bgailer at gmail.com Mon Feb 20 19:59:39 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 20 Feb 2012 13:59:39 -0500 Subject: [Tutor] arrays, while loops In-Reply-To: References: , <4F406AFC.6040002@gmail.com> Message-ID: <4F42981B.1090904@gmail.com> Thanks for your response. Please always reply-all so a copy goes to the tutor list. I'm cc'ing this to that list. On 2/19/2012 10:13 AM, Deborah Knoll wrote: > This is for a class - I wasn't trying to hide that fact. I didn't > want someone to write this for me, I understand and appreciate that. I was commenting more to the other list responders. > just give some help so I could learn, which I did get. As for this > being too advanced, it's a beginner Program Logic course and I think > the code is suppose to be written fairly simply Something got derailed - the question you posed requires prior learning; your attempts don't show that you had that learning. > - it's an online course which makes it harder but I am learning. Would you provide a link to the course so we could see it? > I didn't know of your policy but from now on I will keep it to more > simple quesions instead of the whole program. That's always a good idea. Your program wasn't that big. But there was so much "wrong" with it - that made me question the relevance of the assignment. > I do want to say thanks to everyone for the help - I'm excited to be > learning more. I like hearing that. Please also note that we like to see our answers interspersed with your comments. Please do the same when replying to us. Also delete any part of the email to which you reply that is not relevant to your reply. And please reply. We actually enjoy helping. Some "generic" comments: 1) when working with a fixed-lengthobject (e.g.a list of length 7) start by defining a constant and then refer to that constant. e.g.: SIZE = 7 amounts = [0]*SIZE 2) when obtaining user input that should be a numberbut might not it is essential that you (in one of several ways) anticipate and handle "bad" input. One way is to use isdigit() to ensure that all the characters entered are digits. This assumes that inputs with a decimal point are not allowed, but your problem does not rule them out - it's just harder to detect "bad" input if decimal points are allowed. So let's assume integers only for now. Let's create a function whose job is to get an integer and keep trying till the user enters one. We might as well throw in the range check as this is the best place to do that. def getInteger(): while True: # this keeps asking for in put until user get it right x = raw_input ("Enter an integer amount between 1 and 1000: ") # spell out all the requirements if x.isdigit(): y = int(x) if y >= 1 and y <= 1000: return y else: print(x + " is not between 1 and 1000") else: print(x + " is not an integer") print getInteger() I wrote this as a stand-alone program so I could test it by itself, and added the last line to actually run the test. Once the getInteger function is working then you can add the other logic. Another approach is using try and except as others have mentioned. However I doubt whether your course has introduced exception handling. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Feb 20 20:43:15 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 20 Feb 2012 19:43:15 +0000 Subject: [Tutor] What made Python differ from other Languages? In-Reply-To: References: Message-ID: On 20/02/2012 16:43, Sunil Tech wrote: > *I am Beginner (very little i know), i want to know what are new things i > can find in Python.* > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor This sums up the Python philosophy. C:\Users\Mark\cpython\PCbuild>py -3.2 -c "import this" The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! -- Cheers. Mark Lawrence. From donguye at cisco.com Mon Feb 20 22:17:48 2012 From: donguye at cisco.com (Do Nguyen (donguye)) Date: Mon, 20 Feb 2012 15:17:48 -0600 Subject: [Tutor] ssh from Windows to a Solaris server Message-ID: I'm a newbie in python programming ... I wrote the followings to ssh from Windows to a Solaris server: command1 = "plink -ssh -pw myPassword myUserName at myServerIP" p1 = subprocess.Popen(command1) p2 = subprocess.Popen('ls') I could verify that command1 was executed successfully, ie. the ssh to myServer worked, but command2 was treated locally in the Windows and was not executed on the server. The error was as follows: Traceback (most recent call last): File "C:\Python32\ProgramFiles\test-paramiko.py", line 42, in p2 = subprocess.Popen('ls') File "C:\Python32\lib\subprocess.py", line 741, in __init__ restore_signals, start_new_session) File "C:\Python32\lib\subprocess.py", line 960, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified Any hint ? I am using python 3.2 and did try to install paramiko but could not make it works. -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Mon Feb 20 22:36:53 2012 From: evert.rol at gmail.com (Evert Rol) Date: Mon, 20 Feb 2012 22:36:53 +0100 Subject: [Tutor] ssh from Windows to a Solaris server In-Reply-To: References: Message-ID: <6DEA86EF-7BAD-446F-B997-E18425BBC822@gmail.com> > I?m a newbie in python programming ? > > I wrote the followings to ssh from Windows to a Solaris server: > > command1 = "plink -ssh -pw myPassword myUserName at myServerIP" > p1 = subprocess.Popen(command1) > p2 = subprocess.Popen('ls') > > I could verify that command1 was executed successfully, ie. the ssh to myServer worked, but command2 was treated locally in the Windows and was not executed on the server. As far as I know subprocess, you create a completely new shell environment underneath for every process. So essentially, you are now opening a shell, typing your ssh command, closing the shell (and thus the ssh session), and then create a new shell to type 'ls'. You can put the commands in a single shell script and run that through subprocess. With ssh, it could be somewhat easier: >>> command1 = "plink -ssh -pw myPassword myUserName at myServerIP ls" >>> p1 = subprocess.Popen(command1) So, you can just put the command you want to run at the end of the ssh command. But, I don't know if plink allows that: I simply don't know plink. If it doesn't work this way, there may be an option for it though. (Can't say I like the idea it lets you specify the password on the command line, but hey.) Cheers, Evert > The error was as follows: > > Traceback (most recent call last): > File "C:\Python32\ProgramFiles\test-paramiko.py", line 42, in > p2 = subprocess.Popen('ls') > File "C:\Python32\lib\subprocess.py", line 741, in __init__ > restore_signals, start_new_session) > File "C:\Python32\lib\subprocess.py", line 960, in _execute_child > startupinfo) > WindowsError: [Error 2] The system cannot find the file specified > > Any hint ? I am using python 3.2 and did try to install paramiko but could not make it works. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From ricaraoz at gmail.com Tue Feb 21 00:17:20 2012 From: ricaraoz at gmail.com (Ricardo Araoz) Date: Mon, 20 Feb 2012 20:17:20 -0300 Subject: [Tutor] arrays, while loops In-Reply-To: <4F4277E0.1@davea.name> References: , <4F4021E8.2020009@davea.name> <4F41B749.5030506@davea.name> <4F42756F.6080502@gmail.com> <4F4277E0.1@davea.name> Message-ID: <4F42D480.1030605@gmail.com> El 20/02/12 13:42, Dave Angel escribi?: > I'm not sure who you are, but you forgot to include the list. > Therefore I'll forward this to the list, and add my comments about > your suggestions. > > On 02/20/2012 11:31 AM, Ricardo Araoz wrote: >> Untested : >> while True: >> try: >> amounts[index] = int (input ("Enter an amount: ")) >> amtinput = int (amounts) > > int() won't operate on a list. Probably you meant it to operate on a > string, but there are no strings in it, it's a list of ints. > > sorry I meant : amtinput = int (input ("Enter an amount: ")) amounts[index] = amtinput From mjolewis at gmail.com Tue Feb 21 00:46:37 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Mon, 20 Feb 2012 15:46:37 -0800 Subject: [Tutor] __name__=='__main__' Message-ID: Hi everyone, I am having some trouble understanding how to use __name__== '__main__'. Can you please give me some insight? Also, to use this, it needs to be within a function? Do you typically just throw it in your very last function or create a separate function just for this? I at first put it outside and after all my functions but got the error below and then put it inside my last function and the program ran. (side note, I have an error in my return for MultiplyText that I am still trying to work out, so you can ignore that part). Code: '''homework 5_1''' def MultiplyText(text, multiplier): '''Recieve a S. For digits in S, multiply by multiplier and return updated S.''' for num in text: return ''.join(str(int(num) * multiplier) if num.isdigit() else num for num in text) def GetUserInput(): '''Get S & multiplier. Test multiplier.isdigit(). Call MultiplyText(text, multiplier)''' while True: text = raw_input('Enter some text: ') multiplier = raw_input('Enter a multiplier: ') try: multiplier.isdigit() break except ValueError: continue new_text = MultiplyText(text, multiplier) return new_text if __name == '__main__': print GetUserInput() Error I got when __name == ' __main__' was outside of any function: Traceback (most recent call last): File "C:/Python27/Homework/Homework5_1.py", line 24, in if __name == '__main__': NameError: name '__name' is not defined -- Michael J. Lewis -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Tue Feb 21 00:53:38 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 20 Feb 2012 18:53:38 -0500 Subject: [Tutor] __name__=='__main__' In-Reply-To: References: Message-ID: On Mon, Feb 20, 2012 at 6:46 PM, Michael Lewis wrote: > I at first put it outside and after all my functions but got the error below That's the right place for it, you just spelled it wrong. > and then put it inside my last function and the program ran. That's not the right place for it. Your program ran, but only because nothing ever called your GetUserInput() function any more. > Traceback (most recent call last): > ? File "C:/Python27/Homework/Homework5_1.py", line 24, in > ? ? if __name == '__main__': > NameError: name '__name' is not defined It needs to be spelled "__name__" -- that's two underscores on each side. -- Jerry From steve at pearwood.info Tue Feb 21 00:54:47 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 21 Feb 2012 10:54:47 +1100 Subject: [Tutor] __name__=='__main__' In-Reply-To: References: Message-ID: <4F42DD47.8060104@pearwood.info> Michael Lewis wrote: > Error I got when __name == ' __main__' was outside of any function: > > Traceback (most recent call last): > File "C:/Python27/Homework/Homework5_1.py", line 24, in > if __name == '__main__': > NameError: name '__name' is not defined You have misspelled __name__ as __name. -- Steven From alan.gauld at btinternet.com Tue Feb 21 01:06:01 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 21 Feb 2012 00:06:01 +0000 Subject: [Tutor] ssh from Windows to a Solaris server In-Reply-To: References: Message-ID: On 20/02/12 21:17, Do Nguyen (donguye) wrote: > command1 = "plink -ssh -pw myPassword myUserName at myServerIP" > p1 = subprocess.Popen(command1) > p2 = subprocess.Popen('ls') > > I could verify that command1 was executed successfully, ie. the ssh to > myServer worked, but command2 was treated locally in the Windows Yes, because you created a new subprocess.Popen object. If you want to communicate with ssh in the first subprocess you need to send commands to stdin on p1. There are lots of examples how to read/write to stdin/out in the subprocess documentation. (I'm assuming that plink stays open, I've never used it so don't know) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Feb 21 01:10:04 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 21 Feb 2012 00:10:04 +0000 Subject: [Tutor] __name__=='__main__' In-Reply-To: References: Message-ID: On 20/02/12 23:46, Michael Lewis wrote: > it inside my last function and the program ran. (side note, I have an > error in my return for MultiplyText that I am still trying to work out, You can remove the outer for loop, you are already looping over text inside the generator expression. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Feb 21 01:17:21 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 21 Feb 2012 00:17:21 +0000 Subject: [Tutor] __name__=='__main__' In-Reply-To: References: Message-ID: On 20/02/12 23:46, Michael Lewis wrote: > I am having some trouble understanding how to use __name__== '__main__'. > Can you please give me some insight? Others have told you how to fix it. The insight is that when you import a python file its __name__ attribute is set to the module name. When you run it as the top level script its __name__ is set to __main__. So you want to create an 'if' test, and it can be anywhere in your code there is nothing special about it, but usually it's at the bottom of the file and looks like: def moduleFunc() # this is the code that gets used as a module def anotherFunc(): #and so is this def main(): # put your main program code here # it doesn't get run if the file # is imported # - unless the user chooses to explicitly of course! if __name__ == "__main__": main() # or call it test() if the file is only expected to be used as a module HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Tue Feb 21 01:25:40 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 21 Feb 2012 11:25:40 +1100 Subject: [Tutor] ssh from Windows to a Solaris server In-Reply-To: References: Message-ID: <4F42E484.20502@pearwood.info> Alan Gauld wrote: > On 20/02/12 21:17, Do Nguyen (donguye) wrote: > >> command1 = "plink -ssh -pw myPassword myUserName at myServerIP" >> p1 = subprocess.Popen(command1) >> p2 = subprocess.Popen('ls') >> >> I could verify that command1 was executed successfully, ie. the ssh to >> myServer worked, but command2 was treated locally in the Windows > > Yes, because you created a new subprocess.Popen object. > If you want to communicate with ssh in the first subprocess you need to > send commands to stdin on p1. There are lots of examples how to > read/write to stdin/out in the subprocess documentation. (I'm assuming > that plink stays open, I've never used it so don't know) I don't know about plink, but the right way to run commands on a remote machine using ssh is to give those commands to ssh as an argument. E.g. http://linuxers.org/howto/how-run-commands-remote-machine-using-ssh http://systemsboy.com/2006/07/send-remote-commands-via-ssh.html -- Steven From mjolewis at gmail.com Tue Feb 21 01:53:27 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Mon, 20 Feb 2012 16:53:27 -0800 Subject: [Tutor] Tutor Digest, Vol 96, Issue 83 In-Reply-To: References: Message-ID: > On Mon, Feb 20, 2012 at 6:46 PM, Michael Lewis wrote: > > I at first put it outside and after all my functions but got the error > below > > That's the right place for it, you just spelled it wrong. > > > and then put it inside my last function and the program ran. > > That's not the right place for it. Your program ran, but only because > nothing ever called your GetUserInput() function any more. Now I am confused. I fixed the spelling and put it outside all my functions; however, the code now runs WITHOUT me explicitly importing it. def MultiplyText(text, multiplier): '''Recieve a S & int. For digits in S, multiply by multiplier and return updated S.''' return ' '.join(str(int(num) * multiplier) if num.isdigit() else num for num in text) def GetUserInput(): '''Get S & multiplier. Test multiplier.isdigit(). Call MultiplyText(text, multiplier)''' text = raw_input('Enter some text: ') while True: multiplier = raw_input('Enter a multiplier: ') try: multiplier = int(multiplier) break except ValueError: continue return MultiplyText(text.split(), multiplier) if __name__ == '__main__': GetUserInput() > > > Traceback (most recent call last): > > ? File "C:/Python27/Homework/Homework5_1.py", line 24, in > > ? ? if __name == '__main__': > > NameError: name '__name' is not defined > > It needs to be spelled "__name__" -- that's two underscores on each side. > > -- > Jerry > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Feb 21 01:55:39 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 20 Feb 2012 19:55:39 -0500 Subject: [Tutor] __name__=='__main__' In-Reply-To: References: Message-ID: <4F42EB8B.2030400@gmail.com> No one else has caught another problem. I comment on it below: On 2/20/2012 6:46 PM, Michael Lewis wrote: > Hi everyone, > > I am having some trouble understanding how to use __name__== > '__main__'. Can you please give me some insight? Also, to use this, it > needs to be within a function? Do you typically just throw it in your > very last function or create a separate function just for this? I at > first put it outside and after all my functions but got the error > below and then put it inside my last function and the program ran. > (side note, I have an error in my return for MultiplyText that I am > still trying to work out, so you can ignore that part). > > Code: > > '''homework 5_1''' > > def MultiplyText(text, multiplier): > '''Recieve a S. For digits in S, multiply by multiplier and return > updated S.''' > for num in text: > return ''.join(str(int(num) * multiplier) if num.isdigit() > else num for num in text) This will fail, as multiplier is a string. > > > def GetUserInput(): > '''Get S & multiplier. Test multiplier.isdigit(). Call > MultiplyText(text, multiplier)''' > while True: > text = raw_input('Enter some text: ') > multiplier = raw_input('Enter a multiplier: ') > try: > multiplier.isdigit() multiplier.isdigit() returns True or False. It will not raise an exception! > break > except ValueError: > continue > new_text = MultiplyText(text, multiplier) > return new_text > > if __name == '__main__': > print GetUserInput() > To fix both problems replace multiplier.isdigit() with multiplier = int(multiplier) -- Bob Gailer 919-636-4239 Chapel Hill NC From tahir.hafiz at gmail.com Tue Feb 21 01:58:52 2012 From: tahir.hafiz at gmail.com (Tahir Hafiz) Date: Tue, 21 Feb 2012 00:58:52 +0000 Subject: [Tutor] Scribes with python debugger Message-ID: Does anyone know of a plugin or some other way to run python code in the scribes text editor in a similar way to Idle which has a debugger? Thanks, Tahir From mjolewis at gmail.com Tue Feb 21 02:08:36 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Mon, 20 Feb 2012 17:08:36 -0800 Subject: [Tutor] __name__=='__main__' In-Reply-To: <4F42EB8B.2030400@gmail.com> References: <4F42EB8B.2030400@gmail.com> Message-ID: Thanks. I did end up catching those, but to be fair to all the others, I did ask that they ignore that issue as I was still working through it on my own. On Mon, Feb 20, 2012 at 4:55 PM, bob gailer wrote: > No one else has caught another problem. I comment on it below: > > > On 2/20/2012 6:46 PM, Michael Lewis wrote: > >> Hi everyone, >> >> I am having some trouble understanding how to use __name__== '__main__'. >> Can you please give me some insight? Also, to use this, it needs to be >> within a function? Do you typically just throw it in your very last >> function or create a separate function just for this? I at first put it >> outside and after all my functions but got the error below and then put it >> inside my last function and the program ran. (side note, I have an error in >> my return for MultiplyText that I am still trying to work out, so you can >> ignore that part). >> >> Code: >> >> '''homework 5_1''' >> >> def MultiplyText(text, multiplier): >> '''Recieve a S. For digits in S, multiply by multiplier and return >> updated S.''' >> for num in text: >> return ''.join(str(int(num) * multiplier) if num.isdigit() else >> num for num in text) >> > This will fail, as multiplier is a string. > > >> >> def GetUserInput(): >> '''Get S & multiplier. Test multiplier.isdigit(). Call >> MultiplyText(text, multiplier)''' >> while True: >> text = raw_input('Enter some text: ') >> multiplier = raw_input('Enter a multiplier: ') >> try: >> multiplier.isdigit() >> > multiplier.isdigit() returns True or False. It will not raise an exception! > > break >> except ValueError: >> continue >> new_text = MultiplyText(text, multiplier) >> return new_text >> >> if __name == '__main__': >> print GetUserInput() >> >> To fix both problems replace > multiplier.isdigit() > with > multiplier = int(multiplier) > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > -- Michael J. Lewis mjolewis at gmail.com 415.815.7257 -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Tue Feb 21 02:52:05 2012 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Tue, 21 Feb 2012 02:52:05 +0100 Subject: [Tutor] __name__=='__main__' In-Reply-To: References: Message-ID: > I am having some trouble understanding how to use __name__== '__main__'. Can > you please give me some insight? if __name__ == '__main__': allows you to specify code that will only be run if you run the actual script it's in; anything in the if block won't be run if you import the module. >Also, to use this, it needs to be within a > function? Do you typically just throw it in your very last function or > create a separate function just for this? I at first put it outside and > after all my functions but got the error below and then put it inside my > last function and the program ran. (side note, I have an error in my return > for MultiplyText that I am still trying to work out, so you can ignore that > part). No, it doesn't have to be in a function, but if you wish you can have it in a function main() or similar. The reason why you're getting an error isn't because it's outside a function, it's because you're not using the correct name: > Traceback (most recent call last): > File "C:/Python27/Homework/Homework5_1.py", line 24, in > if __name == '__main__': > NameError: name '__name' is not defined As it says in the traceback, '__name' is not defined. It should be '__name__'. > def GetUserInput(): > ? ? '''Get S & multiplier. Test multiplier.isdigit(). Call > MultiplyText(text, multiplier)''' > ? ? while True: > ? ? ? ? text = raw_input('Enter some text: ') > ? ? ? ? multiplier = raw_input('Enter a multiplier: ') > ? ? ? ? try: > ? ? ? ? ? ? multiplier.isdigit() > ? ? ? ? ? ? break > ? ? ? ? except ValueError: > ? ? ? ? ? ? continue > ? ? new_text = MultiplyText(text, multiplier) > ? ? return new_text > > ? ? if __name == '__main__': > ? ? ? ? print GetUserInput() You shouldn't have the "if '__name__' " block in any of your functions (except possibly main()), it looks bad. I'm unsure if it'll affect things when you import functions, but on the off-chance that it does, you shouldn't do it. A short example: critter.py: class Critter(object): """A virtual pet.""" def __init__(self): print("A new critter has been born!") def talk(self): print("Hi, I'm an instance of class Critter.") if __name__ == '__main__': crit1 = Critter() crit2 = Critter() crit1.talk() crit2.talk() If I run this from critter.py, I will get the following output: A new critter has been born! A new critter has been born! Hi, I'm an instance of class Critter. Hi, I'm an instance of class Critter. However, if I create a critter_import.py and inside it import my Critter class: from critter import Critter if __name__ == '__main__': print("This is critter_import.py") The output will only be: This is critter_import.py If I subsequently create critters in critter_import.py, I will indeed get the output that we see in critter.py, but that's because of class behaviour and not because the if '__name__' block in critter.py executes. I might have made a mess of explaining things. In short: if '__name__' == '__main__': only happens if you run the actual file, whereas it won't happen if you import things from the file. -- best regards, Robert S. From d at davea.name Tue Feb 21 03:11:01 2012 From: d at davea.name (Dave Angel) Date: Mon, 20 Feb 2012 21:11:01 -0500 Subject: [Tutor] __name__=='__main__' In-Reply-To: References: Message-ID: <4F42FD35.9040303@davea.name> On 02/20/2012 06:46 PM, Michael Lewis wrote: > Hi everyone, > > I am having some trouble understanding how to use __name__== '__main__'. > Can you please give me some insight? Also, to use this, it needs to be > within a function? Do you typically just throw it in your very last > function or create a separate function just for this? I at first put it > outside and after all my functions but got the error below and then put it > inside my last function and the program ran. (side note, I have an error in > my return for MultiplyText that I am still trying to work out, so you can > ignore that part). > > Code: Nothing magic about that line (if __name__ == "__main__"). You need to understand the components, and why you're using them. As others have pointed out, your original error was simply due to a typo. Every module has a __name__ attribute. If a module is imported, that attribute is set to the module's name. But if it is run directly (eg. if you run python myfile.py) then it has the name "__main__" rather than "myfile". So if you fix the typo, and still have an error, then explain what you run, and how, rather than saying something like "code now runs WITHOUT me explicitly importing it." For example: my source file is called XXXXX.py which looks like: When I run the Linux commandline: python XXXXX I get the following results. (and yes, I know the above won't work. I'm trying to force you to tell us what you really did) -- DaveA From mjolewis at gmail.com Tue Feb 21 04:07:09 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Mon, 20 Feb 2012 19:07:09 -0800 Subject: [Tutor] __name__=='__main__' In-Reply-To: <4F42FD35.9040303@davea.name> References: <4F42FD35.9040303@davea.name> Message-ID: Now that I am better understanding '__name__'=='__main__', I need to get advice on one last part. Since you put this in the file as an if statement, some instruction must come after. What do you suggest putting after this statement/is that piece of code ever put into action? In my example below, I've done a few tests like putting a print statement under '__name__'=='__main__' and it isn't printed. I am not sure what to put in this code block. def MultiplyText(text, multiplier): '''Recieve a S & int. For digits in S, multiply by multiplier and return updated S.''' return ' '.join(str(int(num) * multiplier) if num.isdigit() else num for num in text) def GetUserInput(): '''Get S & multiplier. Test multiplier.isdigit(). Call MultiplyText(text, multiplier)''' text = raw_input('Enter some text: ') while True: multiplier = raw_input('Enter a multiplier: ') try: multiplier = int(multiplier) break except ValueError: continue return MultiplyText(text.split(), multiplier) if '__name__' == '__main__': GetUserInput() -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue Feb 21 04:26:12 2012 From: d at davea.name (Dave Angel) Date: Mon, 20 Feb 2012 22:26:12 -0500 Subject: [Tutor] __name__=='__main__' In-Reply-To: References: <4F42FD35.9040303@davea.name> Message-ID: <4F430ED4.7080502@davea.name> On 02/20/2012 10:07 PM, Michael Lewis wrote: > Now that I am better understanding '__name__'=='__main__', I need to get > advice on one last part. Since you put this in the file as an if statement, > some instruction must come after. What do you suggest putting after this > statement/is that piece of code ever put into action? > In my example below, I've done a few tests like putting a print statement > under '__name__'=='__main__' and it isn't printed. I am not sure what to > put in this code block. > > def MultiplyText(text, multiplier): > '''Recieve a S& int. For digits in S, multiply by multiplier and > return updated S.''' > return ' '.join(str(int(num) * multiplier) if num.isdigit() else num > for num in text) > > > def GetUserInput(): > '''Get S& multiplier. Test multiplier.isdigit(). Call > MultiplyText(text, multiplier)''' > text = raw_input('Enter some text: ') > while True: > multiplier = raw_input('Enter a multiplier: ') > try: > multiplier = int(multiplier) > break > except ValueError: > continue > return MultiplyText(text.split(), multiplier) > > > if '__name__' == '__main__': > GetUserInput() > I don't see any print statement in the if-clause. In fact I don't see any prints in the entire program. Just how do you expect to know if it even ran? What IS there is a call to GetUserInput(). But for some reason that function doesn't return user-input. Why not? A function should nearly always take some arguments, and return a result. And its name should reflect what it's going to do Besides that, you do return a value from GetUserInput()., but never use that value. So what's the point? Probably what belongs in the if clause is a call to main(). Then you need to write main() function, to call GetUserInput() and save the value returned (a tuple of string and int, my choice). Then it'd call MultiplyText with those two, and with this mysterious num value that you conjured up in MultiplyText. Once you've factored the two functions into separately called entities, you have a chance of debugging your multiple mistakes still remaining. In between the two function calls in main(), you can actually print out your intermediate results, and see if they look reasonable to you. In fact, while testing, you just might want to try calling MultiplyText() with whatever literal arguments make sense. And print the result you get. A few of those tests, and you might get comfortable with the function. -- DaveA From mjolewis at gmail.com Tue Feb 21 05:55:45 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Mon, 20 Feb 2012 20:55:45 -0800 Subject: [Tutor] '__name__' == '__main__' Message-ID: I am back to being confused. I just tried running the module without first importing it, and it worked just fine. How do I do this properly to where the module only runs if I import it? Code: def MultiplyText(text, multiplier): '''Recieve a S & int. For digits in S, multiply by multiplier and return updated S.''' return ' '.join(str(int(num) * multiplier) if num.isdigit() else num for num in text) def GetUserInput(): '''Get S & multiplier. Test multiplier.isdigit(). Call MultiplyText(text, multiplier)''' text = raw_input('Enter some text: ') while True: multiplier = raw_input('Enter a multiplier: ') try: multiplier = int(multiplier) break except ValueError: continue return MultiplyText(text.split(), multiplier) if "__name__" == '__main__': GetUserInput() What I did in IDLE: >>> >>> GetUserInput() Enter some text: 4 times Enter a multiplier: 2 '8 times' >>> -- Michael J. Lewis mjolewis at gmail.com 415.815.7257 -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Tue Feb 21 06:27:55 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 21 Feb 2012 07:27:55 +0200 Subject: [Tutor] '__name__' == '__main__' In-Reply-To: References: Message-ID: <4F432B5B.6060203@compuscan.co.za> On 2012/02/21 06:55 AM, Michael Lewis wrote: > I am back to being confused. I just tried running the module without > first importing it, and it worked just fine. How do I do this properly > to where the module only runs if I import it? > > Code: > > def MultiplyText(text, multiplier): > '''Recieve a S & int. For digits in S, multiply by multiplier and > return updated S.''' > return ' '.join(str(int(num) * multiplier) if num.isdigit() else > num for num in text) > > > def GetUserInput(): > '''Get S & multiplier. Test multiplier.isdigit(). Call > MultiplyText(text, multiplier)''' > text = raw_input('Enter some text: ') > while True: > multiplier = raw_input('Enter a multiplier: ') > try: > multiplier = int(multiplier) > break > except ValueError: > continue > return MultiplyText(text.split(), multiplier) > > > if "__name__" == '__main__': > GetUserInput() > > What I did in IDLE: > > >>> > >>> GetUserInput() > Enter some text: 4 times > Enter a multiplier: 2 > '8 times' > >>> > > -- > Michael J. Lewis > mjolewis at gmail.com > 415.815.7257 > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor If you change '__main__' to the name of the file, without the extension, it will match __name__. Alternatively, you can have an else after your `__name__ == '__main__'` $ cat t1.py if __name__ == '__main__': print 'Executed from __main__' if __name__ == 't1': print 'Executed by import from t2' $ cat t2.py import t1 $ python t1.py Executed from __main__ $ python t2.py Executed by import from t2 $ cat t3.py if __name__ == '__main__': print 'Executed from __main__' else: print 'Executed by import' $ cat t4.py import t3 $ python t3.py Executed from __main__ $ python t4.py Executed by import -- Christian Witts Python Developer COMPUSCAN | CONFIDENCE IN CREDIT Telephone : +27 21 888 6000 National Call Centre : 0861 51 41 31 Fax : +27 21 413 2424 Email : cwitts at compuscan.co.za Website: www.compuscan.co.za Would you like to hear more from us? Register here and receive our newsletters and other business communications. */NOTE:/* This e-mail (including attachments) is subject to the disclaimer published at our website . If you cannot access the disclaimer, request it from email.disclaimer at compuscan.co.za or 0861 514131. National Credit Regulator Credit Bureau Registration No. NCRCB6 /Please consider the environment before printing/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue Feb 21 08:01:11 2012 From: d at davea.name (Dave Angel) Date: Tue, 21 Feb 2012 02:01:11 -0500 Subject: [Tutor] '__name__' == '__main__' In-Reply-To: References: Message-ID: <4F434137.2000506@davea.name> On 02/20/2012 11:55 PM, Michael Lewis wrote: > I am back to being confused. I just tried running the module without first > importing it, and it worked just fine. How do I do this properly to where > the module only runs if I import it? > I'd still like a definition of "just fine." But anyway, your first problem is you somehow added extra quotes to a line that you had right in an earlier version. Comparing two unequal literal strings will never prove true. So the dependent clause never runs. > > if "__name__" == '__main__': > GetUserInput() > that should be if __name__ == "__main__": do something else: do something else You'll have to decide which one you want to call GetUserInput() from. You'll then have to decide if you really want to throw away the result. Just because IDLE dumps something out doesn't mean it'll get printed out when a person runs the program from a commandline. At the very least, you want print GetUserInput() although most of my earlier arguments might apply someday, once you're past this stuff. Try inserting temporary prints into the code, so you can tell what has executed and what has not. -- DaveA From alan.gauld at btinternet.com Tue Feb 21 09:27:12 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 21 Feb 2012 08:27:12 +0000 Subject: [Tutor] __name__=='__main__' In-Reply-To: References: <4F42FD35.9040303@davea.name> Message-ID: On 21/02/12 03:07, Michael Lewis wrote: > Now that I am better understanding '__name__'=='__main__', > if '__name__' == '__main__': > GetUserInput() Note that __name__ is a variable so it should NOT have quotes around it. What you are doing is comparing two literal strings which are obviously different so the if block never gets executed. It has to be: if __name__ == '__main__': GetUserInput() HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Feb 21 09:35:49 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 21 Feb 2012 08:35:49 +0000 Subject: [Tutor] '__name__' == '__main__' In-Reply-To: References: Message-ID: On 21/02/12 04:55, Michael Lewis wrote: > I am back to being confused. I just tried running the module without > first importing it, and it worked just fine. How do I do this properly > to where the module only runs if I import it? Whoooah! That paragraph is so full of ambiguities as to be meaningless. What exactly did you do to "run it without first importing it"? And what happened that was "just fine"? And what do you expect when you say "properly"? What is it that you are expecting to happen? And what does happen? The module always runs when you import it regardless of whether you have an if statement, the only thing that changes is the value of __name__. There is no other magic, the if statement is is just like any other piece of Python code. But, the file will also run if you execute it, again the only difference is the value of __name__. When you import the file it is run with __name__ set to the filename. When you execute the file __name__ is set to "__main__" -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ramit.prasad at jpmorgan.com Tue Feb 21 16:08:52 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 21 Feb 2012 15:08:52 +0000 Subject: [Tutor] Pyhton editor In-Reply-To: References: <191359495-1329536853-cardhu_decombobulator_blackberry.rim.net-55059483-@b13.c5.bise3.blackberry> Message-ID: <5B80DD153D7D744689F57F4FB69AF474155C86@SCACMX008.exchad.jpmchase.net> >>However I stumbled upon PyScripter and I find it really amazing. >Pity it is only for Windows. WINE? Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From tony.pelletier at gmail.com Tue Feb 21 19:10:41 2012 From: tony.pelletier at gmail.com (Tony Pelletier) Date: Tue, 21 Feb 2012 13:10:41 -0500 Subject: [Tutor] Checking for file completion. Message-ID: Hi, I'm struggling with what I think seems to be a problem. I've created a program that does numerous SOAP calls. In short, I create a report on a report server, pull that file down then parse that file that's been written locally for data to make more SOAP calls. My problem is I'm grabbing the filename then losing it somewhere along the way. The only thing I can think of is that it's still open/being written and causing me a problem. Main starts like such. def main(): service = Service() cleanup() reportId = createReport(service) #time.sleep(3) filename = getReport(service,reportId) getEventAttachments(service, filename) Here are the results from a test run. Deleting "files" directory... "files" directory successfully created... Report in Processing state... WeeklyDeliveriesReport_2012-02-21.csv WeeklyDeliveriesReport_2012-02-21.csv report succesfully written out... None File still being written out... getReport() returns a filename and you actually see it twice up in the results. def getReport(service, reportId): reportIds = service.client.factory.create('ArrayOfstring') reportIds.string.append(reportId) try: result = service.client.service.ReportQueryById(reportIds, 'True') if result.Report[0].ReportStatus == 'Processing': print 'Report in Processing state...' time.sleep(3) getReport(service,reportId) else: filename = result.Report[0].ReportFileArgs.ReportFileArg[0].UserFileName print filename encodedfile = result.Report[0].ReportFileArgs.ReportFileArg[0].EncodedValue encodedstring = encodedfile.encode('utf-8') str_list = [] for line in encodedstring: line = line.rstrip() str_list.append(line) string = ''.join(str_list) data = base64.b64decode(string) outfile = open(filename, 'w') outfile.write(data) outfile.close() shutil.copyfile(filename, os.path.join('files', filename)) print filename + ' report succesfully written out...' logging.info(filename + ' report succesfully written out...') return filename except suds.WebFault as e: print e.fault.detail then from main, I'm using filename to then make the call to getEventAttachments and passing in filename. The None you see is a result of my "print filename" statement. Now, if I uncomment that time.sleep(3), it runs flawlessly which I think tells me that the file is still being written to. I *think*... Two questions. 1. Is that not it and if so, am I missing something obvious? 2. If it is it, is there a way to check to see if the file I'm trying to read from is done being written to? Thanks Tony -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue Feb 21 19:30:53 2012 From: d at davea.name (Dave Angel) Date: Tue, 21 Feb 2012 13:30:53 -0500 Subject: [Tutor] Checking for file completion. In-Reply-To: References: Message-ID: <4F43E2DD.3090009@davea.name> On 02/21/2012 01:10 PM, Tony Pelletier wrote: > Hi, > > I'm struggling with what I think seems to be a problem. I've created a > program that does numerous SOAP calls. In short, I create a report on a > report server, pull that file down then parse that file that's been written > locally for data to make more SOAP calls. My problem is I'm grabbing the > filename then losing it somewhere along the way. The only thing I can > think of is that it's still open/being written and causing me a problem. > > Main starts like such. > > def main(): > service = Service() > cleanup() > reportId = createReport(service) > #time.sleep(3) > filename = getReport(service,reportId) > getEventAttachments(service, filename) > > Here are the results from a test run. > > Deleting "files" directory... > "files" directory successfully created... > Report in Processing state... > WeeklyDeliveriesReport_2012-02-21.csv > WeeklyDeliveriesReport_2012-02-21.csv report succesfully written out... > None > File still being written out... > > > getReport() returns a filename and you actually see it twice up in the > results. > > def getReport(service, reportId): > reportIds = service.client.factory.create('ArrayOfstring') > reportIds.string.append(reportId) > > try: > result = service.client.service.ReportQueryById(reportIds, 'True') > if result.Report[0].ReportStatus == 'Processing': > print 'Report in Processing state...' > time.sleep(3) > getReport(service,reportId) > > else: > > filename = result.Report[0].ReportFileArgs.ReportFileArg[0].UserFileName > print filename > encodedfile = result.Report[0].ReportFileArgs.ReportFileArg[0].EncodedValue > > encodedstring = encodedfile.encode('utf-8') > str_list = [] > for line in encodedstring: > line = line.rstrip() > str_list.append(line) > string = ''.join(str_list) > data = base64.b64decode(string) > outfile = open(filename, 'w') > outfile.write(data) > outfile.close() > shutil.copyfile(filename, os.path.join('files', filename)) > print filename + ' report succesfully written out...' > logging.info(filename + ' report succesfully written out...') > return filename > except suds.WebFault as e: > print e.fault.detail > > then from main, I'm using filename to then make the call to > getEventAttachments and passing in filename. The None you see is a result > of my "print filename" statement. > > Now, if I uncomment that time.sleep(3), it runs flawlessly which I think > tells me that the file is still being written to. I *think*... > > Two questions. > 1. Is that not it and if so, am I missing something obvious? > 2. If it is it, is there a way to check to see if the file I'm trying to > read from is done being written to? > > Thanks > Tony > Please post your message again, as a text message rather than an html one. Reading non-trivial python code that's lost all its indentation is impossible. You've done it before, but that case was simple enough to not matter much. -- DaveA From tony.pelletier at gmail.com Tue Feb 21 19:42:35 2012 From: tony.pelletier at gmail.com (Tony Pelletier) Date: Tue, 21 Feb 2012 13:42:35 -0500 Subject: [Tutor] Checking for file completion. In-Reply-To: <4F43E2DD.3090009@davea.name> References: <4F43E2DD.3090009@davea.name> Message-ID: > Please post your message again, as a text message rather than an html one. > ?Reading non-trivial python code that's lost all its indentation is > impossible. ?You've done it before, but that case was simple enough to not > matter much. > > > > -- > > DaveA > Sorry about that. I actually thought i was... my bad... Hi, I'm struggling with what I think seems to be a problem. I've created a program that does numerous SOAP calls. In short, I create a report on a report server, pull that file down then parse that file that's been written locally for data to make more SOAP calls. My problem is I'm grabbing the filename then losing it somewhere along the way. The only thing I can think of is that it's still open/being written and causing me a problem. Main starts like such. def main(): service = Service() cleanup() reportId = createReport(service) #time.sleep(3) filename = getReport(service,reportId) getEventAttachments(service, filename) Here are the results from a test run. Deleting "files" directory... "files" directory successfully created... Report in Processing state... WeeklyDeliveriesReport_2012-02-21.csv WeeklyDeliveriesReport_2012-02-21.csv report succesfully written out... None File still being written out... getReport() returns a filename and you actually see it twice up in the results. def getReport(service, reportId): reportIds = service.client.factory.create('ArrayOfstring') reportIds.string.append(reportId) try: result = service.client.service.ReportQueryById(reportIds, 'True') if result.Report[0].ReportStatus == 'Processing': print 'Report in Processing state...' time.sleep(3) getReport(service,reportId) else: filename = result.Report[0].ReportFileArgs.ReportFileArg[0].UserFileName print filename encodedfile = result.Report[0].ReportFileArgs.ReportFileArg[0].EncodedValue encodedstring = encodedfile.encode('utf-8') str_list = [] for line in encodedstring: line = line.rstrip() str_list.append(line) string = ''.join(str_list) data = base64.b64decode(string) outfile = open(filename, 'w') outfile.write(data) outfile.close() shutil.copyfile(filename, os.path.join('files', filename)) print filename + ' report succesfully written out...' logging.info(filename + ' report succesfully written out...') return filename except suds.WebFault as e: print e.fault.detail then from main, I'm using filename to then make the call to getEventAttachments and passing in filename. The None you see is a result of my "print filename" statement. Now, if I uncomment that time.sleep(3), it runs flawlessly which I think tells me that the file is still being written to. I *think*... Two questions. 1. Is that not it and if so, am I missing something obvious? 2. If it is it, is there a way to check to see if the file I'm trying to read from is done being written to? Thanks From d at davea.name Tue Feb 21 22:56:09 2012 From: d at davea.name (Dave Angel) Date: Tue, 21 Feb 2012 16:56:09 -0500 Subject: [Tutor] Checking for file completion. In-Reply-To: References: <4F43E2DD.3090009@davea.name> Message-ID: <4F4412F9.1010108@davea.name> On 02/21/2012 01:42 PM, Tony Pelletier wrote: >> Please post your message again, as a text message rather than an html one. >> Reading non-trivial python code that's lost all its indentation is >> impossible. You've done it before, but that case was simple enough to not >> matter much. >> >> >> >> -- >> >> DaveA >> > > Sorry about that. I actually thought i was... my bad... > > Hi, > > I'm struggling with what I think seems to be a problem. I've created > a program that does numerous SOAP calls. In short, I create a report > on a report server, pull that file down then parse that file that's > been written locally for data to make more SOAP calls. My problem is > I'm grabbing the filename then losing it somewhere along the way. The > only thing I can think of is that it's still open/being written and > causing me a problem. > > Main starts like such. > > def main(): > service = Service() > cleanup() > reportId = createReport(service) > #time.sleep(3) > filename = getReport(service,reportId) > getEventAttachments(service, filename) > > Here are the results from a test run. > > Deleting "files" directory... > "files" directory successfully created... > Report in Processing state... > WeeklyDeliveriesReport_2012-02-21.csv > WeeklyDeliveriesReport_2012-02-21.csv report succesfully written out... > None > File still being written out... > > > getReport() returns a filename and you actually see it twice up in the results. > > def getReport(service, reportId): > reportIds = service.client.factory.create('ArrayOfstring') > reportIds.string.append(reportId) > > try: > result = service.client.service.ReportQueryById(reportIds, 'True') > if result.Report[0].ReportStatus == 'Processing': > print 'Report in Processing state...' > time.sleep(3) > getReport(service,reportId) Dd you intend to call yourself recursively here? I don't understand all your logic here, but if you really did, I'd at least expect you to save the return value from the recursive call. This is also the first place you're missing a return statement. Is it possible you're trying to use recursion to substitute for a while loop? Generally a bad idea. > > else: > > filename = result.Report[0].ReportFileArgs.ReportFileArg[0].UserFileName > print filename > encodedfile = result.Report[0].ReportFileArgs.ReportFileArg[0].EncodedValue > > encodedstring = encodedfile.encode('utf-8') > str_list = [] > for line in encodedstring: > line = line.rstrip() > str_list.append(line) > string = ''.join(str_list) > data = base64.b64decode(string) > outfile = open(filename, 'w') > outfile.write(data) > outfile.close() > shutil.copyfile(filename, os.path.join('files', filename)) > print filename + ' report succesfully written out...' > logging.info(filename + ' report succesfully written out...') > return filename > except suds.WebFault as e: > print e.fault.detail Missing a return statement in the case of an exception. > > then from main, I'm using filename to then make the call to > getEventAttachments and passing in filename. The None you see is a > result of my "print filename" statement. > Clearly this is Python 2.x code. print is a statement and has no return value (result). You don't state that this is the whole code, but if so, then you're missing return statements from several exit points in the function. It's probably that missing return statement that gives you the None. > Now, if I uncomment that time.sleep(3), it runs flawlessly which I > think tells me that the file is still being written to. I *think*... > > Two questions. > 1. Is that not it and if so, am I missing something obvious? > 2. If it is it, is there a way to check to see if the file I'm trying > to read from is done being written to? > > Thanks > -- DaveA From ml at smtp.fakessh.eu Tue Feb 21 23:00:02 2012 From: ml at smtp.fakessh.eu (ml) Date: Tue, 21 Feb 2012 23:00:02 +0100 Subject: [Tutor] chat openssl Message-ID: <1329861602.24653.3.camel@localhost> hello guys hello master of python "Fu" hello I just finished a chat with openssl rewrite this for secure connections. my script is it well written? https://github.com/fakessh/openprojectssl/blob/master/pyCHATopenssl.py can you tell me what is wrong built sincerely -- http://pgp.mit.edu:11371/pks/lookup?op=get&search=0xC2626742 gpg --keyserver pgp.mit.edu --recv-key C2626742 http://urlshort.eu fakessh @ http://gplus.to/sshfake http://gplus.to/sshswilting http://gplus.to/john.swilting -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: Ceci est une partie de message num?riquement sign?e URL: From tony.pelletier at gmail.com Tue Feb 21 23:20:01 2012 From: tony.pelletier at gmail.com (Tony Pelletier) Date: Tue, 21 Feb 2012 17:20:01 -0500 Subject: [Tutor] Checking for file completion. In-Reply-To: <4F4412F9.1010108@davea.name> References: <4F43E2DD.3090009@davea.name> <4F4412F9.1010108@davea.name> Message-ID: >> >> def getReport(service, reportId): >> ? ? ? ?reportIds = service.client.factory.create('ArrayOfstring') >> ? ? ? ?reportIds.string.append(reportId) >> >> ? ? ? ?try: >> ? ? ? ? ? ? ? ?result = service.client.service.ReportQueryById(reportIds, >> 'True') >> ? ? ? ? ? ? ? ?if result.Report[0].ReportStatus == 'Processing': >> ? ? ? ? ? ? ? ? ? ? ? ?print 'Report in Processing state...' >> ? ? ? ? ? ? ? ? ? ? ? ?time.sleep(3) >> ? ? ? ? ? ? ? ? ? ? ? ?getReport(service,reportId) > > > Dd you intend to call yourself recursively here? ?I don't understand all > your logic here, but if you really did, I'd at least expect you to save the > return value from the recursive call. ?This is also the first place you're > missing a return statement. > > Is it possible you're trying to use recursion to substitute for a while > loop? ?Generally a bad idea. I did intend it. I'm trying to grab the report right after I send the request in, which probably isn't a great idea, but I'll worry about that after I figure this out. The idea is that I know I'll get result.Report[0].ReportStatus to be 'Processing', so I'm sleeping and doing it over. On the second go around, I get the return. > > >> >> ? ? ? ? ? ? ? ?else: >> >> ? ? ? ? ? ? ? ? ? ? ? ?filename = >> ?result.Report[0].ReportFileArgs.ReportFileArg[0].UserFileName >> ? ? ? ? ? ? ? ? ? ? ? ?print filename >> ? ? ? ? ? ? ? ? ? ? ? ?encodedfile = >> result.Report[0].ReportFileArgs.ReportFileArg[0].EncodedValue >> >> ? ? ? ? ? ? ? ? ? ? ? ?encodedstring = encodedfile.encode('utf-8') >> ? ? ? ? ? ? ? ? ? ? ? ?str_list = [] >> ? ? ? ? ? ? ? ? ? ? ? ?for line in encodedstring: >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?line = line.rstrip() >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?str_list.append(line) >> ? ? ? ? ? ? ? ? ? ? ? ?string = ''.join(str_list) >> ? ? ? ? ? ? ? ? ? ? ? ?data = base64.b64decode(string) >> ? ? ? ? ? ? ? ? ? ? ? ?outfile = open(filename, 'w') >> ? ? ? ? ? ? ? ? ? ? ? ?outfile.write(data) >> ? ? ? ? ? ? ? ? ? ? ? ?outfile.close() >> ? ? ? ? ? ? ? ? ? ? ? ?shutil.copyfile(filename, os.path.join('files', >> filename)) >> ? ? ? ? ? ? ? ? ? ? ? ?print filename + ' report succesfully written >> out...' >> ? ? ? ? ? ? ? ? ? ? ? ?logging.info(filename + ' report succesfully >> written out...') >> ? ? ? ? ? ? ? ? ? ? ? ?return filename >> ? ? ? ?except suds.WebFault as e: >> ? ? ? ? ? ? ? ?print e.fault.detail > > > Missing a return statement in the case of an exception. Can you explain this? Why would I want the return on the exception? > > >> >> then from main, I'm using filename to then make the call to >> getEventAttachments and passing in filename. ?The None you see is a >> result of my "print filename" statement. >> > > Clearly this is Python 2.x code. ?print is a statement and has no return > value (result). ?You don't state that this is the whole code, but if so, > then you're missing return statements from several exit points in the > function. ?It's probably that missing return statement that gives you the > None. Not sure I agree here. Again, if put a 3 sec pause in as mentioned below, I get these successful results. C:\Python27\python.exe C:/cygwin/home/Tony/code/soaptraining/getEventAttachments.py Deleting "files" directory... "files" directory successfully created... WeeklyDeliveriesReport_2012-02-21.csv WeeklyDeliveriesReport_2012-02-21.csv report succesfully written out... WeeklyDeliveriesReport_2012-02-21.csv - This is the print statement that returns None .... Rows of data here I print out...... .... TestWordDoc.docx successfully written out! FREE LEARN TO PLAY HOCKEY PROGRAM.docx successfully written out! bookofruby.pdf successfully written out! EmAlex1.jpg successfully written out! Creating archive... bookofruby.pdf EmAlex1.jpg FREE LEARN TO PLAY HOCKEY PROGRAM.docx TestWordDoc.docx WeeklyDeliveriesReport_2012-02-21.csv Done zipping attachments . Starting file transfer... File attachments.zip successfully transferred. > > > >> Now, if I uncomment that time.sleep(3), it runs flawlessly which I >> think tells me that the file is still being written to. ?I *think*... >> >> Two questions. >> 1. ?Is that not it and if so, am I missing something obvious? >> 2. ?If it is it, is there a way to check to see if the file I'm trying >> to read from is done being written to? >> >> Thanks >> > > > -- > > DaveA From d at davea.name Tue Feb 21 23:57:12 2012 From: d at davea.name (Dave Angel) Date: Tue, 21 Feb 2012 17:57:12 -0500 Subject: [Tutor] Checking for file completion. In-Reply-To: References: <4F43E2DD.3090009@davea.name> <4F4412F9.1010108@davea.name> Message-ID: <4F442148.3090408@davea.name> On 02/21/2012 05:20 PM, Tony Pelletier wrote: >>> >>> def getReport(service, reportId): >>> reportIds = service.client.factory.create('ArrayOfstring') >>> reportIds.string.append(reportId) >>> >>> try: >>> result = service.client.service.ReportQueryById(reportIds, >>> 'True') >>> if result.Report[0].ReportStatus == 'Processing': >>> print 'Report in Processing state...' >>> time.sleep(3) >>> getReport(service,reportId) >> >> >> Dd you intend to call yourself recursively here? I don't understand all >> your logic here, but if you really did, I'd at least expect you to save the >> return value from the recursive call. This is also the first place you're >> missing a return statement. >> >> Is it possible you're trying to use recursion to substitute for a while >> loop? Generally a bad idea. > > I did intend it. I'm trying to grab the report right after I send the > request in, which probably isn't a great idea, but I'll worry about > that after I figure this out. The idea is that I know I'll get > result.Report[0].ReportStatus to be 'Processing', so I'm sleeping and > doing it over. On the second go around, I get the return. > But recursion is not "go around". It creates a new stack frame, all new local variables, It calls that factory thingie again, I have no idea what this library of yours does, so I can't directly advise you, but this code is just wrong. >> >> >>> >>> else: >>> >>> filename = >>> result.Report[0].ReportFileArgs.ReportFileArg[0].UserFileName >>> print filename >>> encodedfile = >>> result.Report[0].ReportFileArgs.ReportFileArg[0].EncodedValue >>> >>> encodedstring = encodedfile.encode('utf-8') >>> str_list = [] >>> for line in encodedstring: >>> line = line.rstrip() >>> str_list.append(line) >>> string = ''.join(str_list) >>> data = base64.b64decode(string) >>> outfile = open(filename, 'w') >>> outfile.write(data) >>> outfile.close() >>> shutil.copyfile(filename, os.path.join('files', >>> filename)) >>> print filename + ' report succesfully written >>> out...' >>> logging.info(filename + ' report succesfully >>> written out...') >>> return filename >>> except suds.WebFault as e: >>> print e.fault.detail >> >> >> Missing a return statement in the case of an exception. > > Can you explain this? Why would I want the return on the exception? > I'll answer your question with a question. Just what do YOU think will happen after it prints the e.fault.detail stuff? It'll return to the caller, with a return value of None. You need an explicit return statement to give it a different, explicit value. > >> >> >>> >>> then from main, I'm using filename to then make the call to >>> getEventAttachments and passing in filename. The None you see is a >>> result of my "print filename" statement. > >>> >> >> Clearly this is Python 2.x code. print is a statement and has no return >> value (result). You don't state that this is the whole code, but if so, >> then you're missing return statements from several exit points in the >> function. It's probably that missing return statement that gives you the >> None. > Not sure I agree here. Again, if put a 3 sec pause in as mentioned > below, I get these successful results. You have a return statement on the else clause, so if it happens to execute that path, you'll get a return value for filename. > > C:\Python27\python.exe > C:/cygwin/home/Tony/code/soaptraining/getEventAttachments.py > Deleting "files" directory... > "files" directory successfully created... > WeeklyDeliveriesReport_2012-02-21.csv > WeeklyDeliveriesReport_2012-02-21.csv report succesfully written out... > WeeklyDeliveriesReport_2012-02-21.csv - This is the print statement > that returns None > .... > Rows of data here I print out...... > .... > TestWordDoc.docx successfully written out! > FREE LEARN TO PLAY HOCKEY PROGRAM.docx successfully written out! > bookofruby.pdf successfully written out! > EmAlex1.jpg successfully written out! > > Creating archive... > > bookofruby.pdf > EmAlex1.jpg > FREE LEARN TO PLAY HOCKEY PROGRAM.docx > TestWordDoc.docx > WeeklyDeliveriesReport_2012-02-21.csv > > Done zipping attachments > . > Starting file transfer... > File attachments.zip successfully transferred. > > Look, you don't even include the import statements, nor mention what library you're using for this SOAP stuff. So you aren't likely to get help from whoever happens to know that library. Your output reflects running a lot more code than you show here, so we're all just guessing. I can only give you general help on the python code, and that function has 3 return points, but only one of them has a return statement. It recurses without using the results of the inner calls. Then just returns without using any of that Service code, and without returning a value. So what if you get different results with the sleep() call. That changes the interaction with the unknown library, and the unknown host at the other end of the network. So maybe it works through that path, and not through this one. You could try writing a simple function with the same structure of try/if/recurse/else/except and see if you can make any sense of it. Under the present conditions, I'm done. Good luck. -- DaveA From krush1954 at yahoo.com Wed Feb 22 00:29:01 2012 From: krush1954 at yahoo.com (ken brockman) Date: Tue, 21 Feb 2012 15:29:01 -0800 (PST) Subject: [Tutor] Pyhton editor In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474155C86@SCACMX008.exchad.jpmchase.net> References: <191359495-1329536853-cardhu_decombobulator_blackberry.rim.net-55059483-@b13.c5.bise3.blackberry> <5B80DD153D7D744689F57F4FB69AF474155C86@SCACMX008.exchad.jpmchase.net> Message-ID: <1329866941.17077.YahooMailNeo@web39302.mail.mud.yahoo.com> ________________________________ From: "Prasad, Ramit" To: "tutor at python.org" Sent: Tuesday, February 21, 2012 10:08 AM Subject: Re: [Tutor] Pyhton editor >>However I stumbled upon PyScripter and I find it really amazing. >Pity it is only for Windows. WINE? Ramit I?concur. Pyscripter , though?I've?only installed it a few days ago, seems to be one of the better ones. I am?running?it in a virtualbox winXP on top of?Linux?Ubuntu, but i love the simply way you can use tkinter from a server? No muss no fuss. Just install and go. I understand that the way it had been built, it can't be readily ported to Linux. Mores the pity. Ken Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email.? _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Feb 22 00:35:00 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 22 Feb 2012 10:35:00 +1100 Subject: [Tutor] Checking for file completion. In-Reply-To: References: <4F43E2DD.3090009@davea.name> <4F4412F9.1010108@davea.name> Message-ID: <4F442A24.3030705@pearwood.info> Tony Pelletier wrote: >> Missing a return statement in the case of an exception. > > Can you explain this? Why would I want the return on the exception? Because if you don't, it will return None. -- Steven From williamjstewart at rogers.com Wed Feb 22 00:51:39 2012 From: williamjstewart at rogers.com (William Stewart) Date: Tue, 21 Feb 2012 15:51:39 -0800 (PST) Subject: [Tutor] how to rewrite area.py Message-ID: <1329868299.29511.YahooMailClassic@web88611.mail.bf1.yahoo.com> hello I need to rewrite area.py program so that it has separate functions for the perimeter and area of a square, a rectangle, and a circle (3.14 * radius**2). I am horrible at math and I cannot even figure out what I need to do for this Any help would be appreciated All I have is the menu which looks like this ? ? ? ? import math print "your options are:" print " " print "1) Area(SQUARE)" print "2) Area(RECTANGLE)" print "3) Area(CIRCLE)" print "4) Perimeter(SQUARE)" print "5) Perimeter(RECTANGLE)" print "6) Perimeter(CIRCLE)" print "7) Exit" while True: ??? selection = raw_input("Please select an option from the menu.: ") python area.py print "Calculate information about a rectangle" length = input("Length:") width = input("Width:") print "Area",length*width print "Perimeter",2*length+2*width print 'To find the area of a rectangle,' print 'Enter the width and height below.' print w = input('Width:? ') while w <= 0: ??? print 'Must be a positive number' ??? w = input('Width:? ') h = input('Height: ') while h <= 0: ??? print 'Must be a positive number' ??? h = input('Height: ') print 'Width =',w,' Height =',h,' so Area =',area(w,h) -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Wed Feb 22 01:17:07 2012 From: d at davea.name (Dave Angel) Date: Tue, 21 Feb 2012 19:17:07 -0500 Subject: [Tutor] how to rewrite area.py In-Reply-To: <1329868299.29511.YahooMailClassic@web88611.mail.bf1.yahoo.com> References: <1329868299.29511.YahooMailClassic@web88611.mail.bf1.yahoo.com> Message-ID: <4F443403.6070101@davea.name> On 02/21/2012 06:51 PM, William Stewart wrote: > hello > I need to rewrite area.py program so that it has separate functions for the perimeter and area of a square, a rectangle, and a circle (3.14 * radius**2). > I am horrible at math and I cannot even figure out what I need to do for this > Any help would be appreciated > > All I have is the menu which looks like this > > > > > import math > print "your options are:" > print " " > print "1) Area(SQUARE)" > print "2) Area(RECTANGLE)" > print "3) Area(CIRCLE)" > print "4) Perimeter(SQUARE)" > print "5) Perimeter(RECTANGLE)" > print "6) Perimeter(CIRCLE)" > print "7) Exit" > while True: > selection = raw_input("Please select an option from the menu.: ") > python area.py > > print "Calculate information about a rectangle" > length = input("Length:") > width = input("Width:") > print "Area",length*width > print "Perimeter",2*length+2*width > print 'To find the area of a rectangle,' > print 'Enter the width and height below.' > print > w = input('Width: ') > while w<= 0: > print 'Must be a positive number' > w = input('Width: ') > h = input('Height: ') > while h<= 0: > print 'Must be a positive number' > h = input('Height: ') > print 'Width =',w,' Height =',h,' so Area =',area(w,h) > Just what don't you understand? If it's really just the math, then go ahead and write dummy versions of the needed functions and control structures, and then ask for help modifying the code. There are bugs in the present code that have nothing to do with math, and I'm not just referring to the line "python area.py". -- DaveA From steve at pearwood.info Wed Feb 22 01:25:32 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 22 Feb 2012 11:25:32 +1100 Subject: [Tutor] how to rewrite area.py In-Reply-To: <1329868299.29511.YahooMailClassic@web88611.mail.bf1.yahoo.com> References: <1329868299.29511.YahooMailClassic@web88611.mail.bf1.yahoo.com> Message-ID: <4F4435FC.10608@pearwood.info> William Stewart wrote: > hello > I need to rewrite area.py program so that it has separate functions for the perimeter and area of a square, a rectangle, and a circle (3.14 * radius**2). > I am horrible at math and I cannot even figure out what I need to do for this > Any help would be appreciated Have you learned about functions? Here's an example. Put this in a file and try it. def get_drink(): answer = raw_input("Would you like a cup of tea? (y/n) ").lower() while answer not in ('y', 'yes', 'n', 'no'): print "I'm sorry, I don't understand that response." print "Please enter Yes or No." answer = raw_input("Would you like a cup of tea? (y/n) ").lower() if answer in ('y', 'yes'): return "a nice steaming cup of tea, with a couple of biscuits" else: return "a stale cup of bitter coffee" drink = get_drink() print "I have", drink Notice a few things: First, you define a function with the "def" keyword, and give it a name, in this case, "get_drink". Names should usually be verbs ("doing words"), because functions do things. Second, the function normally should use the "return" statement to send a result back to the caller. Third, you call the function by name, using round brackets (parentheses) to indicate to Python that you are calling it, and save the result in a variable ("drink" in the above example). And finally, you can then use the variable for further processing. In your case, you want six functions, to get the area of a square, the perimeter of a rectangle, etc. So for each function, you need to decide on a descriptive name, such as this: def get_area_of_square(): # Ask the user for the width of the square. ... # Calculate the area. area = width**2 return area The dots ... need to be filled in by you. Your program already has code that asks the user for a width, just grab it and put it inside the function. The formulae you need are: SQUARES: area = width*width = width**2 perimeter = width+width+width+width = 4*width RECTANGLES: area = width*height perimeter = width+height+width+height = 2*(width+height) CIRCLES: area = pi*radius**2 circumference = 2*pi*radius To get the value of pi, put this at the top of your program: from math import pi Hope this helps. -- Steven From bgailer at gmail.com Wed Feb 22 01:27:14 2012 From: bgailer at gmail.com (bob gailer) Date: Tue, 21 Feb 2012 19:27:14 -0500 Subject: [Tutor] how to rewrite area.py In-Reply-To: <1329868299.29511.YahooMailClassic@web88611.mail.bf1.yahoo.com> References: <1329868299.29511.YahooMailClassic@web88611.mail.bf1.yahoo.com> Message-ID: <4F443662.40706@gmail.com> On 2/21/2012 6:51 PM, William Stewart wrote: > hello > I need to rewrite area.py program so that it has separate functions > for the perimeter and area of a square, a rectangle, and a circle > (3.14 * radius**2). > "Need to"" - why? Is this a homework assignment? > I am horrible at math and I cannot even figure out what I need to do > for this > Any help would be appreciated > All I have is the menu which looks like this > Did you run this program? What results did you get? How did they differ from what you expected? What does being "horrible at mat" have to do with this? What do you know about defining functions? Did you write this program yourself? If you are taking a Python class and don't know what to do either the class is poorly designed or you are in the wrong class. Please say more about this. We are glad to help, but won't write your homework for you. > import math > print "your options are:" > print " " > print "1) Area(SQUARE)" > print "2) Area(RECTANGLE)" > print "3) Area(CIRCLE)" > print "4) Perimeter(SQUARE)" > print "5) Perimeter(RECTANGLE)" > print "6) Perimeter(CIRCLE)" > print "7) Exit" > while True: > selection = raw_input("Please select an option from the menu.: ") > python area.py > > print "Calculate information about a rectangle" > length = input("Length:") > width = input("Width:") > print "Area",length*width > print "Perimeter",2*length+2*width > print 'To find the area of a rectangle,' > print 'Enter the width and height below.' > print > w = input('Width: ') > while w <= 0: > print 'Must be a positive number' > w = input('Width: ') > h = input('Height: ') > while h <= 0: > print 'Must be a positive number' > h = input('Height: ') > print 'Width =',w,' Height =',h,' so Area =',area(w,h) > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From sukhpreet2294sidhu at ymail.com Wed Feb 22 01:40:57 2012 From: sukhpreet2294sidhu at ymail.com (Sukhpreet Sdhu) Date: Wed, 22 Feb 2012 06:10:57 +0530 (IST) Subject: [Tutor] Python assginment Message-ID: <1329871257.10880.YahooMailNeo@web137610.mail.in.yahoo.com> hi i m working on Python assignment to convert roman numericals to arabic and vice versa.I had tried many different codes but those are not working. Can you please suggest me the code to do this by using while , if and else statements. thanks Sukhpreet Sidhu -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Feb 22 01:46:03 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 22 Feb 2012 00:46:03 +0000 Subject: [Tutor] how to rewrite area.py In-Reply-To: <1329868299.29511.YahooMailClassic@web88611.mail.bf1.yahoo.com> References: <1329868299.29511.YahooMailClassic@web88611.mail.bf1.yahoo.com> Message-ID: On 21/02/12 23:51, William Stewart wrote: > I need to rewrite area.py program so that it has separate functions for > the perimeter and area of a square, a rectangle, and a circle (3.14 * > radius**2). You will find something similar in my tutorial in the topic Branching. Look under the heading "Python multi-selection" and there is some code you should be able to include as template. Have a go and come back with questions. > I am horrible at math and I cannot even figure out what I need to do for > this Steven has done the math bit for you, so just plug it into the python code you need. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Wed Feb 22 01:48:26 2012 From: d at davea.name (Dave Angel) Date: Tue, 21 Feb 2012 19:48:26 -0500 Subject: [Tutor] Python assginment In-Reply-To: <1329871257.10880.YahooMailNeo@web137610.mail.in.yahoo.com> References: <1329871257.10880.YahooMailNeo@web137610.mail.in.yahoo.com> Message-ID: <4F443B5A.60209@davea.name> On 02/21/2012 07:40 PM, Sukhpreet Sdhu wrote: > hi > i m working on Python assignment to convert roman numericals to arabic and vice versa.I had tried many different codes but those are not working. > Can you please suggest me the code to do this by using while , if and else statements. > thanks > Sukhpreet Sidhu You need to indent the code following the if statement on line 244. Or if you haven't tried, you might want to attempt a few lines before asking for help here. -- DaveA From alan.gauld at btinternet.com Wed Feb 22 02:01:50 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 22 Feb 2012 01:01:50 +0000 Subject: [Tutor] Pyhton editor In-Reply-To: <1329866941.17077.YahooMailNeo@web39302.mail.mud.yahoo.com> References: <191359495-1329536853-cardhu_decombobulator_blackberry.rim.net-55059483-@b13.c5.bise3.blackberry> <5B80DD153D7D744689F57F4FB69AF474155C86@SCACMX008.exchad.jpmchase.net> <1329866941.17077.YahooMailNeo@web39302.mail.mud.yahoo.com> Message-ID: On 21/02/12 23:29, ken brockman wrote: > I concur. Pyscripter , though I've only installed it a few days ago, > seems to be one of the better ones. I played with it when I had Windows but it seemed to e tied to a specific version of Python. Has that changed? > i love the simply way you can use tkinter from a server? > No muss no fuss. Can you elaborate on that? I have no idea what you mean? You can run a tkinter program on a server and display it on your local PC using X, but that has nothing to do with Pyscripter? And not much to do with tkinter for that matter! I assume you mean something else? > understand that the way it had been built, it can't be readily ported to > Linux. Mores the pity. I seem to recall it was written in Borland's Delphi. There is FreePascal which is very Delphi like, although not quite a clone, it might be possible to port it to FreePascal if somebody was keen enough! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cyclicflux at yahoo.com Wed Feb 22 03:57:13 2012 From: cyclicflux at yahoo.com (cyclicflux at yahoo.com) Date: Tue, 21 Feb 2012 21:57:13 -0500 Subject: [Tutor] Python Editor In-Reply-To: References: Message-ID: <74b42202-fcbd-47bc-9ad6-375def84fa73@blur> I agree, pyscripter if using windows used to be my favorite, and is in the top 3 favorite python editors. Based on your tastes and your editor selection I'd say that you might like another batteries-included(not much config, autocomplete, ability to test code/etc... ) editor for python native to both Windows & Linux would be that of Aptana Studio(primary focus is that of web), customized from eclipse however depending on the distro you use is may have to be compiled. But pydev(Aptana's python-based plugin) is included with Aptana Studio. If indeed the lack of a pre-configured system-ready package/compiling from source is not enticing, then one can use the pkg-management conducive to your distro and install eclipse(as most distros have that). Then go to the plug-in installation in Eclipse's help menu and install pydev, from I believe http://pydev.org. Its def. A great editor, and I have used it alot, and the fact both windows, and linux use it your able to seamlessly resume your work no matter what os your using. But Wine most certainly isnt bad and I have gotten if memory serves me correctly pyscripter to work on my archlinux install. Some other editors that are more so geared towards python development on linux are cream/pida, eric, & spyder(probably most similar to pyscripter). My one concern with pyscripter I believe is that its not being updated currently(I could be wrong, but I think thats what I last saw. ). Good luck! Will Sent from my Verizon Wireless Phone -----Original message----- From: tutor-request at python.org To: tutor at python.org Sent: Wed, Feb 22, 2012 00:28:23 GMT+00:00 Subject: Tutor Digest, Vol 96, Issue 89 Send Tutor mailing list submissions to tutor at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-request at python.org You can reach the person managing the list at tutor-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Re: Pyhton editor (ken brockman) 2. Re: Checking for file completion. (Steven D'Aprano) 3. how to rewrite area.py (William Stewart) 4. Re: how to rewrite area.py (Dave Angel) 5. Re: how to rewrite area.py (Steven D'Aprano) ---------------------------------------------------------------------- Message: 1 Date: Tue, 21 Feb 2012 15:29:01 -0800 (PST) From: ken brockman To: "Prasad, Ramit" , "tutor at python.org" Subject: Re: [Tutor] Pyhton editor Message-ID: <1329866941.17077.YahooMailNeo at web39302.mail.mud.yahoo.com> Content-Type: text/plain; charset="iso-8859-1" ________________________________ From: "Prasad, Ramit" To: "tutor at python.org" Sent: Tuesday, February 21, 2012 10:08 AM Subject: Re: [Tutor] Pyhton editor >>However I stumbled upon PyScripter and I find it really amazing. >Pity it is only for Windows. WINE? Ramit I?concur. Pyscripter , though?I've?only installed it a few days ago, seems to be one of the better ones. I am?running?it in a virtualbox winXP on top of?Linux?Ubuntu, but i love the simply way you can use tkinter from a server? No muss no fuss. Just install and go. I understand that the way it had been built, it can't be readily ported to Linux. Mores the pity. Ken Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email.? _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 2 Date: Wed, 22 Feb 2012 10:35:00 +1100 From: Steven D'Aprano To: Python Tutor Subject: Re: [Tutor] Checking for file completion. Message-ID: <4F442A24.3030705 at pearwood.info> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Tony Pelletier wrote: >> Missing a return statement in the case of an exception. > > Can you explain this? Why would I want the return on the exception? Because if you don't, it will return None. -- Steven ------------------------------ Message: 3 Date: Tue, 21 Feb 2012 15:51:39 -0800 (PST) From: William Stewart To: tutor at python.org Subject: [Tutor] how to rewrite area.py Message-ID: <1329868299.29511.YahooMailClassic at web88611.mail.bf1.yahoo.com> Content-Type: text/plain; charset="iso-8859-1" hello I need to rewrite area.py program so that it has separate functions for the perimeter and area of a square, a rectangle, and a circle (3.14 * radius**2). I am horrible at math and I cannot even figure out what I need to do for this Any help would be appreciated All I have is the menu which looks like this ? ? ? ? import math print "your options are:" print " " print "1) Area(SQUARE)" print "2) Area(RECTANGLE)" print "3) Area(CIRCLE)" print "4) Perimeter(SQUARE)" print "5) Perimeter(RECTANGLE)" print "6) Perimeter(CIRCLE)" print "7) Exit" while True: ??? selection = raw_input("Please select an option from the menu.: ") python area.py print "Calculate information about a rectangle" length = input("Length:") width = input("Width:") print "Area",length*width print "Perimeter",2*length+2*width print 'To find the area of a rectangle,' print 'Enter the width and height below.' print w = input('Width:? ') while w <= 0: ??? print 'Must be a positive number' ??? w = input('Width:? ') h = input('Height: ') while h <= 0: ??? print 'Must be a positive number' ??? h = input('Height: ') print 'Width =',w,' Height =',h,' so Area =',area(w,h) -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 4 Date: Tue, 21 Feb 2012 19:17:07 -0500 From: Dave Angel To: William Stewart Cc: tutor at python.org Subject: Re: [Tutor] how to rewrite area.py Message-ID: <4F443403.6070101 at davea.name> Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 02/21/2012 06:51 PM, William Stewart wrote: > hello > I need to rewrite area.py program so that it has separate functions for the perimeter and area of a square, a rectangle, and a circle (3.14 * radius**2). > I am horrible at math and I cannot even figure out what I need to do for this > Any help would be appreciated > > All I have is the menu which looks like this > > > > > import math > print "your options are:" > print " " > print "1) Area(SQUARE)" > print "2) Area(RECTANGLE)" > print "3) Area(CIRCLE)" > print "4) Perimeter(SQUARE)" > print "5) Perimeter(RECTANGLE)" > print "6) Perimeter(CIRCLE)" > print "7) Exit" > while True: > selection = raw_input("Please select an option from the menu.: ") > python area.py > > print "Calculate information about a rectangle" > length = input("Length:") > width = input("Width:") > print "Area",length*width > print "Perimeter",2*length+2*width > print 'To find the area of a rectangle,' > print 'Enter the width and height below.' > print > w = input('Width: ') > while w<= 0: > print 'Must be a positive number' > w = input('Width: ') > h = input('Height: ') > while h<= 0: > print 'Must be a positive number' > h = input('Height: ') > print 'Width =',w,' Height =',h,' so Area =',area(w,h) > Just what don't you understand? If it's really just the math, then go ahead and write dummy versions of the needed functions and control structures, and then ask for help modifying the code. There are bugs in the present code that have nothing to do with math, and I'm not just referring to the line "python area.py". -- DaveA ------------------------------ Message: 5 Date: Wed, 22 Feb 2012 11:25:32 +1100 From: Steven D'Aprano To: tutor at python.org Subject: Re: [Tutor] how to rewrite area.py Message-ID: <4F4435FC.10608 at pearwood.info> Content-Type: text/plain; charset=ISO-8859-1; format=flowed William Stewart wrote: > hello > I need to rewrite area.py program so that it has separate functions for the perimeter and area of a square, a rectangle, and a circle (3.14 * radius**2). > I am horrible at math and I cannot even figure out what I need to do for this > Any help would be appreciated Have you learned about functions? Here's an example. Put this in a file and try it. def get_drink(): answer = raw_input("Would you like a cup of tea? (y/n) ").lower() while answer not in ('y', 'yes', 'n', 'no'): print "I'm sorry, I don't understand that response." print "Please enter Yes or No." answer = raw_input("Would you like a cup of tea? (y/n) ").lower() if answer in ('y', 'yes'): return "a nice steaming cup of tea, with a couple of biscuits" else: return "a stale cup of bitter coffee" drink = get_drink() print "I have", drink Notice a few things: First, you define a function with the "def" keyword, and give it a name, in this case, "get_drink". Names should usually be verbs ("doing words"), because functions do things. Second, the function normally should use the "return" statement to send a result back to the caller. Third, you call the function by name, using round brackets (parentheses) to indicate to Python that you are calling it, and save the result in a variable ("drink" in the above example). And finally, you can then use the variable for further processing. In your case, you want six functions, to get the area of a square, the perimeter of a rectangle, etc. So for each function, you need to decide on a descriptive name, such as this: def get_area_of_square(): # Ask the user for the width of the square. ... # Calculate the area. area = width**2 return area The dots ... need to be filled in by you. Your program already has code that asks the user for a width, just grab it and put it inside the function. The formulae you need are: SQUARES: area = width*width = width**2 perimeter = width+width+width+width = 4*width RECTANGLES: area = width*height perimeter = width+height+width+height = 2*(width+height) CIRCLES: area = pi*radius**2 circumference = 2*pi*radius To get the value of pi, put this at the top of your program: from math import pi Hope this helps. -- Steven ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 96, Issue 89 ************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: From mjolewis at gmail.com Wed Feb 22 04:00:40 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Tue, 21 Feb 2012 19:00:40 -0800 Subject: [Tutor] Recognizing real numbers Message-ID: Hi everyone, I have some code where I import a file to use a module. That module that I import takes text and a multiplier, checks for any numbers in that text and will then multiply those numbers by the given multiplier. The imported module is below. I am getting the text from a file that I have which starts out as: .5 lb. butter 1.75 Cups Graham Cracker Crumbs 2.0 Cups Powder Sugar 1.0 Cups Peanut Butter 2.0 Cups Semi-sweet Chocolate Chips It seems that the .isdigit() function that I use doesn't recognize the .5 as a number and therefore doesn't multiply it. How can I get my code to recognize numbers such as .5, 1.75 as numbers? Imported module: def MultiplyText(text, multiplier): '''Recieve a S & int. For digits in S, multiply by multiplier and return updated S.''' return ' '.join(str(float(num) * multiplier) if num.isdigit() else num for num in text) Module doing the importing/opening/reading/creating a new file import Homework5_1 as multiply def DoubleDigits(file_name): '''Open file/read file/write new file that doubles all int's in the read file''' try: read_file = open(file_name) except IOError: return 'No such file.' new_file_name = file_name + '2' try: write_file = open(new_file_name, 'w') except IOError: read_file.close() return 'No such file to write to.' for line in read_file: new_line = line.split() new_line = ''.join(multiply.MultiplyText(new_line, 2)) write_file.write(new_line + '\n') read_file.close() write_file.close() def main(): DoubleDigits(raw_input('What file do you want to open? ')) if '__name__' == '__main__': print main() Output that is written to my file: Peanut Butter Bars Ingredients .5 lb. butter 1.75 Cups Graham Cracker Crumbs 4.0 Cups Powder Sugar 2.0 Cups Peanut Butter 4.0 Cups Semi-sweet Chocolate Chips Melt butter. Add graham cracker crumbs, peanut butter and sugar. Mix well and pat into sheet pan. Cover with melted chocolate. Refrigerate until semi-firm, then cut into squares. -- Michael J. Lewis -------------- next part -------------- An HTML attachment was scrubbed... URL: From krush1954 at yahoo.com Wed Feb 22 05:00:17 2012 From: krush1954 at yahoo.com (ken brockman) Date: Tue, 21 Feb 2012 20:00:17 -0800 (PST) Subject: [Tutor] Pyhton editor In-Reply-To: References: <191359495-1329536853-cardhu_decombobulator_blackberry.rim.net-55059483-@b13.c5.bise3.blackberry> <5B80DD153D7D744689F57F4FB69AF474155C86@SCACMX008.exchad.jpmchase.net> <1329866941.17077.YahooMailNeo@web39302.mail.mud.yahoo.com> Message-ID: <1329883217.31582.YahooMailNeo@web39301.mail.mud.yahoo.com> ________________________________ Pyscripter.. I played with it when I had Windows but it seemed to e tied to a specific version of Python. Has that changed? ? *I have no clue which version you had ran it with, I am using it with Python 3.2.2 and it works great. > i love the simply way you can use tkinter from a server? > No muss no fuss. Can you elaborate on that? I have no idea what you mean? ?*As I had said, I had just played with it for a half an hour or so. I had seen remote listed in the menu, and had assumed it had to do with tkinter and Wx not being os based. What's that old chestnut about not assuming.. This is from the Pyscripter doc: ??? ??Remote Tk This remote Python engine is specifically created to run and debug Tkinter applications including pylabusing the Tkagg backend. It also supports running pylab in interactive mode. The engine activates a Tkinter mainloop and replaces the mainloop with a dummy function so that the Tkinter scripts you are running or debugging do not block the engine.? You may even develop and test Tkinter widgets using the interactive console. Being a?neophyte to Python, I was under the impression that you had to install tkinter independently.of python.This was a fresh install of WinXp, unless it either comes bundles with windows or Python, I was surprised it was there to load. -- Alan G Ken _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From elainahyde at gmail.com Wed Feb 22 06:44:57 2012 From: elainahyde at gmail.com (Elaina Ann Hyde) Date: Wed, 22 Feb 2012 16:44:57 +1100 Subject: [Tutor] Reading/dealing/matching with truly huge (ascii) files Message-ID: So, Python question of the day: I have 2 files that I could normally just read in with asciitable, The first file is a 12 column 8000 row table that I have read in via asciitable and manipulated. The second file is enormous, has over 50,000 rows and about 20 columns. What I want to do is find the best match for (file 1 column 1 and 2) with (file 2 column 4 and 5), return all rows that match from the huge file, join them togeather and save the whole mess as a file with 8000 rows (assuming the smaller table finds one match per row) and 32=12+20 columns. So my read code so far is as follows: ------------------------------------------------- import sys import asciitable import matplotlib import scipy import numpy as np from numpy import * import math import pylab import random from pylab import * import astropysics import astropysics.obstools import astropysics.coords x=small_file #cannot read blank values (string!) if blank insert -999.99 dat=asciitable.read(x,Reader=asciitable.CommentedHeader, fill_values=['','-999.99']) y=large_file fopen2=open('cfile2match.list','w') dat2=asciitable.read(y,Reader=asciitable.CommentedHeader, fill_values=['','-999.99']) #here are the 2 values for the small file Radeg=dat['ra-drad']*180./math.pi Decdeg=dat['dec-drad']*180./math.pi #here are the 2 values for the large file Radeg2=dat2['ra-drad']*180./math.pi Decdeg2=dat2['dec-drad']*180./math.pi for i in xrange(len(Radeg)): for j in xrange(len(Radeg2)): #select the value if it is very, very, very close if i != j and Radeg[i] <= (Radeg2[j]+0.000001) and Radeg[i] >= (Radeg2[j]-0.000001) and Decdeg[i] <= (Decdeg2[j]+0.000001) and Decdeg[i] >= (Decdeg2[j]-0.000001): fopen.write( " ".join([str(k) for k in list(dat[i])])+" "+" ".join([str(k) for k in list(dat[j])])+"\n") ------------------------------------------- Now this is where I had to stop, this is way, way too long and messy. I did a similar approach with smaller (9000 lines each) files and it worked but took awhile, the problem here is I am going to have to play with the match range to return the best result and give only one (1!) match per row for my smaller file, i.e. row 1 of small file must match only 1 row of large file..... then I just need to return them both. However, it isn't clear to me that this is the best way forward. I have been changing the xrange to low values to play with the matching, but I would appreciate any ideas. Thanks ~Elaina -- PhD Candidate Department of Physics and Astronomy Faculty of Science Macquarie University North Ryde, NSW 2109, Australia -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Feb 22 08:34:51 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 22 Feb 2012 18:34:51 +1100 Subject: [Tutor] Pyhton editor In-Reply-To: References: <191359495-1329536853-cardhu_decombobulator_blackberry.rim.net-55059483-@b13.c5.bise3.blackberry> <5B80DD153D7D744689F57F4FB69AF474155C86@SCACMX008.exchad.jpmchase.net> <1329866941.17077.YahooMailNeo@web39302.mail.mud.yahoo.com> Message-ID: <20120222073450.GA5661@ando> On Wed, Feb 22, 2012 at 01:01:50AM +0000, Alan Gauld wrote: > I seem to recall it was written in Borland's Delphi. > There is FreePascal which is very Delphi like, although not quite a > clone, it might be possible to port it to FreePascal if somebody was > keen enough! There is also GNU Pascal, which supports Borland Pascal 7 and some Delphi features. http://www.gnu-pascal.de/gpc/h-index.html -- Steven From steve at pearwood.info Wed Feb 22 08:47:06 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 22 Feb 2012 18:47:06 +1100 Subject: [Tutor] Recognizing real numbers In-Reply-To: References: Message-ID: <20120222074705.GB5661@ando> On Tue, Feb 21, 2012 at 07:00:40PM -0800, Michael Lewis wrote: > It seems that the .isdigit() function that I use doesn't recognize the .5 > as a number and therefore doesn't multiply it. How can I get my code to > recognize numbers such as .5, 1.75 as numbers? As the saying goes, it is often Easier to Ask for Forgiveness than Permission ("EAFP"). In Python terms, that means when you want to do something, just do it, and then catch the exception if it fails. Wrap this in a function, and it allows you to use a nifty Look Before You Leap ("LBYL") style of programming: def isfloat(obj): """Return True if obj is a number or string-like floating point number. """ try: float(obj) except (TypeError, ValueError): return False else: # no errors return True And some examples of it in use: >>> isfloat("123.456") True >>> isfloat("123.45...6") False >>> isfloat(".1") True >>> isfloat("1.1e6") # 1.1 million True >>> isfloat("1.1g6") False >>> isfloat("+.1") True >>> isfloat(".") False -- Steven From steve at pearwood.info Wed Feb 22 08:53:17 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 22 Feb 2012 18:53:17 +1100 Subject: [Tutor] Python assginment In-Reply-To: <1329871257.10880.YahooMailNeo@web137610.mail.in.yahoo.com> References: <1329871257.10880.YahooMailNeo@web137610.mail.in.yahoo.com> Message-ID: <20120222075317.GC5661@ando> On Wed, Feb 22, 2012 at 06:10:57AM +0530, Sukhpreet Sdhu wrote: > hi > i m working on Python assignment to convert roman numericals to arabic and vice versa.I had tried many different codes but those are not working. > Can you please suggest me the code to do this by using while , if and else statements. Everything you need to know to solve this problem can be found at this website: http://catb.org/esr/faqs/smart-questions.html Please read it, and then if you have any more questions, come back and ask and we'll see what we can do to help. -- Steven From alan.gauld at btinternet.com Wed Feb 22 09:31:23 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 22 Feb 2012 08:31:23 +0000 Subject: [Tutor] Reading/dealing/matching with truly huge (ascii) files In-Reply-To: References: Message-ID: On 22/02/12 05:44, Elaina Ann Hyde wrote: > file is enormous, has over 50,000 rows and about 20 columns. On modern computers its not that enormous - probably around 10M? But there are techniques for this which we can cover another time is you do hit files bigger than fit in memory. I didn't go through the code in detail. but... e = 0.000001 if i != j and Radeg[i] <= (Radeg2[j]+e) and Radeg[i] >= (Radeg2[j]-e) and Decdeg[i] <= (Decdeg2[j]+e) and Decdeg[i] >= (Decdeg2[j]-e): Using e helps tune the precision as needed. That layout style will help you see the logic more easily. But in Python you can tidy that up even more by rewriting it like if i != j and (Radeg2[j]-e) <= Radeg[i] <= (Radeg2[j]+e) and (Decdeg2[j]-e) <= Decdeg[i] <= (Decdeg2[j]+e): And you could put it in a function to further control readability of the main program and encapsulate the tests. def rowsEquate(row1,row2, i, j):... if i != j and rowsEquate(Radeg,Radeg2,i,j) and rowsEquate(Deceg, Deceg2,i,j): > fopen.write( " ".join([str(k) for k in list(dat[i])])+" > "+" ".join([str(k) for k in list(dat[j])])+"\n") I may be wrong but it looks like something wrong with the quoting there? The last quote on the first line, after the +? > ------------------------------------------- > Now this is where I had to stop, this is way, way too long and messy. Its not really that long or messy, but it could be tidied up a little. > did a similar approach with smaller (9000 lines each) files and it > worked but took awhile, This might be the biggest problem, it will take a long time on big files. Personally I would tend to tackle a problem like this using a database and write a query to select the rows that match in one operation. Especially if I had to process a lot of files. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Feb 22 09:35:21 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 22 Feb 2012 08:35:21 +0000 Subject: [Tutor] Pyhton editor In-Reply-To: <1329883217.31582.YahooMailNeo@web39301.mail.mud.yahoo.com> References: <191359495-1329536853-cardhu_decombobulator_blackberry.rim.net-55059483-@b13.c5.bise3.blackberry> <5B80DD153D7D744689F57F4FB69AF474155C86@SCACMX008.exchad.jpmchase.net> <1329866941.17077.YahooMailNeo@web39302.mail.mud.yahoo.com> <1329883217.31582.YahooMailNeo@web39301.mail.mud.yahoo.com> Message-ID: On 22/02/12 04:00, ken brockman wrote: > Being a neophyte to Python, I was under the impression that you had to > install tkinter independently.of python. No, its part of the standard library. On some *nix installs tk support is not compiled in but tkinter should be there. But on Windows its always there. Running it in a separate thread sounds like what this feature is doing. But IDLE has been doing that for the last several releases too (since v2.5?) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Wed Feb 22 09:54:13 2012 From: wprins at gmail.com (Walter Prins) Date: Wed, 22 Feb 2012 08:54:13 +0000 Subject: [Tutor] Reading/dealing/matching with truly huge (ascii) files In-Reply-To: References: Message-ID: Hi Elaina, On 22 February 2012 05:44, Elaina Ann Hyde wrote: > #select the value if it is very, very, very close > ??????????????? if i != j and Radeg[i] <= (Radeg2[j]+0.000001) and Radeg[i] Alan's pretty much said what I was thinking, but I have an additional question/concern: Why do you include the i != j condition in your if statement? This is saying that you never want to compare entries from the 2 files if they're on the same row number? Is that actually intentional and correct or not? (It seems somehow wrong to me since you've not said anything about it in your post, and everything else suggests you're comparing only the data values to select your output records...) Walter From steve at pearwood.info Wed Feb 22 10:00:03 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 22 Feb 2012 20:00:03 +1100 Subject: [Tutor] Reading/dealing/matching with truly huge (ascii) files In-Reply-To: References: Message-ID: <20120222090003.GD5661@ando> On Wed, Feb 22, 2012 at 04:44:57PM +1100, Elaina Ann Hyde wrote: > So, Python question of the day: I have 2 files that I could normally just > read in with asciitable, The first file is a 12 column 8000 row table that > I have read in via asciitable and manipulated. The second file is > enormous, has over 50,000 rows and about 20 columns. What I want to do is > find the best match for (file 1 column 1 and 2) with (file 2 column 4 and > 5), return all rows that match from the huge file, join them togeather and > save the whole mess as a file with 8000 rows (assuming the smaller table > finds one match per row) and 32=12+20 columns. I don't know much about asciitable, so I'm going to have to guess what some of your code does. I think the critical part is where you grab a column from each file: Radeg=dat['ra-drad']*180./math.pi Decdeg=dat['dec-drad']*180./math.pi Radeg2=dat2['ra-drad']*180./math.pi Decdeg2=dat2['dec-drad']*180./math.pi and then compare them, element by element: for i in xrange(len(Radeg)): for j in xrange(len(Radeg2)): #select the value if it is very, very, very close ... The selection criteria is messy and complicated. Start by cleaning it up: elegant code is easier to work with. The first step is to operate on items in the columns directly, rather than indirectly via an index value. Instead of writing your for-loops like this: for i in xrange(len(column)): do something with column[i] do another thing with column[i] Python can iterate over the values in the column directly: for x in column: do something with x do another thing with x You don't save any lines, but you gain a lot of clarity without the unnecessary indirection. Disclaimer: I have never used asciitable, and it is possible that asciitable's column type does not support this. If not, that's pretty awful design! But you can rescue the situation by manually assigning to a variable inside the loop: for i in xrange(len(column)): x = column[i] do something with x do another thing with x If you need the index as well, use the enumerate function: for i, x in enumerate(column): ... Using that form, if column = [1.1, 2.2, 3.3, ...] then (i, x) will take the values (0, 1.1), (1, 2.2), (2, 3.3) ... However, in your case, you have not one column but two. This is where the zip function comes to the rescue, it lines the columns up like teeth in a zipper: delta = 0.000001 for i, (a, b) in enumerate(zip(Radeg, Decdeg)): for j, (c, d) in enumerate(zip(Radeg2, Decdeg2)): if i == j: # skip an iteration -- but why???? continue if a <= c+delta and a >= c-delta \ and b <= d+delta and b >= d-delta: write_stuff_to_file(...) Now we can simplify the selection criteria: delta = 0.000001 for i, (a, b) in enumerate(zip(Radeg, Decdeg)): for j, (c, d) in enumerate(zip(Radeg2, Decdeg2)): if i == j: # skip an iteration -- but why???? continue if c-delta <= a <= c+delta and d-delta <= b <= d+delta: write_stuff_to_file(...) Already easier to read. (And also likely to be a little faster, although not enough to really make a difference.) Or at least, I find it easier to read, and I hope you do too! You're comparing the (a,b) values from the small file (8,000 rows) with each of the (c,d) values from the large file (50,000 rows). You will have to compare 8000*50000=400 million values, which isn't going to be fast in Python unless you can avoid some of those comparisons. If you can assume that there will only be one match per row, then once you have found that match, you can skip to the next iteration of the outer loop by breaking out of the inner loop, and avoid 42,000+ comparisons per row! If you can do this, that will be a BIG saving. delta = 0.000001 for i, (a, b) in enumerate(zip(Radeg, Decdeg)): for j, (c, d) in enumerate(zip(Radeg2, Decdeg2)): if i == j: # skip an iteration -- but why???? continue if c-delta <= a <= c+delta and d-delta <= b <= d+delta: write_stuff_to_file(...) # there can only be one match, and we've just found it, # so go on with the next outer loop break But I don't know if that is a safe assumption to make. That depends on the semantics of your data. The next thing to look at is the "write_stuff_to_file(...)" placeholder, which I'm using to stand in for your code: fopen.write( " ".join([str(k) for k in list(dat[i])]) + " " + " ".join([str(k) for k in list(dat[j])])+"\n") and see if that can be improved, but frankly I have to go now, I'll try to come back to that later. P.S. you have: > import astropysics Is that module really called astropysics with no H? -- Steven From __peter__ at web.de Wed Feb 22 10:50:56 2012 From: __peter__ at web.de (Peter Otten) Date: Wed, 22 Feb 2012 10:50:56 +0100 Subject: [Tutor] Reading/dealing/matching with truly huge (ascii) files References: Message-ID: Elaina Ann Hyde wrote: > So, Python question of the day: I have 2 files that I could normally just > read in with asciitable, The first file is a 12 column 8000 row table that > I have read in via asciitable and manipulated. The second file is > enormous, has over 50,000 rows and about 20 columns. What I want to do is > find the best match for (file 1 column 1 and 2) with (file 2 column 4 and > 5), return all rows that match from the huge file, join them togeather and > save the whole mess as a file with 8000 rows (assuming the smaller table > finds one match per row) and 32=12+20 columns. So my read code so far is > as follows: > ------------------------------------------------- > import sys > import asciitable > import matplotlib > import scipy > import numpy as np > from numpy import * > import math > import pylab > import random > from pylab import * > import astropysics > import astropysics.obstools > import astropysics.coords > > x=small_file > #cannot read blank values (string!) if blank insert -999.99 > dat=asciitable.read(x,Reader=asciitable.CommentedHeader, > fill_values=['','-999.99']) > y=large_file > fopen2=open('cfile2match.list','w') > dat2=asciitable.read(y,Reader=asciitable.CommentedHeader, > fill_values=['','-999.99']) > #here are the 2 values for the small file > Radeg=dat['ra-drad']*180./math.pi > Decdeg=dat['dec-drad']*180./math.pi > > #here are the 2 values for the large file > Radeg2=dat2['ra-drad']*180./math.pi > Decdeg2=dat2['dec-drad']*180./math.pi > > for i in xrange(len(Radeg)): > for j in xrange(len(Radeg2)): > #select the value if it is very, very, very close > if i != j and Radeg[i] <= (Radeg2[j]+0.000001) and > Radeg[i] >>= (Radeg2[j]-0.000001) and Decdeg[i] <= (Decdeg2[j]+0.000001) and > Decdeg[i] >= (Decdeg2[j]-0.000001): > fopen.write( " ".join([str(k) for k in > list(dat[i])])+" "+" ".join([str(k) for k in list(dat[j])])+"\n") > ------------------------------------------- > Now this is where I had to stop, this is way, way too long and messy. I > did a similar approach with smaller (9000 lines each) files and it worked > but took awhile, the problem here is I am going to have to play with the > match range to return the best result and give only one (1!) match per row > for my smaller file, i.e. row 1 of small file must match only 1 row of > large file..... then I just need to return them both. However, it isn't > clear to me that this is the best way forward. I have been changing the > xrange to low values to play with the matching, but I would appreciate any > ideas. Thanks If you calculate the distance instead of checking if it's under a certain threshold you are guaranteed to get (one of the) best matches. Pseudo-code: from functools import partial big_rows = read_big_file_into_memory() def distance(small_row, big_row): ... for small_row in read_small_file(): best_match = min(big_rows, key=partial(dist, small_row)) write_to_result_file(best_match) As to the actual implementation of the distance() function, I don't understand your problem description (two columns in the first, three in the second, how does that work), but generally a, c = extract_columns_from_small_row(small_row) b, d = extract_columns_from_big_row(big_row) if (a <= b + eps) and (c <= d + eps): # it's good would typically become distance(small_row, big_row): a, c = extract_columns_from_small_row(small_row) b, d = extract_columns_from_big_row(big_row) x = a-b y = c-d return math.sqrt(x*x+y*y) From dcdavemail at gmail.com Wed Feb 22 11:57:56 2012 From: dcdavemail at gmail.com (David Craig) Date: Wed, 22 Feb 2012 10:57:56 +0000 Subject: [Tutor] return integer from function Message-ID: <4F44CA34.6030005@ucdconnect.ie> Hi, I have a function that calculates the distance between two points on a sphere. It works but I cant get it to return a float for use in another script. Anyone know how I do that?? The function is below, Thanks, D import math def distance_on_unit_sphere(lat1, long1, lat2, long2): # Convert latitude and longitude to # spherical coordinates in radians. degrees_to_radians = math.pi/180.0 # phi = 90 - latitude phi1 = (90.0 - lat1)*degrees_to_radians phi2 = (90.0 - lat2)*degrees_to_radians # theta = longitude theta1 = long1*degrees_to_radians theta2 = long2*degrees_to_radians # Compute spherical distance from spherical coordinates. # For two locations in spherical coordinates # (1, theta, phi) and (1, theta, phi) # cosine( arc length ) = # sin phi sin phi' cos(theta-theta') + cos phi cos phi' # distance = rho * arc length cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) + math.cos(phi1)*math.cos(phi2)) arc = math.acos( cos ) type(arc) arc = arc*6378.1 #print str(arc*6378.1)+' km' # Remember to multiply arc by the radius of the earth # in your favorite set of units to get length. return arc From brian.van.den.broek at gmail.com Wed Feb 22 14:13:25 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Wed, 22 Feb 2012 15:13:25 +0200 Subject: [Tutor] return integer from function In-Reply-To: <4F44CA34.6030005@ucdconnect.ie> References: <4F44CA34.6030005@ucdconnect.ie> Message-ID: On 22 February 2012 12:57, David Craig wrote: > Hi, > I have a function that calculates the distance between two points on a > sphere. It works but I cant get it to return a float for use in another > script. Anyone know how I do that?? > > ? ?cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) + > ? ? ? ? ? math.cos(phi1)*math.cos(phi2)) > ? ?arc = math.acos( cos ) > ? ?type(arc) > ? ?arc = arc*6378.1 > ? ?#print str(arc*6378.1)+' km' > ? ?# Remember to multiply arc by the radius of the earth > ? ?# in your favorite set of units to get length. > ? ?return arc Hi David, I'm a bit puzzled. A few lines above the return, you have 'type(arc)'. Try replacing that with 'print type(arc)' and also include 'print type(arc)' immediately above your return. I think you will find that the code you posted does return a float. Best, Brian vdB From dcdavemail at gmail.com Wed Feb 22 14:14:44 2012 From: dcdavemail at gmail.com (David Craig) Date: Wed, 22 Feb 2012 13:14:44 +0000 Subject: [Tutor] Create a table by writing to a text file. Message-ID: <4F44EA44.3050600@gmail.com> Hi, I have created a list of containing strings that represent distances between many different points and would like to display the results in a table. I have been trying to write them to a text file but it is difficult to organise them into rows and columns with appropriate spacing to make it readable. I would like something like, Stations Station1 Station2 Station1 0.0 33.57654 Station2 33.57654 0.0 but get, Stations Station1 Station2 Station1 0.0 33.57654 Station2 33.57654 0.0 I've tried adding spaces but to some of the values (i.e. '0.0 ') but this is very messy. Is there a better way to do this?? My code is below. Thanks D # Distance between stations from dist import dist import matplotlib.pyplot as plt import numpy as np # Guralp GPS decimal coordinates. # station = [lat, lon, alt] UFAN = [55.2333142, -7.6770179, 78.3] UCRUI = [54.9846137, -8.3771698, 75.8] UGLEN = [54.7064869, -8.7406732, 42.4] UEASK = [54.2894659, -8.9583439, 9.1] UACH = [53.8758499, -9.9621948, 22.0] ULET = [53.5519317, -9.9413447, 70.4] UHAG = [52.9393892, -9.4344939, 22.7] ULOOP = [52.5809163, -9.8456417, 10.4] UBALF = [52.1625237, -10.4099873, 74.3] ULAMB = [51.7653115, -10.1531573, 13.5] USHE = [51.5536226, -9.7907148, 115.3] UGALL = [51.529665, -8.9529546, 33.4] names = ['UFAN', 'UCRUI', 'UGLEN', 'UEASK', 'UACH', 'ULET', 'UHAG', 'ULOOP', 'UBALF', 'ULAMB', 'USHE', 'UGALL'] stations = [UFAN, UCRUI, UGLEN, UEASK, UACH, ULET, UHAG, ULOOP, UBALF, ULAMB, USHE, UGALL] distance = [[]]*len(stations) for i in range(0,len(stations)): #distance[i,0] = names[i] temp = [] for j in range(0,len(stations)): temp.append(' '+str(dist(stations[i][0],stations[i][1],stations[j][0],stations[j][1]))) distance[i] = temp testFile = open('testFile.txt', 'a') testFile.write('Stations ') for i in range(0,len(stations)): testFile.write(names[i]+' ') testFile.write('\n') for i in range(0,len(stations)): testFile.write(names[i]+' ') for j in range(0,len(stations)): testFile.write(distance[i][j]+' ') testFile.write('\n') testFile.close() From evert.rol at gmail.com Wed Feb 22 14:40:16 2012 From: evert.rol at gmail.com (Evert Rol) Date: Wed, 22 Feb 2012 14:40:16 +0100 Subject: [Tutor] Create a table by writing to a text file. In-Reply-To: <4F44EA44.3050600@gmail.com> References: <4F44EA44.3050600@gmail.com> Message-ID: <1609C037-BD99-4E03-8E12-B2BA6E8B5163@gmail.com> > Hi, > I have created a list of containing strings that represent distances between many different points and would like to display the results in a table. > I have been trying to write them to a text file but it is difficult to organise them into rows and columns with appropriate spacing to make it readable. I would like something like, > > Stations Station1 Station2 > Station1 0.0 33.57654 > Station2 33.57654 0.0 > > but get, > > Stations Station1 Station2 > Station1 0.0 33.57654 > Station2 33.57654 0.0 > > I've tried adding spaces but to some of the values (i.e. '0.0 ') but this is very messy. > Is there a better way to do this?? My code is below. This is always a tricky thing to go about. Nicely human-readable doesn't imply nicely machine readable. Sometimes a single space or a single tab between values/columns is more practical for a(nother) program to read, but not for humans. So I will work from the assummption that you want it human-readable only. In that case, have a careful read through the string formatting options: http://docs.python.org/library/stdtypes.html#string-formatting Before the two tables there, there's a point 4 which mention a minimum field width; that'd be something you could use. Eg: >>> print "|%20d|" % 10 | 10| >>> print "|%20.5f|" % 12.3456789 | 12.34568| >>> Hopefully that gets you on the way. Cheers, Evert > Thanks > D > > > # Distance between stations > > from dist import dist > import matplotlib.pyplot as plt > import numpy as np > > > # Guralp GPS decimal coordinates. > # station = [lat, lon, alt] > UFAN = [55.2333142, -7.6770179, 78.3] > UCRUI = [54.9846137, -8.3771698, 75.8] > UGLEN = [54.7064869, -8.7406732, 42.4] > UEASK = [54.2894659, -8.9583439, 9.1] > UACH = [53.8758499, -9.9621948, 22.0] > ULET = [53.5519317, -9.9413447, 70.4] > UHAG = [52.9393892, -9.4344939, 22.7] > ULOOP = [52.5809163, -9.8456417, 10.4] > UBALF = [52.1625237, -10.4099873, 74.3] > ULAMB = [51.7653115, -10.1531573, 13.5] > USHE = [51.5536226, -9.7907148, 115.3] > UGALL = [51.529665, -8.9529546, 33.4] > > names = ['UFAN', 'UCRUI', 'UGLEN', 'UEASK', 'UACH', 'ULET', 'UHAG', 'ULOOP', 'UBALF', 'ULAMB', 'USHE', 'UGALL'] > stations = [UFAN, UCRUI, UGLEN, UEASK, UACH, ULET, UHAG, ULOOP, UBALF, ULAMB, USHE, UGALL] > > distance = [[]]*len(stations) > > > for i in range(0,len(stations)): > #distance[i,0] = names[i] > temp = [] > for j in range(0,len(stations)): > temp.append(' '+str(dist(stations[i][0],stations[i][1],stations[j][0],stations[j][1]))) > distance[i] = temp > > testFile = open('testFile.txt', 'a') > testFile.write('Stations ') > > for i in range(0,len(stations)): > testFile.write(names[i]+' ') > testFile.write('\n') > > for i in range(0,len(stations)): > testFile.write(names[i]+' ') > for j in range(0,len(stations)): > testFile.write(distance[i][j]+' ') > testFile.write('\n') > testFile.close() > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From breamoreboy at yahoo.co.uk Wed Feb 22 15:03:28 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 22 Feb 2012 14:03:28 +0000 Subject: [Tutor] Create a table by writing to a text file. In-Reply-To: <1609C037-BD99-4E03-8E12-B2BA6E8B5163@gmail.com> References: <4F44EA44.3050600@gmail.com> <1609C037-BD99-4E03-8E12-B2BA6E8B5163@gmail.com> Message-ID: On 22/02/2012 13:40, Evert Rol wrote: >> Hi, > This is always a tricky thing to go about. Nicely human-readable doesn't imply nicely machine readable. Sometimes a single space or a single tab between values/columns is more practical for a(nother) program to read, but not for humans. > So I will work from the assummption that you want it human-readable only. > In that case, have a careful read through the string formatting options: http://docs.python.org/library/stdtypes.html#string-formatting > Before the two tables there, there's a point 4 which mention a minimum field width; that'd be something you could use. Eg: >>>> print "|%20d|" % 10 > | 10| >>>> print "|%20.5f|" % 12.3456789 > | 12.34568| >>>> > > Hopefully that gets you on the way. > > Cheers, > > Evert > > Note that string formatting referenced above is old style, new style can be found here http://docs.python.org/library/string.html#formatexamples -- Cheers. Mark Lawrence. From steve at pearwood.info Wed Feb 22 15:34:37 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 23 Feb 2012 01:34:37 +1100 Subject: [Tutor] Create a table by writing to a text file. In-Reply-To: <4F44EA44.3050600@gmail.com> References: <4F44EA44.3050600@gmail.com> Message-ID: <4F44FCFD.5030208@pearwood.info> David Craig wrote: > I have been trying to write them to a text file but it is difficult to > organise them into rows and columns with appropriate spacing to make it > readable. I would like something like, > > Stations Station1 Station2 > Station1 0.0 33.57654 > Station2 33.57654 0.0 [...] > I've tried adding spaces but to some of the values (i.e. '0.0 > ') but this is very messy. Try using string formatting strings. E.g.: print "%s %8.2f %8.2f" % ("station1", 0, 4) will produce this output: station1 0.00 4.00 Naturally you don't have to pass the resultant string to print. You can store it in a variable, and write it to a file: line = "%s %8.2f %8.2f" % ("station1", 0, 4) myfile.write(line + '\n') The format string codes cover a lot of options. Each code starts with a % sign, and ends with a letter s, d, f, and a few others. %s string %d decimal number %f floating point number %% use a literal percentage sign plus others Inside the format target, you can add optional terms for the field width, number of decimal points, etc. A few examples: %8.2f Pad the number to a total width of 8 (or more if necessary), using two figures after the decimal place. The number is right-justified and padded on the left with spaces. %-4.1f Pad the number to a total width of 4 (or more if necessary), using one figure after the decimal place. The number is left-justified and padded on the right with spaces. Lots more options here: http://docs.python.org/library/stdtypes.html#string-formatting-operations Alternatively, if you have Python 2.6 or newer, you can use the format method: print "{0} {1:8.2f} {2:8.2f}".format("station1", 0, 4) will produce this output: station1 0.00 4.00 See here for more options: http://docs.python.org/library/string.html#string-formatting -- Steven From __peter__ at web.de Wed Feb 22 15:51:27 2012 From: __peter__ at web.de (Peter Otten) Date: Wed, 22 Feb 2012 15:51:27 +0100 Subject: [Tutor] Create a table by writing to a text file. References: <4F44EA44.3050600@gmail.com> Message-ID: David Craig wrote: > distance = [[]]*len(stations) That doesn't do what you think it does: >>> a = [[]] * 3 >>> a [[], [], []] >>> a[0].append(42) >>> a [[42], [42], [42]] See? You get a list that contains the same list len(stations) times. Use [[] for _ in stations] instead. From steve at pearwood.info Wed Feb 22 15:18:37 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 23 Feb 2012 01:18:37 +1100 Subject: [Tutor] return integer from function In-Reply-To: <4F44CA34.6030005@ucdconnect.ie> References: <4F44CA34.6030005@ucdconnect.ie> Message-ID: <4F44F93D.8070503@pearwood.info> David Craig wrote: > Hi, > I have a function that calculates the distance between two points on a > sphere. It works but I cant get it to return a float for use in another > script. Anyone know how I do that?? You are going to have to explain what you mean in more detail. If you mean, how can you pass the output of one script as the input of another in the shell, remember that the shell communicates by passing strings through stdout and stdin. So you need to have your first script actually print its output, and then pipe it to the next script, just like you would when using shell commands. On the other hand, if you mean, how do you re-use your distance_on_unit_sphere function in another Python program, you need to import it exactly the same as you import math. For example, if your distance function is in a file "sphere.py", and you want to use it in a file "calculations.py" (say), then put this line at the top of calculations.py: import sphere and now you can use sphere.distance_on_unit_sphere just as you can use math.sin and math.cos. For this to work, though, sphere.py and calculations.py need to be in the same folder. (There are other ways to make that work, but they start getting a little tricky to get right.) On the third hand, if you mean something else, you're going to need to explain what you mean because I have no idea what it might be! :) -- Steven From dcdavemail at gmail.com Wed Feb 22 16:24:19 2012 From: dcdavemail at gmail.com (David Craig) Date: Wed, 22 Feb 2012 15:24:19 +0000 Subject: [Tutor] Create a table by writing to a text file. In-Reply-To: <1609C037-BD99-4E03-8E12-B2BA6E8B5163@gmail.com> References: <4F44EA44.3050600@gmail.com> <1609C037-BD99-4E03-8E12-B2BA6E8B5163@gmail.com> Message-ID: <4F4508A3.5030301@gmail.com> Thanks everyone, was able to get what I wanted from '/t' but I'm sure the other formatting options will be useful in future. @Peter >>> a = [[]] * 3 >>> >>> a [[], [], []] >>> >>> a[0].append(42) >>> >>> a [[42], [42], [42]] you had me worried for a minute, but a = [[]] * 3 a[0]=[1,2,3] a [[1, 2, 3], [], []] On 02/22/2012 01:40 PM, Evert Rol wrote: >> Hi, >> I have created a list of containing strings that represent distances between many different points and would like to display the results in a table. >> I have been trying to write them to a text file but it is difficult to organise them into rows and columns with appropriate spacing to make it readable. I would like something like, >> >> Stations Station1 Station2 >> Station1 0.0 33.57654 >> Station2 33.57654 0.0 >> >> but get, >> >> Stations Station1 Station2 >> Station1 0.0 33.57654 >> Station2 33.57654 0.0 >> >> I've tried adding spaces but to some of the values (i.e. '0.0 ') but this is very messy. >> Is there a better way to do this?? My code is below. > This is always a tricky thing to go about. Nicely human-readable doesn't imply nicely machine readable. Sometimes a single space or a single tab between values/columns is more practical for a(nother) program to read, but not for humans. > So I will work from the assummption that you want it human-readable only. > In that case, have a careful read through the string formatting options: http://docs.python.org/library/stdtypes.html#string-formatting > Before the two tables there, there's a point 4 which mention a minimum field width; that'd be something you could use. Eg: >>>> print "|%20d|" % 10 > | 10| >>>> print "|%20.5f|" % 12.3456789 > | 12.34568| > Hopefully that gets you on the way. > > Cheers, > > Evert > > > >> Thanks >> D >> >> >> # Distance between stations >> >> from dist import dist >> import matplotlib.pyplot as plt >> import numpy as np >> >> >> # Guralp GPS decimal coordinates. >> # station = [lat, lon, alt] >> UFAN = [55.2333142, -7.6770179, 78.3] >> UCRUI = [54.9846137, -8.3771698, 75.8] >> UGLEN = [54.7064869, -8.7406732, 42.4] >> UEASK = [54.2894659, -8.9583439, 9.1] >> UACH = [53.8758499, -9.9621948, 22.0] >> ULET = [53.5519317, -9.9413447, 70.4] >> UHAG = [52.9393892, -9.4344939, 22.7] >> ULOOP = [52.5809163, -9.8456417, 10.4] >> UBALF = [52.1625237, -10.4099873, 74.3] >> ULAMB = [51.7653115, -10.1531573, 13.5] >> USHE = [51.5536226, -9.7907148, 115.3] >> UGALL = [51.529665, -8.9529546, 33.4] >> >> names = ['UFAN', 'UCRUI', 'UGLEN', 'UEASK', 'UACH', 'ULET', 'UHAG', 'ULOOP', 'UBALF', 'ULAMB', 'USHE', 'UGALL'] >> stations = [UFAN, UCRUI, UGLEN, UEASK, UACH, ULET, UHAG, ULOOP, UBALF, ULAMB, USHE, UGALL] >> >> distance = [[]]*len(stations) >> >> >> for i in range(0,len(stations)): >> #distance[i,0] = names[i] >> temp = [] >> for j in range(0,len(stations)): >> temp.append(' '+str(dist(stations[i][0],stations[i][1],stations[j][0],stations[j][1]))) >> distance[i] = temp >> >> testFile = open('testFile.txt', 'a') >> testFile.write('Stations ') >> >> for i in range(0,len(stations)): >> testFile.write(names[i]+' ') >> testFile.write('\n') >> >> for i in range(0,len(stations)): >> testFile.write(names[i]+' ') >> for j in range(0,len(stations)): >> testFile.write(distance[i][j]+' ') >> testFile.write('\n') >> testFile.close() >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > From malaclypse2 at gmail.com Wed Feb 22 16:41:35 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 22 Feb 2012 10:41:35 -0500 Subject: [Tutor] Create a table by writing to a text file. In-Reply-To: <4F4508A3.5030301@gmail.com> References: <4F44EA44.3050600@gmail.com> <1609C037-BD99-4E03-8E12-B2BA6E8B5163@gmail.com> <4F4508A3.5030301@gmail.com> Message-ID: On Wed, Feb 22, 2012 at 10:24 AM, David Craig wrote: > you had me worried for a minute, but > a = [[]] * 3 > a[0]=[1,2,3] > a > [[1, 2, 3], [], []] > That's not the same thing. In your example you create three copies of the same empty list inside your outer list. You then throw away the first copy of the empty list and replace it with a new list. What Peter showed was mutating that inner list in place. If you aren't really, really careful, you will eventually get bitten by this if you create your lists with multiplication. >>> container = [[]] * 3 You can see that this really is three references to the exact same list: >>> print [id(item) for item in container] [17246328, 17246328, 17246328] If you replace the items, you're fine: >>> container[0] = [1, 2, 3] >>> print [id(item) for item in container] [17245808, 17246328, 17246328] But as soon as you change the contents of one of those duplicate lists, you're in trouble: >>> container[1].append('Data') >>> print container [[1, 2, 3], ['Data'], ['Data']] >>> print [id(item) for item in container] [17245808, 17246328, 17246328] >>> -- Jerry -------------- next part -------------- An HTML attachment was scrubbed... URL: From williamjstewart at rogers.com Wed Feb 22 17:00:00 2012 From: williamjstewart at rogers.com (William Stewart) Date: Wed, 22 Feb 2012 08:00:00 -0800 (PST) Subject: [Tutor] how to rewrite area.py Message-ID: <1329926400.79954.YahooMailClassic@web88607.mail.bf1.yahoo.com> On 2/21/2012 6:51 PM, William Stewart wrote: hello I need to rewrite area.py program so that it has separate functions for the perimeter and area of a square, a rectangle, and a circle (3.14 * radius**2). "Need to"" - why? Is this a homework assignment? I am horrible at math and I cannot even figure out what I need to do for this Any help would be appreciated All I have is the menu which looks like this ? ? Did you run this program? What results did you get? How did they differ from what you expected? Yes it wont run tdue to some problems in my indents but I am working on it What does being "horrible at mat" have to do with this? I dont know What do you know about defining functions? Not much Did you write this program yourself? this is new to me it a beginners computer class, but I think this may be too advanced for me , I havent learned anything about python before starting except some basic tutorials If you are taking a Python class and don't know what to do either the class is poorly designed or you are in the wrong class. Please say more about this. We are glad to help, but won't write your homework for you. Someone game me some help but Im not sure if I piut it in right it looks like this ? import math from math import pi ? print "your options are:" print " " print "1) Area(SQUARE)" print "2) Area(RECTANGLE)" print "3) Area(CIRCLE)" print "4) Perimeter(SQUARE)" print "5) Perimeter(RECTANGLE)" print "6) Perimeter(CIRCLE)" print "7) Exit" while True: ??? selection = raw_input("Please select an option from the menu.: ") def get_area_of_square(): ??? print "Please enter the width of a square" ??? area = width**2 ??? return area def get_area_of_rectangle(): ??? Print "please enter the width of a rectangle" ??? area = width*height ??? return area def get_radius_of_circle(): ??? print "please enter the radius of a circle" ??? radius = pi**2 ??? retrun radius ??? ??? SQUARES: ??? area = width*width = width**2 ??? perimeter = width+width+width+width = 4*width RECTANGLES: ??? area = width*height ??? perimeter = width+height+width+height = 2*(width+height) CIRCLES: ??? area = pi*radius**2 ??? circumference = 2*pi*radius ??? thanks ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Feb 22 18:45:24 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 22 Feb 2012 17:45:24 +0000 Subject: [Tutor] Create a table by writing to a text file. In-Reply-To: <4F44EA44.3050600@gmail.com> References: <4F44EA44.3050600@gmail.com> Message-ID: On 22/02/12 13:14, David Craig wrote: > Hi, > I have created a list of containing strings that represent distances > between many different points and would like to display the results in a > table. Others have mentioned using format strings. If it is only for display you could switch to html. Then defining the table and adding numbers to the cells not only aligns the values but gives you control over colours, borders and fonts. Just another option to consider. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From existentialleo at gmail.com Wed Feb 22 19:50:12 2012 From: existentialleo at gmail.com (leo degon) Date: Wed, 22 Feb 2012 13:50:12 -0500 Subject: [Tutor] Help Designing a simple Program called Life Message-ID: Hello All, My name is Leo. I'm just beginning to learn python. I am learning on my own and have no previous programming experience. I decided to create a version of john conway's game of life as a personal project. I've been wondering what GUI to use. I've been using Tkinter so far but I've not gotten very far. So far I've started the basic window but now I'm kinda of stuck in how to proceed. My idea is when the program initializes to have a root menu with a series of options. Accepting these options under the new game launches a window where you can set the initial state of the board to the correct dimensions, colors, rules, name and initial distribution of live cells. Accepting that window would launch a window containing the game board and the in-game options. I would like to be able to pause the game, run it at different speeds, and add new live cells to the board. I would like to have multiple boards able to run at once, and I would like the option to save a board and its rules to load at a later time. I'd like any ideas on how to approach this project in general and specific. I'll post the code that I already have later today. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Feb 22 20:35:32 2012 From: bgailer at gmail.com (bob gailer) Date: Wed, 22 Feb 2012 14:35:32 -0500 Subject: [Tutor] Help Designing a simple Program called Life In-Reply-To: References: Message-ID: <4F454384.8010703@gmail.com> On 2/22/2012 1:50 PM, leo degon wrote: > Hello All, > My name is Leo. Hi Leo & Welcome to Python help. We are a few volunteers who like assisting others. A few guidelines: - always reply-all so a copy goes to the list - reply in-line rather than at the top. - if your code is large put it in a pastebin on the web and post the link. > I'm just beginning to learn python. I am learning on my own and have > no previous programming experience. I decided to create a version of > john conway's game of life as a personal project. > > I've been wondering what GUI to use. > I've been using Tkinter so far but I've not gotten very far. So far > I've started the basic window but now I'm kinda of stuck in how to > proceed. There are a number of good tutorials on tkinter. Find one and go thru it. > > My idea is when the program initializes to have a root menu with a > series of options. > Accepting these options under the new game launches a window where > you can set the initial state of the board to the correct dimensions, > colors, rules, name and initial distribution of live cells. Accepting > that window would launch a window containing the game board and the > in-game options. I would like to be able to pause the game, run it at > different speeds, and add new live cells to the board. I would like to > have multiple boards able to run at once, and I would like the option > to save a board and its rules to load at a later time. You have chosen a very ambitious project (for a beginner). I suggest you start by creating one part of the whole - get that working then add one more piece. > I'd like any ideas on how to approach this project in general and > specific. > One idea - start with a fixed dimension grid and one initial state - get the grid to display with the initial state. Then step back, say "well done,Leo" then add code to advance to subsequent states with some limit. > > I'll post the code that I already have later today. > -- Bob Gailer 919-636-4239 Chapel Hill NC From bgailer at gmail.com Wed Feb 22 22:35:44 2012 From: bgailer at gmail.com (bob gailer) Date: Wed, 22 Feb 2012 16:35:44 -0500 Subject: [Tutor] Recognizing real numbers In-Reply-To: References: Message-ID: <4F455FB0.1090202@gmail.com> On 2/21/2012 10:00 PM, Michael Lewis wrote: > Hi everyone, > > I have some code where I import a file to use a module. That module > that I import > takes text and a multiplier, checks for any numbers in that text and > will then multiply those numbers by the given multiplier. The imported > module is below. I am getting the text from a file that I have which > starts out as: > > .5 lb. butter > 1.75 Cups Graham Cracker Crumbs > 2.0 Cups Powder Sugar > 1.0 Cups Peanut Butter > 2.0 Cups Semi-sweet Chocolate Chips > > It seems that the .isdigit() function that I use doesn't recognize the > .5 as a number and therefore doesn't multiply it. How can I get my > code to recognize numbers such as .5, 1.75 as numbers? > Wow - the requirements just changed. Up tilll now we were dealing with multiplying each digit. Now we have to parse out a string that represents a number with decimal places! I hope that we don't raise the oven temperature in the process. Is it true that the number to multiply is always at the beginning of a line? If so that makes the job a lot easier. > Imported module: > > def MultiplyText(text, multiplier): > '''Recieve a S & int. For digits in S, multiply by multiplier and > return updated S.''' > return ' '.join(str(float(num) * multiplier) if num.isdigit() else > num for num in text) > > Module doing the importing/opening/reading/creating a new file > > import Homework5_1 as multiply > > def DoubleDigits(file_name): > '''Open file/read file/write new file that doubles all int's in the > read file''' > try: > read_file = open(file_name) > except IOError: > return 'No such file.' > new_file_name = file_name + '2' > try: > write_file = open(new_file_name, 'w') > except IOError: > read_file.close() > return 'No such file to write to.' > for line in read_file: > new_line = line.split() > new_line = ''.join(multiply.MultiplyText(new_line, 2)) > write_file.write(new_line + '\n') > read_file.close() > write_file.close() > > def main(): > DoubleDigits(raw_input('What file do you want to open? ')) > > > if '__name__' == '__main__': > print main() > > Output that is written to my file: > > Peanut Butter Bars > > Ingredients > > .5 lb. butter > 1.75 Cups Graham Cracker Crumbs > 4.0 Cups Powder Sugar > 2.0 Cups Peanut Butter > 4.0 Cups Semi-sweet Chocolate Chips > > Melt butter. Add graham cracker crumbs, > peanut butter and sugar. Mix well and > pat into sheet pan. Cover with melted > chocolate. Refrigerate until semi-firm, > then cut into squares. > > -- > Michael J. Lewis > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From emeraldoffice at hotmail.com Wed Feb 22 23:23:25 2012 From: emeraldoffice at hotmail.com (Tamar Osher) Date: Wed, 22 Feb 2012 16:23:25 -0600 Subject: [Tutor] I cannot "run" any Python programs Message-ID: Hi. I need help. I have installed Python 3.2.2 and have been using IDLE (the "Python shell") to type and save a Python program, such as 'Hello World'. However, the command prompt (the black box) will not allow me to type a Python program or to "run" a Python program. So I tried to run a Python program using Notepad++, and while I am able to type it, I am not able to save it. I am not able to "run" any Python programs. I have read so much about Python, and have researched the situation in detail, and have experimented with various "environmental variables" and user/system paths. I need help to correct the situation.. Can someone please help me? Thanks for helping. I look forward to hearing from you. >From Your Friend: Tamar Osher Skype: tamarosher Email: EmeraldOffice at hotmail.com Message Phone: 011- 1- 513-252-2936 www.HowToBeGifted.com - marketing communication, web design, and much more -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Wed Feb 22 23:33:22 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 22 Feb 2012 17:33:22 -0500 Subject: [Tutor] I cannot "run" any Python programs In-Reply-To: References: Message-ID: On Wed, Feb 22, 2012 at 5:23 PM, Tamar Osher wrote: > Hi.? I need help. > > I have installed Python 3.2.2 and have been using IDLE (the "Python shell") > to type and save a Python program, such as 'Hello World'. > > However, the command prompt (the black box) will not allow me to type a > Python program or to "run" a Python program.? So I tried to run a Python > program using Notepad++, and while I am able to type it, I am not able to > save it. > > I am not able to "run" any Python programs.? I have read so much about > Python, and have researched the situation in detail, and have experimented > with various "environmental variables" and user/system paths.? I need help > to correct the situation.. > > Can someone please help me?? Thanks for helping.? I look forward to hearing > from you. > > From Your Friend: Tamar Osher > Skype: tamarosher > Email: EmeraldOffice at hotmail.com > Message Phone: 011- 1- 513-252-2936 > www.HowToBeGifted.com - marketing communication, web design, and much more > run cmd to get to the shell. in the shell, navigate to the directory where you have saved your file. type: python myprogram.py Tell us what happens. > > > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick From emeraldoffice at hotmail.com Wed Feb 22 23:49:39 2012 From: emeraldoffice at hotmail.com (Tamar Osher) Date: Wed, 22 Feb 2012 16:49:39 -0600 Subject: [Tutor] I cannot "run" any Python programs In-Reply-To: References: , Message-ID: Dear Joel: HI! Thanks for helping. When I use the Python shell, and navigate to the saved Python program, what happens is: A second Python shell pops up, displaying the coding of the program (which is a tiny 'hello world' program). This is what is displayed in the second Python shell: >>> print("Hello, World!") In the first Python shell, when I type in what you requested, this is what happens: >>> python myprogram.py SyntaxError: invalid syntax >>> python hello.py SyntaxError: invalid syntax >>> I am not able to use the Python shell to find the saved Python program. I am able to use Notepad++ to locate the saved Python program, but I cannot run the program. I cannot do anything with the command prompt (black box). I request help to figure out how to run Python programs. Thanks for helping me! >From Your Friend: Tamar Osher Email: EmeraldOffice at hotmail.com > Date: Wed, 22 Feb 2012 17:33:22 -0500 > Subject: Re: [Tutor] I cannot "run" any Python programs > From: joel.goldstick at gmail.com > To: emeraldoffice at hotmail.com > CC: tutor at python.org > > On Wed, Feb 22, 2012 at 5:23 PM, Tamar Osher wrote: > > Hi. I need help. > > > > I have installed Python 3.2.2 and have been using IDLE (the "Python shell") > > to type and save a Python program, such as 'Hello World'. > > > > However, the command prompt (the black box) will not allow me to type a > > Python program or to "run" a Python program. So I tried to run a Python > > program using Notepad++, and while I am able to type it, I am not able to > > save it. > > > > I am not able to "run" any Python programs. I have read so much about > > Python, and have researched the situation in detail, and have experimented > > with various "environmental variables" and user/system paths. I need help > > to correct the situation.. > > > > Can someone please help me? Thanks for helping. I look forward to hearing > > from you. > > > > From Your Friend: Tamar Osher > > Skype: tamarosher > > Email: EmeraldOffice at hotmail.com > > Message Phone: 011- 1- 513-252-2936 > > www.HowToBeGifted.com - marketing communication, web design, and much more > > > > run cmd to get to the shell. > in the shell, navigate to the directory where you have saved your file. > > type: > > python myprogram.py > > Tell us what happens. > > > > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Wed Feb 22 23:52:37 2012 From: d at davea.name (Dave Angel) Date: Wed, 22 Feb 2012 17:52:37 -0500 Subject: [Tutor] Recognizing real numbers In-Reply-To: References: Message-ID: <4F4571B5.4050505@davea.name> On 02/21/2012 10:00 PM, Michael Lewis wrote: > Hi everyone, > > I have some code where I import a file to use a module. That module that I > import takes text and a multiplier, checks for any numbers in that text and > will then multiply those numbers by the given multiplier. The imported > module is below. I am getting the text from a file that I have which starts > out as: > > .5 lb. butter > 1.75 Cups Graham Cracker Crumbs > 2.0 Cups Powder Sugar > 1.0 Cups Peanut Butter > 2.0 Cups Semi-sweet Chocolate Chips > > It seems that the .isdigit() function that I use doesn't recognize the .5 > as a number and therefore doesn't multiply it. How can I get my code to > recognize numbers such as .5, 1.75 as numbers? > > Imported module: > > def MultiplyText(text, multiplier): > '''Recieve a S& int. For digits in S, multiply by multiplier and > return updated S.''' > return ' '.join(str(float(num) * multiplier) if num.isdigit() else num > for num in text) > Somehow, every other time I read that code I missed the "for num in text" phrase that was wrapped around by the mail. I'm apologizing for my earlier remarks stating that this function would not work. i would clean up the variable names (text is a list, and num is a string), and the function comment states that you're multiplying individual digits). But since it works, it's a good base to start with for your floating point question. Easiest answer is to write a function that does check if a string is a valid float, the same as num.isdigit() (lousy names also occur in the standard library) does for int. The new function would be easiest to write with a try/except form. Take a string as a formal parameter, try to float() it in a try block, and if it succeeds, return True. It'd be convenient if there were such a method in str, but since there isn't, you'd have to change num.isdigit() to isfloat(num). Have you gotten to try/except in your class yet? -- DaveA From joel.goldstick at gmail.com Wed Feb 22 23:59:09 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 22 Feb 2012 17:59:09 -0500 Subject: [Tutor] Recognizing real numbers In-Reply-To: <4F455FB0.1090202@gmail.com> References: <4F455FB0.1090202@gmail.com> Message-ID: On Wed, Feb 22, 2012 at 4:35 PM, bob gailer wrote: > On 2/21/2012 10:00 PM, Michael Lewis wrote: > > Hi everyone, > > I have some code where I import a file to use a module. That module that I > import > > takes text and a multiplier, checks for any numbers in that text and will > then multiply those numbers by the given multiplier. The imported module is > below. I am getting the text from a file that I have which starts out as: > > .5 lb. butter > 1.75 Cups Graham Cracker Crumbs > 2.0 Cups Powder Sugar > 1.0 Cups Peanut Butter > 2.0 Cups Semi-sweet Chocolate Chips > > It seems that the .isdigit() function that I use doesn't recognize the .5 as > a number and therefore doesn't multiply it. How can I get my code to > recognize numbers such as .5, 1.75 as numbers? > > Wow - the requirements just changed. Up tilll now we were dealing with > multiplying each digit. Now we have to parse out a string that represents a > number with decimal places! I hope that we don't raise the oven temperature > in the process. > > Is it true that the number to multiply is always at the beginning of a line? > If so that makes the job a lot easier. > > Imported module: > > def MultiplyText(text, multiplier): > ? ? '''Recieve a S & int. For digits in S, multiply by multiplier and return > updated S.''' > ? ? return ' '.join(str(float(num) * multiplier) if num.isdigit() else num > for num in text) > > Module doing the importing/opening/reading/creating a new file > > import Homework5_1 as multiply > > def DoubleDigits(file_name): > ? ? '''Open file/read file/write new file that doubles all int's in the > ? ? read file''' > ? ? try: > ? ? ? ? read_file = open(file_name) > ? ? except IOError: > ? ? ? ? return 'No such file.' > ? ? new_file_name = file_name + '2' > ? ? try: > ? ? ? ? write_file = open(new_file_name, 'w') > ? ? except IOError: > ? ? ? ? read_file.close() > ? ? ? ? return 'No such file to write to.' > ? ? for line in read_file: > ? ? ? ? new_line = line.split() > ? ? ? ? new_line = ''.join(multiply.MultiplyText(new_line, 2)) > ? ? ? ? write_file.write(new_line + '\n') > ? ? read_file.close() > ? ? write_file.close() > > def main(): > ? ? DoubleDigits(raw_input('What file do you want to open? ')) > > > if '__name__' == '__main__': > ? ? print main() > > Output that is written to my file: > > Peanut Butter Bars > > Ingredients > > .5 lb. butter > 1.75 Cups Graham Cracker Crumbs > 4.0 Cups Powder Sugar > 2.0 Cups Peanut Butter > 4.0 Cups Semi-sweet Chocolate Chips > > Melt butter. Add graham cracker crumbs, > peanut butter and sugar. Mix well and > pat into sheet pan. Cover with melted > chocolate. Refrigerate until semi-firm, > then cut into squares. > > -- > Michael J. Lewis > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > If the first stuff in the line is always the number, and you capture the line in s then: n = float(s.split()[0]) will give you the number. You should wrap this up with a try block so that it doesn't fail if it isn't a number split method separates on whitespace and puts each part of the string in a list. [0] takes the first of those list items. float converts to a float -- Joel Goldstick From joel.goldstick at gmail.com Thu Feb 23 00:02:23 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 22 Feb 2012 18:02:23 -0500 Subject: [Tutor] I cannot "run" any Python programs In-Reply-To: References: Message-ID: On Wed, Feb 22, 2012 at 5:49 PM, Tamar Osher wrote: > Dear Joel: HI!? Thanks for helping.? When I use the Python shell, and > navigate to the saved Python program, what happens is: > A second Python shell pops up, displaying the coding of the program (which > is a tiny 'hello world' program).? This is what is displayed in the second > Python shell: >>>> print("Hello, World!") > > In the first Python shell, when I type in what you requested, this is what > happens: >>>> python myprogram.py > SyntaxError: invalid syntax >>>> python hello.py > SyntaxError: invalid syntax >>>> > > I am not able to use the Python shell to find the saved Python program.? I > am able to use Notepad++ to locate the saved Python program, but I cannot > run the program.? I cannot do anything with the command prompt (black box). > > I request help to figure out how to run Python programs. Thanks for helping > me! > from the >>>> stuff at the start of each line, you are in a python shell. Don't do that. Just get into a command shell. Since I believe you are in windows, press the start button, then run command and the command you run should be cmd This will bring you to a window which looks a lot like DOS used to look. You probably are too young for that. Anyway, at that point, try typing python myprogram.py -- Joel Goldstick From emeraldoffice at hotmail.com Thu Feb 23 00:11:33 2012 From: emeraldoffice at hotmail.com (Tamar Osher) Date: Wed, 22 Feb 2012 17:11:33 -0600 Subject: [Tutor] I cannot "run" any Python programs In-Reply-To: References: , , , Message-ID: Dear Joel: Hi! Thanks for helping. I typed cmd, and got the same black box, this time labeled C:\windows\system32\cmd.exe instead of "Command Prompt". When I type python myprogram.py, this is what appears on the screen:'python' is not recognized as an internal or external command, operable program, or batch file. Can you help me? I hope so! >From Your Friend: Tamar Osher Email: EmeraldOffice at hotmail.com > Date: Wed, 22 Feb 2012 18:02:23 -0500 > Subject: Re: [Tutor] I cannot "run" any Python programs > From: joel.goldstick at gmail.com > To: emeraldoffice at hotmail.com > CC: tutor at python.org > > On Wed, Feb 22, 2012 at 5:49 PM, Tamar Osher wrote: > > Dear Joel: HI! Thanks for helping. When I use the Python shell, and > > navigate to the saved Python program, what happens is: > > A second Python shell pops up, displaying the coding of the program (which > > is a tiny 'hello world' program). This is what is displayed in the second > > Python shell: > >>>> print("Hello, World!") > > > > In the first Python shell, when I type in what you requested, this is what > > happens: > >>>> python myprogram.py > > SyntaxError: invalid syntax > >>>> python hello.py > > SyntaxError: invalid syntax > >>>> > > > > I am not able to use the Python shell to find the saved Python program. I > > am able to use Notepad++ to locate the saved Python program, but I cannot > > run the program. I cannot do anything with the command prompt (black box). > > > > I request help to figure out how to run Python programs. Thanks for helping > > me! > > > > from the >>>> stuff at the start of each line, you are in a python > shell. Don't do that. Just get into a command shell. > Since I believe you are in windows, press the start button, then run > command and the command you run should be cmd > > This will bring you to a window which looks a lot like DOS used to > look. You probably are too young for that. Anyway, at that point, > try typing python myprogram.py > > > -- > Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu Feb 23 00:25:44 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 22 Feb 2012 18:25:44 -0500 Subject: [Tutor] I cannot "run" any Python programs In-Reply-To: References: Message-ID: On Wed, Feb 22, 2012 at 6:11 PM, Tamar Osher wrote: > Dear Joel: Hi!? Thanks for helping.? I typed cmd, and got the same black > box, this time labeled C:\windows\system32\cmd.exe instead of "Command > Prompt".? When I type python myprogram.py, this is what appears on the > screen: > 'python' is not recognized as an internal or external command, operable > program, or batch file. > > Can you help me?? I hope so! > > > From Your Friend: Tamar Osher > Email: EmeraldOffice at hotmail.com > > > > > > > >> Date: Wed, 22 Feb 2012 18:02:23 -0500 > >> Subject: Re: [Tutor] I cannot "run" any Python programs >> From: joel.goldstick at gmail.com >> To: emeraldoffice at hotmail.com >> CC: tutor at python.org >> >> On Wed, Feb 22, 2012 at 5:49 PM, Tamar Osher >> wrote: >> > Dear Joel: HI!? Thanks for helping.? When I use the Python shell, and >> > navigate to the saved Python program, what happens is: >> > A second Python shell pops up, displaying the coding of the program >> > (which >> > is a tiny 'hello world' program).? This is what is displayed in the >> > second >> > Python shell: >> >>>> print("Hello, World!") >> > >> > In the first Python shell, when I type in what you requested, this is >> > what >> > happens: >> >>>> python myprogram.py >> > SyntaxError: invalid syntax >> >>>> python hello.py >> > SyntaxError: invalid syntax >> >>>> >> > >> > I am not able to use the Python shell to find the saved Python program. >> > I >> > am able to use Notepad++ to locate the saved Python program, but I >> > cannot >> > run the program.? I cannot do anything with the command prompt (black >> > box). >> > >> > I request help to figure out how to run Python programs. Thanks for >> > helping >> > me! >> > >> >> from the >>>> stuff at the start of each line, you are in a python >> shell. Don't do that. Just get into a command shell. >> Since I believe you are in windows, press the start button, then run >> command and the command you run should be cmd >> >> This will bring you to a window which looks a lot like DOS used to >> look. You probably are too young for that. Anyway, at that point, >> try typing python myprogram.py >> >> >> -- >> Joel Goldstick Don't top post. Put your comments at the bottom of the message or intersperse where appropriate. I'm not a windows guy anymore. Someone who is can help you figure out how to find out where python is and put it on your path. In the mean time, google "microsoft python setting up path" and you may be on your way! -- Joel Goldstick From emeraldoffice at hotmail.com Thu Feb 23 00:29:43 2012 From: emeraldoffice at hotmail.com (Tamar Osher) Date: Wed, 22 Feb 2012 17:29:43 -0600 Subject: [Tutor] I cannot "run" any Python programs In-Reply-To: References: , , , , , Message-ID: Thanks! I hope to find a Windows7 expert to help me. -------------- next part -------------- An HTML attachment was scrubbed... URL: From williamjstewart at rogers.com Thu Feb 23 00:45:48 2012 From: williamjstewart at rogers.com (William Stewart) Date: Wed, 22 Feb 2012 15:45:48 -0800 (PST) Subject: [Tutor] how to rewrite area.py In-Reply-To: Message-ID: <1329954348.99751.YahooMailClassic@web88614.mail.bf1.yahoo.com> so I copied your format except I changed shape 3 to circle,?Did I do the circle part right? and would this be considered seperate functions? ? Thanks for your help import math from math import pi menu = """ Pick a shape(1-3): ?? 1) Square ?? 2) Rectangle ?? 3) Triangle ?? 4) Quit """ shape = int(input(menu)) while shape != 4: ?? if shape == 1: ????? length = float(input("Length: ")) ????? print( "Area of square = ", length ** 2 ) ?? elif shape == 2: ????? length = float(input("Length: ")) ????? width = float(input("Width: ")) ????? print( "Area of rectangle = ", length * width )?? ?? elif shape == 3: ????? area = float(input("Radius: ")) ????? circumference = float(input("radius: ")) ????? print( "Area of Circle = ", pi*radius**2 ) ?? shape = int(input(menu)) ? ? ? OR would this work better? ? ? import math from math import pi print "your options are:" print " " print "1) Area(SQUARE)" print "2) Area(RECTANGLE)" print "3) Area(CIRCLE)" print "4) Perimeter(SQUARE)" print "5) Perimeter(RECTANGLE)" print "6) Perimeter(CIRCLE)" print "7) Exit" while True: ??? selection = raw_input("Please select an option from the menu.: ") def get_area_of_square(): ??? print "Please enter the width of a square" ??? area = width**2 ??? return area def get_area_of_rectangle(): ??? Print "please enter the width of a rectangle" ??? area = width*height ??? return area def get_radius_of_circle(): ??? print "please enter the radius of a circle" ??? radius = pi**2 ??? retrun radius ??? ??? SQUARES: ??? area = width*width = width**2 ??? perimeter = width+width+width+width = 4*width RECTANGLES: ??? area = width*height ??? perimeter = width+height+width+height = 2*(width+height) CIRCLES: ??? area = pi*radius**2 ??? circumference = 2*pi*radius ??? ? ? --- On Tue, 2/21/12, Alan Gauld wrote: From: Alan Gauld Subject: Re: [Tutor] how to rewrite area.py To: tutor at python.org Date: Tuesday, February 21, 2012, 7:46 PM On 21/02/12 23:51, William Stewart wrote: > I need to rewrite area.py program so that it has separate functions for > the perimeter and area of a square, a rectangle, and a circle (3.14 * > radius**2). You will find something similar in my tutorial in the topic Branching. Look under the heading "Python multi-selection" and there is some code you should be able to include as template. Have a go and come back with questions. > I am horrible at math and I cannot even figure out what I need to do for > this Steven has done the math bit for you, so just plug it into the python code you need. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Feb 23 01:25:51 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 23 Feb 2012 00:25:51 +0000 Subject: [Tutor] Help Designing a simple Program called Life In-Reply-To: References: Message-ID: On 22/02/12 18:50, leo degon wrote: > Hello All, > My name is Leo. I'm just beginning to learn python. I am > learning on my own and have no previous programming experience. I > decided to create a version of john conway's game of life as a personal > project. OK, Thats quite a good project for a beginner because it will require ac number of differentb concepts. > I've been wondering what GUI to use. Personally I'd say don't. at least not for a start. Get the game working on the console first then transfer it to the GUI later. One of the fundamental paradigms for GUI program is the Model-View paradigm where you have separate code to represent the logic of the program - the model - from that which displays the UI - The view. You can have different views of the same model. eg. a text view and a graphical view. You can even have both open at the same time! In your case start with a very simple text view using print statements. > My idea is when the program initializes to have a root menu with a > series of options. In GUI progrqamming beginners often start by thinking about the GUI layout and controls. Thats usually the wrong place to start. Start with the model. In your case that's a grid or matrix with some cells filled in. You need to cyclically recalculate the status of each cell based on the status of the cells around it. (Hint: it may be easier to create a grid thats 1 cell bigger in every direction than your display...) > in-game options. I would like to be able to pause the game, run it at > different speeds, and add new live cells to the board. I would like to > have multiple boards able to run at once, and I would like the option to > save a board and its rules to load at a later time. All good ideas but get the most basic one working first a hard coded starting point that morphs into the second generation. Once that works get the cycles running until you hit a key to stop. At that stage we might think about introducing a GUI... But thats probably quie a long way off just yet. > I'd like any ideas on how to approach this project in general and specific. Build a little, test a lot. Think about how you will test it before you build it (this is known as test driven development - TDD - in software engineering circles. But it's good for amateurs too!) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From breamoreboy at yahoo.co.uk Thu Feb 23 01:34:15 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 23 Feb 2012 00:34:15 +0000 Subject: [Tutor] I cannot "run" any Python programs In-Reply-To: References: , , , , , Message-ID: On 22/02/2012 23:29, Tamar Osher wrote: > > Thanks! I hope to find a Windows7 expert to help me. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Try reading this http://docs.python.org/using/windows.html -- Cheers. Mark Lawrence. From alan.gauld at btinternet.com Thu Feb 23 01:37:58 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 23 Feb 2012 00:37:58 +0000 Subject: [Tutor] I cannot "run" any Python programs In-Reply-To: References: , , , , , Message-ID: On 22/02/12 23:29, Tamar Osher wrote: > Thanks! I hope to find a Windows7 expert to help me. You don't need a Windows 7 expert, just to set things up properly. First open up Notepad++ again and enter everything between the #### then save to a file called myHello.py and exit Notepad++. #################### print ("Hello world, Python calling!") input("Hit return to exit") #################### Find myhello.py in Windows explorer and double click it. (It's probably a good idea to create a special folder to store your python programs. It'll be easier to find them in the future!) If python is installed correctly a black window should open displaying: Hello world, Python calling Hit return to exit If you hit return the window should close. Now open the same file in IDLE (File->Open) You should have a new edit window. In IDLE choose the Run->Run Module menu item. Your program should now run inside IDLE and display its output in the Python Shell window of IDLE. When you hit return this time IDLE stays open but returnms to the Python shell prompt >>> If that all works, great, you are set up. If it doesn't come back and tell us *exactly* what you did and what was displayed. Copy 'n paste any error messages if possible. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Feb 23 01:46:41 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 23 Feb 2012 00:46:41 +0000 Subject: [Tutor] how to rewrite area.py In-Reply-To: <1329954348.99751.YahooMailClassic@web88614.mail.bf1.yahoo.com> References: <1329954348.99751.YahooMailClassic@web88614.mail.bf1.yahoo.com> Message-ID: On 22/02/12 23:45, William Stewart wrote: > so I copied your format except I changed shape 3 to circle, Did I do the > circle part right? Nearly. The circumference is wrong, you need to calculate it not read it from the user. > and would this be considered separate functions? No, but your second variant is separate functions. You just need to insert them into the first version as appropriate. (After you get them working of course!:-) > *elif shape == 3: > area = float(input("Radius: ")) > circumference = float(input("radius: ")) > print( "Area of Circle = ", pi*radius**2 ) > shape = int(input(menu))* > while True: > selection = raw_input("Please select an option from the menu.: ") > > def get_area_of_square(): > print "Please enter the width of a square" This line needs to be an input as you did above. All you are doing here is printing a message not reading anything back. And certainly not assigning anything to width. > area = width**2 > return area That defines the function but does not call it. You should put the definition outside the loop - above all the code above - and then call it inside the if/else statement: area = get_area_of_square() or even print "Area of square = ", get_area_of_square() HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sbjaved at gmail.com Thu Feb 23 01:59:01 2012 From: sbjaved at gmail.com (Saad Javed) Date: Thu, 23 Feb 2012 05:59:01 +0500 Subject: [Tutor] help writing functions Message-ID: I am learning python and need guidance for writing some code. I've written a simple program (with pointers from people) that parses an tv show xml feed and prints their values in plain text after performing some string operations. [CODE]feed = urllib.urlopen(rssPage) #rssPage: address of xml feed tree = etree.parse(feed) x = tree.xpath("/rss/channel/item/title/text()") x = str(x[0]) for tag in tags: #tags is a list of items like hdtv, xvid, 720p etc x = re.sub(r'\b' + tag + r'\b', '', x) z = re.sub(r'[^\w\s]', '', x) y = tree1.xpath("/rss/channel/item/pubDate/text()") print "%s - %s" %(z.rstrip(), y[0][:16])[/CODE] The code works fine (prints the name of the show and date). Now since I am parsing more than one feed, I thought the better way was to split the functionality into diff functions: one to get the values and the other to remove the tags. I'm still *very* new to python and came up with the following code. [CODE]def get_value(feed): try: url = urllib2.urlopen(feed) tree = etree.parse(url) x = tree.xpath("/rss/channel/item/title/text()") y = tree.xpath("/rss/channel/item/pubDate/text()") x = str(x[0]) y = str(y[0][:16]) return x return y except SyntaxError: print 'Service Unavailable' pass def del_tag(x): tags = ['HDTV', 'LOL', 'VTV', 'x264', 'DIMENSION', 'XviD', '720P', 'IMMERSE', '720p', 'X264'] for tag in tags: x = re.sub(r'\b' + tag + r'\b', '', x) y = re.sub(r'[^\w\s]', '', x) def main(): a = get_value(rssPage) b = del_tag(a) print b if __name__ == '__main__': main()[/CODE] My desired working is to supply the xml feed address to the [B]get_value[/B] function which returns the title and date as strings assigned to [B]x[/B] and [B]y[/B]. Then I run the [B]del_tag[/B] function on the title string ([B]x[/B]) and remove tags and the [B]main()[/B] function prints both [B]x[/B] and [B]y[/B] (Title, Date). Running this code returns [B]None[/B]. Let the teaching begin :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From emeraldoffice at hotmail.com Thu Feb 23 02:00:57 2012 From: emeraldoffice at hotmail.com (Tamar Osher) Date: Wed, 22 Feb 2012 19:00:57 -0600 Subject: [Tutor] Which computer operating system is best for Python developers? Message-ID: Hi. I am still having trouble installing and using Python on my (new) Windows 7 computer, but I plan to contact Microsoft forums and see if they can help me, since this is a Windows problem and not a Python problem. My question: For the future, what type of computer is best for Python developers? Do all Python developers use some type of Unix computer? I appreciate your feedback and look forward to hearing from you. Thanks for your time. >From Your Friend: Tamar Osher Email: EmeraldOffice at hotmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at graniteweb.com Thu Feb 23 02:19:12 2012 From: david at graniteweb.com (David Rock) Date: Wed, 22 Feb 2012 19:19:12 -0600 Subject: [Tutor] Which computer operating system is best for Python developers? In-Reply-To: References: Message-ID: <20120223011912.GD3652@wdfs.graniteweb.com> * Tamar Osher [2012-02-22 19:00]: > > Hi. I am still having trouble installing and using Python on my (new) > Windows 7 computer, but I plan to contact Microsoft forums and see if > they can help me, since this is a Windows problem and not a Python > problem. > > My question: For the future, what type of computer is best for Python > developers? Do all Python developers use some type of Unix computer? > I appreciate your feedback and look forward to hearing from you. > Thanks for your time. As always, the answer is "it depends." If you plan on doing Win32 python programming, it doesn't make sense to use anything other than a Windows system. It is usually easier if you can develop on a system that is similar to where your programs will run, but it is by no means a requirement. Your biggest challenge if developing on unlike systems, will be using methods that might be OS-specific (os.fork() comes to mind). As long as you keep things neutral, you shouldn't have huge issues. -- David Rock david at graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 190 bytes Desc: not available URL: From breamoreboy at yahoo.co.uk Thu Feb 23 02:23:46 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 23 Feb 2012 01:23:46 +0000 Subject: [Tutor] Which computer operating system is best for Python developers? In-Reply-To: References: Message-ID: On 23/02/2012 01:00, Tamar Osher wrote: > > Hi. I am still having trouble installing and using Python on my (new) Windows 7 computer, but I plan to contact Microsoft forums and see if they can help me, since this is a Windows problem and not a Python problem. > > My question: For the future, what type of computer is best for Python developers? Do all Python developers use some type of Unix computer? > I appreciate your feedback and look forward to hearing from you. Thanks for your time. > >> From Your Friend: Tamar Osher > Email: EmeraldOffice at hotmail.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor I use Windows simply for the convenience and have never had a problem that couldn't be solved. I guess that some 40 years of industry experience tells me that reading manuals before trying something tends to save time in the long run. -- Cheers. Mark Lawrence. From emeraldoffice at hotmail.com Thu Feb 23 02:32:21 2012 From: emeraldoffice at hotmail.com (Tamar Osher) Date: Wed, 22 Feb 2012 19:32:21 -0600 Subject: [Tutor] installing Python and running a Python program In-Reply-To: References: Message-ID: Dear Alan: Hi. Thanks for helping me. I did it exactly the way you described, and everything worked perfectly. Thanks for being a kind friend! >From Your Friend: Tamar Osher Email: EmeraldOffice at hotmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From mjolewis at gmail.com Thu Feb 23 02:44:40 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Wed, 22 Feb 2012 17:44:40 -0800 Subject: [Tutor] Recognizing real numbers (bob gailer) Message-ID: > Hi everyone, > > I have some code where I import a file to use a module. That module > that I import > takes text and a multiplier, checks for any numbers in that text and > will then multiply those numbers by the given multiplier. The imported > module is below. I am getting the text from a file that I have which > starts out as: > > .5 lb. butter > 1.75 Cups Graham Cracker Crumbs > 2.0 Cups Powder Sugar > 1.0 Cups Peanut Butter > 2.0 Cups Semi-sweet Chocolate Chips > > It seems that the .isdigit() function that I use doesn't recognize the > .5 as a number and therefore doesn't multiply it. How can I get my > code to recognize numbers such as .5, 1.75 as numbers? > Wow - the requirements just changed. Up tilll now we were dealing with multiplying each digit. Now we have to parse out a string that represents a number with decimal places! I hope that we don't raise the oven temperature in the process. Well - this is part of my homework and the first question dealt with only multiplying each digit. the second part of the homework then asked to write a file that imported the file from the previous homework portion and utilized the multiplication function in that file. No oven temperature changes...I promise. Is it true that the number to multiply is always at the beginning of a line? If so that makes the job a lot easier. It's not true. The number can be anywhere in the text. > Imported module: > > def MultiplyText(text, multiplier): > '''Recieve a S & int. For digits in S, multiply by multiplier and > return updated S.''' > return ' '.join(str(float(num) * multiplier) if num.isdigit() else > num for num in text) > > Module doing the importing/opening/reading/creating a new file > > import Homework5_1 as multiply > > def DoubleDigits(file_name): > '''Open file/read file/write new file that doubles all int's in the > read file''' > try: > read_file = open(file_name) > except IOError: > return 'No such file.' > new_file_name = file_name + '2' > try: > write_file = open(new_file_name, 'w') > except IOError: > read_file.close() > return 'No such file to write to.' > for line in read_file: > new_line = line.split() > new_line = ''.join(multiply.MultiplyText(new_line, 2)) > write_file.write(new_line + '\n') > read_file.close() > write_file.close() > > def main(): > DoubleDigits(raw_input('What file do you want to open? ')) > > > if '__name__' == '__main__': > print main() > > Output that is written to my file: > > Peanut Butter Bars > > Ingredients > > .5 lb. butter > 1.75 Cups Graham Cracker Crumbs > 4.0 Cups Powder Sugar > 2.0 Cups Peanut Butter > 4.0 Cups Semi-sweet Chocolate Chips > > Melt butter. Add graham cracker crumbs, > peanut butter and sugar. Mix well and > pat into sheet pan. Cover with melted > chocolate. Refrigerate until semi-firm, > then cut into squares. > > -- > Michael J. Lewis -------------- next part -------------- An HTML attachment was scrubbed... URL: From mjolewis at gmail.com Thu Feb 23 02:54:54 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Wed, 22 Feb 2012 17:54:54 -0800 Subject: [Tutor] Recognizing real numbers In-Reply-To: <4F4571B5.4050505@davea.name> References: <4F4571B5.4050505@davea.name> Message-ID: On Wed, Feb 22, 2012 at 2:52 PM, Dave Angel wrote: > On 02/21/2012 10:00 PM, Michael Lewis wrote: > >> Hi everyone, >> >> I have some code where I import a file to use a module. That module that I >> import takes text and a multiplier, checks for any numbers in that text >> and >> will then multiply those numbers by the given multiplier. The imported >> module is below. I am getting the text from a file that I have which >> starts >> out as: >> >> .5 lb. butter >> 1.75 Cups Graham Cracker Crumbs >> 2.0 Cups Powder Sugar >> 1.0 Cups Peanut Butter >> 2.0 Cups Semi-sweet Chocolate Chips >> >> It seems that the .isdigit() function that I use doesn't recognize the .5 >> as a number and therefore doesn't multiply it. How can I get my code to >> recognize numbers such as .5, 1.75 as numbers? >> >> Imported module: >> >> def MultiplyText(text, multiplier): >> '''Recieve a S& int. For digits in S, multiply by multiplier and >> >> return updated S.''' >> return ' '.join(str(float(num) * multiplier) if num.isdigit() else num >> for num in text) >> >> Somehow, every other time I read that code I missed the "for num in > text" phrase that was wrapped around by the mail. > No worries - this list has been crazy helpful to me. > > I'm apologizing for my earlier remarks stating that this function would > not work. i would clean up the variable names (text is a list, and num is > a string), and the function comment states that you're multiplying > individual digits). But since it works, it's a good base to start with for > your floating point question. > > Easiest answer is to write a function that does check if a string is a > valid float, the same as num.isdigit() (lousy names also occur in the > standard library) does for int. > > The new function would be easiest to write with a try/except form. Take a > string as a formal parameter, try to float() it in a try block, and if it > succeeds, return True. > > It'd be convenient if there were such a method in str, but since there > isn't, you'd have to change num.isdigit() to isfloat(num). > > Have you gotten to try/except in your class yet? We have. I actually have a function written in my imported file to check if a string is a valid float, but I didn't use it because I also have raw_input in that same function, which I don't want. I'll rework the imported function to remove the raw_input and put that in a function by itself so I can utilize the valid float try/except that I've already written. > > > -- > > DaveA > > -- Michael J. Lewis mjolewis at gmail.com 415.815.7257 -------------- next part -------------- An HTML attachment was scrubbed... URL: From elainahyde at gmail.com Thu Feb 23 02:55:40 2012 From: elainahyde at gmail.com (Elaina Ann Hyde) Date: Thu, 23 Feb 2012 12:55:40 +1100 Subject: [Tutor] Reading/dealing/matching with truly huge (ascii) files In-Reply-To: References: Message-ID: On Wed, Feb 22, 2012 at 8:50 PM, Peter Otten <__peter__ at web.de> wrote: > Elaina Ann Hyde wrote: > > > So, Python question of the day: I have 2 files that I could normally > just > > read in with asciitable, The first file is a 12 column 8000 row table > that > > I have read in via asciitable and manipulated. The second file is > > enormous, has over 50,000 rows and about 20 columns. What I want to do > is > > find the best match for (file 1 column 1 and 2) with (file 2 column 4 and > > 5), return all rows that match from the huge file, join them togeather > and > > save the whole mess as a file with 8000 rows (assuming the smaller table > > finds one match per row) and 32=12+20 columns. So my read code so far is > > as follows: > > ------------------------------------------------- > > import sys > > import asciitable > > import matplotlib > > import scipy > > import numpy as np > > from numpy import * > > import math > > import pylab > > import random > > from pylab import * > > import astropysics > > import astropysics.obstools > > import astropysics.coords > > > > x=small_file > > #cannot read blank values (string!) if blank insert -999.99 > > dat=asciitable.read(x,Reader=asciitable.CommentedHeader, > > fill_values=['','-999.99']) > > y=large_file > > fopen2=open('cfile2match.list','w') > > dat2=asciitable.read(y,Reader=asciitable.CommentedHeader, > > fill_values=['','-999.99']) > > #here are the 2 values for the small file > > Radeg=dat['ra-drad']*180./math.pi > > Decdeg=dat['dec-drad']*180./math.pi > > > > #here are the 2 values for the large file > > Radeg2=dat2['ra-drad']*180./math.pi > > Decdeg2=dat2['dec-drad']*180./math.pi > > > > for i in xrange(len(Radeg)): > > for j in xrange(len(Radeg2)): > > #select the value if it is very, very, very close > > if i != j and Radeg[i] <= (Radeg2[j]+0.000001) and > > Radeg[i] > >>= (Radeg2[j]-0.000001) and Decdeg[i] <= (Decdeg2[j]+0.000001) and > > Decdeg[i] >= (Decdeg2[j]-0.000001): > > fopen.write( " ".join([str(k) for k in > > list(dat[i])])+" "+" ".join([str(k) for k in list(dat[j])])+"\n") > > ------------------------------------------- > > Now this is where I had to stop, this is way, way too long and messy. I > > did a similar approach with smaller (9000 lines each) files and it worked > > but took awhile, the problem here is I am going to have to play with the > > match range to return the best result and give only one (1!) match per > row > > for my smaller file, i.e. row 1 of small file must match only 1 row of > > large file..... then I just need to return them both. However, it isn't > > clear to me that this is the best way forward. I have been changing the > > xrange to low values to play with the matching, but I would appreciate > any > > ideas. Thanks > > If you calculate the distance instead of checking if it's under a certain > threshold you are guaranteed to get (one of the) best matches. > Pseudo-code: > > from functools import partial > big_rows = read_big_file_into_memory() > > def distance(small_row, big_row): > ... > > for small_row in read_small_file(): > best_match = min(big_rows, key=partial(dist, small_row)) > write_to_result_file(best_match) > > > As to the actual implementation of the distance() function, I don't > understand your problem description (two columns in the first, three in the > second, how does that work), but generally > > a, c = extract_columns_from_small_row(small_row) > b, d = extract_columns_from_big_row(big_row) > if (a <= b + eps) and (c <= d + eps): > # it's good > > would typically become > > distance(small_row, big_row): > a, c = extract_columns_from_small_row(small_row) > b, d = extract_columns_from_big_row(big_row) > x = a-b > y = c-d > return math.sqrt(x*x+y*y) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Thanks for all the helpful hints, I really like the idea of using distances instead of a limit. Walter was right that the 'i !=j' condition was causing problems. I think that Alan and Steven's use of the index separately was great as it makes this much easier to test (and yes 'astropysics' is a valid package, it's in there for later when I convert astrophysical coordinates and whatnot, pretty great but a little buggy FYI). So I thought, hey, why not try to do a little of all these ideas, and, if you'll forgive the change in syntax, I think the problem is that the file might really just be too big to handle, and I'm not sure I have the right idea with the best_match: ----------------------------------- #!/usr/bin/python import sys import asciitable import matplotlib import scipy import numpy as np import math import pylab import random from pylab import * import astropysics import astropysics.obstools import astropysics.coords from astropysics.coords import ICRSCoordinates,GalacticCoordinates #small x=open('allfilematch.list') #really big 2MASS file called 'sgr_2df_big.list' y=open('/Volumes/Diemos/sgr_2df_big.list') dat=asciitable.read(x,Reader=asciitable.CommentedHeader, fill_values=['','-999.99']) dat2=asciitable.read(y,Reader=asciitable.NoHeader, start_line=4,fill_values=['nan','-999.99']) fopen=open('allfiles_rod2Mass.list','w') #first convert from decimal radians to degrees Radeg=dat['ra-drad']*180./math.pi Decdeg=dat['dec-drad']*180./math.pi #here are the 2 values for the large file #converts hexadecimal in multiple columns to regular degrees Radeg2=15*(dat2['col1']+(dat2['col2']/60.)+(dat2['col3']/(60.*60.))) Decdeg2=dat2['col4']+(dat2['col5']/60.)+(dat2['col6']/(60.*60.)) #try defining distances instead of a limit... def distance(dat, dat2): x = Radeg - Radeg2 y = Decdeg - Decdeg2 return np.sqrt(x*x+y*y) for i in xrange(len(Radeg)): best_match=min(Radeg2,key=partial(dist,Radeg)) fopen.write(best_match) fopen.close() --------------- The errors are as follows: --------------------- Python(4085,0xa01d3540) malloc: *** mmap(size=2097152) failed (error code=12) *** error: can't allocate region *** set a breakpoint in malloc_error_break to debug Traceback (most recent call last): File "read_2MASS.py", line 38, in dat2=asciitable.read(y,Reader=asciitable.NoHeader,data_start=4,fill_values=['nan','-9.999']) File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/asciitable-0.8.0-py2.7.egg/asciitable/ui.py", line 131, in read dat = _guess(table, new_kwargs) File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/asciitable-0.8.0-py2.7.egg/asciitable/ui.py", line 175, in _guess dat = reader.read(table) File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/asciitable-0.8.0-py2.7.egg/asciitable/core.py", line 841, in read self.lines = self.inputter.get_lines(table) File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/asciitable-0.8.0-py2.7.egg/asciitable/core.py", line 158, in get_lines lines = table.splitlines() MemoryError ---------------------- So this means I don't have enough memory to run through the large file? Even if I just read in with asciitable I get this problem, I looked again and the large file is 1.5GB of text lines, so very large. I was thinking of trying to tell the read function to skip lines that are too far away, the file is much, much bigger than the area I need. Thanks for the comments so far. ~Elaina -- PhD Candidate Department of Physics and Astronomy Faculty of Science Macquarie University North Ryde, NSW 2109, Australia -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Thu Feb 23 03:08:01 2012 From: d at davea.name (Dave Angel) Date: Wed, 22 Feb 2012 21:08:01 -0500 Subject: [Tutor] Recognizing real numbers In-Reply-To: References: <4F4571B5.4050505@davea.name> Message-ID: <4F459F81.1000102@davea.name> On 02/22/2012 08:54 PM, Michael Lewis wrote: > On Wed, Feb 22, 2012 at 2:52 PM, Dave Angel wrote: > > > I actually have a function written in my imported file to check if > a string is a valid float, but I didn't use it because I also have > raw_input in that same function, which I don't want. I'll rework the > imported function to remove the raw_input and put that in a function by > itself so I can utilize the valid float try/except that I've already > written. > That alone is a valuable lesson. When writing functions, try to make each function do one task, thoroughly and flexibly. Then it's much more likely to be reusable. -- DaveA From breamoreboy at yahoo.co.uk Thu Feb 23 03:14:37 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 23 Feb 2012 02:14:37 +0000 Subject: [Tutor] Reading/dealing/matching with truly huge (ascii) files In-Reply-To: References: Message-ID: On 23/02/2012 01:55, Elaina Ann Hyde wrote: [big snips] Hi Elaina, I'm sorry but I can't help with your problem with the memory cos I don't know enough about the combination of Python and Unix wrt memory management. However can I suggest that you use more whitespace in your code to make it easier on all MkI eyeballs, e.g. you have Decdeg2=dat2['col4']+(dat2['col5']/60.)+(dat2['col6']/(60.*60.)) I think this looks better as Decdeg2 = dat2['col4'] + (dat2['col5']/60.) + (dat2['col6'] / (60.*60.)) -- Cheers. Mark Lawrence. From mjolewis at gmail.com Thu Feb 23 04:29:42 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Wed, 22 Feb 2012 19:29:42 -0800 Subject: [Tutor] Compiled Python File Message-ID: First, thanks to everyone who helped me out regarding my Recognizing real numbers post. I gained a lot of knowledge over the past two days! I've noticed that after I execute some of my .py files, a Compiled Python File is automatically saved to my directory. This doesn't happen for every file that I execute though. Why is that? Thanks! -- Michael J. Lewis -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Feb 23 05:02:49 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 23 Feb 2012 15:02:49 +1100 Subject: [Tutor] Compiled Python File In-Reply-To: References: Message-ID: <20120223040249.GA11871@ando> On Wed, Feb 22, 2012 at 07:29:42PM -0800, Michael Lewis wrote: > First, thanks to everyone who helped me out regarding my Recognizing real > numbers post. I gained a lot of knowledge over the past two days! > > I've noticed that after I execute some of my .py files, a Compiled Python > File is automatically saved to my directory. This doesn't happen for every > file that I execute though. Why is that? When you execute a file directly from the shell, using something like this command: $ python my_python_script.py no .pyc file is created. But when you import a file from within Python, either by hand or within a script: >>> import my_module Python compiles it and saves the compiled version to my_module.pyc so that the next time you call import, it will be faster. -- Steven From steve at pearwood.info Thu Feb 23 05:33:34 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 23 Feb 2012 15:33:34 +1100 Subject: [Tutor] Which computer operating system is best for Python developers? In-Reply-To: References: Message-ID: <20120223043334.GB11871@ando> On Wed, Feb 22, 2012 at 07:00:57PM -0600, Tamar Osher wrote: > > Hi. I am still having trouble installing and using Python on my (new) Windows 7 computer, but I plan to contact Microsoft forums and see if they can help me, since this is a Windows problem and not a Python problem. > > My question: For the future, what type of computer is best for Python developers? Do all Python developers use some type of Unix computer? > I appreciate your feedback and look forward to hearing from you. Thanks for your time. For sure, Linux is the best OS for development. That doesn't mean that you can't develop on other OSes, or that Linux is perfect, but generally speaking it is the simplest and easiest, at least once you learn the Linux/Unix ways of thinking, or can memorize a few of the most common commands you need to use. And please don't read this as an attack on Windows, or Mac OS, or whatever your favourite OS is. All OSes have their strengths and weaknesses, and the range and quality of free development tools happens to be one of Linux's biggest strength. If you hang around on the python-dev mailing list, you will see that one of Python's ongoing weaknesses is that the developers don't have enough people able and willing to test Python under Windows and fix problems as they occur. When you ask why, they tell you that it's because dealing with Microsoft licencing is difficult, that the C compilers change too often in backwards-incompatible ways, that they can't get people to do testing, that in a thousand little ways it just isn't fun or easy to develop Python on Windows. Or even develop *in* Python. On my Linux system, I get Python pre-installed, plus a whole bunch of programmers' editors, debugging tools, admin tools, etc. If they don't come installed, they are usually one command away: yum install name-of-package aptitude install name-of-package depending on whether you are using Red Hat based Linux, or Debian based Linux. On Windows, every package needs to be installed by hand. If there's a binary installer, I better hope it works on my system, because compiling it myself is a PITA even if I had a C compiler, which I don't. On Windows, I have Notepad, which is a crap editor, WordPad, which isn't designed for programming, or heavyweight IDEs that come with my compiler. I would need to learn a whole new IDE for every language I learn. On Linux, I have half a dozen programmer's editors already available for me. Even the feeblest, nano, is more powerful than Notepad. I just use whatever tools I'm already used to using, and it just works: http://blog.sanctum.geek.nz/series/unix-as-ide/ Unix/Linux is designed to be an development environment, rather than having development be an optional extra. No suprises there: Linux particularly, but also Unix back in the early days, was built by programmers to scratch their own itch: they wanted a good development environment, and so they built Unix to be a good development environment. With Windows and Mac OS, it is primarily designed as a desktop OS, with development being a necessary evil rather than a design choice. If you decide to shift from Windows to something else, you may find that it's more work learning the new OS than it would have been to have just stuck with what you know and learn to use it effectively. -- Steven From mjolewis at gmail.com Thu Feb 23 06:04:41 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Wed, 22 Feb 2012 21:04:41 -0800 Subject: [Tutor] Writing to a file/changing the file name Message-ID: Hi everyone, I have a program where I open a file (recipe.txt), I read that file and write it to another file. I am doing some multiplying of numbers in between; however, my question is, when I name the file I am writing to, the file extension is changed, but the file name is not. What am I doing wrong? Code: import Homework5_1 as multiply def MultiplyNumbersInFile(file_name, multiplier): '''Open file/read file/write new file that doubles all int's in the read file''' try: read_file = open(file_name) except IOError: print "I can't find file: ", file_name return new_file_name = file_name + '2' try: write_file = open(new_file_name, 'w') except IOError: read_file.close() print "I can't open file: ", new_file_name return for line in read_file: new_line = line.split() new_line = ''.join(multiply.MultiplyText(new_line, multiplier)) write_file.write(new_line + '\n') read_file.close() write_file.close() def main(): file_name = raw_input('What file do you want to open? ') multiplier = multiply.GetUserNumber() MultiplyNumbersInFile(file_name, multiplier) if __name__ == '__main__': main() What I am doing in IDLE: What file do you want to open? recipe.txt Enter a multiplier: 2 The file that is actually created in my directory is still named recipe; however, the file type is now TXT2 File. How do I make it so I am updating the file name to recipe2 instead of the file type? -- Michael J. Lewis -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Thu Feb 23 06:26:23 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 23 Feb 2012 07:26:23 +0200 Subject: [Tutor] Writing to a file/changing the file name In-Reply-To: References: Message-ID: <4F45CDFF.3020306@compuscan.co.za> On 2012/02/23 07:04 AM, Michael Lewis wrote: > Hi everyone, > > I have a program where I open a file (recipe.txt), I read that file > and write it to another file. I am doing some multiplying of numbers > in between; however, my question is, when I name the file I am writing > to, the file extension is changed, but the file name is not. What am I > doing wrong? > > Code: > > import Homework5_1 as multiply > > def MultiplyNumbersInFile(file_name, multiplier): > '''Open file/read file/write new file that doubles all int's in the > read file''' > try: > read_file = open(file_name) > except IOError: > print "I can't find file: ", file_name > return > new_file_name = file_name + '2' > try: > write_file = open(new_file_name, 'w') > except IOError: > read_file.close() > print "I can't open file: ", new_file_name > return > for line in read_file: > new_line = line.split() > new_line = ''.join(multiply.MultiplyText(new_line, multiplier)) > write_file.write(new_line + '\n') > read_file.close() > write_file.close() > > def main(): > file_name = raw_input('What file do you want to open? ') > multiplier = multiply.GetUserNumber() > MultiplyNumbersInFile(file_name, multiplier) > > if __name__ == '__main__': > main() > > What I am doing in IDLE: > > What file do you want to open? recipe.txt > Enter a multiplier: 2 > > The file that is actually created in my directory is still named > recipe; however, the file type is now TXT2 File. How do I make it so I > am updating the file name to recipe2 instead of the file type? > > > -- > Michael J. Lewis > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor That's because your `file_name` variable contains the file name and extension. You will need to split it into it's component pieces and then put it back together once you've changed the name, and for that you can use os.path.splitext >>> import os >>> filename, extension = os.path.splitext('recipe.txt') >>> print (filename, extension) ('recipe', '.txt') >>> new_filename = filename + '2' + extension >>> print new_filename 'recipe2.txt' -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From andipersti at gmail.com Thu Feb 23 07:16:41 2012 From: andipersti at gmail.com (Andreas Perstinger) Date: Thu, 23 Feb 2012 07:16:41 +0100 Subject: [Tutor] help writing functions In-Reply-To: References: Message-ID: <4F45D9C9.4070805@gmail.com> On 2012-02-23 01:59, Saad Javed wrote: > I am learning python and need guidance for writing some code. I've written > a simple program (with pointers from people) that parses an tv show xml > feed and prints their values in plain text after performing some string > operations. > > [CODE]feed = urllib.urlopen(rssPage) #rssPage: address of xml feed ^^^^^^ [snip] > Running this code returns [B]None[/B]. ^^^^^^^^^^^ This is not a web forum, so please post only in plain text. Bye, Andreas From __peter__ at web.de Thu Feb 23 09:39:48 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 23 Feb 2012 09:39:48 +0100 Subject: [Tutor] Reading/dealing/matching with truly huge (ascii) files References: Message-ID: Elaina Ann Hyde wrote: > Thanks for all the helpful hints, I really like the idea of using > distances > instead of a limit. Walter was right that the 'i !=j' condition was > causing problems. I think that Alan and Steven's use of the index > separately was great as it makes this much easier to test (and yes > 'astropysics' is a valid package, it's in there for later when I convert > astrophysical coordinates and whatnot, pretty great but a little buggy > FYI). So I thought, hey, why not try to do a little of all these ideas, > and, if you'll forgive the change in syntax, I think the problem is that > the file might really just be too big to handle, and I'm not sure I have > the right idea with the best_match: > The errors are as follows: dat2=asciitable.read(y,Reader=asciitable.NoHeader,data_start=4,fill_values=['nan','-9.999']) > File > "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site- packages/asciitable-0.8.0-py2.7.egg/asciitable/ui.py", > line 131, in read > dat = _guess(table, new_kwargs) > File > "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site- packages/asciitable-0.8.0-py2.7.egg/asciitable/ui.py", > line 175, in _guess > dat = reader.read(table) > File > "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site- packages/asciitable-0.8.0-py2.7.egg/asciitable/core.py", > line 841, in read > self.lines = self.inputter.get_lines(table) > File > "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site- packages/asciitable-0.8.0-py2.7.egg/asciitable/core.py", > line 158, in get_lines > lines = table.splitlines() > MemoryError > ---------------------- > So this means I don't have enough memory to run through the large file? > Even if I just read in with asciitable I get this problem, I looked again > and the large file is 1.5GB of text lines, so very large. I was thinking > of trying to tell the read function to skip lines that are too far away, > the file is much, much bigger than the area I need. Thanks for the > comments so far. > ~Elaina > Hmm, 1.5GB would be about 30,000 bytes per line if the 50,000 lines you mentioned before are correct. What does $ wc say? Can you give the first few lines of here or on pastebin.com? I don't have asciitables installed but a quick look into the code suggests it consumes a lot more memory than necessary to solve your problem. If the file format is simple a viable alternative may be to extract the interesting columns manually together with the line index. Once you have the best matches you can build the result from and the indices of the best matches. Alternatively you can split into a few parts, calculate the best matches for each part, and finally calculate the best matches of the partial best matches combined. From alan.gauld at btinternet.com Thu Feb 23 09:49:39 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 23 Feb 2012 08:49:39 +0000 Subject: [Tutor] help writing functions In-Reply-To: References: Message-ID: On 23/02/12 00:59, Saad Javed wrote: > [CODE]feed = urllib.urlopen(rssPage) #rssPage: address of xml feed > tree = etree.parse(feed) > x = tree.xpath("/rss/channel/item/title/text()") > x = str(x[0]) > for tag in tags: #tags is a list of items like hdtv, xvid, 720p etc > x = re.sub(r'\b' + tag + r'\b', '', x) > z = re.sub(r'[^\w\s]', '', x) > y = tree1.xpath("/rss/channel/item/pubDate/text()") > print "%s - %s" %(z.rstrip(), y[0][:16])[/CODE] Please don;t insert wiki style markers, its just confusing. Also please use plain text for email otherwise the formatting tends to get lost. > [CODE]def get_value(feed): > try: > url = urllib2.urlopen(feed) > tree = etree.parse(url) > x = tree.xpath("/rss/channel/item/title/text()") > y = tree.xpath("/rss/channel/item/pubDate/text()") > x = str(x[0]) > y = str(y[0][:16]) > return x > return y This will always return x and never y because a return statement terminates the function. If you want to return both values you need to put them in the same return statement: return x,y If you want to return only one you need to select which with an if/else. return x if else y or just if return x else return y If you prefer. > except SyntaxError: You should probably not try catching Syntax errors since thats usually a fault in your code! Instead fix the syntax error. > def del_tag(x): > tags = ['HDTV', 'LOL', 'VTV', 'x264', 'DIMENSION', 'XviD', '720P', > 'IMMERSE', '720p', 'X264'] > for tag in tags: > x = re.sub(r'\b' + tag + r'\b', '', x) > y = re.sub(r'[^\w\s]', '', x) You don't return x or y so they get thrown away at the end of the function. Which makes the whole thing a waste of space... > def main(): > a = get_value(rssPage) > b = del_tag(a) > print b > if __name__ == '__main__': > main()[/CODE] > > Running this code returns [B]None[/B]. None is the default return value if you do not provide one. main has no return statement. Neither does del_tag() Both main and del_tag will therefore return None. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Feb 23 10:00:30 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 23 Feb 2012 09:00:30 +0000 Subject: [Tutor] Which computer operating system is best for Python developers? In-Reply-To: References: Message-ID: On 23/02/12 01:00, Tamar Osher wrote: > Hi. I am still having trouble installing and using Python on my (new) > Windows 7 computer, but I plan to contact Microsoft forums and see if > they can help me, since this is a Windows problem and not a Python problem. I doubt if you have any big issues. You probably only need to set two environment variables that the latest Pythion installers do not set for you. (I'm not sure why!) > My question: For the future, what type of computer is best for Python > developers? Do all Python developers use some type of Unix computer? By no means, one of Pythons strengths is that the same code can run on many OS. But as Steven has mentioned many developers use Linux because GNU/Linux is designed as a developer's OS and comes with oodles of tools. Most of those are available for Windows too but you have to go find them, download them and install them. I used Python on Windows for 11 years. I only switched to Linux full time a year ago when Windows 7 became too expensive and I decided I wasn't paying that much for an OS when a free alternative existed! But I still have Python on my Win7 work's laptop. And I also have it on my 10 year old MacOS iBook. And the same python code runs on all of them... So you don't need to switch OS, just tweak a couple of settings. Go through the procedure I outlined in my previous mail and tell us how you get on. It may be a reinstall of Python is needed, or it may just be the two settings I mentioned above (PATH and PYTHONPATH) One thing: If you do a reinstall, download the ActiveState version rather than the Python.org version. Active state tweak their Windows version of Python to include a bunch of extra goodies for Windows programmers. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Feb 23 11:07:57 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 23 Feb 2012 10:07:57 +0000 Subject: [Tutor] Reading/dealing/matching with truly huge (ascii) files In-Reply-To: References: Message-ID: On 23/02/12 01:55, Elaina Ann Hyde wrote: ns/7.2/lib/python2.7/site-packages/asciitable-0.8.0-py2.7.egg/asciitable/core.py", > line 158, in get_lines > lines = table.splitlines() > MemoryError > ---------------------- > So this means I don't have enough memory to run through the large file? Probably, or the code you are using is doing something extremely inefficient. > Even if I just read in with asciitable I get this problem, I looked > again and the large file is 1.5GB of text lines, so very large. How much RAM do you have? Probably only 1-2G? so I'd suggest trying another approach. Peter has suggested a couple of ideas. The other way is to simply load both files into database tables and use a SQL SELECT to pull out the combined lines. This will probably be faster than trying to do line by line stitch ups in Python. You can also use the SQL interactive prompt to experiment with the query till you are sure its right! Do you know any SQL? If not it is very easy to learn. (See the database topic in my tutorial(v2 only) ) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From dcdavemail at gmail.com Thu Feb 23 13:57:39 2012 From: dcdavemail at gmail.com (David Craig) Date: Thu, 23 Feb 2012 12:57:39 +0000 Subject: [Tutor] Solve wave equation Message-ID: <4F4637C3.2080100@gmail.com> Hi, I am trying to write some code that will solve the 2D wave equation by the finite difference method, but it just returns an array full of zeros and NaN's. Not sure where I am going wrong, the code is attached so if could someone point me in the right direction I'd appreciate this. Thanks D -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Wave.py URL: From steve at pearwood.info Thu Feb 23 14:36:51 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 24 Feb 2012 00:36:51 +1100 Subject: [Tutor] Solve wave equation In-Reply-To: <4F4637C3.2080100@gmail.com> References: <4F4637C3.2080100@gmail.com> Message-ID: <4F4640F3.2040301@pearwood.info> David Craig wrote: > Hi, > I am trying to write some code that will solve the 2D wave equation by > the finite difference method, but it just returns an array full of zeros > and NaN's. Not sure where I am going wrong, the code is attached so if > could someone point me in the right direction I'd appreciate this. I'm not enough of a mathematician to tell what the solution of the 2D wave equation by the finite difference method should be. Are you sure that an array full of zeroes and NANs is not the right answer? Perhaps this is telling you that there is no solution? A couple of other random stumbles in the dark: > dt = 1**-4 Do you realise that 1**-4 == 1? > # Set up pressure field. > p=empty([nx,nz,nsteps]) This sets p to an array with random values (whatever rubbish just happens to be in memory at the time). You are expected to initialize the values yourself. Since you go on to try to initialize to all zeroes, you should consider using numpy's zeroes() function instead of empty(). > for t in range(0,nsteps-1): > for z in range(0,nz-1): > for x in range(0,nx-1): > p[x,z,t] = 0 I'm pretty sure you end the loops one iteration too early here. Your array is indexed by x = 0...nx-1 inclusive z = 0...nz-1 inclusive t = 0...nsteps-1 inclusive (that is, the half-open intervals [0, nx) etc.) but you initialize only the values x = 0...nx-2 inclusive, etc. This is because Python's range() is already half-open on the right: py> range(0, 10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] By subtracting one, you miss an item: py> range(0, 10-1) [0, 1, 2, 3, 4, 5, 6, 7, 8] -- Steven From mail at timgolden.me.uk Thu Feb 23 15:15:50 2012 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 23 Feb 2012 14:15:50 +0000 Subject: [Tutor] Which computer operating system is best for Python developers? In-Reply-To: References: Message-ID: <4F464A16.1080802@timgolden.me.uk> On 23/02/2012 09:00, Alan Gauld wrote: > By no means, one of Pythons strengths is that the same code can run on > many OS. But as Steven has mentioned many developers use Linux because > GNU/Linux is designed as a developer's OS and comes with oodles of > tools. Most of those are available for Windows too but you have to go > find them, download them and install them. > One thing: > If you do a reinstall, download the ActiveState version rather > than the Python.org version. Active state tweak their Windows > version of Python to include a bunch of extra goodies for Windows > programmers. > Just seconding both of Alan's points here. I have been fruitfully using Python on Windows for more than 12 years now and I am one of the very few core developers who works in Windows (although sadly lacking the time at the moment to contribute much). I develop Python-based websites which run unaltered on my Win7 laptop, my WinXP desktop, and whatever flavour of Linux my hosting provider is using. (It could be RedHat or CentOS but I don't care because it just works). You need to do a very small bit of initial assumption-bashing to ensure that things will work across platforms, but once that's done you never have to change anything again. I also recommend the ActiveState distro. It sets Python up on the PATH and adds pip in the right places. Both of those are easy enough to do for yourself, but it's nice to have it done for you. TJG From jugurtha.hadjar at gmail.com Thu Feb 23 16:23:07 2012 From: jugurtha.hadjar at gmail.com (Jugurtha Hadjar) Date: Thu, 23 Feb 2012 16:23:07 +0100 Subject: [Tutor] Which computer operating system is best for Python developers? In-Reply-To: References: Message-ID: <4F4659DB.9040605@gmail.com> On 23/02/2012 02:00, Tamar Osher wrote: > Hi. I am still having trouble installing and using Python on my (new) Windows 7 computer, but I plan to contact Microsoft forums and see if they can help me, since this is a Windows problem and not a Python problem. > > My question: For the future, what type of computer is best for Python developers? Do all Python developers use some type of Unix computer? > I appreciate your feedback and look forward to hearing from you. Thanks for your time. > That's actually a good question. I am in Instrumentation Engineering (Electronics), and a lot of the software is designed to run only in Windows, or, the equivalent software in Linux is more for hobbyists than for professionnals (Think software for printed circuit boards), or, in the best case there are versions that run on Linux, but they aren't as featured or updated as the one that run on Windows. So I work on Windows. I have both Python26 and Python32 installed (Python26 for things like Numpy/SciPy). I also installed VirtualBox and run Ubuntu 11.10. It's nice because most of the software I use is on Windows, but I fire up the virtual machine sometimes for programming stuff. So it depends what you do and the software you use. One last point: Having two versions of Python, here's what I did in order to chose which version is used depending what I'm doing (If I'm tinkering with Numpy, I must use Python26) Python 2.6 is installed in C:\Python26 Python 3.2 is installed in C:\Python32 I added both paths to the Windows Environment Variables. I created two .bat files named Python26.bat and Python32.bat, each one in the respective directory. The Python26.bat file contains the follwoing lines: @echo off C:\Python26\python.exe %1 And the Python32.bat file contains the follwoing lines: @echo off C:\Python32\python.exe %1 So, if I write "python26 test.py" in the command line, the script gets "executed" by Python 2.6. In the same way, if I write "python32 test.py", it gets executed by Python 3.2.. Just a little thing to make my life easier. PS: If you have any question regarding the setting of the Virtual Box to run Ubuntu as a guest on Windows, feel free to ask for details. I'll be glad to provide links and things like that. -- ~Jugurtha Hadjar, From dcdavemail at gmail.com Thu Feb 23 16:24:45 2012 From: dcdavemail at gmail.com (David Craig) Date: Thu, 23 Feb 2012 15:24:45 +0000 Subject: [Tutor] Solve wave equation In-Reply-To: <12104546.1330004390350.JavaMail.root@elwamui-lapwing.atl.sa.earthlink.net> References: <12104546.1330004390350.JavaMail.root@elwamui-lapwing.atl.sa.earthlink.net> Message-ID: <4F465A3D.80704@gmail.com> Hooray it works, thanks On 02/23/2012 01:39 PM, Ken Oliver wrote: > Do you really want dt = 1**-4 or would 10**-4 be better > > -----Original Message----- >> From: David Craig >> Sent: Feb 23, 2012 7:57 AM >> To: tutor at python.org >> Subject: [Tutor] Solve wave equation >> >> Hi, >> I am trying to write some code that will solve the 2D wave equation by >> the finite difference method, but it just returns an array full of zeros >> and NaN's. Not sure where I am going wrong, the code is attached so if >> could someone point me in the right direction I'd appreciate this. >> Thanks >> D > > . > From sbjaved at gmail.com Thu Feb 23 16:41:44 2012 From: sbjaved at gmail.com (Saad Javed) Date: Thu, 23 Feb 2012 20:41:44 +0500 Subject: [Tutor] help writing functions In-Reply-To: References: Message-ID: Sorry for the formatting. Added return statements to both functions. Adding return [x, y] to get_value func. That solved the problem. Thank you! :) Saad On Thursday, February 23, 2012, Alan Gauld wrote: > On 23/02/12 00:59, Saad Javed wrote: > > [CODE]feed = urllib.urlopen(rssPage) #rssPage: address of xml feed >> tree = etree.parse(feed) >> x = tree.xpath("/rss/channel/item/**title/text()") >> x = str(x[0]) >> for tag in tags: #tags is a list of items like hdtv, xvid, 720p etc >> x = re.sub(r'\b' + tag + r'\b', '', x) >> z = re.sub(r'[^\w\s]', '', x) >> y = tree1.xpath("/rss/channel/**item/pubDate/text()") >> print "%s - %s" %(z.rstrip(), y[0][:16])[/CODE] >> > > Please don;t insert wiki style markers, its just confusing. > Also please use plain text for email otherwise the formatting > tends to get lost. > > [CODE]def get_value(feed): >> try: >> url = urllib2.urlopen(feed) >> tree = etree.parse(url) >> x = tree.xpath("/rss/channel/item/**title/text()") >> y = tree.xpath("/rss/channel/item/**pubDate/text()") >> x = str(x[0]) >> y = str(y[0][:16]) >> return x >> return y >> > > This will always return x and never y because a return statement > terminates the function. If you want to return both values you need to put > them in the same return statement: > > return x,y > > If you want to return only one you need to select which > with an if/else. > > return x if else y > > or just > > if > return x > else > return y > > If you prefer. > > except SyntaxError: >> > > You should probably not try catching Syntax errors since thats usually a > fault in your code! Instead fix the syntax error. > > def del_tag(x): >> tags = ['HDTV', 'LOL', 'VTV', 'x264', 'DIMENSION', 'XviD', '720P', >> 'IMMERSE', '720p', 'X264'] >> for tag in tags: >> x = re.sub(r'\b' + tag + r'\b', '', x) >> y = re.sub(r'[^\w\s]', '', x) >> > > You don't return x or y so they get thrown away at the end of the > function. Which makes the whole thing a waste of space... > > def main(): >> a = get_value(rssPage) >> b = del_tag(a) >> print b >> if __name__ == '__main__': >> main()[/CODE] >> >> Running this code returns [B]None[/B]. >> > > None is the default return value if you do not provide one. > main has no return statement. Neither does del_tag() > Both main and del_tag will therefore return None. > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Thu Feb 23 16:46:40 2012 From: d at davea.name (Dave Angel) Date: Thu, 23 Feb 2012 10:46:40 -0500 Subject: [Tutor] Which computer operating system is best for Python developers? In-Reply-To: <4F4659DB.9040605@gmail.com> References: <4F4659DB.9040605@gmail.com> Message-ID: <4F465F60.7030709@davea.name> On 02/23/2012 10:23 AM, Jugurtha Hadjar wrote: > > One last point: Having two versions of Python, here's what I did in > order to chose which version is used depending what I'm doing (If I'm > tinkering with Numpy, I must use Python26) > > > Python 2.6 is installed in C:\Python26 > Python 3.2 is installed in C:\Python32 > > I added both paths to the Windows Environment Variables. > > I created two .bat files named Python26.bat and Python32.bat, each one > in the respective directory. > > The Python26.bat file contains the follwoing lines: > > @echo off > C:\Python26\python.exe %1 > > And the Python32.bat file contains the follwoing lines: > > @echo off > C:\Python32\python.exe %1 > I'm not running Windows any more (except in a VirtualBox), but your batch files could be improved: Since you only have the one useful line in the batch file, just put the @ on that line; no need to turn off echo for the whole file, when the file is one line. And i forget whether it's %* or %$ but there is a substitution string you can use to mean "all the arguments", rather than just taking one. Remember that sometimes people want to run python with multiple arguments. I also made a "bat" directory, and added it to the PATH. Then you put both those batch files, plus some others, into the bat directory. That assumes you'll keep finding more utilities you'd like to add to the path. No biggie, just trying to help. There are more complicated changes that I used to do, which I won't mention here. -- DaveA From jugurtha.hadjar at gmail.com Thu Feb 23 17:12:39 2012 From: jugurtha.hadjar at gmail.com (Jugurtha Hadjar) Date: Thu, 23 Feb 2012 17:12:39 +0100 Subject: [Tutor] Which computer operating system is best for Python developers? In-Reply-To: <4F465F60.7030709@davea.name> References: <4F4659DB.9040605@gmail.com> <4F465F60.7030709@davea.name> Message-ID: <4F466577.2000803@gmail.com> On 23/02/2012 16:46, Dave Angel wrote: > I'm not running Windows any more (except in a VirtualBox), but your > batch files could be improved: > > Since you only have the one useful line in the batch file, just put > the @ on that line; no need to turn off echo for the whole file, when > the file is one line. > > And i forget whether it's %* or %$ but there is a substitution > string you can use to mean "all the arguments", rather than just > taking one. Remember that sometimes people want to run python with > multiple arguments. > > I also made a "bat" directory, and added it to the PATH. Then you put > both those batch files, plus some others, into the bat directory. > That assumes you'll keep finding more utilities you'd like to add to > the path. > > No biggie, just trying to help. There are more complicated changes > that I used to do, which I won't mention here. > > -- > > DaveA Hey, these are very neat ideas (especially the "bat" folder and the arguments point) .. Thank you ! -- ~Jugurtha Hadjar, From breamoreboy at yahoo.co.uk Thu Feb 23 17:35:38 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 23 Feb 2012 16:35:38 +0000 Subject: [Tutor] Which computer operating system is best for Python developers? In-Reply-To: <4F4659DB.9040605@gmail.com> References: <4F4659DB.9040605@gmail.com> Message-ID: On 23/02/2012 15:23, Jugurtha Hadjar wrote: > On 23/02/2012 02:00, Tamar Osher wrote: >> Hi. I am still having trouble installing and using Python on my (new) >> Windows 7 computer, but I plan to contact Microsoft forums and see if >> they can help me, since this is a Windows problem and not a Python >> problem. >> >> My question: For the future, what type of computer is best for Python >> developers? Do all Python developers use some type of Unix computer? >> I appreciate your feedback and look forward to hearing from you. >> Thanks for your time. >> > > That's actually a good question. > > I am in Instrumentation Engineering (Electronics), and a lot of the > software is designed to run only in Windows, or, the equivalent software > in Linux is more for hobbyists than for professionnals (Think software > for printed circuit boards), or, in the best case there are versions > that run on Linux, but they aren't as featured or updated as the one > that run on Windows. > > So I work on Windows. I have both Python26 and Python32 installed > (Python26 for things like Numpy/SciPy). > > I also installed VirtualBox and run Ubuntu 11.10. It's nice because most > of the software I use is on Windows, but I fire up the virtual machine > sometimes for programming stuff. > > So it depends what you do and the software you use. > > One last point: Having two versions of Python, here's what I did in > order to chose which version is used depending what I'm doing (If I'm > tinkering with Numpy, I must use Python26) > > > Python 2.6 is installed in C:\Python26 > Python 3.2 is installed in C:\Python32 > > I added both paths to the Windows Environment Variables. > > I created two .bat files named Python26.bat and Python32.bat, each one > in the respective directory. > > The Python26.bat file contains the follwoing lines: > > @echo off > C:\Python26\python.exe %1 > > And the Python32.bat file contains the follwoing lines: > > @echo off > C:\Python32\python.exe %1 > > > So, if I write "python26 test.py" in the command line, the script gets > "executed" by Python 2.6. > In the same way, if I write "python32 test.py", it gets executed by > Python 3.2.. > > Just a little thing to make my life easier. > > > PS: If you have any question regarding the setting of the Virtual Box to > run Ubuntu as a guest on Windows, feel free to ask for details. I'll be > glad to provide links and things like that. > Have you seen pylauncher? https://bitbucket.org/vinay.sajip/pylauncher Here's the background http://www.python.org/dev/peps/pep-0397/ -- Cheers. Mark Lawrence. From bgailer at gmail.com Thu Feb 23 17:57:05 2012 From: bgailer at gmail.com (bob gailer) Date: Thu, 23 Feb 2012 11:57:05 -0500 Subject: [Tutor] Writing to a file/changing the file name In-Reply-To: References: Message-ID: <4F466FE1.1090404@gmail.com> On 2/23/2012 12:04 AM, Michael Lewis wrote: > Hi everyone, > > I have a program where I open a file (recipe.txt), I read that file > and write it to another file. I am doing some multiplying of numbers > in between; however, my question is, when I name the file I am writing > to, the file extension is changed, but the file name is not. What am I > doing wrong? Christian gave you the answer (he "fished" for you) How to "fish" for yourself: Before posting a question do a walkthru of the program. This means pretending you are the Python interpreter and your job is to execute the program step-by-step, writing down the effect of each statement You will find many answers yourself this way, saving all of us time and energy. in the above case take the statement new_file_name = file_name + '2' and do this: file_name is "recipe.txt" file_name + '2' is If you come up with anything other than "recipe.txt2" then you need to review how Python works. Another idea is: when you get an unexpected result there must be a very good reason for it. Do a little hunting. Each time you solve a problem for yourself you get stronger. HTH -- Bob Gailer 919-636-4239 Chapel Hill NC From dcdavemail at gmail.com Thu Feb 23 18:32:39 2012 From: dcdavemail at gmail.com (David Craig) Date: Thu, 23 Feb 2012 17:32:39 +0000 Subject: [Tutor] Solve wave equation Message-ID: <4F467837.8000009@gmail.com> OK so I can solve the equation but now I am having trouble plotting the solution! I would like to produce a surface plot with colors defined by p and animate it. That is plot the value of p at all x and z, over time (t). My code to get p is below but I really have no idea how to plot this. Anyone know the best way to go about this? thanks, D -------- Original Message -------- Subject: Re: [Tutor] Solve wave equation Date: Thu, 23 Feb 2012 15:24:45 +0000 From: David Craig To: tutor at python.org Hooray it works, thanks On 02/23/2012 01:39 PM, Ken Oliver wrote: > Do you really want dt = 1**-4 or would 10**-4 be better > > -----Original Message----- >> From: David Craig >> Sent: Feb 23, 2012 7:57 AM >> To: tutor at python.org >> Subject: [Tutor] Solve wave equation >> >> Hi, >> I am trying to write some code that will solve the 2D wave equation by >> the finite difference method, but it just returns an array full of zeros >> and NaN's. Not sure where I am going wrong, the code is attached so if >> could someone point me in the right direction I'd appreciate this. >> Thanks >> D > > . > # 2D Finite Distance Wave Equation. from pylab import * from numpy import math ion() # Set up variables. nx = 100 nz = 100 nsteps = 300 c = 3500 dt = 10**-4 h = 1 t = arange(0,nsteps,dt) # Define source as a spike. s = zeros(nsteps) s[1] = 1 s[2] = 2 s[3] = 1 # Position source. xs = 50 zs = 50 ##plot(t,s) ##show() # Set up pressure field. p=empty([nx,nz,nsteps]) for t in range(0,nsteps-1): for z in range(0,nz-1): for x in range(0,nx-1): p[x,z,t] = 0 # Solve wave equation for t in range(2,nsteps-1): for z in range(1,nz-1): for x in range(2,nx-1): p[xs,zs,t] = s[t] k = (c*dt/h)**2 p[x,z,t] = 2*p[x,z,t-1] - p[x,z,t-2] + k*(p[x+1,z,t-1]-4*p[x,z,t-1]+p[x-1,z,t-1]+p[x,z+1,t-1]+p[x,z-1,t-1]) #Plot somehow draw() #close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Thu Feb 23 19:12:09 2012 From: evert.rol at gmail.com (Evert Rol) Date: Thu, 23 Feb 2012 19:12:09 +0100 Subject: [Tutor] Solve wave equation In-Reply-To: <4F467837.8000009@gmail.com> References: <4F467837.8000009@gmail.com> Message-ID: > OK so I can solve the equation but now I am having trouble plotting the solution! I would like to produce a surface plot with colors defined by p and animate it. That is plot the value of p at all x and z, over time (t). My code to get p is below but I really have no idea how to plot this. Anyone know the best way to go about this? A quick search on "matplotlib surface plot" (since you're already using matplotlib) led me to http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/tutorial.html#surface-plots Perhaps that's something you can use? Your statement 'colors defined by p' leads more to using contour plots instead, and variants thereof: http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.contourf I assume with "animate it", you just want to show every plot, continuously updating it. With matplotlib, that may be a bit slow, but you could save each figure to disk and then use some tool to put them into a movie (mpeg, wmv, animated gif, anything) if this is something you want to present to other people. Evert > thanks, > D > > -------- Original Message -------- > Subject: Re: [Tutor] Solve wave equation > Date: Thu, 23 Feb 2012 15:24:45 +0000 > From: David Craig > To: tutor at python.org > > Hooray it works, > thanks > > On 02/23/2012 01:39 PM, Ken Oliver wrote: > > Do you really want dt = 1**-4 or would 10**-4 be better > > > > -----Original Message----- > >> From: David Craig > > > >> Sent: Feb 23, 2012 7:57 AM > >> To: > tutor at python.org > > >> Subject: [Tutor] Solve wave equation > >> > >> Hi, > >> I am trying to write some code that will solve the 2D wave equation by > >> the finite difference method, but it just returns an array full of zeros > >> and NaN's. Not sure where I am going wrong, the code is attached so if > >> could someone point me in the right direction I'd appreciate this. > >> Thanks > >> D > > > > . > > > > # 2D Finite Distance Wave Equation. > from pylab import * > from numpy import math > > ion() > > # Set up variables. > nx = 100 > nz = 100 > nsteps = 300 > c = 3500 > dt = 10**-4 > h = 1 > t = arange(0,nsteps,dt) > > > > # Define source as a spike. > s = zeros(nsteps) > s[1] = 1 > s[2] = 2 > s[3] = 1 > > # Position source. > xs = 50 > zs = 50 > ##plot(t,s) > ##show() > > # Set up pressure field. > p=empty([nx,nz,nsteps]) > > for t in range(0,nsteps-1): > > for z in range(0,nz-1): > > for x in range(0,nx-1): > > p[x,z,t] = 0 > > > # Solve wave equation > > for t in range(2,nsteps-1): > > for z in range(1,nz-1): > > for x in range(2,nx-1): > > p[xs,zs,t] = s[t] > k = (c*dt/h)**2 > > p[x,z,t] = 2*p[x,z,t-1] - p[x,z,t-2] + k*(p[x+1,z,t-1]-4*p[x,z,t-1]+p[x-1,z,t-1]+p[x,z+1,t-1]+p[x,z-1,t-1]) > > > #Plot somehow > > draw() > > #close() > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From comer.duncan at gmail.com Thu Feb 23 21:14:39 2012 From: comer.duncan at gmail.com (Comer Duncan) Date: Thu, 23 Feb 2012 15:14:39 -0500 Subject: [Tutor] how to uninstall distutils? Message-ID: Hi, I have distutils 0.9 install under Python 2.7. I want to uninstall it. I am on a Macbook pro running Lion. The site-packages directory is in /Lib/Python/2.7/site-packages. There distutils exists along with a lot of other stuff I have installed. I do not have pip installed and in fact installed distutils 0.9 from the distutils directory by running as usual sudo python2.7 setup.py install. I am unsure whether I can just remove the distutils stuff in the site-packages directory and do so safely. Can you please advise me on the safe way to completely remove distutils? Thanks for your help. Comer From comer.duncan at gmail.com Thu Feb 23 21:54:47 2012 From: comer.duncan at gmail.com (Comer Duncan) Date: Thu, 23 Feb 2012 15:54:47 -0500 Subject: [Tutor] how to uninstall distutils? In-Reply-To: References: Message-ID: Wow, I screwed up. I meant docutils rather than distutils !! Sorry for the crazy fingers. On Thu, Feb 23, 2012 at 3:14 PM, Comer Duncan wrote: > Hi, > > I have distutils 0.9 install under Python 2.7. I want to uninstall it. > ?I am on a Macbook pro running Lion. The site-packages directory is in > /Lib/Python/2.7/site-packages. ?There distutils exists along with a > lot of other stuff ?I have installed. ?I do not have pip installed and > in fact installed distutils 0.9 from the distutils directory by > running as usual sudo python2.7 setup.py install. ?I am unsure whether > I can just remove the distutils stuff in the site-packages directory > and do so safely. ?Can you please advise me on the safe way to > completely remove distutils? > > Thanks for your help. > > Comer From elainahyde at gmail.com Fri Feb 24 06:11:36 2012 From: elainahyde at gmail.com (Elaina Ann Hyde) Date: Fri, 24 Feb 2012 16:11:36 +1100 Subject: [Tutor] Reading/dealing/matching with truly huge (ascii) files In-Reply-To: References: Message-ID: On Thu, Feb 23, 2012 at 9:07 PM, Alan Gauld wrote: > On 23/02/12 01:55, Elaina Ann Hyde wrote: > ns/7.2/lib/python2.7/site-**packages/asciitable-0.8.0-py2.**7.egg/asciitable/core.py", > > >> line 158, in get_lines >> lines = table.splitlines() >> MemoryError >> ---------------------- >> So this means I don't have enough memory to run through the large file? >> > > Probably, or the code you are using is doing something extremely > inefficient. > > > Even if I just read in with asciitable I get this problem, I looked >> again and the large file is 1.5GB of text lines, so very large. >> > > How much RAM do you have? Probably only 1-2G? so I'd suggest trying > another approach. > > Peter has suggested a couple of ideas. > > The other way is to simply load both files into database tables and use a > SQL SELECT to pull out the combined lines. This will probably be faster > than trying to do line by line stitch ups in Python. > > You can also use the SQL interactive prompt to experiment with the query > till you are sure its right! > > Do you know any SQL? If not it is very easy to learn. > (See the database topic in my tutorial(v2 only) ) > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > Ok, if I use awk I seperate the file into an edible 240MB chunk, I do my initial sorting there. Now, having learned my lesson from last time, using numpy is/can be faster than looping for an array, so if I want to find the minimum distance and get matches. I cobbled these together and now the matching is reasonably fast and seems to be doing quite well. ------------------------------------------------------------------------ #!/usr/bin/python # import modules used here -- sys is a very standard one import sys import asciitable import matplotlib import matplotlib.path as mpath import matplotlib.pyplot as plt from matplotlib.pyplot import figure, show from matplotlib.patches import Ellipse import scipy import numpy as np from numpy import * import math import pylab import random from pylab import * import astropysics import astropysics.obstools import astropysics.coords from astropysics.coords import ICRSCoordinates,GalacticCoordinates x=open('Core_rod_name.list') y=open('2MASS_subsetJKmikesigs18_19_36_27') dat=asciitable.read(x,Reader=asciitable.CommentedHeader, fill_values=['','-999.99']) #first convert from decimal radians to degrees Radeg=dat['ra-drad']*180./math.pi Decdeg=dat['dec-drad']*180./math.pi dat2 = asciitable.read(y,Reader=asciitable.NoHeader,fill_values=[' nan','-99.9']) fopen = open('allfiles_rod2Mass.list','w') #here are the 2 values for the large file #converts hexadecimal in multiple columns to regular degrees Radeg2 = 15*(dat2['col1']+(dat2['col2']/60.)+(dat2['col3']/(60.*60.))) Decdeg2 = dat2['col4']-(dat2['col5']/60.)-(dat2['col6']/(60.*60.)) #try defining distances instead of a limit #built in numpy function faster than a loop, combine numpy and loop def distance(Ra1,Dec1,Ra2,Dec2): x = Ra1 - Ra2 y = Dec1 - Dec2 return np.sqrt(x*x+y*y) fopen=open('matches.list','w') best_match=[] for i in xrange(len(Radeg)): dist2 = np.array(distance(Radeg[i],Decdeg[i],Radeg2,Decdeg2)) best_match = where(dist2==min(dist2))[0][0] Rab = Radeg2[best_match] Decb = Decdeg2[best_match] fopen.write(str(dist2[best_match])+" "+" ".join([str(k) for k in list(dat[i])])+" "+" ".join([str(k) for k in list(dat2[best_match])])+"\n") fopen.close() ---------------------------------------------------------- Thanks everyone! All your comments were really helpful, I think I might even be getting the hang of this! ~Elaina -- PhD Candidate Department of Physics and Astronomy Faculty of Science Macquarie University North Ryde, NSW 2109, Australia -------------- next part -------------- An HTML attachment was scrubbed... URL: From pasokan at talentsprint.com Fri Feb 24 06:33:30 2012 From: pasokan at talentsprint.com (Asokan Pichai) Date: Fri, 24 Feb 2012 11:03:30 +0530 Subject: [Tutor] Reading/dealing/matching with truly huge (ascii) files In-Reply-To: References: Message-ID: Did you try loadtxt() from numpy? http://mail.scipy.org/pipermail/scipy-user/2010-August/026431.html the poster above notes that 2.5 million lines and 10 columns takes 3 minutes to load. Asokan Pichai From alan.gauld at btinternet.com Fri Feb 24 08:36:28 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 24 Feb 2012 07:36:28 +0000 Subject: [Tutor] Reading/dealing/matching with truly huge (ascii) files In-Reply-To: References: Message-ID: On 24/02/12 05:11, Elaina Ann Hyde wrote: > Ok, if I use awk I seperate the file into an edible 240MB chunk, Why awk? Python is nearly always faster than awk... Even nawk or gawk. awk is a great language but I rarely use it nowadays other than for one liners because perl/python/ruby are all generally faster for non trivial tasks. split OTOH should be faster still for chunking a file. But by keeping the chunking as part of your program you don't have the switching time between apps. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ljmamoreira at gmail.com Fri Feb 24 11:30:43 2012 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Fri, 24 Feb 2012 10:30:43 +0000 Subject: [Tutor] Solve wave equation In-Reply-To: <4F4637C3.2080100@gmail.com> References: <4F4637C3.2080100@gmail.com> Message-ID: <10393047.JEqUO4zSnH@mu.site> On Thursday, February 23, 2012 12:57:39 PM David Craig wrote: > Hi, > I am trying to write some code that will solve the 2D wave equation by > the finite difference method, but it just returns an array full of zeros > and NaN's. Not sure where I am going wrong, the code is attached so if > could someone point me in the right direction I'd appreciate this. > Thanks > D Let me add my 2 cents to Steven's suggestions. The main cicle of your program can be reorganized, pulling out all constant calculations. Where you write >for t in range(2,nsteps-1): > > > for z in range(1,nz-1): > > for x in range(2,nx-1): > > p[xs,zs,t] = s[t] > > k = (c*dt/h)**2 > > p[x,z,t] = 2*p[x,z,t-1] - p[x,z,t-2] + [...] I'd write k = (c*dt/h)**2 for t in range(2,nsteps-1): p[xs,zs,t] = s[t] for z in range(1,nz-1): for x in range(2,nx-1): p[x,z,t] = 2*p[x,z,t-1] - p[x,z,t-2] + [...] Like that you don't have to compute the value of k (wich is constant) for each cell in your mesh and for every time slice. I didn't quite understand the way you integrate the source in the calculation, but if it works the way you do it, it should also work putting it out of the x and z loops; like that, you just have to compute it once for each time slice. Also, whenever possible, try to implement the iterations (for loops) over array elements as whole array operations, wich are way faster then python for loops. For instance, the laplacian of the wave function, > k*(p[x+1,z,t-1]-4*p[x,z,t-1]+p[x-1,z,t-1]+p[x,z+1,t-1]+p[x,z-1,t-1]) can be computed at once (without for loops) with something like (haven't tryed it, take care, read the docs) >k*(roll(p[:,:,t-1],-1,axis=1) - 4*p[:,:,t-1] + roll(p[:,:,t-1],1,axis=1) + roll(p[:,:,t-1],-1,axis=0) + roll(p[:,:,t-1],1,axis=0)) (mind the linebreak). This expression returns an array with the dimensions of your pressure array p. It may have to be tweaked a bit because of boundary behaviour of the roll function. roll() is a numpy function (must be imported from numpy) that shifts the array elements. See http://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html Some examples: In [1]: from numpy import * In [2]: m=array([[11,12,13],[21,22,23],[31,32,33]]) In [3]: print m [[11 12 13] [21 22 23] [31 32 33]] In [4]: roll(m,-1,axis=1) Out[4]: array([[12, 13, 11], [22, 23, 21], [32, 33, 31]]) In [5]: roll(m,1,axis=0) Out[5]: array([[31, 32, 33], [11, 12, 13], [21, 22, 23]]) Finally, about the plot, I find the matplotlib contour function too slow (it's not trivial to compute the contour lines) for animations. I prefer a method that directly maps values into colors. Someone in this list suggested pygame's surfarray methods, and that's what I've been using. I hope this helps. Cheers, Ze -------------- next part -------------- An HTML attachment was scrubbed... URL: From nsivaram.net at gmail.com Fri Feb 24 16:43:25 2012 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Fri, 24 Feb 2012 21:13:25 +0530 Subject: [Tutor] Suggestions for a good intro OO & Python Message-ID: <82mx88grtu.fsf@gmail.com> Can someone point me to a good intro on OO in Python? If it does OO basics too, even better, assuming no prior knowledge of Object Orientation. sivaram -- From akekhofananaye at yahoo.co.uk Fri Feb 24 17:08:51 2012 From: akekhofananaye at yahoo.co.uk (SKHUMBUZO ZIKHALI) Date: Fri, 24 Feb 2012 16:08:51 +0000 (GMT) Subject: [Tutor] Attribute error message received on Card Game program Message-ID: <1330099731.47759.YahooMailNeo@web24004.mail.ird.yahoo.com> Hi I am trying to run the following program?from Guide to Programming with Python by Micheal Dawson: ? class Card(object): ??? RANK = ["A","2","3","4","5","6","7" ??????????? "8","9","K","Q","J"] ??? SUIT = ["s","d","h","c"] ??? def __init__(self,rank, suit): ??????? self.rank = rank ??????? self.suit = suit ??? def __str__(self): ??????? rep = self.rank + self.suit ??????? return rep ???????????? class Hand(object): ??? def __init__(self): ??????? self.cards = [] ??? def __str__(self): ??????? if self.cards: ??????????? rep = '' ??????????? for card in self.card: ??????????????? rep += str(Card)+''????? ??????? else: ??????????? rep = "" ??????????? return rep ??? def clear(self): ??????? self.cards =[] ??? def add(self, card): ??????? self.cards.append(card) ??? def give(self, card, other_hand): ??????? self.cards.remove(card) ??????? other_hand.add(card) # Main card1 = Card(rank = "A", suit ="c") print 'Printing a Card object' print card1 card2 = Card(rank = "2", suit ="c") card3 = Card(rank = "3", suit ="c") card4 = Card(rank = "4", suit ="c") card5 = Card(rank = "5", suit ="c") print card2 print card3 print card4 print card5 my_hand = Hand() print '\nPrinting my hand before I add my card:' print my_hand my_hand.add(card1) my_hand.add(card2) my_hand.add(card3) my_hand.add(card4) my_hand.add(card5) print '\nPrinting my hand after adding 5 cards:' print my_hand your_hand = Hand() my_hand.give(card1, your_hand) my_hand.give(card2, your_hand) print '\nGave the first two cards from my hand to your hand.' print 'Your hand:' print your_hand print 'My hand:' my_hand my_hand.clear() print '\nMy hand after clearing it:' raw_input('\n\nPress the enter key to exist.') However, I can partly run it for eventually receive attribute error message. Printing response is as follows: 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> ================================ RESTART ================================ >>> Printing a Card object Ac 2c 3c 4c 5c Printing my hand before I add my card: Printing my hand after adding 5 cards: Traceback (most recent call last): ? File "C:/Python27/Card Game.py", line 69, in ??? print my_hand ? File "C:/Python27/Card Game.py", line 25, in __str__ ??? for card in self.card: AttributeError: 'Hand' object has no attribute 'card' >>> Would you please help me as to where I got it wrong with this program and lastly inform how?how does Hand object gets linked or connected with Card object?? With thanks? Sikhumbuzo??? -------------- next part -------------- An HTML attachment was scrubbed... URL: From dcdavemail at gmail.com Fri Feb 24 17:11:20 2012 From: dcdavemail at gmail.com (David Craig) Date: Fri, 24 Feb 2012 16:11:20 +0000 Subject: [Tutor] problem editing modules and defs Message-ID: <4F47B6A8.2060200@ucdconnect.ie> Hi, I am new to python and have made a couple of definitions. I imported them and they worked ok. I they worked except for one which gave me the error "NameError: global name 'np' is not defined". I then edited my script for the def to include "import numpy as np" saved it and imported the def again. However, it still gives me the same error. I know I have to be doing something basic wrong but cant figure it out, anyone know what I am doing wrong. The def is below. thanks D import numpy as np def find_nearest(array,value): idx=(np.abs(array-value)).argmin() return array[idx] From evert.rol at gmail.com Fri Feb 24 17:28:16 2012 From: evert.rol at gmail.com (Evert Rol) Date: Fri, 24 Feb 2012 17:28:16 +0100 Subject: [Tutor] problem editing modules and defs In-Reply-To: <4F47B6A8.2060200@ucdconnect.ie> References: <4F47B6A8.2060200@ucdconnect.ie> Message-ID: <87E945D1-A482-4686-B7E9-9EF8974522CB@gmail.com> Hi David, > Hi, > I am new to python and have made a couple of definitions. I imported them and they worked ok. I they worked except for one which gave me the error "NameError: global name 'np' is not defined". I then edited my script for the def to include "import numpy as np" saved it and imported the def again. However, it still gives me the same error. I know I have to be doing something basic wrong but cant figure it out, anyone know what I am doing wrong. The def is below. > thanks Minor thing first: in Python terminology, most of the time your 'definitions' are simply called functions, although you're correct that "def" refers to definition. But thatt's more about where the function is defined, in contrast to where in the code it is called (or perhaps even declared, though I don't think that applies to Python). When you say "I imported the def again", it sounds like you're working on the Python interpreter, and doing >>> import myscript or similar. If that's how you run things, you would have to use the reload() function to reload the new function definition, which has your correction. However, you also talk about 'my script'. A script is something I would run from the shell command line, like $> python myscript.py If you do things that way, you would always be ensured that python uses the latest edits in your script. It does mean that any command you would normally type into the Python interpreter, you would now have to enter in the script. And while the interpreter always shows the evaluation result of the last command entered, a script would require a print for that. Compare: >>> a=1 >>> a 1 versus (inside a script): a = 1 a # this doesn't show anything print a # this does Perhaps this is too basic, but I have to guess a bit what you are doing from your text. A few tips to get more practical help: - Python normally shows a stack trace when there is an error. It is good to copy-paste the whole thing in your emails. Just typing the last bit often doesn't help. - Copy-paste (again, don't type) whatever you're doing in the Python interpreter, if that's what you are using. So we can how you do things (examples are clearer than descriptions). If needs be, intersperse with comments. Compare eg: >>> import myscript NameError: global name 'np' is not defined". >>> # editing myscript.py >>> import myscript NameError: global name 'np' is not defined". And we can immediately see you don't reload() the script. Hope this gets you further. Have fun, Evert > D > > import numpy as np > > def find_nearest(array,value): > idx=(np.abs(array-value)).argmin() > return array[idx] > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From dcdavemail at gmail.com Fri Feb 24 17:29:28 2012 From: dcdavemail at gmail.com (David Craig) Date: Fri, 24 Feb 2012 16:29:28 +0000 Subject: [Tutor] problem editing modules and defs Message-ID: <4F47BAE8.6020604@gmail.com> Hi, I am new to python and have made a couple of definitions. I imported them and they worked ok except for one which gave me the error "NameError: global name 'np' is not defined". I then edited my script for the def to include "import numpy as np" saved it and imported the def again. However, it still gives me the same error. I know I have to be doing something basic wrong but cant figure it out, anyone know what I am doing wrong. The def is below. thanks D import numpy as np def find_nearest(array,value): idx=(np.abs(array-value)).argmin() return array[idx] From bgailer at gmail.com Fri Feb 24 17:34:22 2012 From: bgailer at gmail.com (bob gailer) Date: Fri, 24 Feb 2012 11:34:22 -0500 Subject: [Tutor] Attribute error message received on Card Game program In-Reply-To: <1330099731.47759.YahooMailNeo@web24004.mail.ird.yahoo.com> References: <1330099731.47759.YahooMailNeo@web24004.mail.ird.yahoo.com> Message-ID: <4F47BC0E.90601@gmail.com> On 2/24/2012 11:08 AM, SKHUMBUZO ZIKHALI wrote: > Hi > /*I am trying to run the following program from Guide to Programming > with Python by Micheal Dawson:*/ > /**/ > > class Card(object): > RANK = ["A","2","3","4","5","6","7" > "8","9","K","Q","J"] > SUIT = ["s","d","h","c"] > def __init__(self,rank, suit): > self.rank = rank > self.suit = suit > def __str__(self): > rep = self.rank + self.suit > return rep > > class Hand(object): > def __init__(self): > self.cards = [] > def __str__(self): > if self.cards: > rep = '' > for card in self.card: Did you mean self.cards? > rep += str(Card)+'' > else: > rep = "" > return rep > def clear(self): > self.cards =[] > def add(self, card): > self.cards.append(card) > def give(self, card, other_hand): > self.cards.remove(card) > other_hand.add(card) > # Main > card1 = Card(rank = "A", suit ="c") > print 'Printing a Card object' > print card1 > card2 = Card(rank = "2", suit ="c") > card3 = Card(rank = "3", suit ="c") > card4 = Card(rank = "4", suit ="c") > card5 = Card(rank = "5", suit ="c") > print card2 > print card3 > print card4 > print card5 > my_hand = Hand() > print '\nPrinting my hand before I add my card:' > print my_hand > my_hand.add(card1) > my_hand.add(card2) > my_hand.add(card3) > my_hand.add(card4) > my_hand.add(card5) > print '\nPrinting my hand after adding 5 cards:' > print my_hand > your_hand = Hand() > my_hand.give(card1, your_hand) > my_hand.give(card2, your_hand) > print '\nGave the first two cards from my hand to your hand.' > print 'Your hand:' > print your_hand > print 'My hand:' > my_hand > my_hand.clear() > print '\nMy hand after clearing it:' > raw_input('\n\nPress the enter key to exist.') > /*However, I can partly run it for eventually receive attribute error > message. Printing response is as follows:*/ > 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on > win32 > Type "copyright", "credits" or "license()" for more information. > >>> ================================ RESTART > ================================ > >>> > Printing a Card object > Ac > 2c > 3c > 4c > 5c > Printing my hand before I add my card: > > Printing my hand after adding 5 cards: > Traceback (most recent call last): > File "C:/Python27/Card Game.py", line 69, in > print my_hand > File "C:/Python27/Card Game.py", line 25, in __str__ > for card in self.card: > AttributeError: 'Hand' object has no attribute 'card' > >>> > /*Would you please help me as to where I got it wrong with this > program and lastly inform how how does Hand object gets linked or > connected with Card object? */ > With thanks > Sikhumbuzo */ > /* > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From wayne at waynewerner.com Fri Feb 24 18:00:58 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Fri, 24 Feb 2012 11:00:58 -0600 (CST) Subject: [Tutor] help writing functions In-Reply-To: References: Message-ID: On Thu, 23 Feb 2012, Saad Javed wrote: > I am learning python and need guidance for > writing some code. I've written a simple > program (with pointers from people) that > parses an tv show xml feed and prints their > values in plain text after performing some > string operations. Unless you're really interested in doing this fire the sake of the exercise you should probably take a look at feedparser it's designed for parsing read and atom feeds. HTH, Wayne From d at davea.name Fri Feb 24 18:38:07 2012 From: d at davea.name (Dave Angel) Date: Fri, 24 Feb 2012 12:38:07 -0500 Subject: [Tutor] Attribute error message received on Card Game program In-Reply-To: <4F47BC0E.90601@gmail.com> References: <1330099731.47759.YahooMailNeo@web24004.mail.ird.yahoo.com> <4F47BC0E.90601@gmail.com> Message-ID: <4F47CAFF.9060400@davea.name> On 02/24/2012 11:34 AM, bob gailer wrote: > On 2/24/2012 11:08 AM, SKHUMBUZO ZIKHALI wrote: >> Hi >> /*I am trying to run the following program from Guide to Programming >> with Python by Micheal Dawson:*/ >> /**/ >> >> class Card(object): >> RANK = ["A","2","3","4","5","6","7" >> "8","9","K","Q","J"] >> SUIT = ["s","d","h","c"] >> def __init__(self,rank, suit): >> self.rank = rank >> self.suit = suit >> def __str__(self): >> rep = self.rank + self.suit >> return rep >> >> class Hand(object): >> def __init__(self): >> self.cards = [] >> def __str__(self): >> if self.cards: >> rep = '' >> for card in self.card: > Did you mean self.cards? >> rep += str(Card)+'' >> else: >> rep = "" Did you mean to return rep for both the if and else portion? If so, this return statement should be unindented to line up with the else: line. >> return rep >> def clear(self): >> self.cards =[] >> def add(self, card): >> self.cards.append(card) >> def give(self, card, other_hand): >> self.cards.remove(card) >> other_hand.add(card) >> # Main >> card1 = Card(rank = "A", suit ="c") >> print 'Printing a Card object' >> print card1 >> card2 = Card(rank = "2", suit ="c") >> card3 = Card(rank = "3", suit ="c") >> card4 = Card(rank = "4", suit ="c") >> card5 = Card(rank = "5", suit ="c") >> print card2 >> print card3 >> print card4 >> print card5 >> my_hand = Hand() >> print '\nPrinting my hand before I add my card:' >> print my_hand >> my_hand.add(card1) >> my_hand.add(card2) >> my_hand.add(card3) >> my_hand.add(card4) >> my_hand.add(card5) >> print '\nPrinting my hand after adding 5 cards:' >> print my_hand >> your_hand = Hand() >> my_hand.give(card1, your_hand) >> my_hand.give(card2, your_hand) >> print '\nGave the first two cards from my hand to your hand.' >> print 'Your hand:' >> print your_hand >> print 'My hand:' >> my_hand >> my_hand.clear() >> print '\nMy hand after clearing it:' >> raw_input('\n\nPress the enter key to exist.') >> /*However, I can partly run it for eventually receive attribute error >> message. Printing response is as follows:*/ >> 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on >> win32 >> Type "copyright", "credits" or "license()" for more information. >> >>> ================================ RESTART >> ================================ >> >>> >> Printing a Card object >> Ac >> 2c >> 3c >> 4c >> 5c >> Printing my hand before I add my card: >> >> Printing my hand after adding 5 cards: >> Traceback (most recent call last): >> File "C:/Python27/Card Game.py", line 69, in >> print my_hand >> File "C:/Python27/Card Game.py", line 25, in __str__ >> for card in self.card: >> AttributeError: 'Hand' object has no attribute 'card' >> >>> >> /*Would you please help me as to where I got it wrong with this >> program and lastly inform how how does Hand object gets linked or >> connected with Card object? */ >> With thanks >> Sikhumbuzo */ >> /* >> -- DaveA From dcdavemail at gmail.com Fri Feb 24 18:48:14 2012 From: dcdavemail at gmail.com (David Craig) Date: Fri, 24 Feb 2012 17:48:14 +0000 Subject: [Tutor] problem editing modules and defs In-Reply-To: <87E945D1-A482-4686-B7E9-9EF8974522CB@gmail.com> References: <4F47B6A8.2060200@ucdconnect.ie> <87E945D1-A482-4686-B7E9-9EF8974522CB@gmail.com> Message-ID: <4F47CD5E.4040201@gmail.com> Hi again, sorry if that wasnt clear. I am using the ipython interpreter to debug scripts. I have a function:-) saved as part of a module called daves_modules.py. import numpy as np def find_nearest(array,value): idx=(np.abs(array-value)).argmin() return array[idx], idx If I run the module from the interpreter as follows, In [610]: %run daves_modules.py In [611]: a = find_nearest(pos_time, highTime) In [612]: a Out[612]: (20.009998091697867, 200) it works fine. However, if I use the same function in a script like this, import numpy as np import pylab as py from daves_modules import dist, find_nearest . . . a = find_nearest(pos_time, highTime) I get the following error, %run SNR_UFAN_UCRUI.py --------------------------------------------------------------------------- IndexError Traceback (most recent call last) /home/davcra/python_scripts/SNR_UFAN_UCRUI.py in () 88 b = find_nearest(pos_time, lowTime) 89 ---> 90 pos_noise = (np.sum(pos_signal[0:a[1]])+np.sum(pos_signal[b[1]:-1])) / (a[1] + (len(pos_signal)-b[1])) 91 neg_noise = (np.sum(neg_signal[0:-a[1]])+np.sum(neg_signal[-b[1]:-1])) / (a[1] + (len(neg_signal)-b[1])) 92 IndexError: invalid index to scalar variable. WARNING: Failure executing file: If I then try to use the function in ipython again, In [614]: a = find_nearest(pos_time, highTime) In [615]: a Out[615]: 20.009998091697867 Note: the function originally only returned array[idx], so it seems to have reverted to this somehow. On 02/24/2012 04:28 PM, Evert Rol wrote: > Hi David, > >> Hi, >> I am new to python and have made a couple of definitions. I imported them and they worked ok. I they worked except for one which gave me the error "NameError: global name 'np' is not defined". I then edited my script for the def to include "import numpy as np" saved it and imported the def again. However, it still gives me the same error. I know I have to be doing something basic wrong but cant figure it out, anyone know what I am doing wrong. The def is below. >> thanks > Minor thing first: in Python terminology, most of the time your 'definitions' are simply called functions, although you're correct that "def" refers to definition. But thatt's more about where the function is defined, in contrast to where in the code it is called (or perhaps even declared, though I don't think that applies to Python). > > > When you say "I imported the def again", it sounds like you're working on the Python interpreter, and doing >>>> import myscript > or similar. > If that's how you run things, you would have to use the reload() function to reload the new function definition, which has your correction. > > However, you also talk about 'my script'. A script is something I would run from the shell command line, like > $> python myscript.py > > If you do things that way, you would always be ensured that python uses the latest edits in your script. > It does mean that any command you would normally type into the Python interpreter, you would now have to enter in the script. And while the interpreter always shows the evaluation result of the last command entered, a script would require a print for that. Compare: >>>> a=1 >>>> a > 1 > > versus (inside a script): > a = 1 > a # this doesn't show anything > print a # this does > > Perhaps this is too basic, but I have to guess a bit what you are doing from your text. > > A few tips to get more practical help: > - Python normally shows a stack trace when there is an error. It is good to copy-paste the whole thing in your emails. Just typing the last bit often doesn't help. > - Copy-paste (again, don't type) whatever you're doing in the Python interpreter, if that's what you are using. So we can how you do things (examples are clearer than descriptions). If needs be, intersperse with comments. > Compare eg: >>>> import myscript > NameError: global name 'np' is not defined". >>>> # editing myscript.py >>>> import myscript > NameError: global name 'np' is not defined". > > And we can immediately see you don't reload() the script. > > Hope this gets you further. > > Have fun, > > Evert > > > >> D >> >> import numpy as np >> >> def find_nearest(array,value): >> idx=(np.abs(array-value)).argmin() >> return array[idx] >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Fri Feb 24 19:01:16 2012 From: d at davea.name (Dave Angel) Date: Fri, 24 Feb 2012 13:01:16 -0500 Subject: [Tutor] problem editing modules and defs In-Reply-To: <4F47B6A8.2060200@ucdconnect.ie> References: <4F47B6A8.2060200@ucdconnect.ie> Message-ID: <4F47D06C.2060406@davea.name> On 02/24/2012 11:11 AM, David Craig wrote: > Hi, > I am new to python and have made a couple of definitions. I imported > them and they worked ok. I they worked except for one which gave me > the error "NameError: global name 'np' is not defined". I then edited > my script for the def to include "import numpy as np" saved it and > imported the def again. However, it still gives me the same error. I > know I have to be doing something basic wrong but cant figure it out, > anyone know what I am doing wrong. The def is below. > thanks > D > > import numpy as np > > def find_nearest(array,value): > idx=(np.abs(array-value)).argmin() > return array[idx] Evert's response was correct. But let me put it simpler. When (from a debugger) you import a MODULE a second time, it does essentially nothing. It notices that it's already there, and doesn't waste time reloading it. After all modules don't change during a program run. There is a reload() function that theoretically works. But it has enough limitations that I've never even bothered. If you're going to change an imported source file, exit the interpreter and start over. Or do what I do, and always run the SCRIPT from a command line, or from an IDE. A point on terminology. When you run a script, it's called a SCRIPT. If you import the same file, it's called a MODULE. The two have slightly different behaviors. -- DaveA From wprins at gmail.com Fri Feb 24 20:45:08 2012 From: wprins at gmail.com (Walter Prins) Date: Fri, 24 Feb 2012 19:45:08 +0000 Subject: [Tutor] problem editing modules and defs In-Reply-To: <4F47BAE8.6020604@gmail.com> References: <4F47BAE8.6020604@gmail.com> Message-ID: Hi Dave, On 24 February 2012 16:29, David Craig wrote: > Hi, > I am new to python and have made a couple of definitions. I imported them > and they worked ok except for one which gave me the error "NameError: global > name 'np' is not defined". I then edited my script for the def to include > "import numpy as np" saved it and imported the def again. However, it still > gives me the same error. I know I have to be doing something basic wrong but > cant figure it out, anyone know what I am doing wrong. The def is below. Did you try completely restarting your Python interpreter? It may be that you've still got the previous version of your module/function in memory hence why it's still giving you your old error. You could try the reload() built in function to get the interpreter to reload your previously imported module: http://docs.python.org/library/functions.html#reload HTH, Walter From wprins at gmail.com Fri Feb 24 20:48:06 2012 From: wprins at gmail.com (Walter Prins) Date: Fri, 24 Feb 2012 19:48:06 +0000 Subject: [Tutor] problem editing modules and defs In-Reply-To: <4F47BAE8.6020604@gmail.com> References: <4F47BAE8.6020604@gmail.com> Message-ID: Hi, On 24 February 2012 16:29, David Craig wrote: > Hi, > I am new to python and have made a couple of definitions. I imported them > and they worked ok except for one which gave me the error "NameError: global > name 'np' is not defined". I then edited my script for the def to include > "import numpy as np" saved it and imported the def again. However, it still > gives me the same error. I know I have to be doing something basic wrong but > cant figure it out, anyone know what I am doing wrong. The def is below. > thanks I see others have responded to another post in more detail so please feel free to ignore my brief response. :) Walter From alan.gauld at btinternet.com Fri Feb 24 22:58:53 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 24 Feb 2012 21:58:53 +0000 Subject: [Tutor] Suggestions for a good intro OO & Python In-Reply-To: <82mx88grtu.fsf@gmail.com> References: <82mx88grtu.fsf@gmail.com> Message-ID: On 24/02/12 15:43, Sivaram Neelakantan wrote: > Can someone point me to a good intro on OO in Python? If it does OO > basics too, even better, assuming no prior knowledge of Object > Orientation. You can try the OOP topic in my tutorial. It also has some pointers to some more advanced tutors and books for the next steps... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From papillion at gmail.com Sat Feb 25 00:02:47 2012 From: papillion at gmail.com (Anthony Papillion) Date: Fri, 24 Feb 2012 17:02:47 -0600 Subject: [Tutor] Checking if a GtkEntry is empty Message-ID: Hi Everyone, I'm learning pyGtk and am developing my first application. I'm trying to check if a GtkEntry is empty and I'm using the following code: if txtSearch.get_text() == "": print "The entry is empty" This didn't work. So I thought, maybe I need to reference self and tried: if self.txtSearch.get_text() == "": print "The entry is empty" Neither worked. What am I doing wrong? Thanks1 Anthony -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Sat Feb 25 00:10:48 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 24 Feb 2012 23:10:48 +0000 Subject: [Tutor] Checking if a GtkEntry is empty In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47415ECC8@SCACMX008.exchad.jpmchase.net> >if txtSearch.get_text() == "": >??? print "The entry is empty" >This didn't work. So I thought, maybe I need to reference self and tried: >if self.txtSearch.get_text() == "": >??? print "The entry is empty" >Neither worked. What am I doing wrong? Please post a more significant code sample as I have no idea from this, but at least one of those should have given you an error. Always include the full error (including stacktrace) you get from Python. Use copy/paste and do not try and retype or rephrase it. Do not attach a file as many users of this list do not receive attachments. Welcome to the list! Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From papillion at gmail.com Sat Feb 25 00:49:17 2012 From: papillion at gmail.com (Anthony Papillion) Date: Fri, 24 Feb 2012 17:49:17 -0600 Subject: [Tutor] Checking if a GtkEntry is empty In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47415ECC8@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF47415ECC8@SCACMX008.exchad.jpmchase.net> Message-ID: On Fri, Feb 24, 2012 at 5:10 PM, Prasad, Ramit wrote: > > Please post a more significant code sample as I have no idea from this, > but at least one of those should have given you an error. Always include > the full error (including stacktrace) you get from Python. Use copy/paste > and do not try and retype or rephrase it. Do not attach a file as many > users > of this list do not receive attachments. Hi Ramit, Thanks for the welcome. Basically, that's actually the code. But here is the complete function that includes the code: def on_btnSearch_click(self, data=None): if btnSearch.get_text() == "": print "Nothing to search" else: print "I would do this search" The code above does nothing. No error, no print, nothing. Any idea? Thanks! Anthony From alan.gauld at btinternet.com Sat Feb 25 01:07:52 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 25 Feb 2012 00:07:52 +0000 Subject: [Tutor] Checking if a GtkEntry is empty In-Reply-To: References: <5B80DD153D7D744689F57F4FB69AF47415ECC8@SCACMX008.exchad.jpmchase.net> Message-ID: On 24/02/12 23:49, Anthony Papillion wrote: Add a trace to see if the method ever gets called > def on_btnSearch_click(self, data=None): print "I'm in on_btnSearch_click" > if btnSearch.get_text() == "": > print "Nothing to search" > else: > print "I would do this search" > The code above does nothing. No error, no print, nothing. Any idea? Where are you looking for the printout? How are you running it? If the message I added doesn't print you need to look at how you are associating the method with the widget event. You don't show us enough code for us to tell. In fact you still don't show us enough to answer the original question about how to reference btnSearch. we would need to see where btnSearch is created. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ramit.prasad at jpmorgan.com Sat Feb 25 00:55:29 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 24 Feb 2012 23:55:29 +0000 Subject: [Tutor] Checking if a GtkEntry is empty In-Reply-To: References: <5B80DD153D7D744689F57F4FB69AF47415ECC8@SCACMX008.exchad.jpmchase.net> Message-ID: <5B80DD153D7D744689F57F4FB69AF47415EF03@SCACMX008.exchad.jpmchase.net> >def on_btnSearch_click(self, data=None): > if btnSearch.get_text() == "": > print "Nothing to search" > else: > print "I would do this search" >The code above does nothing. No error, no print, nothing. Any idea? How are you running this? I assume from an IDE because this should most likely cause an error. I would recommend trying to run your python script from the commandline which is much more likely to print an error. $python your_script.py btnSearch.get_text() should be self. btnSearch.get_text() Typically print statements are not seen in UI applications because they are not run from command very often or the loop in charge of handling events swallows them (which is what happens in an IDE). I would recommend using a popup window or changing the text of a field instead. Or you can use the python logger and just look at the log file afterwards. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From papillion at gmail.com Sat Feb 25 01:17:52 2012 From: papillion at gmail.com (Anthony Papillion) Date: Fri, 24 Feb 2012 18:17:52 -0600 Subject: [Tutor] Checking if a GtkEntry is empty In-Reply-To: References: <5B80DD153D7D744689F57F4FB69AF47415ECC8@SCACMX008.exchad.jpmchase.net> Message-ID: On Fri, Feb 24, 2012 at 6:07 PM, Alan Gauld wrote: > > Add a trace to see if the method ever gets called The method is definitely getting called. If I remove the attempt to get the widgets text and replace it with print "btnSearch has been clicked" The method is called and the message is printed to the console as expected. > Where are you looking for the printout? > How are you running it? I'm looking for the printout on the console screen. I'm running it by typing 'python trial.py' in the console. > If the message I added doesn't print you need to look at how you are > associating the method with the widget event. > > You don't show us enough code for us to tell. > In fact you still don't show us enough to answer the original question about > how to reference btnSearch. we would need to see where btnSearch is created. The entire GUI is created using Glade. In Glade, I've clicked on the button widget and then the Signals tab. I'm associating the btnSearch's click event with the on_btnSearch.clicked method. As I said above, the method is being called, I'm just not able to actually get the widgets text. Does that make it clearer? Thanks! Anthony From papillion at gmail.com Sat Feb 25 01:22:27 2012 From: papillion at gmail.com (Anthony Papillion) Date: Fri, 24 Feb 2012 18:22:27 -0600 Subject: [Tutor] Checking if a GtkEntry is empty In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47415EF03@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF47415ECC8@SCACMX008.exchad.jpmchase.net> <5B80DD153D7D744689F57F4FB69AF47415EF03@SCACMX008.exchad.jpmchase.net> Message-ID: On Fri, Feb 24, 2012 at 5:55 PM, Prasad, Ramit wrote: > > How are you running this? I assume from an IDE because this should most > likely cause an error. I would recommend trying to run your python script > from the commandline which is much more likely to print an error. > > $python your_script.py Hi Ramit, I'm running this from terminal in exactly the way you're saying. > btnSearch.get_text() should be self. btnSearch.get_text() When I change the code as you suggest, I'm getting this error: if self.btnSearch.text == "": AttributeError: 'DocuManager' object has no attribute 'btnSearch' Here is the entire text of the code I have so far: #!/usr/bin/env python import pygtk pygtk.require("2.0") import gtk import sqlite3 as lite class Manager(object): def __init__(self): builder = gtk.Builder() builder.add_from_file("winMain.glade") builder.connect_signals(self) self.window = builder.get_object("winMain") self.window.show() conn = None try: conn = lite.connect('docs.db') sql = "create table if not exists documents(id integer, name text, location text, tags text)" c = conn.cursor() c.execute(sql) conn.commit() except lite.Error, e: print "Error: " + e.args[0] def on_btnSearch_clicked(self, data=None): if self.btnSearch.text == "": print "No text" else: print "There is text" def on_tbExit_clicked(self, data=None): exit() if __name__ == "__main__": app = Manager() gtk.main() From alan.gauld at btinternet.com Sat Feb 25 01:31:22 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 25 Feb 2012 00:31:22 +0000 Subject: [Tutor] Checking if a GtkEntry is empty In-Reply-To: References: <5B80DD153D7D744689F57F4FB69AF47415ECC8@SCACMX008.exchad.jpmchase.net> Message-ID: On 25/02/12 00:17, Anthony Papillion wrote: > The entire GUI is created using Glade. In Glade, I've clicked on the > button widget and then the Signals tab. I'm associating the > btnSearch's click event with the on_btnSearch.clicked method. As I > said above, the method is being called, I'm just not able to actually > get the widgets text. > > Does that make it clearer? Yes thanks, that fills in the gaps nicely. Unfortunately it also takes you outside my area of knowledge since I've never used Glade (tried but couldn't get it to work!) Hopefully somebody else here knows more... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Feb 25 03:08:02 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 25 Feb 2012 13:08:02 +1100 Subject: [Tutor] Checking if a GtkEntry is empty In-Reply-To: References: <5B80DD153D7D744689F57F4FB69AF47415ECC8@SCACMX008.exchad.jpmchase.net> <5B80DD153D7D744689F57F4FB69AF47415EF03@SCACMX008.exchad.jpmchase.net> Message-ID: <4F484282.1070807@pearwood.info> Anthony Papillion wrote: > class Manager(object): > def __init__(self): > builder = gtk.Builder() > builder.add_from_file("winMain.glade") > builder.connect_signals(self) > self.window = builder.get_object("winMain") > self.window.show() > > conn = None > try: > conn = lite.connect('docs.db') > sql = "create table if not exists documents(id integer, > name text, location text, tags text)" > c = conn.cursor() > c.execute(sql) > conn.commit() > except lite.Error, e: > print "Error: " + e.args[0] Are you aware that the database connection gets made, but not stored anywhere? Once the Manager instance is created, the database connection is thrown away. My guess is that you mean to use self.conn instead of conn in the above. Which brings me to another point. It seems to me that the above is poor design. When you create a Manager instance, if something goes wrong with the database entry, you end up with an instance with an unspecified, and possibly broken, inst.conn. That's bad, because the caller can't trust the value of inst.conn to be in a sensible state, and they may not have any easy way to tell the difference between inst.conn is safe to use and inst.conn is broken. In other words, you should use one of these designs instead: # broken connections are never allowed and are always fatal errors def __init__(self): builder = gtk.Builder() builder.add_from_file("winMain.glade") builder.connect_signals(self) self.window = builder.get_object("winMain") self.window.show() conn = lite.connect('docs.db') sql = ( "create table if not exists documents(" "id integer, name text, location text, tags text)" ) c = conn.cursor() c.execute(sql) conn.commit() self.conn = conn # broken connections are allowed and given a warning def __init__(self): builder = gtk.Builder() builder.add_from_file("winMain.glade") builder.connect_signals(self) self.window = builder.get_object("winMain") self.window.show() try: conn = lite.connect('docs.db') sql = ( "create table if not exists documents(" "id integer, name text, location text, tags text)" ) c = conn.cursor() c.execute(sql) conn.commit() except lite.Error, e: print "Warning:", e.args[0] # Warning, not an error. conn = None self.conn = conn Notice that it is important to set conn = None *after* catching the exception, because if you do it before, it will be changed to a broken connection before you save it as self.conn. Also note that you shouldn't frighten users with "Error" when it isn't an error, merely a warning, nor should you hide useful tracebacks for fatal errors. -- Steven From papillion at gmail.com Sat Feb 25 03:18:43 2012 From: papillion at gmail.com (Anthony Papillion) Date: Fri, 24 Feb 2012 20:18:43 -0600 Subject: [Tutor] Checking if a GtkEntry is empty In-Reply-To: <4F484282.1070807@pearwood.info> References: <5B80DD153D7D744689F57F4FB69AF47415ECC8@SCACMX008.exchad.jpmchase.net> <5B80DD153D7D744689F57F4FB69AF47415EF03@SCACMX008.exchad.jpmchase.net> <4F484282.1070807@pearwood.info> Message-ID: On Fri, Feb 24, 2012 at 8:08 PM, Steven D'Aprano wrote: > > Are you aware that the database connection gets made, but not stored > anywhere? Once the Manager instance is created, the database connection is > thrown away. > > My guess is that you mean to use self.conn instead of conn in the above. Hi Steven, Thanks for all the fantastic feedback! I'm fairly new to Python and still trying to wrap my head around some of the basic concepts as well as learn pyGtk at the same time. While I should have known about the problems you mentioned, I completely spaced them out and good design wasn't really in my head when I wrote this code, unfortunately. Thanks for the helpful hints. Duly noted and implemented :-) Anthony -------------- next part -------------- An HTML attachment was scrubbed... URL: From carolina.cadi at maine.edu Sat Feb 25 04:18:27 2012 From: carolina.cadi at maine.edu (Carolina Dianne LaCourse) Date: Fri, 24 Feb 2012 22:18:27 -0500 Subject: [Tutor] Help with Python Program Message-ID: Hi, I have never programed before and am brand new to python also. I am trying to create a Hi-Lo game and am not really sure where to start. These are the instructions that I have. I know that I will need to import the random number generator and have looked up how to do that. I understand that I need to ask for raw input from the user and that I need to be able to use the if elif else to tell the user whether their number matches or id too high or to low but am just not sure what to do first. Any advice would be greatly appreciated! I have tried some online tutorials to get the basics but still am having a really hard time. I did work with scratch a bit earlier this semester and got that, but am really struggling with python. For your second project, you will create a Python guessing game. In this game, the user will be asked to guess a number between 1 and 100. For each guess, you will output one of three things: The user guess is correct -- tell the user he or she won, asking if he/she wants to play again. The user guess is too high -- tell him or her so. The user guess is too low -- tell him or her so. Your program should be able to run multiple games. That is, after each game, the user should be asked if they want to play again. If they type yes, then you pick a new number and play again. If they type no, then the program should say goodbye and exit. You should keep the following stats about the player's efforts: Number of games played Total number of guesses made You should output the number of games played as well as the average number of guess per game. This program will require loops (nested ones, in fact), an if-elif-else statement, and the use of Python's random number generator. From bgailer at gmail.com Sat Feb 25 04:41:43 2012 From: bgailer at gmail.com (bob gailer) Date: Fri, 24 Feb 2012 22:41:43 -0500 Subject: [Tutor] Help with Python Program In-Reply-To: References: Message-ID: <4F485877.6040202@gmail.com> On 2/24/2012 10:18 PM, Carolina Dianne LaCourse wrote: > Hi, > I have never programed before and am brand new to python also. I am > trying to create a Hi-Lo game and am not really sure where to start. > These are the instructions that I have. I know that I will need to > import the random number generator and have looked up how to do that. > I understand that I need to ask for raw input from the user and that I > need to be able to use the if elif else to tell the user whether their > number matches or id too high or to low but am just not sure what to > do first. Any advice would be greatly appreciated! I have tried some > online tutorials to get the basics but still am having a really hard > time. I did work with scratch What is scratch? > a bit earlier this semester and got > that, but am really struggling with python. We get many requests like this. I always wonder why there is a mismatch between the course and the student. A beginner's programming class should give you the tools you need to solve the problem. Can you help us understand why this is not happening for you? I assume this is not your fault - that there is something wrong with the course and/or the instructor. As a rule we don't write the program for you; we take a look at what you've done and help you over the rough spots. Please write any amount of code you can and return with that. > > For your second project, What was the first project? How did that go? > you will create a Python guessing game. In > this game, the user will be asked to guess a number between 1 and 100. > For each guess, you will output one of three things: > The user guess is correct -- tell the user he or she won, > asking if he/she wants to play again. > The user guess is too high -- tell him or her so. > The user guess is too low -- tell him or her so. > Your program should be able to run multiple games. That is, after > each game, the user should be asked if they want to play again. If > they type yes, then you pick a new number and play again. If they type > no, then the program should say goodbye and exit. You should keep the > following stats about the player's efforts: > Number of games played > Total number of guesses made > You should output the number of games played as well as the > average number of guess per game. This program will require loops > (nested ones, in fact), an if-elif-else statement, and the use of > Python's random number generator. Do you know how to create a loop? If not, why not? Do you know how to test for low or high? If not why not? If your answers to these questions is no then (IMHO) you are in the wrong class. -- Bob Gailer 919-636-4239 Chapel Hill NC From steve at pearwood.info Sat Feb 25 04:59:45 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 25 Feb 2012 14:59:45 +1100 Subject: [Tutor] Help with Python Program In-Reply-To: References: Message-ID: <4F485CB1.2060606@pearwood.info> Carolina Dianne LaCourse wrote: [...] > I understand that I need to ask for raw input from the user and that I > need to be able to use the if elif else to tell the user whether their > number matches or id too high or to low but am just not sure what to > do first. Any advice would be greatly appreciated! I have tried some > online tutorials to get the basics but still am having a really hard > time. I did work with scratch a bit earlier this semester and got > that, but am really struggling with python. Start by writing down in plain English the steps of how you would play the guessing game. This is a called an algorithm, which is something very similar to a recipe or a set of instructions. You might have something like this: (1) Think of a number between 1 and 100, and remember it. (2) Repeat the following steps until the game is over: (3) - Ask the person playing for a number between 1 and 100. (4) - If the number is too low, tell them it is too low. (5) - If the number is too high, tell them it is too high. (6) - If the number is equal to the number you thought of, the game is over. All that makes up *one* game. Then you need instructions to play multiple games: (a) Play one game, as above. (b) Repeat the following steps until done: (c) - Ask the player if they want to play again. (d) - If they say Yes, play one game, as above. (e) - Otherwise, we are done. (f) Finally, print how many games were played, how many guesses were needed, and the average number of guesses per game. Now, you need to change the English instructions to instructions the computer can follow, using Python. For example, Step (1) above picks a random number and remembers it as the target of the game: import random target = random.randint(1, 100) Step (2) is a bit harder -- it's a loop. You should have learned about while loops and for loops. I expect a while loop is better for this, because you can't tell ahead of time how many times you need to go round and round the loop. while guess != target: Step (3) ask the user for a number, and call it "guess" if guess < target: print "too low" elif guess > target: print "too high" # otherwise guess == target so the game will be over Notice that this isn't exactly Python code. The most obvious problem is the line "Step (3)..." which is plain English. You need to replace that with code to actually ask the user for a number. (Hint: you will need the raw_input function.) Another problem is that the *first* time you enter the loop, the name "guess" isn't defined. You need to give it a value to start with, before the loop. Any value will do, so long as it isn't target. I suggest 0. Does this help you get started? Go ahead and write some code, and see where it takes you. Piece by piece, step by step, you should work towards replacing each bit of English instruction with some Python code to do that. You should aim to write code to play *one* game first. Get that right, first, then adapt it to play multiple games. Write some code, see how it works (or where is fails to work), and anything that is unclear, come back and ask. -- Steven From ckava3 at gmail.com Sat Feb 25 09:31:41 2012 From: ckava3 at gmail.com (Chris Kavanagh) Date: Sat, 25 Feb 2012 03:31:41 -0500 Subject: [Tutor] Staticmethod & Classmethod Question Message-ID: <4F489C6D.70505@gmail.com> Hey Everyone, I came across this code in 'A Byte Of Python' & realized there was a line I didn't understand. The line is "howMany = staticmethod(howMany)" (Complete code pasted below.) I don't think, in my very short Python career, I've heard of a staticmethod or classmethod. There's very little explanation of them in the book. I've googled them, but am still confused on exactly what they are & why they should be used. The only sense I can make of them is, a staticmethod can be called WITHOUT actually creating an object first. Anyways, if someone could give me a simple explanation with a very simple example, I will be elated! As always, thank you in advance for any help!! Code Below: PS: Please keep in mind, Python is my 1st language, & I'm very new to it (4 to 5 months). class Robot: '''Represents a robot, with a name.''' # A class variable, counting the number of robots population = 0 def __init__(self, name): '''Initializes the data.''' self.name = name print('(Initializing {0})'.format(self.name)) # When this person is created, the robot # adds to the population Robot.population += 1 def __del__(self): '''I am dying.''' print('{0} is being destroyed!'.format(self.name)) Robot.population -= 1 if Robot.population == 0: print('{0} was the last one.'.format(self.name)) else: print('There are still {0:d} robots working.'.format(Robot.population)) def sayHi(self): '''Greeting by the robot. Yeah, they can do that.''' print('Greetings, my masters call me {0}.'.format(self.name)) def howMany(): '''Prints the current population.''' print('We have {0:d} robots.'.format(Robot.population)) howMany = staticmethod(howMany) droid1 = Robot('R2-D2') droid1.sayHi() Robot.howMany() droid2 = Robot('C-3PO') droid2.sayHi() Robot.howMany() print("\nRobots can do some work here.\n") print("Robots have finished their work. So let's destroy them.") del droid1 del droid2 Robot.howMany() From alan.gauld at btinternet.com Sat Feb 25 10:32:23 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 25 Feb 2012 09:32:23 +0000 Subject: [Tutor] Staticmethod & Classmethod Question In-Reply-To: <4F489C6D.70505@gmail.com> References: <4F489C6D.70505@gmail.com> Message-ID: On 25/02/12 08:31, Chris Kavanagh wrote: > I don't think, in my very short Python career, I've heard of a > staticmethod or classmethod. There's very little explanation of them in > the book. I've googled them, but am still confused on exactly what they > are & why they should be used. The only sense I can make of them is, a > staticmethod can be called WITHOUT actually creating an object first. In general you can ignore staticmethod, it was an earlier attempt to do what classmethod does. I suspect it is only kept around because removing it would break some older code. (There are some subtle differences in the way they work but they are not significant IMHO). In most cases I would recommend using classmethod nowadays. Here is a link that summarises the diofferences succintly: http://rapd.wordpress.com/2008/07/02/python-staticmethod-vs-classmethod/ So what do they do? What are they used for? They define a method as belonging to the class itself rather than to instances of the class. This is best described by examples. Consider a class of employees. You would create instance methods to add, delete, modify, print an employee. but you could create class methods to, for example, find an employee out of all of the instances that exist. Or to return the total number of employees in existence. These two operations operate on the whole class of employees not on any single instance. Some languages treat instance creation as a class method too, you ask the class to create a new instance of itself. Smalltalk is a good example of this. In Python we don't need to do that explicitly. Because they operate on the class rather than on an instance they can be called without any instances being in existence. In the examples above the results would be empty/zero but the method could still be called. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Sat Feb 25 10:34:36 2012 From: d at davea.name (Dave Angel) Date: Sat, 25 Feb 2012 04:34:36 -0500 Subject: [Tutor] Staticmethod & Classmethod Question In-Reply-To: <4F489C6D.70505@gmail.com> References: <4F489C6D.70505@gmail.com> Message-ID: <4F48AB2C.5090601@davea.name> On 02/25/2012 03:31 AM, Chris Kavanagh wrote: > Hey Everyone, > > I came across this code in 'A Byte Of Python' & realized there was > a line I didn't understand. The line is "howMany = > staticmethod(howMany)" (Complete code pasted below.) > > I don't think, in my very short Python career, I've heard of a > staticmethod or classmethod. There's very little explanation of them > in the book. I've googled them, but am still confused on exactly what > they are & why they should be used. The only sense I can make of them > is, a staticmethod can be called WITHOUT actually creating an object > first. > > Anyways, if someone could give me a simple explanation with a very > simple example, I will be elated! As always, thank you in advance for > any help!! Code Below: > > PS: Please keep in mind, Python is my 1st language, & I'm very new to > it (4 to 5 months). > > > > class Robot: > '''Represents a robot, with a name.''' > > # A class variable, counting the number of robots > population = 0 > > def __init__(self, name): > '''Initializes the data.''' > self.name = name > print('(Initializing {0})'.format(self.name)) > > # When this person is created, the robot > # adds to the population > Robot.population += 1 > > def __del__(self): > '''I am dying.''' > print('{0} is being destroyed!'.format(self.name)) > > Robot.population -= 1 > > if Robot.population == 0: > print('{0} was the last one.'.format(self.name)) > else: > print('There are still {0:d} robots > working.'.format(Robot.population)) > > def sayHi(self): > '''Greeting by the robot. > > Yeah, they can do that.''' > print('Greetings, my masters call me {0}.'.format(self.name)) > > def howMany(): > '''Prints the current population.''' > print('We have {0:d} robots.'.format(Robot.population)) > howMany = staticmethod(howMany) > > droid1 = Robot('R2-D2') > droid1.sayHi() > Robot.howMany() > > droid2 = Robot('C-3PO') > droid2.sayHi() > Robot.howMany() > > print("\nRobots can do some work here.\n") > > print("Robots have finished their work. So let's destroy them.") > del droid1 > del droid2 > > Robot.howMany() Defining a function inside a class makes it a method. Two distinctions exist between an ordinary function and a method. One is which namespace the name is known in, and the other is this mysterious thing called self. The namespace thing means that "sayHi" for example is not an attribute of the module, but of the instance of the class. So other classes might have a method of the same name without conflict. The self thing means that when you say droid2.sayHi(), there is an extra parameter added to the list (only one in this case), the 'self' parameter. What staticmethod() does is to strip out the second feature. For methods that don't need a 'self' parameter, (ie. that don't care which instance they're called on, and are willing to hardcode any refs to other class things) this works out great. classmethod() converts the method so it supplies the class of the object as its first parameter (cls). This can be useful if you have more than one class derived from each other, and the method still needs to know which class it actually was called on. Does this help some? -- DaveA From mnickey at gmail.com Sat Feb 25 11:07:15 2012 From: mnickey at gmail.com (Mike Nickey) Date: Sat, 25 Feb 2012 02:07:15 -0800 Subject: [Tutor] GameTracker help Message-ID: Hey all, I'm trying to wok on a game tracker for my friends. What I have here partly works but there are areas that I want to change and some areas that are just not working for me. The areas that I am having difficulty with are the def pointsNeeded and oppPointsNeeded. What is strange to me is that I had pointsNeeded almost exactly as oppPointsNeeded and only pointsNeeded worked. I'd like to change this to one function since it does the same thing. I've tried using a dictionary but that does not seem to be working well either. Any advice would be great. Thanks in advance. CODE #=============================================================================== # Get users name -- DONE # Get Users opponent name DONE # Get user opponents APA number --DONE # get users APA number -- DONE # Determine if this is 8-ball or 9-ball -- DONE # create number of points needed to win for 9-ball # create number of games needed to win for 8-ball # Get Users skill level -- DONE # get users current opponent skill level -- DONE # get number of innings played # number of defenses played # record who won and lost #=============================================================================== import __builtin__ import string pointDictionary = {1:14, 2:19, 3:25, 4:31, 5:38, 6:46, 7:55, 8:65, 9:75} def getUserName(): return raw_input("Enter your name: ") def getUserOppName(): return raw_input ("Enter your opponents name: ") def getUserNumber(): UserID = raw_input("Enter your APA ID number: ") while (str.isdigit(UserID)==False): UserID = raw_input("That is not a proper ID. Please re-enter your APA number: ") return UserID def getUserOppNumber(): OppUserID = raw_input("Enter your opponents APA ID number: ") while (str.isdigit(OppUserID)==False): UserID = raw_input("That is not a proper ID. Please re-enter your opponents APA number: ") return OppUserID def getGameType(): temp = 0 while temp == 0: GameType = raw_input("Are you playing 8-ball or 9-ball? ") if GameType == "8": print "Good luck and don't get an early 8" GameType = 8 temp = 1 elif GameType == "9": print "Good luck! Let's hope you sink the stripe on the break!" GameType = 9 temp = 1 else: print "That's not a valid entry, Please try again.: " return int(GameType) def CheckRange8Ball(GameType, min=1, max=8): if not min <= GameType <= max: raise ValueError('Value out of range') def getUserSkillLvl(GameType): if GameType == 8: UserSkillLvl = prompt = "Enter your current 8-ball skill level: " elif GameType == 9: UserSkillLvl = prompt = "Enter your current 9-ball level:" UserSkillLvl = raw_input(prompt) UserSkillLvl = int(UserSkillLvl) if GameType == 9: temp = 0 while temp == 0: if ((UserSkillLvl <= 9) and (UserSkillLvl >=1)): print "Thank You" temp = 1 break elif ((UserSkillLvl >9) or (UserSkillLvl < 1)): while temp == 0: UserSkillLvl = raw_input("Please re-enter your 9-ball skill level") return UserSkillLvl if GameType == 8: temp = 0 while temp == 0: if ((UserSkillLvl <= 8) and (UserSkillLvl >=1)): print "thank you" temp = 1 break elif (UserSkillLvl >8) or (UserSkillLvl < 1): while temp == 0: UserSkillLvl = raw_input("Please re-enter your skill level: ") return UserSkillLvl def getUserOppSkillLvl(): UserOppSkillLvl = raw_input("Enter your opponents current skill level: ") while (str.isdigit(UserOppSkillLvl)==False): UserOppSkillLvl = raw_input("That is not a proper Skill Level. \ Please enter a number between 1 and 9 for 9-ball or 1 and 8 for 8-ball: ") UserOppSkillLvl = int(UserOppSkillLvl) return UserOppSkillLvl def getPointsNeeded(): if (GameType == 9): for UserSkillLvl in range (0, len(pointDictionary)): pointsNeeded = pointDictionary(UserSkillLvl) return pointsNeeded def getOppPointsNeeded(): if (GameType == 9): if (UserOppSkillLvl == 9): oppPointsNeeded = 75 elif (UserOppSkillLvl == 8): oppPointsNeeded = 65 elif (UserOppSkillLvl == 7): oppPointsNeeded = 55 elif(UserOppSkillLvl == 6): oppPointsNeeded = 46 elif (UserOppSkillLvl == 5): oppPointsNeeded = 38 elif (UserOppSkillLvl == 4): oppPointsNeeded = 31 elif (UserOppSkillLvl == 3): oppPointsNeeded = 25 elif (UserOppSkillLvl == 2): oppPointsNeeded = 19 elif (UserOppSkillLvl == 1): oppPointsNeeded = 14 return oppPointsNeeded UserName = getUserName() UserOppName = getUserOppName() UserID = getUserNumber() OppUserID = getUserOppNumber() GameType = getGameType() UserSkillLvl = getUserSkillLvl(GameType) UserOppSkillLvl = getUserOppSkillLvl() print "\nPlayer Name:",UserName, "\nOpponent Name:", UserOppName, "\nUser ID: ",UserID, "\nOpponent APA ID", OppUserID, \ "\nGameType: ",GameType,"\nUser Skill Level: ",UserSkillLvl, "\nUser Opponents Level: ",UserOppSkillLvl pointsNeeded = getPointsNeeded() oppPointsNeeded = getOppPointsNeeded() print "\nYou need", pointsNeeded, "to win while your opponent needs", oppPointsNeeded,"." -- ~MEN From joel.goldstick at gmail.com Sat Feb 25 11:17:45 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 25 Feb 2012 05:17:45 -0500 Subject: [Tutor] GameTracker help In-Reply-To: References: Message-ID: On Sat, Feb 25, 2012 at 5:07 AM, Mike Nickey wrote: > Hey all, > > I'm trying to wok on a game tracker for my friends. What I have here > partly works but there are areas that I want to change and some areas > that are just not working for me. > > The areas that I am having difficulty with are the def pointsNeeded > and oppPointsNeeded. > What is strange to me is that I had pointsNeeded almost exactly as > oppPointsNeeded and only pointsNeeded worked. > > I'd like to change this to one function since it does the same thing. > I've tried using a dictionary but that does not seem to be working > well either. > > Any advice would be great. > Thanks in advance. > > CODE > #=============================================================================== > # Get users name -- DONE > # Get Users opponent name DONE > # Get user opponents APA number --DONE > # get users APA number -- DONE > # Determine if this is 8-ball or 9-ball -- DONE > # create number of points needed to win for 9-ball > # create number of games needed to win for 8-ball > # Get Users skill level -- DONE > # get users current opponent skill level -- DONE > # get number of innings played > # number of defenses played > # record who won and lost > #=============================================================================== > import __builtin__ > import string > > pointDictionary = {1:14, 2:19, 3:25, 4:31, 5:38, 6:46, 7:55, 8:65, 9:75} > > def getUserName(): > ? ?return raw_input("Enter your name: ") > > def getUserOppName(): > ? ?return raw_input ("Enter your opponents name: ") > > def getUserNumber(): > ? ?UserID = raw_input("Enter your APA ID number: ") > ? ?while (str.isdigit(UserID)==False): > ? ? ? ?UserID = raw_input("That is not a proper ID. Please re-enter > your APA number: ") > ? ?return UserID > > def getUserOppNumber(): > ? ?OppUserID = raw_input("Enter your opponents APA ID number: ") > ? ?while (str.isdigit(OppUserID)==False): > ? ? ? ?UserID = raw_input("That is not a proper ID. Please re-enter Above looks wrong. Shouldn't it be OppUserID = raw_input ... > your opponents APA number: ") > ? ?return OppUserID > > def getGameType(): > ? ?temp = 0 > ? ?while temp == 0: > ? ? ? ?GameType = raw_input("Are you playing 8-ball or 9-ball? ") > ? ? ? ?if GameType == "8": > ? ? ? ? ? ?print "Good luck and don't get an early 8" > ? ? ? ? ? ?GameType = 8 > ? ? ? ? ? ?temp = 1 > ? ? ? ?elif GameType == "9": > ? ? ? ? ? ?print "Good luck! Let's hope you sink the stripe on the break!" > ? ? ? ? ? ?GameType = 9 > ? ? ? ? ? ?temp = 1 > ? ? ? ?else: > ? ? ? ? ? ?print "That's not a valid entry, Please try again.: " > ? ?return int(GameType) > > def CheckRange8Ball(GameType, min=1, max=8): > ? ?if not min <= GameType <= max: > ? ? ? ?raise ValueError('Value out of range') > > def getUserSkillLvl(GameType): > ? ?if GameType == 8: > ? ? ? ?UserSkillLvl = prompt = "Enter your current 8-ball skill level: " > ? ?elif GameType == 9: > ? ? ? ?UserSkillLvl = prompt = "Enter your current 9-ball level:" > > ? ?UserSkillLvl = raw_input(prompt) > ? ?UserSkillLvl = int(UserSkillLvl) > > ? ?if GameType == 9: > ? ? ? ?temp = 0 > ? ? ? ?while temp == 0: > ? ? ? ? ? ?if ((UserSkillLvl <= 9) and (UserSkillLvl >=1)): > ? ? ? ? ? ? ? ?print "Thank You" > ? ? ? ? ? ? ? ?temp = 1 > ? ? ? ? ? ? ? ?break > ? ? ? ? ? ?elif ((UserSkillLvl >9) or (UserSkillLvl < 1)): > ? ? ? ? ? ? ? ?while temp == 0: > ? ? ? ? ? ? ? ? ? ?UserSkillLvl = raw_input("Please re-enter your > 9-ball skill level") > ? ? ? ? ? ? ? ? ? ?return UserSkillLvl > > ? ?if GameType == 8: > ? ? ? ?temp = 0 > ? ? ? ?while temp == 0: > ? ? ? ? ? ?if ((UserSkillLvl <= 8) and (UserSkillLvl >=1)): > ? ? ? ? ? ? ? ?print "thank you" > ? ? ? ? ? ? ? ?temp = 1 > ? ? ? ? ? ? ? ?break > ? ? ? ? ? ?elif (UserSkillLvl >8) or (UserSkillLvl < 1): > ? ? ? ? ? ? ? ?while temp == 0: > ? ? ? ? ? ? ? ? ? ?UserSkillLvl = raw_input("Please re-enter your > skill level: ") > ? ?return UserSkillLvl > > def getUserOppSkillLvl(): > ? ?UserOppSkillLvl = raw_input("Enter your opponents current skill level: ") > ? ?while (str.isdigit(UserOppSkillLvl)==False): > ? ? ? ?UserOppSkillLvl = raw_input("That is not a proper Skill Level. \ > ? ? ? ?Please enter a number between 1 and 9 for 9-ball or 1 and 8 > for 8-ball: ") > ? ? ? ?UserOppSkillLvl = int(UserOppSkillLvl) > ? ?return UserOppSkillLvl > > def getPointsNeeded(): > ? ?if (GameType == 9): > ? ? ? ?for UserSkillLvl in range (0, len(pointDictionary)): > ? ? ? ? ? ?pointsNeeded = pointDictionary(UserSkillLvl) > ? ?return pointsNeeded > > def getOppPointsNeeded(): > ? ?if (GameType == 9): > ? ? ? ?if (UserOppSkillLvl == 9): > ? ? ? ? ? ?oppPointsNeeded = 75 > ? ? ? ?elif (UserOppSkillLvl == 8): > ? ? ? ? ? ?oppPointsNeeded = 65 > ? ? ? ?elif (UserOppSkillLvl == 7): > ? ? ? ? ? ?oppPointsNeeded = 55 > ? ? ? ?elif(UserOppSkillLvl == 6): > ? ? ? ? ? ?oppPointsNeeded = 46 > ? ? ? ?elif (UserOppSkillLvl == 5): > ? ? ? ? ? ?oppPointsNeeded = 38 > ? ? ? ?elif (UserOppSkillLvl == 4): > ? ? ? ? ? ?oppPointsNeeded = 31 > ? ? ? ?elif (UserOppSkillLvl == 3): > ? ? ? ? ? ?oppPointsNeeded = 25 > ? ? ? ?elif (UserOppSkillLvl == 2): > ? ? ? ? ? ?oppPointsNeeded = 19 > ? ? ? ?elif (UserOppSkillLvl == 1): > ? ? ? ? ? ?oppPointsNeeded = 14 > ? ?return oppPointsNeeded > > UserName = getUserName() > UserOppName = getUserOppName() > UserID = getUserNumber() > OppUserID = getUserOppNumber() > GameType = getGameType() > UserSkillLvl = getUserSkillLvl(GameType) > UserOppSkillLvl = getUserOppSkillLvl() > > print "\nPlayer Name:",UserName, "\nOpponent Name:", UserOppName, > "\nUser ID: ",UserID, "\nOpponent APA ID", OppUserID, \ > "\nGameType: ",GameType,"\nUser Skill Level: ",UserSkillLvl, "\nUser > Opponents Level: ",UserOppSkillLvl > > pointsNeeded = getPointsNeeded() > oppPointsNeeded = getOppPointsNeeded() > print "\nYou need", pointsNeeded, "to win while your opponent needs", > oppPointsNeeded,"." > > > -- > ~MEN > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick From mnickey at gmail.com Sat Feb 25 11:57:28 2012 From: mnickey at gmail.com (Mike Nickey) Date: Sat, 25 Feb 2012 02:57:28 -0800 Subject: [Tutor] GameTracker help In-Reply-To: References: Message-ID: I think I found the issue. It seems that the UserOppSkillLvl wasn't passing the integer version of this variable back. Changing line 97 from return UserOppSkillLvl to return int(UserOppSkillLvl) seems to have helped. Any suggestions on how to implement the UserSkillLvl section so it's not redundant code? On Sat, Feb 25, 2012 at 02:07, Mike Nickey wrote: > Hey all, > > I'm trying to wok on a game tracker for my friends. What I have here > partly works but there are areas that I want to change and some areas > that are just not working for me. > > The areas that I am having difficulty with are the def pointsNeeded > and oppPointsNeeded. > What is strange to me is that I had pointsNeeded almost exactly as > oppPointsNeeded and only pointsNeeded worked. > > I'd like to change this to one function since it does the same thing. > I've tried using a dictionary but that does not seem to be working > well either. > > Any advice would be great. > Thanks in advance. > > CODE > #=============================================================================== > # Get users name -- DONE > # Get Users opponent name DONE > # Get user opponents APA number --DONE > # get users APA number -- DONE > # Determine if this is 8-ball or 9-ball -- DONE > # create number of points needed to win for 9-ball > # create number of games needed to win for 8-ball > # Get Users skill level -- DONE > # get users current opponent skill level -- DONE > # get number of innings played > # number of defenses played > # record who won and lost > #=============================================================================== > import __builtin__ > import string > > pointDictionary = {1:14, 2:19, 3:25, 4:31, 5:38, 6:46, 7:55, 8:65, 9:75} > > def getUserName(): > ? ?return raw_input("Enter your name: ") > > def getUserOppName(): > ? ?return raw_input ("Enter your opponents name: ") > > def getUserNumber(): > ? ?UserID = raw_input("Enter your APA ID number: ") > ? ?while (str.isdigit(UserID)==False): > ? ? ? ?UserID = raw_input("That is not a proper ID. Please re-enter > your APA number: ") > ? ?return UserID > > def getUserOppNumber(): > ? ?OppUserID = raw_input("Enter your opponents APA ID number: ") > ? ?while (str.isdigit(OppUserID)==False): > ? ? ? ?UserID = raw_input("That is not a proper ID. Please re-enter > your opponents APA number: ") > ? ?return OppUserID > > def getGameType(): > ? ?temp = 0 > ? ?while temp == 0: > ? ? ? ?GameType = raw_input("Are you playing 8-ball or 9-ball? ") > ? ? ? ?if GameType == "8": > ? ? ? ? ? ?print "Good luck and don't get an early 8" > ? ? ? ? ? ?GameType = 8 > ? ? ? ? ? ?temp = 1 > ? ? ? ?elif GameType == "9": > ? ? ? ? ? ?print "Good luck! Let's hope you sink the stripe on the break!" > ? ? ? ? ? ?GameType = 9 > ? ? ? ? ? ?temp = 1 > ? ? ? ?else: > ? ? ? ? ? ?print "That's not a valid entry, Please try again.: " > ? ?return int(GameType) > > def CheckRange8Ball(GameType, min=1, max=8): > ? ?if not min <= GameType <= max: > ? ? ? ?raise ValueError('Value out of range') > > def getUserSkillLvl(GameType): > ? ?if GameType == 8: > ? ? ? ?UserSkillLvl = prompt = "Enter your current 8-ball skill level: " > ? ?elif GameType == 9: > ? ? ? ?UserSkillLvl = prompt = "Enter your current 9-ball level:" > > ? ?UserSkillLvl = raw_input(prompt) > ? ?UserSkillLvl = int(UserSkillLvl) > > ? ?if GameType == 9: > ? ? ? ?temp = 0 > ? ? ? ?while temp == 0: > ? ? ? ? ? ?if ((UserSkillLvl <= 9) and (UserSkillLvl >=1)): > ? ? ? ? ? ? ? ?print "Thank You" > ? ? ? ? ? ? ? ?temp = 1 > ? ? ? ? ? ? ? ?break > ? ? ? ? ? ?elif ((UserSkillLvl >9) or (UserSkillLvl < 1)): > ? ? ? ? ? ? ? ?while temp == 0: > ? ? ? ? ? ? ? ? ? ?UserSkillLvl = raw_input("Please re-enter your > 9-ball skill level") > ? ? ? ? ? ? ? ? ? ?return UserSkillLvl > > ? ?if GameType == 8: > ? ? ? ?temp = 0 > ? ? ? ?while temp == 0: > ? ? ? ? ? ?if ((UserSkillLvl <= 8) and (UserSkillLvl >=1)): > ? ? ? ? ? ? ? ?print "thank you" > ? ? ? ? ? ? ? ?temp = 1 > ? ? ? ? ? ? ? ?break > ? ? ? ? ? ?elif (UserSkillLvl >8) or (UserSkillLvl < 1): > ? ? ? ? ? ? ? ?while temp == 0: > ? ? ? ? ? ? ? ? ? ?UserSkillLvl = raw_input("Please re-enter your > skill level: ") > ? ?return UserSkillLvl > > def getUserOppSkillLvl(): > ? ?UserOppSkillLvl = raw_input("Enter your opponents current skill level: ") > ? ?while (str.isdigit(UserOppSkillLvl)==False): > ? ? ? ?UserOppSkillLvl = raw_input("That is not a proper Skill Level. \ > ? ? ? ?Please enter a number between 1 and 9 for 9-ball or 1 and 8 > for 8-ball: ") > ? ? ? ?UserOppSkillLvl = int(UserOppSkillLvl) > ? ?return UserOppSkillLvl > > def getPointsNeeded(): > ? ?if (GameType == 9): > ? ? ? ?for UserSkillLvl in range (0, len(pointDictionary)): > ? ? ? ? ? ?pointsNeeded = pointDictionary(UserSkillLvl) > ? ?return pointsNeeded > > def getOppPointsNeeded(): > ? ?if (GameType == 9): > ? ? ? ?if (UserOppSkillLvl == 9): > ? ? ? ? ? ?oppPointsNeeded = 75 > ? ? ? ?elif (UserOppSkillLvl == 8): > ? ? ? ? ? ?oppPointsNeeded = 65 > ? ? ? ?elif (UserOppSkillLvl == 7): > ? ? ? ? ? ?oppPointsNeeded = 55 > ? ? ? ?elif(UserOppSkillLvl == 6): > ? ? ? ? ? ?oppPointsNeeded = 46 > ? ? ? ?elif (UserOppSkillLvl == 5): > ? ? ? ? ? ?oppPointsNeeded = 38 > ? ? ? ?elif (UserOppSkillLvl == 4): > ? ? ? ? ? ?oppPointsNeeded = 31 > ? ? ? ?elif (UserOppSkillLvl == 3): > ? ? ? ? ? ?oppPointsNeeded = 25 > ? ? ? ?elif (UserOppSkillLvl == 2): > ? ? ? ? ? ?oppPointsNeeded = 19 > ? ? ? ?elif (UserOppSkillLvl == 1): > ? ? ? ? ? ?oppPointsNeeded = 14 > ? ?return oppPointsNeeded > > UserName = getUserName() > UserOppName = getUserOppName() > UserID = getUserNumber() > OppUserID = getUserOppNumber() > GameType = getGameType() > UserSkillLvl = getUserSkillLvl(GameType) > UserOppSkillLvl = getUserOppSkillLvl() > > print "\nPlayer Name:",UserName, "\nOpponent Name:", UserOppName, > "\nUser ID: ",UserID, "\nOpponent APA ID", OppUserID, \ > "\nGameType: ",GameType,"\nUser Skill Level: ",UserSkillLvl, "\nUser > Opponents Level: ",UserOppSkillLvl > > pointsNeeded = getPointsNeeded() > oppPointsNeeded = getOppPointsNeeded() > print "\nYou need", pointsNeeded, "to win while your opponent needs", > oppPointsNeeded,"." > > > -- > ~MEN -- ~MEN From joel.goldstick at gmail.com Sat Feb 25 16:37:46 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 25 Feb 2012 10:37:46 -0500 Subject: [Tutor] GameTracker help In-Reply-To: References: Message-ID: On Sat, Feb 25, 2012 at 5:57 AM, Mike Nickey wrote: > I think I found the issue. It seems that the UserOppSkillLvl wasn't > passing the integer version of this variable back. > Changing line 97 from > ? ?return UserOppSkillLvl > to > ? ?return int(UserOppSkillLvl) > ?seems to have helped. > > Any suggestions on how to implement the UserSkillLvl section so it's > not redundant code? > > On Sat, Feb 25, 2012 at 02:07, Mike Nickey wrote: >> Hey all, >> >> I'm trying to wok on a game tracker for my friends. What I have here >> partly works but there are areas that I want to change and some areas >> that are just not working for me. >> >> The areas that I am having difficulty with are the def pointsNeeded >> and oppPointsNeeded. >> What is strange to me is that I had pointsNeeded almost exactly as >> oppPointsNeeded and only pointsNeeded worked. >> >> I'd like to change this to one function since it does the same thing. >> I've tried using a dictionary but that does not seem to be working >> well either. >> >> Any advice would be great. >> Thanks in advance. >> >> CODE >> #=============================================================================== >> # Get users name -- DONE >> # Get Users opponent name DONE >> # Get user opponents APA number --DONE >> # get users APA number -- DONE >> # Determine if this is 8-ball or 9-ball -- DONE >> # create number of points needed to win for 9-ball >> # create number of games needed to win for 8-ball >> # Get Users skill level -- DONE >> # get users current opponent skill level -- DONE >> # get number of innings played >> # number of defenses played >> # record who won and lost >> #=============================================================================== >> import __builtin__ >> import string >> >> pointDictionary = {1:14, 2:19, 3:25, 4:31, 5:38, 6:46, 7:55, 8:65, 9:75} >> >> def getUserName(): >> ? ?return raw_input("Enter your name: ") >> >> def getUserOppName(): >> ? ?return raw_input ("Enter your opponents name: ") >> >> def getUserNumber(): >> ? ?UserID = raw_input("Enter your APA ID number: ") >> ? ?while (str.isdigit(UserID)==False): >> ? ? ? ?UserID = raw_input("That is not a proper ID. Please re-enter >> your APA number: ") >> ? ?return UserID >> >> def getUserOppNumber(): >> ? ?OppUserID = raw_input("Enter your opponents APA ID number: ") >> ? ?while (str.isdigit(OppUserID)==False): >> ? ? ? ?UserID = raw_input("That is not a proper ID. Please re-enter >> your opponents APA number: ") >> ? ?return OppUserID >> >> def getGameType(): >> ? ?temp = 0 >> ? ?while temp == 0: >> ? ? ? ?GameType = raw_input("Are you playing 8-ball or 9-ball? ") >> ? ? ? ?if GameType == "8": >> ? ? ? ? ? ?print "Good luck and don't get an early 8" >> ? ? ? ? ? ?GameType = 8 >> ? ? ? ? ? ?temp = 1 >> ? ? ? ?elif GameType == "9": >> ? ? ? ? ? ?print "Good luck! Let's hope you sink the stripe on the break!" >> ? ? ? ? ? ?GameType = 9 >> ? ? ? ? ? ?temp = 1 >> ? ? ? ?else: >> ? ? ? ? ? ?print "That's not a valid entry, Please try again.: " >> ? ?return int(GameType) >> >> def CheckRange8Ball(GameType, min=1, max=8): >> ? ?if not min <= GameType <= max: >> ? ? ? ?raise ValueError('Value out of range') >> >> def getUserSkillLvl(GameType): >> ? ?if GameType == 8: >> ? ? ? ?UserSkillLvl = prompt = "Enter your current 8-ball skill level: " This is kind of odd looking. Istead try this: prompt = "Enter your current %d-ball skill level: " % prompt Look at http://docs.python.org/release/2.5.2/lib/typesseq-strings.html or just google python string formatting Then you can get rid of this below >> ? ?elif GameType == 9: >> ? ? ? ?UserSkillLvl = prompt = "Enter your current 9-ball level:" >> >> ? ?UserSkillLvl = raw_input(prompt) >> ? ?UserSkillLvl = int(UserSkillLvl) >> Now, below. It looks like if GameType is 9, SkillLvl is from 1 to 9. If GameType is 8, SkillLvl is from 1 to 8. Your elif statements are complicated. Since the if case succeeds for Lvl from 1 to GameType, the elif is redundant. You need the else, but else will always be true if the 'if' code failed. So simplify elif to else with no condition. Notice that your logic is identical except for the test dependant on the game. That logic identical except for the upper range -- if game 8 then 8, if game 9 then 9. So, try to clean this up and figure a way to just test once, depending on the game. >> ? ?if GameType == 9: >> ? ? ? ?temp = 0 >> ? ? ? ?while temp == 0: >> ? ? ? ? ? ?if ((UserSkillLvl <= 9) and (UserSkillLvl >=1)): >> ? ? ? ? ? ? ? ?print "Thank You" >> ? ? ? ? ? ? ? ?temp = 1 >> ? ? ? ? ? ? ? ?break >> ? ? ? ? ? ?elif ((UserSkillLvl >9) or (UserSkillLvl < 1)): >> ? ? ? ? ? ? ? ?while temp == 0: >> ? ? ? ? ? ? ? ? ? ?UserSkillLvl = raw_input("Please re-enter your >> 9-ball skill level") >> ? ? ? ? ? ? ? ? ? ?return UserSkillLvl >> >> ? ?if GameType == 8: >> ? ? ? ?temp = 0 >> ? ? ? ?while temp == 0: >> ? ? ? ? ? ?if ((UserSkillLvl <= 8) and (UserSkillLvl >=1)): >> ? ? ? ? ? ? ? ?print "thank you" >> ? ? ? ? ? ? ? ?temp = 1 >> ? ? ? ? ? ? ? ?break >> ? ? ? ? ? ?elif (UserSkillLvl >8) or (UserSkillLvl < 1): >> ? ? ? ? ? ? ? ?while temp == 0: >> ? ? ? ? ? ? ? ? ? ?UserSkillLvl = raw_input("Please re-enter your >> skill level: ") >> ? ?return UserSkillLvl >> >> def getUserOppSkillLvl(): >> ? ?UserOppSkillLvl = raw_input("Enter your opponents current skill level: ") >> ? ?while (str.isdigit(UserOppSkillLvl)==False): >> ? ? ? ?UserOppSkillLvl = raw_input("That is not a proper Skill Level. \ >> ? ? ? ?Please enter a number between 1 and 9 for 9-ball or 1 and 8 >> for 8-ball: ") >> ? ? ? ?UserOppSkillLvl = int(UserOppSkillLvl) >> ? ?return UserOppSkillLvl >> >> def getPointsNeeded(): >> ? ?if (GameType == 9): >> ? ? ? ?for UserSkillLvl in range (0, len(pointDictionary)): >> ? ? ? ? ? ?pointsNeeded = pointDictionary(UserSkillLvl) >> ? ?return pointsNeeded >> >> def getOppPointsNeeded(): >> ? ?if (GameType == 9): >> ? ? ? ?if (UserOppSkillLvl == 9): >> ? ? ? ? ? ?oppPointsNeeded = 75 >> ? ? ? ?elif (UserOppSkillLvl == 8): >> ? ? ? ? ? ?oppPointsNeeded = 65 >> ? ? ? ?elif (UserOppSkillLvl == 7): >> ? ? ? ? ? ?oppPointsNeeded = 55 >> ? ? ? ?elif(UserOppSkillLvl == 6): >> ? ? ? ? ? ?oppPointsNeeded = 46 >> ? ? ? ?elif (UserOppSkillLvl == 5): >> ? ? ? ? ? ?oppPointsNeeded = 38 >> ? ? ? ?elif (UserOppSkillLvl == 4): >> ? ? ? ? ? ?oppPointsNeeded = 31 >> ? ? ? ?elif (UserOppSkillLvl == 3): >> ? ? ? ? ? ?oppPointsNeeded = 25 >> ? ? ? ?elif (UserOppSkillLvl == 2): >> ? ? ? ? ? ?oppPointsNeeded = 19 >> ? ? ? ?elif (UserOppSkillLvl == 1): >> ? ? ? ? ? ?oppPointsNeeded = 14 >> ? ?return oppPointsNeeded >> >> UserName = getUserName() >> UserOppName = getUserOppName() >> UserID = getUserNumber() >> OppUserID = getUserOppNumber() >> GameType = getGameType() >> UserSkillLvl = getUserSkillLvl(GameType) >> UserOppSkillLvl = getUserOppSkillLvl() >> >> print "\nPlayer Name:",UserName, "\nOpponent Name:", UserOppName, >> "\nUser ID: ",UserID, "\nOpponent APA ID", OppUserID, \ >> "\nGameType: ",GameType,"\nUser Skill Level: ",UserSkillLvl, "\nUser >> Opponents Level: ",UserOppSkillLvl >> >> pointsNeeded = getPointsNeeded() >> oppPointsNeeded = getOppPointsNeeded() >> print "\nYou need", pointsNeeded, "to win while your opponent needs", >> oppPointsNeeded,"." >> >> >> -- >> ~MEN > > > > -- > ~MEN > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick From ckava3 at gmail.com Sun Feb 26 02:02:38 2012 From: ckava3 at gmail.com (Chris Kavanagh) Date: Sat, 25 Feb 2012 20:02:38 -0500 Subject: [Tutor] Staticmethod & Classmethod Question In-Reply-To: <4F48AB2C.5090601@davea.name> References: <4F489C6D.70505@gmail.com> <4F48AB2C.5090601@davea.name> Message-ID: <4F4984AE.4050509@gmail.com> On 2/25/2012 4:34 AM, Dave Angel wrote: > On 02/25/2012 03:31 AM, Chris Kavanagh wrote: >> Hey Everyone, >> >> I came across this code in 'A Byte Of Python' & realized there was a >> line I didn't understand. The line is "howMany = >> staticmethod(howMany)" (Complete code pasted below.) >> >> I don't think, in my very short Python career, I've heard of a >> staticmethod or classmethod. There's very little explanation of them >> in the book. I've googled them, but am still confused on exactly what >> they are & why they should be used. The only sense I can make of them >> is, a staticmethod can be called WITHOUT actually creating an object >> first. >> >> Anyways, if someone could give me a simple explanation with a very >> simple example, I will be elated! As always, thank you in advance for >> any help!! Code Below: >> >> PS: Please keep in mind, Python is my 1st language, & I'm very new to >> it (4 to 5 months). >> >> >> >> class Robot: >> '''Represents a robot, with a name.''' >> >> # A class variable, counting the number of robots >> population = 0 >> >> def __init__(self, name): >> '''Initializes the data.''' >> self.name = name >> print('(Initializing {0})'.format(self.name)) >> >> # When this person is created, the robot >> # adds to the population >> Robot.population += 1 >> >> def __del__(self): >> '''I am dying.''' >> print('{0} is being destroyed!'.format(self.name)) >> >> Robot.population -= 1 >> >> if Robot.population == 0: >> print('{0} was the last one.'.format(self.name)) >> else: >> print('There are still {0:d} robots working.'.format(Robot.population)) >> >> def sayHi(self): >> '''Greeting by the robot. >> >> Yeah, they can do that.''' >> print('Greetings, my masters call me {0}.'.format(self.name)) >> >> def howMany(): >> '''Prints the current population.''' >> print('We have {0:d} robots.'.format(Robot.population)) >> howMany = staticmethod(howMany) >> >> droid1 = Robot('R2-D2') >> droid1.sayHi() >> Robot.howMany() >> >> droid2 = Robot('C-3PO') >> droid2.sayHi() >> Robot.howMany() >> >> print("\nRobots can do some work here.\n") >> >> print("Robots have finished their work. So let's destroy them.") >> del droid1 >> del droid2 >> >> Robot.howMany() > > Defining a function inside a class makes it a method. Two distinctions > exist between an ordinary function and a method. One is which namespace > the name is known in, and the other is this mysterious thing called self. > > The namespace thing means that "sayHi" for example is not an attribute > of the module, but of the instance of the class. So other classes might > have a method of the same name without conflict. > > The self thing means that when you say droid2.sayHi(), there is an extra > parameter added to the list (only one in this case), the 'self' parameter. > > What staticmethod() does is to strip out the second feature. For methods > that don't need a 'self' parameter, (ie. that don't care which instance > they're called on, and are willing to hardcode any refs to other class > things) this works out great. > > classmethod() converts the method so it supplies the class of the object > as its first parameter (cls). This can be useful if you have more than > one class derived from each other, and the method still needs to know > which class it actually was called on. > > Does this help some? > Yes & No, lol. BTW, thanks for the reply Dave, it's much appreciated. Maybe if I tell you what I know, it will make it easier for you to understand what I don't know. Such as, I know a method is just a function inside a class. . . Ok, 1st, I learned Classes & Objects using Python 'Old Style' Classes & Objects. I hadn't thought (until now) there was much difference other than terminology, ie. using class(object): in the parent class. Instead of class(self): ect. 2nd, I understood 'self' is just a place holder for the object that will be created. I get that a staticmethod does not need the 'self', but why would this be necessary?? You said, "For methods > that don't need a 'self' parameter, (ie. that don't care which instance > they're called on, and are willing to hardcode any refs to other class > things)" I know this will sound stupid, but why would the method care which instance it's called on?? I think this is where my confusion is coming in. . .I hope I've made sense here. . . From steve at pearwood.info Sun Feb 26 03:37:14 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 26 Feb 2012 13:37:14 +1100 Subject: [Tutor] Staticmethod & Classmethod Question In-Reply-To: <4F4984AE.4050509@gmail.com> References: <4F489C6D.70505@gmail.com> <4F48AB2C.5090601@davea.name> <4F4984AE.4050509@gmail.com> Message-ID: <4F499ADA.1030307@pearwood.info> Chris Kavanagh wrote: > I know this will sound stupid, but why would the method care which > instance it's called on?? I think this is where my confusion is coming > in. . .I hope I've made sense here. . . Typical use for class instances is to store per-instance information. For example, both "spam" and "ham" are strings, they are instances of the class str, but they differ in their per-instance information. Namely, one includes the four characters s p a m while the other contains three characters h a m. When you call a str method like this: >>> s = 'spam' # create a str instance >>> s.upper() 'SPAM' how does the upper() method know to return 'SPAM' rather than 'HAM' or 'CHEESE'? It knows, because it has access to the instance 'spam'. For instances you create yourself, the typical pattern is to write a class like this: class Parrot(object): def __init__(self, name): self.name = name # Per instance information. def talk(self): print "%s wants a cracker." % self.name.title() >>> polly = Parrot('polly') >>> alfonse = Parrot('alfonse') >>> polly.talk() Polly wants a cracker. How does the talk method know to print "Polly..." instead of "Alfonse..."? Because it has access to the specific instance. But sometimes you have methods that don't care about the per-instance information, they only care about the class information. For example, the built-in dict class includes a method "fromkeys" which creates a new dictionary. It doesn't matter which dict instance you call it from, you get the same result: >>> a = {'a': 1} >>> b = {'B': None, 'c': 42} >>> a.fromkeys([1, 2, 3]) {1: None, 2: None, 3: None} >>> b.fromkeys([1, 2, 3]) {1: None, 2: None, 3: None} In fact, you don't even need to create a dict instance first before calling fromkeys, you can call it directly from the class itself: >>> dict.fromkeys([1, 2, 3]) {1: None, 2: None, 3: None} So the fromkeys method is a class method, and instead of automatically taking the instance as the first argument (by convention called self), it gets the class as the first argument (by convention called cls). Even rarer are cases where the method doesn't care about the instance or the class. These are called static methods in Python, and are equivalent to pure functions except they are bound to a class. Static methods don't receive any automatic arguments, neither the instance nor the class. (Note: in case you decide to do some googling on this, be aware of the terminology differences. In Java, a "static method" is what we call a "class method" in Python; as far as I know, Java doesn't have anything like what we call a "static method".) -- Steven From breamoreboy at yahoo.co.uk Sun Feb 26 06:04:17 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 26 Feb 2012 05:04:17 +0000 Subject: [Tutor] GameTracker help In-Reply-To: References: Message-ID: On 25/02/2012 15:37, Joel Goldstick wrote: > On Sat, Feb 25, 2012 at 5:57 AM, Mike Nickey wrote: >> I think I found the issue. It seems that the UserOppSkillLvl wasn't >> passing the integer version of this variable back. >> Changing line 97 from >> return UserOppSkillLvl >> to >> return int(UserOppSkillLvl) >> seems to have helped. >> >> Any suggestions on how to implement the UserSkillLvl section so it's >> not redundant code? >> >> On Sat, Feb 25, 2012 at 02:07, Mike Nickey wrote: >>> Hey all, >>> >>> I'm trying to wok on a game tracker for my friends. What I have here >>> partly works but there are areas that I want to change and some areas >>> that are just not working for me. >>> >>> The areas that I am having difficulty with are the def pointsNeeded >>> and oppPointsNeeded. >>> What is strange to me is that I had pointsNeeded almost exactly as >>> oppPointsNeeded and only pointsNeeded worked. >>> >>> I'd like to change this to one function since it does the same thing. >>> I've tried using a dictionary but that does not seem to be working >>> well either. >>> >>> Any advice would be great. >>> Thanks in advance. >>> >>> CODE >>> #=============================================================================== >>> # Get users name -- DONE >>> # Get Users opponent name DONE >>> # Get user opponents APA number --DONE >>> # get users APA number -- DONE >>> # Determine if this is 8-ball or 9-ball -- DONE >>> # create number of points needed to win for 9-ball >>> # create number of games needed to win for 8-ball >>> # Get Users skill level -- DONE >>> # get users current opponent skill level -- DONE >>> # get number of innings played >>> # number of defenses played >>> # record who won and lost >>> #=============================================================================== >>> import __builtin__ >>> import string >>> >>> pointDictionary = {1:14, 2:19, 3:25, 4:31, 5:38, 6:46, 7:55, 8:65, 9:75} >>> >>> def getUserName(): >>> return raw_input("Enter your name: ") >>> >>> def getUserOppName(): >>> return raw_input ("Enter your opponents name: ") >>> >>> def getUserNumber(): >>> UserID = raw_input("Enter your APA ID number: ") >>> while (str.isdigit(UserID)==False): >>> UserID = raw_input("That is not a proper ID. Please re-enter >>> your APA number: ") >>> return UserID >>> >>> def getUserOppNumber(): >>> OppUserID = raw_input("Enter your opponents APA ID number: ") >>> while (str.isdigit(OppUserID)==False): >>> UserID = raw_input("That is not a proper ID. Please re-enter >>> your opponents APA number: ") >>> return OppUserID >>> >>> def getGameType(): >>> temp = 0 >>> while temp == 0: >>> GameType = raw_input("Are you playing 8-ball or 9-ball? ") >>> if GameType == "8": >>> print "Good luck and don't get an early 8" >>> GameType = 8 >>> temp = 1 >>> elif GameType == "9": >>> print "Good luck! Let's hope you sink the stripe on the break!" >>> GameType = 9 >>> temp = 1 >>> else: >>> print "That's not a valid entry, Please try again.: " >>> return int(GameType) >>> >>> def CheckRange8Ball(GameType, min=1, max=8): >>> if not min<= GameType<= max: >>> raise ValueError('Value out of range') >>> >>> def getUserSkillLvl(GameType): >>> if GameType == 8: > >>> UserSkillLvl = prompt = "Enter your current 8-ball skill level: " > > This is kind of odd looking. Istead try this: > prompt = "Enter your current %d-ball skill level: " % prompt > > Look at http://docs.python.org/release/2.5.2/lib/typesseq-strings.html > or just google python string formatting > Then you can get rid of this below > >>> elif GameType == 9: >>> UserSkillLvl = prompt = "Enter your current 9-ball level:" >>> >>> UserSkillLvl = raw_input(prompt) >>> UserSkillLvl = int(UserSkillLvl) >>> > > Now, below. It looks like if GameType is 9, SkillLvl is from 1 to 9. > If GameType is 8, SkillLvl is from 1 to 8. > Your elif statements are complicated. Since the if case succeeds for > Lvl from 1 to GameType, the elif is redundant. You need the else, but > else will always be true if the 'if' code failed. > So simplify elif to else with no condition. > > Notice that your logic is identical except for the test dependant on > the game. That logic identical except for the upper range -- if game > 8 then 8, if game 9 then 9. > > So, try to clean this up and figure a way to just test once, depending > on the game. > To go further you don't need all those round brackets and you can chain comparisons in Python so this should work. if 1 <= UserSkillLvl <= GameType: >>> if GameType == 9: >>> temp = 0 >>> while temp == 0: >>> if ((UserSkillLvl<= 9) and (UserSkillLvl>=1)): >>> print "Thank You" >>> temp = 1 >>> break >>> elif ((UserSkillLvl>9) or (UserSkillLvl< 1)): >>> while temp == 0: >>> UserSkillLvl = raw_input("Please re-enter your >>> 9-ball skill level") >>> return UserSkillLvl >>> >>> if GameType == 8: >>> temp = 0 >>> while temp == 0: >>> if ((UserSkillLvl<= 8) and (UserSkillLvl>=1)): >>> print "thank you" >>> temp = 1 >>> break >>> elif (UserSkillLvl>8) or (UserSkillLvl< 1): >>> while temp == 0: >>> UserSkillLvl = raw_input("Please re-enter your >>> skill level: ") >>> return UserSkillLvl >>> >>> def getUserOppSkillLvl(): >>> UserOppSkillLvl = raw_input("Enter your opponents current skill level: ") >>> while (str.isdigit(UserOppSkillLvl)==False): >>> UserOppSkillLvl = raw_input("That is not a proper Skill Level. \ >>> Please enter a number between 1 and 9 for 9-ball or 1 and 8 >>> for 8-ball: ") >>> UserOppSkillLvl = int(UserOppSkillLvl) >>> return UserOppSkillLvl >>> >>> def getPointsNeeded(): >>> if (GameType == 9): >>> for UserSkillLvl in range (0, len(pointDictionary)): >>> pointsNeeded = pointDictionary(UserSkillLvl) >>> return pointsNeeded getPointsNeeded will never work as :- a) you can't call a dictionary, i.e. pointsNeeded = pointDictionary(UserSkillLvl) is incorrect b) if you write pointsNeeded = pointDictionary[UserSkillLvl] instead you'll get a KeyError c) if GameType isn't 9 you'll get an UnboundLocalError How do I know this? I've tried it at the interactive prompt, one of Python's great strengths. >>> pointDictionary = {1:14, 2:19, 3:25, 4:31, 5:38, 6:46, 7:55, 8:65, 9:75} >>> def getPointsNeeded(): if (GameType == 9): for UserSkillLvl in range (0, len(pointDictionary)): pointsNeeded = pointDictionary(UserSkillLvl) return pointsNeeded >>> GameType = 9 >>> pointsNeeded = getPointsNeeded() Traceback (most recent call last): File "", line 1, in File "", line 4, in getPointsNeeded TypeError: 'dict' object is not callable! >>> def getPointsNeeded(): ... if GameType == 9: ... for UserSkillLvl in range (0, len(pointDictionary)): ... pointsNeeded = pointDictionary[UserSkillLvl] ... return pointsNeeded ... >>> pointsNeeded = getPointsNeeded() Traceback (most recent call last): File "", line 1, in File "", line 4, in getPointsNeeded KeyError: 0 >>> GameType = 8 >>> pointsNeeded = getPointsNeeded() Traceback (most recent call last): File "", line 1, in File "", line 6, in getPointsNeeded UnboundLocalError: local variable 'pointsNeeded' referenced before assignment But this function isn't needed anyway just have. pointsNeeded = pointDictionary[UserSkillLvl] Hence. >>> UserSkillLvl = 5 >>> pointsNeeded = pointDictionary[UserSkillLvl] >>> pointsNeeded 38 >>> >>> def getOppPointsNeeded(): >>> if (GameType == 9): >>> if (UserOppSkillLvl == 9): >>> oppPointsNeeded = 75 >>> elif (UserOppSkillLvl == 8): >>> oppPointsNeeded = 65 >>> elif (UserOppSkillLvl == 7): >>> oppPointsNeeded = 55 >>> elif(UserOppSkillLvl == 6): >>> oppPointsNeeded = 46 >>> elif (UserOppSkillLvl == 5): >>> oppPointsNeeded = 38 >>> elif (UserOppSkillLvl == 4): >>> oppPointsNeeded = 31 >>> elif (UserOppSkillLvl == 3): >>> oppPointsNeeded = 25 >>> elif (UserOppSkillLvl == 2): >>> oppPointsNeeded = 19 >>> elif (UserOppSkillLvl == 1): >>> oppPointsNeeded = 14 >>> return oppPointsNeeded >>> >>> UserName = getUserName() >>> UserOppName = getUserOppName() >>> UserID = getUserNumber() >>> OppUserID = getUserOppNumber() >>> GameType = getGameType() >>> UserSkillLvl = getUserSkillLvl(GameType) >>> UserOppSkillLvl = getUserOppSkillLvl() >>> >>> print "\nPlayer Name:",UserName, "\nOpponent Name:", UserOppName, >>> "\nUser ID: ",UserID, "\nOpponent APA ID", OppUserID, \ >>> "\nGameType: ",GameType,"\nUser Skill Level: ",UserSkillLvl, "\nUser >>> Opponents Level: ",UserOppSkillLvl >>> >>> pointsNeeded = getPointsNeeded() >>> oppPointsNeeded = getOppPointsNeeded() >>> print "\nYou need", pointsNeeded, "to win while your opponent needs", >>> oppPointsNeeded,"." >>> >>> >>> -- >>> ~MEN >> >> >> >> -- >> ~MEN >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > -- Cheers. Mark Lawrence. From josempalaka at gmail.com Sun Feb 26 12:07:59 2012 From: josempalaka at gmail.com (JOSEPH MARTIN MPALAKA) Date: Sun, 26 Feb 2012 14:07:59 +0300 Subject: [Tutor] SOME KNOWLEDGE OF IRONPYTHON? Message-ID: Hullo to you All, Has any one used IronPython studio from microsoft Visual Studio. Am so new into IronPython please. It?s missing a help menu Tutorial link of "HOW TO" along the menu bar, so as to be used in learning and knowing how make out something. Could one be able to structure for me this code in IronPython OR, to find me any other tutorial documentation of designing the above interfaces in IronPython studio? joseph -- MY BEING was HIS BEING. Of what is magnificent and liked of me, this was him too. In VAIN, I will always miss u,thou i live with YOU in vain. Lt.Col.Sam .E. Lukakamwa (DADDY) From steve at pearwood.info Sun Feb 26 14:26:39 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 27 Feb 2012 00:26:39 +1100 Subject: [Tutor] SOME KNOWLEDGE OF IRONPYTHON? In-Reply-To: References: Message-ID: <4F4A330F.6000804@pearwood.info> JOSEPH MARTIN MPALAKA wrote: > Hullo to you All, > Has any one used IronPython studio from microsoft Visual Studio. > > Am so new into IronPython please. > > It?s missing a help menu Tutorial link of "HOW TO" along the menu bar, > so as to be used in learning and knowing how make out something. Could > one be able to structure for me this code in IronPython OR, to find me > any other tutorial documentation of designing the above interfaces in > IronPython studio? This is a mailing list for learning Python the language, not specific features of individual implementations. Unfortunately, we have a bias here for CPython over Jython, IronPython, PyPy, Stackless, and other even lesser-known versions of Python. This bias is due to familiarity, not because we don't like the other implementations. You may be better off asking your question on a dedicated IronPython mailing list or forum: http://lists.ironpython.com/listinfo.cgi http://ironpython.net/support/ Good luck! -- Steven From alan.gauld at btinternet.com Sun Feb 26 17:01:44 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 26 Feb 2012 16:01:44 +0000 Subject: [Tutor] SOME KNOWLEDGE OF IRONPYTHON? In-Reply-To: References: Message-ID: On 26/02/12 11:07, JOSEPH MARTIN MPALAKA wrote: > It?s missing a help menu Tutorial link of "HOW TO" along the menu bar, > so as to be used in learning and knowing how make out something. Could > one be able to structure for me this code in IronPython OR, to find me > any other tutorial documentation of designing the above interfaces in > IronPython studio? A quick Google throws up several tutorials/manuals. Here is one that looked promising: http://www.ironpython.info/index.php/Contents You are welcome to asks questions about Python here, but I don't know if we have many IronPython users so questions about VisualStudio aspects are probably better handled on a more specific forum. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From carolina.cadi at maine.edu Sun Feb 26 18:52:58 2012 From: carolina.cadi at maine.edu (Carolina Dianne LaCourse) Date: Sun, 26 Feb 2012 12:52:58 -0500 Subject: [Tutor] Help with Python Program In-Reply-To: <4F485CB1.2060606@pearwood.info> References: <4F485CB1.2060606@pearwood.info> Message-ID: First off I want to really thank you for all of the help! I am in my first semester as I started as a non traditional student in January. Even though I am in an intro class I think that many of my class mates had more of a c/s foundation in high then I did. It took me a few tries but I did finally get my program to run using this code!!!! :) #import random target = random.randint(1,100) import random #import random number generator module target = random.randint(1,100) #generates random number between 1 and 100 guess = float(raw_input('pick a number between 1 and 100')) while guess != target: if guess < target: print 'too low' elif guess > target: print 'too high' #otherwise guess == target and game is over I am having trouble getting it to run for more than one game but am trying. Also I started off using the idle shell to write the codes but it wont let you run it from there, so I opened a new window and retyped it for my first few attempts. I am unsure why you would use the idle shell if you would need to open a new window and retype it anyway. Is there an easier way or something that I am not getting? After doing that several times I just opened a new window and started from there without using the shell and it worked fine, so can I always do it that way and not use the shell at all? I am also still kind of unsure about the loops and was hoping you could explain a little more about it or may know of a good online resource? Thanks again for all the help...Steve really helped by explaining it simply to me and I really appreciate it! It took me like 10-15 tries but I was so excited when I finally got it to run! On 2/24/12, Steven D'Aprano wrote: > Carolina Dianne LaCourse wrote: > > [...] >> I understand that I need to ask for raw input from the user and that I >> need to be able to use the if elif else to tell the user whether their >> number matches or id too high or to low but am just not sure what to >> do first. Any advice would be greatly appreciated! I have tried some >> online tutorials to get the basics but still am having a really hard >> time. I did work with scratch a bit earlier this semester and got >> that, but am really struggling with python. > > Start by writing down in plain English the steps of how you would play the > guessing game. This is a called an algorithm, which is something very > similar > to a recipe or a set of instructions. You might have something like this: > > (1) Think of a number between 1 and 100, and remember it. > (2) Repeat the following steps until the game is over: > (3) - Ask the person playing for a number between 1 and 100. > (4) - If the number is too low, tell them it is too low. > (5) - If the number is too high, tell them it is too high. > (6) - If the number is equal to the number you thought of, the game is over. > > All that makes up *one* game. Then you need instructions to play multiple > games: > > (a) Play one game, as above. > (b) Repeat the following steps until done: > (c) - Ask the player if they want to play again. > (d) - If they say Yes, play one game, as above. > (e) - Otherwise, we are done. > (f) Finally, print how many games were played, how many guesses were needed, > and the average number of guesses per game. > > > Now, you need to change the English instructions to instructions the > computer > can follow, using Python. For example, Step (1) above picks a random number > and remembers it as the target of the game: > > import random > target = random.randint(1, 100) > > Step (2) is a bit harder -- it's a loop. You should have learned about while > loops and for loops. I expect a while loop is better for this, because you > can't tell ahead of time how many times you need to go round and round the > loop. > > > while guess != target: > Step (3) ask the user for a number, and call it "guess" > if guess < target: > print "too low" > elif guess > target: > print "too high" > # otherwise guess == target so the game will be over > > > Notice that this isn't exactly Python code. The most obvious problem is the > line "Step (3)..." which is plain English. You need to replace that with > code > to actually ask the user for a number. (Hint: you will need the raw_input > function.) > > Another problem is that the *first* time you enter the loop, the name > "guess" > isn't defined. You need to give it a value to start with, before the loop. > Any > value will do, so long as it isn't target. I suggest 0. > > Does this help you get started? Go ahead and write some code, and see where > it > takes you. Piece by piece, step by step, you should work towards replacing > each bit of English instruction with some Python code to do that. > > You should aim to write code to play *one* game first. Get that right, > first, > then adapt it to play multiple games. > > Write some code, see how it works (or where is fails to work), and anything > that is unclear, come back and ask. > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From robert.sjoblom at gmail.com Mon Feb 27 00:24:54 2012 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Mon, 27 Feb 2012 00:24:54 +0100 Subject: [Tutor] Help with Python Program In-Reply-To: References: <4F485CB1.2060606@pearwood.info> Message-ID: > import random #import random number generator module > target = random.randint(1,100) #generates random number between 1 and 100 > guess = float(raw_input('pick a number between 1 and 100')) > while guess != target: > ? ?if guess < target: print 'too low' > ? ?elif guess > target: print 'too high' > ? ?#otherwise guess == target and game is over > > I am having trouble getting it to run for more than one game but am > trying. Also I started off using the idle shell to write the codes but > it wont let you run it from there, so I opened a new window and > retyped it for my first few attempts. I am unsure why you would use > the idle shell if you would need to open a new window and retype it > anyway. [snip] > so can I always > do it that way and not use the shell at all? The shell is for testing out things; it's not really for writing entire programs in. But as a test-tool it's priceless. Don't know what random.randint() does? Use the shell to find out. Want to see if you can convert ints to floats? Use the shell. It's a great way to test short things like that, because it will give you instant feedback. You can write longer code in it, but it can be cumbersome. In the end, it's another tool for your belt, I guess you could say. >?I am also still kind of > unsure about the loops and was hoping you could explain a little more > about it or may know of a good online resource? The while loop you're using tests for one thing: is guess == target. If it isn't, the contents of the while loop executes. I should note that while your loop works, it doesn't work as intended: what happens if you guess too low? Let's see how the program runs: computer picks a number between 1 and 100 and stores it in variable 'target' computer then asks user for a number between 1 and 100 and stores it in variable 'guess' while loop checks whether guess is the same as target. If it's not, it checks if the guess is higher than target or lower than target and then prints the corresponding response. the while loop checks again if guess == target. It's not, since we never change the value of guess. It checks if the guess is higher than target or lower than target...(etc) the while loop checks again... In short, you can say that the loop is named because of its behaviour: it loops until it shouldn't any longer. I'm sure you can see the problem here. So, while you now can check whether a variable is equal to another variable, you currently have no way to change 'guess' for a new try. Can you think of any way to solve that? And while this might not be entirely on topic, there's a wonderful book for complete beginners -- I've used it as well -- that I'd like to recommend: Python Programming for the Absolute Beginner. In fact, one of the excercises happen to be this particular game. -- best regards, Robert S. From sukhpreet2294sidhu at ymail.com Mon Feb 27 00:29:43 2012 From: sukhpreet2294sidhu at ymail.com (Sukhpreet Sdhu) Date: Mon, 27 Feb 2012 04:59:43 +0530 (IST) Subject: [Tutor] roman to arabic Message-ID: <1330298983.10244.YahooMailNeo@web137610.mail.in.yahoo.com> Hi I just wrote python code to convert roman to arabic numerals, but its not working. Can you just check where the problem is and way to correct that. So here is my python code import string print "Welcome to the numeric conversion program" print "Please enter command" data=raw_input() now = 0 previous = 0 total = 0 if data == "r": ??? print "Enter roman numeric to convert in arabic" ??? roman_numeric=string.swapcase(raw_input("Enter the Roman Numeral to convert to arabic")) ?if roman_numeric == ("M" or "D" or "L" or "C" or "L" or "X" or "V" or "I"):???????????????????????????????????????????????????????????????????????????????????????????????? ???? Length = len(roman_numeric) - 1 ???? i = roman_numeric[Length] ???? if i == "M": ???????? now = 1000 ???????? if i == "D": ???????????? now = 500 ???????????? if i == "C": ???????????????? now = 100 ???????????????? if i == "L": ???????????????????? now = 50 ???????????????????? if i == "X": ???????????????????????? now = 10 ???????????????????????? if i == "V": ???????????????????????????? now = 5 ???????????????????????????? if i == "I": ???????????????????????????????? now = 1 ???????????????????????????????? acc = now ???????????????????????????????? if (previous >= now): ???????????????????????????????????? total += acc-prvious ???????????????????????????????????? print "The total is",total ???????????????????????????????????? if (previous <= now): ???????????????????????????????????????? total += acc-prevous ???????????????????????????????????????? print "The total is",total ???????????????????????????????????????? else : ???????????????????????????????????????????? if data == "a" : ???????????????????????????????????????????????? print "Arabic number to convert" ???????thanks sukhpreet sidhu????????????????????????????????????????????????????????????????? From breamoreboy at yahoo.co.uk Mon Feb 27 00:47:41 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 26 Feb 2012 23:47:41 +0000 Subject: [Tutor] roman to arabic In-Reply-To: <1330298983.10244.YahooMailNeo@web137610.mail.in.yahoo.com> References: <1330298983.10244.YahooMailNeo@web137610.mail.in.yahoo.com> Message-ID: On 26/02/2012 23:29, Sukhpreet Sdhu wrote: > Hi > I just wrote python code to convert roman to arabic numerals, but its not working. > Can you just check where the problem is and way to correct that. > So here is my python code > import string > print "Welcome to the numeric conversion program" > print "Please enter command" > data=raw_input() > now = 0 > previous = 0 > total = 0 > if data == "r": > print "Enter roman numeric to convert in arabic" > roman_numeric=string.swapcase(raw_input("Enter the Roman Numeral to convert to arabic")) > if roman_numeric == ("M" or "D" or "L" or "C" or "L" or "X" or "V" or "I"): > Length = len(roman_numeric) - 1 > i = roman_numeric[Length] > if i == "M": > now = 1000 > if i == "D": > now = 500 > if i == "C": > now = 100 > if i == "L": > now = 50 > if i == "X": > now = 10 > if i == "V": > now = 5 > if i == "I": > now = 1 > acc = now > if (previous>= now): > total += acc-prvious > print "The total is",total > if (previous<= now): > total += acc-prevous > print "The total is",total > else : > if data == "a" : > print "Arabic number to convert" > > thanks > sukhpreet sidhu > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I'm sorry but the code is so badly formatted via Thunderbird that it's pretty much impossible to work out what you intend. Try resending with the code correctly formatted. Also put print statements into the code so that you can follow the flow and see what it's doing, then you'll be able to make some progress yourself. -- Cheers. Mark Lawrence. From wprins at gmail.com Mon Feb 27 01:09:29 2012 From: wprins at gmail.com (Walter Prins) Date: Mon, 27 Feb 2012 00:09:29 +0000 Subject: [Tutor] roman to arabic In-Reply-To: <1330298983.10244.YahooMailNeo@web137610.mail.in.yahoo.com> References: <1330298983.10244.YahooMailNeo@web137610.mail.in.yahoo.com> Message-ID: Hi , On 26 February 2012 23:29, Sukhpreet Sdhu wrote: > Hi > I just wrote python code to convert roman to arabic numerals, but its not working. How exactly is it not working? Please don't make us guess or work more than neccesary trying to help you... > Can you just check where the problem is and way to correct that. > So here is my python code > import string > print "Welcome to the numeric conversion program" > print "Please enter command" > data=raw_input() > now = 0 > previous = 0 > total = 0 > if data == "r": > ??? print "Enter roman numeric to convert in arabic" > ??? roman_numeric=string.swapcase(raw_input("Enter the Roman Numeral to convert to arabic")) > ?if roman_numeric == ("M" or "D" or "L" or "C" or "L" or "X" or "V" or "I"): > ???? Length = len(roman_numeric) - 1 > ???? i = roman_numeric[Length] > ???? if i == "M": > ???????? now = 1000 > ???????? if i == "D": > ???????????? now = 500 > ???????????? if i == "C": > ???????????????? now = 100 > ???????????????? if i == "L": > ???????????????????? now = 50 > ???????????????????? if i == "X": > ???????????????????????? now = 10 > ???????????????????????? if i == "V": > ???????????????????????????? now = 5 > ???????????????????????????? if i == "I": > ???????????????????????????????? now = 1 > ???????????????????????????????? acc = now > ???????????????????????????????? if (previous >= now): > ???????????????????????????????????? total += acc-prvious > ???????????????????????????????????? print "The total is",total > ???????????????????????????????????? if (previous <= now): > ???????????????????????????????????????? total += acc-prevous > ???????????????????????????????????????? print "The total is",total > ???????????????????????????????????????? else : > ???????????????????????????????????????????? if data == "a" : > ???????????????????????????????????????????????? print "Arabic number to convert" > > ???????thanks > sukhpreet sidhu Is your code really indented like that? A quote worth mentioning here is: "If you need more than 3 levels of indentation, you're screwed anyway, and should fix your program." -- Linus Torvalds Now he was writing w.r.t. C/C++ but the principle holds for Python also in general -- very highly nested levels of indentation are indicative of some kind of program problem, and will likely cause you to conceptually lose control of what the code's supposed to be doing. Can you please explain in english (pseudocode) your algorithm for converting a roman numeral string to arabic numbers, with a more direct explanation of what you've tried and how your solution is not working from what you're expecting. Then we'll be able to help you better and will not be left having to guess at how All that said, apart from the indentation weirdness, a few more offhand observations: I can see 3 different spellings for "previous" in the code, which will obviously cause problems. The logic to deal with smaller numbers preceding larger numbers seem broken (though I've not looked too closely). The conditions both include equality (>= and <=) which is likely wrong, the indentation is wrong and both conditions seem to be doing the same thing, which must likewise be wrong. (You'd expect there to be some difference in handling the case when the previous number is smaller that the current number vs when it's larger...) HTH, Walter From alan.gauld at btinternet.com Mon Feb 27 02:45:03 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Feb 2012 01:45:03 +0000 Subject: [Tutor] roman to arabic In-Reply-To: <1330298983.10244.YahooMailNeo@web137610.mail.in.yahoo.com> References: <1330298983.10244.YahooMailNeo@web137610.mail.in.yahoo.com> Message-ID: On 26/02/12 23:29, Sukhpreet Sdhu wrote: > import string Are you using a very old versioon opf python? If not you should not use string. The built in string methods can do everything you want without resorting to string. > print "Welcome to the numeric conversion program" > print "Please enter command" > data=raw_input() > now = 0 > previous = 0 > total = 0 > if data == "r": > print "Enter roman numeric to convert in arabic" > roman_numeric=string.swapcase(raw_input("Enter the Roman Numeral to convert to arabic")) Are you sure you want swapcase()? I'd have thought uppercase() would be more effective given the tests below. Using built in methods that line becomes: roman_numeric=raw_input("Enter the Roman Numeral to convert to arabic").uppercase() > if roman_numeric == ("M" or "D" or "L" or "C" or "L" or "X" or "V" or "I"): This is just wrong! The parenthesised list will evaluate to True so you are testing if the variable is True, which it will be if not empty. You want: if roman_numeric in ("M","D","L","C","L","X","V","I"): > Length = len(roman_numeric) - 1 If the variable is one of the items in your list it is only 1 char long so you re setting Length to zero. Is that what you want? > i = roman_numeric[Length] If you really want to extract the last digit use a -1 index. In which case you dshould do the same for the check on valid values... > if i == "M": > now = 1000 > if i == "D": > now = 500 Are you sure you want this structure? It would look a lot neater using elif if i == "M": now = 1000 elif i == "D": now = 500 elif i == "C": now = 100 But better still would be to use a dictionary: values = { 'I':1, 'V':5, 'X':10,...'D':500, 'M':1000 } now = values[i] > acc = now > if (previous>= now): > total += acc-prvious spelling error in prvious > print "The total is",total > if (previous<= now): > total += acc-prevous > print "The total is",total > else : This else doesn't line up with any if. > if data == "a" : else: if : could just be elif : HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Mon Feb 27 05:23:02 2012 From: bgailer at gmail.com (bob gailer) Date: Sun, 26 Feb 2012 23:23:02 -0500 Subject: [Tutor] roman to arabic In-Reply-To: <1330298983.10244.YahooMailNeo@web137610.mail.in.yahoo.com> References: <1330298983.10244.YahooMailNeo@web137610.mail.in.yahoo.com> Message-ID: <4F4B0526.7000209@gmail.com> On 2/26/2012 6:29 PM, Sukhpreet Sdhu wrote: > Hi > I just wrote python code to convert roman to arabic numerals [snip] Yuk what a mess. May I suggest you start with a much simpler program, which is to take a roman number between 1 and 3 (just i's) and convert that. First describe how you'd convert the number by hand. Then convert that process to Python. Test the program. Fix any problems. Report back to us success or a problem you don't know how to address. Tell us exactly what went wrong. (e.g. I entered iii expecting 3 and got 17 or if you get a traceback post it. For example when I run your program I get: Traceback ( File "", line 12 if roman_numeric == ("M" or "D" or "L" or "C" or "L" or "X" or "V" or "I"): ^ IndentationError: unindent does not match any outer indentation level Then add v (now the number is between 1 and 8). You will come up with a completely different program! And it will be the correct one. Also provide meaningful prompts. print "Please enter command" If I was running your program and saw that I'd have to give up since I have no idea what is expected. print "Please enter command - r for roman-arabic" would be much better. -- Bob Gailer 919-636-4239 Chapel Hill NC From ashish.makani at gmail.com Mon Feb 27 12:19:46 2012 From: ashish.makani at gmail.com (ashish makani) Date: Mon, 27 Feb 2012 16:49:46 +0530 Subject: [Tutor] What made Python differ from other Languages? In-Reply-To: References: Message-ID: An excellent recent article on hn(hacker news) on why python is important http://blaag.haard.se/Why-Python-is-important-for-you/ (via http://news.ycombinator.com/item?id=3579847 ) cheers ashish On Tue, Feb 21, 2012 at 1:13 AM, Mark Lawrence wrote: > On 20/02/2012 16:43, Sunil Tech wrote: > >> *I am Beginner (very little i know), i want to know what are new things i >> can find in Python.* >> >> >> >> >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > This sums up the Python philosophy. > > C:\Users\Mark\cpython\PCbuild>**py -3.2 -c "import this" > The Zen of Python, by Tim Peters > > Beautiful is better than ugly. > Explicit is better than implicit. > Simple is better than complex. > Complex is better than complicated. > Flat is better than nested. > Sparse is better than dense. > Readability counts. > Special cases aren't special enough to break the rules. > Although practicality beats purity. > Errors should never pass silently. > Unless explicitly silenced. > In the face of ambiguity, refuse the temptation to guess. > There should be one-- and preferably only one --obvious way to do it. > Although that way may not be obvious at first unless you're Dutch. > Now is better than never. > Although never is often better than *right* now. > If the implementation is hard to explain, it's a bad idea. > If the implementation is easy to explain, it may be a good idea. > Namespaces are one honking great idea -- let's do more of those! > > -- > Cheers. > > Mark Lawrence. > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cranky.frankie at gmail.com Mon Feb 27 15:41:41 2012 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Mon, 27 Feb 2012 09:41:41 -0500 Subject: [Tutor] roman to arabic Message-ID: Walter Prins wrote: <> I've always wondered about this quote. I'm thinking it means you might want to have functions or subroutines, depending on the language, to do big chunks of logic, so the main control flow is clean and easy to read, like "structured programming" in COBOL. Still, every language offers almost unlimted indentation, so it's up to the programmer to not use it? Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?How you do anything is how you do everything.? - from Alabama Crimson Tide training room From jensenjohn59 at yahoo.com Mon Feb 27 16:22:20 2012 From: jensenjohn59 at yahoo.com (John Jensen) Date: Mon, 27 Feb 2012 07:22:20 -0800 (PST) Subject: [Tutor] new to programming and wondering about an IDE for Python on Linux Message-ID: <1330356140.95758.YahooMailNeo@web125601.mail.ne1.yahoo.com> Hi All, I'm?new to programming and wondering about an IDE for Python on Linux. I'd appreciate any feedback on this and good tutorials or books on Python 3 and the IDEs suggested. There are many available and I'm wondering what you as users find effective. Thanks, John -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 27 16:37:31 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Feb 2012 15:37:31 +0000 Subject: [Tutor] roman to arabic In-Reply-To: References: Message-ID: On 27/02/12 14:41, Cranky Frankie wrote: > < of indentation, you're screwed > > I've always wondered about this quote. I'm thinking it means you might > want to have functions or subroutines, depending on the language, to > do big chunks of logic, That's one option. The OP also had the option of using a lookup table(dictionary) or just using elifs instead of nested ifs. Often a different algorithm helps. Also functional programming (ie. not just procedural!) can reduce the numbers of indentation levels. (See the FP topic in my tutor for some examples of this.) Simple hiding of indentation levels inside a function is kind of the last resort in reducing indentation levels. Generally deep indentation reveals problems in the basic algorithm and/or data structures. > offers almost unlimited indentation, so it's up to the programmer to > not use it? Correct, this is a program design decision not a language feature. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From fomcl at yahoo.com Mon Feb 27 17:28:05 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 27 Feb 2012 08:28:05 -0800 (PST) Subject: [Tutor] roman to arabic In-Reply-To: References: Message-ID: <1330360085.57100.YahooMailNeo@web110713.mail.gq1.yahoo.com> Hi, I wrote a little program that does the conversion (I won't post it because it would be a spoiler for the OP). The one thing I don't know, though, is how to formalise that it is not allowed to write something like IIIIIIIIX, but instead just II. Or not DM but simply D. The rule is to write it the shortest possible way. Am I wrong or is it really not trivial at all to write an error class for such lengthy roman numerals? ? Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? >________________________________ > From: Alan Gauld >To: tutor at python.org >Sent: Monday, February 27, 2012 4:37 PM >Subject: Re: [Tutor] roman to arabic > >On 27/02/12 14:41, Cranky Frankie wrote: > >> <> of indentation, you're screwed >> >> I've always wondered about this quote. I'm thinking it means you might >> want to have functions or subroutines, depending on the language, to >> do big chunks of logic, > >That's one option. > >The OP also had the option of using a lookup table(dictionary) >or just using elifs instead of nested ifs. > >Often a different algorithm helps. > >Also functional programming (ie. not just procedural!) can reduce the numbers of indentation levels. (See the FP topic in my tutor for some examples of this.) > >Simple hiding of indentation levels inside a function is kind of >the last resort in reducing indentation levels. Generally deep indentation reveals problems in the basic algorithm and/or >data structures. > >> offers almost unlimited indentation, so it's up to the programmer to >> not use it? > >Correct, this is a program design decision not a language feature. > >-- Alan G >Author of the Learn to Program web site >http://www.alan-g.me.uk/ > >_______________________________________________ >Tutor maillist? -? Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 27 17:37:19 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Feb 2012 16:37:19 +0000 Subject: [Tutor] roman to arabic In-Reply-To: <1330360085.57100.YahooMailNeo@web110713.mail.gq1.yahoo.com> References: <1330360085.57100.YahooMailNeo@web110713.mail.gq1.yahoo.com> Message-ID: On 27/02/12 16:28, Albert-Jan Roskam wrote: > possible way. Am I wrong or is it really not trivial at all to write an > error class for such lengthy roman numerals? Its non trivial, you need something like a state machine to detect valid transitions as you read each character. Alan G. From evert.rol at gmail.com Mon Feb 27 17:42:27 2012 From: evert.rol at gmail.com (Evert Rol) Date: Mon, 27 Feb 2012 17:42:27 +0100 Subject: [Tutor] roman to arabic In-Reply-To: <1330360085.57100.YahooMailNeo@web110713.mail.gq1.yahoo.com> References: <1330360085.57100.YahooMailNeo@web110713.mail.gq1.yahoo.com> Message-ID: <3F85CBEC-4BAD-4490-A3C1-3FAFAE27A71A@gmail.com> > I wrote a little program that does the conversion (I won't post it because it would be a spoiler for the OP). The one thing I don't know, though, is how to formalise > that it is not allowed to write something like IIIIIIIIX, but instead just II. Or not DM but simply D. The rule is to write it the shortest possible way. Am I wrong or is it really not trivial at all to write an error class for such lengthy roman numerals? Mark Pilgrim wrote whole sections on Roman numerals in his Dive Into Python tutorial. While the numerals pop up in various examples throughout the chapters of the tutorial, for this, the tutorial on unit testing may proof helpful: http://www.diveintopython.net/unit_testing/romantest.html Somewhere in that example, there's unit testing code just for examples as above. From the unit test, follow the tutorial into chapter 14 to see how it's done. Hope that helps, Evert > > Regards, > Albert-Jan > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a > fresh water system, and public health, what have the Romans ever done for us? > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > From: Alan Gauld > To: tutor at python.org > Sent: Monday, February 27, 2012 4:37 PM > Subject: Re: [Tutor] roman to arabic > > On 27/02/12 14:41, Cranky Frankie wrote: > > > < > of indentation, you're screwed > > > > I've always wondered about this quote. I'm thinking it means you might > > want to have functions or subroutines, depending on the language, to > > do big chunks of logic, > > That's one option. > > The OP also had the option of using a lookup table(dictionary) > or just using elifs instead of nested ifs. > > Often a different algorithm helps. > > Also functional programming (ie. not just procedural!) can reduce the numbers of indentation levels. (See the FP topic in my tutor for some examples of this.) > > Simple hiding of indentation levels inside a function is kind of > the last resort in reducing indentation levels. Generally deep indentation reveals problems in the basic algorithm and/or > data structures. > > > offers almost unlimited indentation, so it's up to the programmer to > > not use it? > > Correct, this is a program design decision not a language feature. > > -- Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Mon Feb 27 17:50:11 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Feb 2012 16:50:11 +0000 Subject: [Tutor] new to programming and wondering about an IDE for Python on Linux In-Reply-To: <1330356140.95758.YahooMailNeo@web125601.mail.ne1.yahoo.com> References: <1330356140.95758.YahooMailNeo@web125601.mail.ne1.yahoo.com> Message-ID: On 27/02/12 15:22, John Jensen wrote: > I'm new to programming and wondering about an IDE for Python on Linux. Linux is an IDE :-) But, smiley's aside it's true. You can use basic tools like vim, emacs and terminal windows etc. To cut n paste between them is trivial (Much more so than in Windows or MacOS). Tools like diff, grep and ctags enable cross file navigation between functions etc and are fully integrated with the common editors. Unix was built for software development by software developers. There is little that a modern IDE can do that Unix tools can't do almost as easily (tooltips is about the only thing I'm aware of!) And there's lots that Unix can do that most IDEs struggle with. > I'd appreciate any feedback on this and good tutorials or books on > Python 3 and the IDEs suggested. There are many available and I'm > wondering what you as users find effective. But if you must have an IDE the usual suspects are available: Netbeans, Eclipse, Wing, SPE, and many others... ...and of course IDLE which comes with Python. Personally I go with vim, and 2 terminal windows. One running a prompt and one to execute the program for testing.-- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From fomcl at yahoo.com Mon Feb 27 18:29:22 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 27 Feb 2012 09:29:22 -0800 (PST) Subject: [Tutor] roman to arabic In-Reply-To: <3F85CBEC-4BAD-4490-A3C1-3FAFAE27A71A@gmail.com> References: <1330360085.57100.YahooMailNeo@web110713.mail.gq1.yahoo.com> <3F85CBEC-4BAD-4490-A3C1-3FAFAE27A71A@gmail.com> Message-ID: <1330363762.72566.YahooMailNeo@web110715.mail.gq1.yahoo.com> Ah, nice! Thank you! Sseeing the formal rules makes it easier: http://www.diveintopython.net/unit_testing/stage_5.html A regex is used to test whether the roman numeral is valid. Very elegant! ? Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? >________________________________ > From: Evert Rol >To: Albert-Jan Roskam >Cc: Python Tutor >Sent: Monday, February 27, 2012 5:42 PM >Subject: Re: [Tutor] roman to arabic > >> I wrote a little program that does the conversion (I won't post it because it would be a spoiler for the OP). The one thing I don't know, though, is how to formalise >> that it is not allowed to write something like IIIIIIIIX, but instead just II. Or not DM but simply D. The rule is to write it the shortest possible way. Am I wrong or is it really not trivial at all to write an error class for such lengthy roman numerals? > >Mark Pilgrim wrote whole sections on Roman numerals in his Dive Into Python tutorial. While the numerals pop up in various examples throughout the chapters of the tutorial, for this, the tutorial on unit testing may proof helpful: http://www.diveintopython.net/unit_testing/romantest.html >Somewhere in that example, there's unit testing code just for examples as above. From the unit test, follow the tutorial into chapter 14 to see how it's done. > >Hope that helps, > >? Evert > > > >>? >> Regards, >> Albert-Jan >> >> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ >> All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a >> fresh water system, and public health, what have the Romans ever done for us? >> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ >> From: Alan Gauld >> To: tutor at python.org >> Sent: Monday, February 27, 2012 4:37 PM >> Subject: Re: [Tutor] roman to arabic >> >> On 27/02/12 14:41, Cranky Frankie wrote: >> >> > <> > of indentation, you're screwed >> > >> > I've always wondered about this quote. I'm thinking it means you might >> > want to have functions or subroutines, depending on the language, to >> > do big chunks of logic, >> >> That's one option. >> >> The OP also had the option of using a lookup table(dictionary) >> or just using elifs instead of nested ifs. >> >> Often a different algorithm helps. >> >> Also functional programming (ie. not just procedural!) can reduce the numbers of indentation levels. (See the FP topic in my tutor for some examples of this.) >> >> Simple hiding of indentation levels inside a function is kind of >> the last resort in reducing indentation levels. Generally deep indentation reveals problems in the basic algorithm and/or >> data structures. >> >> > offers almost unlimited indentation, so it's up to the programmer to >> > not use it? >> >> Correct, this is a program design decision not a language feature. >> >> -- Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> _______________________________________________ >> Tutor maillist? -? Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> >> _______________________________________________ >> Tutor maillist? -? Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Mon Feb 27 20:10:42 2012 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Mon, 27 Feb 2012 20:10:42 +0100 Subject: [Tutor] new to programming and wondering about an IDE for Python on Linux In-Reply-To: References: <1330356140.95758.YahooMailNeo@web125601.mail.ne1.yahoo.com> Message-ID: >> I'd appreciate any feedback on this and good tutorials or books on >> Python 3 and the IDEs suggested. There are many available and I'm >> wondering what you as users find effective. I fiddled a bit with the Eric Python IDE; Eric5 for Python3 and Eric4 for Python2; overall I'd say that Eclipse was a better experience, but Eric was by no means bad. I guess it comes down to user preferences. As for books, Dive Into Python 3 is one of the better books I've come across. http://eric-ide.python-projects.org/ -- best regards, Robert S. From jsantos.lazer at gmail.com Tue Feb 28 12:23:46 2012 From: jsantos.lazer at gmail.com (Joaquim Santos) Date: Tue, 28 Feb 2012 11:23:46 +0000 Subject: [Tutor] new to programming and wondering about an IDE for Python on Linux (Robert Sjoblom) Message-ID: ---------------------------------------------------------------------- > > Message: 1 > Date: Mon, 27 Feb 2012 20:10:42 +0100 > From: Robert Sjoblom > To: Alan Gauld > Cc: tutor at python.org > Subject: Re: [Tutor] new to programming and wondering about an IDE for > Python on Linux > Message-ID: > > > Content-Type: text/plain; charset=ISO-8859-1 > > >> I'd appreciate any feedback on this and good tutorials or books on > >> Python 3 and the IDEs suggested. There are many available and I'm > >> wondering what you as users find effective. > > I fiddled a bit with the Eric Python IDE; Eric5 for Python3 and Eric4 > for Python2; overall I'd say that Eclipse was a better experience, but > Eric was by no means bad. I guess it comes down to user preferences. > As for books, Dive Into Python 3 is one of the better books I've come > across. > > http://eric-ide.python-projects.org/ > > -- > best regards, > Robert S. > -> My 2 cents on that (being also a beginner...). > A very interesting and customizable IDE for Linux is the Spyder project. http://code.google.com/p/spyderlib/ It was previously known as Pydee and has lot's of features that I, as a beginner, find good, like the calltips, function browser, console, online help... and so on! Best regards! Joaquim Santos -------------- next part -------------- An HTML attachment was scrubbed... URL: From nsivaram.net at gmail.com Tue Feb 28 15:40:10 2012 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Tue, 28 Feb 2012 20:10:10 +0530 Subject: [Tutor] initialising all elements of a matrix Message-ID: <82vcmrc985.fsf@gmail.com> I was wondering whether there is a faster/better/cleaner way of element wise operations of arbitrarily nested list. I wrote something like this for 1 level nested lists and am wondering whether there are any good idioms in python. I did this after a ridiculous amount of bad thinking/missteps in python for the simplest of cases. def init_p (arr): # input is always 2D matrix; init to uniform probability dist. q = [] row = len(arr) col = len(arr[0]) uni_dist = 1.0/(row *col) q = [ [uni_dist] * col for i in range(row)] return q Of course, without using external packages like numpy or any other scientific packages. sivaram -- From __peter__ at web.de Tue Feb 28 17:40:17 2012 From: __peter__ at web.de (Peter Otten) Date: Tue, 28 Feb 2012 17:40:17 +0100 Subject: [Tutor] initialising all elements of a matrix References: <82vcmrc985.fsf@gmail.com> Message-ID: Sivaram Neelakantan wrote: > > I was wondering whether there is a faster/better/cleaner way of > element wise operations of arbitrarily nested list. I wrote something > like this for 1 level nested lists and am wondering whether there are > any good idioms in python. I did this after a ridiculous amount of > bad thinking/missteps in python for the simplest of cases. > > def init_p (arr): > # input is always 2D matrix; init to uniform probability dist. > q = [] > row = len(arr) > col = len(arr[0]) > uni_dist = 1.0/(row *col) > q = [ [uni_dist] * col for i in range(row)] > return q > > Of course, without using external packages like numpy or any other > scientific packages. Here's how I would break up the problem: # untested def nested_list(shape, value): if len(shape) == 1: return [value] * shape[0] return [nested_list(shape[1:], value) for _ in range(shape[0])] def get_shape(arr): shape = [] while isinstance(arr, list): shape.append(len(arr)) arr = arr[0] return shape def product(factors, product=1): for factor in factors: product *= factor return product def init_p(arr): shape = get_shape(arr) value = 1.0 / product(shape) return nested_list(shape, value) Now you can proceed to improve the parts independently... From bgailer at gmail.com Tue Feb 28 18:26:52 2012 From: bgailer at gmail.com (bob gailer) Date: Tue, 28 Feb 2012 12:26:52 -0500 Subject: [Tutor] initialising all elements of a matrix In-Reply-To: References: <82vcmrc985.fsf@gmail.com> Message-ID: <4F4D0E5C.8030805@gmail.com> On 2/28/2012 11:40 AM, Peter Otten wrote: def product(factors, product=1): for factor in factors: product *= factor return product can be "simplified" def product(factors): import operator return reduce(operator.mul, factors) -- Bob Gailer 919-636-4239 Chapel Hill NC From __peter__ at web.de Tue Feb 28 19:03:32 2012 From: __peter__ at web.de (Peter Otten) Date: Tue, 28 Feb 2012 19:03:32 +0100 Subject: [Tutor] initialising all elements of a matrix References: <82vcmrc985.fsf@gmail.com> <4F4D0E5C.8030805@gmail.com> Message-ID: bob gailer wrote: > On 2/28/2012 11:40 AM, Peter Otten wrote: > > def product(factors, product=1): > for factor in factors: > product *= factor > return product > > can be "simplified" > > def product(factors): > import operator > return reduce(operator.mul, factors) If I had used the variant with reduce() would you have posted > def product(factors): > return reduce(operator.mul, factors) > > can be "complexified" > > def product(factors, product=1): > for factor in factors: > product *= factor > return product (Just a pointless thought experiment) From fargusjustin at gmail.com Tue Feb 28 23:48:14 2012 From: fargusjustin at gmail.com (justin fargus) Date: Tue, 28 Feb 2012 17:48:14 -0500 Subject: [Tutor] python questions about dictionary loops Message-ID: Hello, I'm new to Python. Just started a few weeks ago and I've been learning some basic things that I would like to put together but I don't even know where to began. I am trying to do the following: Make a program using two sentences of about 8 words (total between the two sentences). I would then like to create a dictionary {} and split the words of each sentence using one sentence as a dictionary key and using the other sentence for the dictionary value. I would then like to use a loop (while or for) that will write out a file that has the dictionary key and dictionary value to it. How can I go about doing this? I've noticed with Python there is more than one way to do most things. I would like the simplest so that I can practice over and over again on my own until I understand it. Thanks in advance Regards, Justin -------------- next part -------------- An HTML attachment was scrubbed... URL: From fargusjustin at gmail.com Wed Feb 29 00:04:22 2012 From: fargusjustin at gmail.com (justin fargus) Date: Tue, 28 Feb 2012 18:04:22 -0500 Subject: [Tutor] python dictionary and loop Message-ID: Hello, I am trying to do the following: Make a program using two sentences of about 8 words (total between the two sentences). I would then like to create a dictionary {} and split the words of each sentence using one sentence as a dictionary key and using the other sentence for the dictionary value. I would then like to use a loop (while or for) that will write out a file that has the dictionary key and dictionary value to it. How can I go about doing this? I've noticed with Python there is more than one way to do most things. I would like the simplest so that I can practice over and over again on my own until I understand it. Thanks in advance I forgot to add in my first email that I am using Windows Vista 64x and running Python 3.2.2. The two sentences I would like to use in the program is the following: "This is line one\nThis is line two!" so I write: text_message = "This is line one\nThis is line two!" The dictionary name and key/value pairs will be: my_sentences {'This':'This','is':'is','line':'line','one':'two'} # Does this code split the words of each sentence so that the words in sentence 1 are keys, and the words in sentence 2 are values? -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Wed Feb 29 00:08:08 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 28 Feb 2012 23:08:08 +0000 Subject: [Tutor] python questions about dictionary loops In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474164C93@SCACMX008.exchad.jpmchase.net> Justin wrote: >I'm new to Python. Just started a few weeks ago and I've been learning some basic things that I would like to put together but I don't even know where to began. I am trying to do the following: >Make a program using two sentences of about 8 words (total between the two sentences). I would then like to create a dictionary {} and split the words of each sentence using one sentence as a dictionary key and using the other sentence for the dictionary value. I would then like to use a loop (while or for) that will write out a file that has the dictionary key and dictionary value to it. How can I go about doing this? I've noticed with Python there is more than one way to do most things. I would like the simplest so that I can practice over and over again on my own until I understand it. Thanks in advance Steps: 1. Do you know how to input / retrieve the two sentences? (Look at open() or raw_input() if you do not ) 2. Do you know how to split strings? Look at the string operations (the python web API will show you if you read it) 3. Do you know how to create a dictionary and set values? Play around on the interactive prompt if you do not. 4. How do you want to write this out? You have lots of options, look at open(), pickle, shelve for just a few options. Now try and code something together and if you get stuck we can help. If you manage to finish it we can help improve it as well. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From steve at pearwood.info Wed Feb 29 00:25:45 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 29 Feb 2012 10:25:45 +1100 Subject: [Tutor] python questions about dictionary loops In-Reply-To: References: Message-ID: <4F4D6279.2000803@pearwood.info> justin fargus wrote: > Hello, > > > I'm new to Python. Just started a few weeks ago and I've been learning some > basic things that I would like to put together but I don't even know where > to began. I am trying to do the following: > > Make a program using two sentences of about 8 words (total between the two > sentences). I would then like to create a dictionary {} and split the > words of each sentence using one sentence as a dictionary key and using the > other sentence for the dictionary value. I would then like to use a loop > (while or for) that will write out a file that has the dictionary key and > dictionary value to it. How can I go about doing this? You don't tell us what parts of the problem are causing you trouble. Also, I don't know if this is homework or not, but a dictionary does not sound like the right data structure to use here. What happens if the first sentence (the keys) contains duplicate words? Here are some examples to get you started. Run them in Python, and see what they do. They won't solve your problem exactly, but if you study them and see what they are doing, you should be able to adapt them to solve your problem. If anything is unclear, please ask. paragraph = "This line has one sentence.\nAnd so does this one." first_line, second_line = paragraph.split('\n') print(first_line) print(second_line) sentence = "this is a sentence of seven words" words = sentence.split() ordinals = "1st 2nd 3rd 4th 5th 6th 7th".split() for ordinal, word in zip(ordinals, words): print("%s :: %s" % (ordinal, word)) d = {} for key, value in zip(['a', 'bb', 'ccc', 'dddd'], [1, 2, 3, 4]): d[key] = value for k, v in d.items(): print("%s :: %s" % (k, v)) Do you need any of this code explained, or is it clear what it does? -- Steven From ramit.prasad at jpmorgan.com Wed Feb 29 00:28:45 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 28 Feb 2012 23:28:45 +0000 Subject: [Tutor] python dictionary and loop In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474164CDA@SCACMX008.exchad.jpmchase.net> >The two sentences I would like to use in the program is the following: >"This is line one\nThis is line two!" so I write:?text_message = "This is line one\nThis is line two!" >The dictionary name and key/value pairs will be: >my_sentences {'This':'This','is':'is','line':'line','one':'two'} ? # Does this code split the words of each sentence so that the words in sentence 1 are keys, and the words in sentence 2 are values?? That code does not split anything; it manually hard codes the results you want! Although the dictionary you show is where each word in sentence one is the key for the corresponding word in sentence two. Based on your description, I was thinking you wanted something more like my_sentences = { 'This is line one': 'This is line two' } What happens for 1 sentence or 3 sentences? What if the sentences are not the same length? This type of manipulation makes sense for handling tabular data, but not sure exactly what your use case is... Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From silideba at gmail.com Wed Feb 29 15:33:36 2012 From: silideba at gmail.com (Debashish Saha) Date: Wed, 29 Feb 2012 20:03:36 +0530 Subject: [Tutor] how to stop a program in python which is running for long time Message-ID: From ajarncolin at gmail.com Wed Feb 29 15:39:40 2012 From: ajarncolin at gmail.com (col speed) Date: Wed, 29 Feb 2012 21:39:40 +0700 Subject: [Tutor] how to stop a program in python which is running for long time In-Reply-To: References: Message-ID: I'm not sure in windows, but in Linux, press Ctrl_C On 29 February 2012 21:33, Debashish Saha wrote: > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From d at davea.name Wed Feb 29 15:39:52 2012 From: d at davea.name (Dave Angel) Date: Wed, 29 Feb 2012 09:39:52 -0500 Subject: [Tutor] how to stop a program in python which is running for long time In-Reply-To: References: Message-ID: <4F4E38B8.2050704@davea.name> On 02/29/2012 09:33 AM, Debashish Saha wrote: Press the little X in the corner of the GUI ? Windows, Linux, or other? Console app running in the foreground, or a background app or gui? In Linux, you can either do a Ctrl-C or Ctrl-\ if the process is running in a terminal window, or a combination of ps and kill if not. -- DaveA From silideba at gmail.com Wed Feb 29 16:02:02 2012 From: silideba at gmail.com (Debashish Saha) Date: Wed, 29 Feb 2012 20:32:02 +0530 Subject: [Tutor] how to stop a program in python which is running for long time , I am using windows Message-ID: From bgailer at gmail.com Wed Feb 29 18:27:44 2012 From: bgailer at gmail.com (bob gailer) Date: Wed, 29 Feb 2012 12:27:44 -0500 Subject: [Tutor] how to stop a program in python which is running for long time , I am using windows In-Reply-To: References: Message-ID: <4F4E6010.9090705@gmail.com> GUI - task manager cmd line - taskkill " running for long time" is relative and irrelevant. Above stops regardless. -- Bob Gailer 919-636-4239 Chapel Hill NC From nikunjbadjatya at gmail.com Wed Feb 29 18:38:12 2012 From: nikunjbadjatya at gmail.com (Nikunj Badjatya) Date: Wed, 29 Feb 2012 23:08:12 +0530 Subject: [Tutor] Popen.terminate() - WindowsError: [Error 5] Access is denied Message-ID: Howdy All, Py ver - 3.2, Windows-XP . Logged in as user with admin privileges. >From my main python program, I am running powershell program using subprocess.Popen(....). Now I have created a signal_handler() function in main python script which will handle CTRL-C ( This works fine ). Now when I put "proc.terminate()" in my signal_handler() function to terminate the subprocess created as well, It is giving me "WindowsError: [Error 5] Access is denied" error. I have tried with os.kill() also, same error. Tried with Popen.kill() also same error. Have googled a bit but couldn't understand them. In general, How to kill a subprocesses created from a python program.? If that subprocess also creates a new process from itself, how can I kill all child processes from my main python script.? Any ideas.?? Thanks, Nikunj -------------- next part -------------- An HTML attachment was scrubbed... URL: