From steve at pearwood.info Tue Dec 1 01:15:55 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 1 Dec 2015 17:15:55 +1100 Subject: [Tutor] Python 3.5 console logging In-Reply-To: References: Message-ID: <20151201061555.GA18779@ando.pearwood.info> Hi Tyler, and welcome, On Mon, Nov 30, 2015 at 04:50:35PM -0500, Tyler Smithers wrote: > I am doing a project for my school and i am trying to find out how to make > a event log. But every where i look all it has is just making a text > document and it having in their what they put in their script. But i cant > find out how to code python into recording everything that happens when i > run the program. And can you please help me soon because i don't have much > time. Thank you! I'm not sure I understand what you want. Do you mean you want to use the interactive interpreter, and every time you enter a line, that line gets saved in a log file? That's normally called "history", and Python 3.5 will have history automatically turned on. If you hit the UP or DOWN arrows, the prompt will go through the history, showing each line. Is that what you mean? Otherwise, perhaps you could look at sys.__interactivehook__ and sys.__displayhook__. I'm not sure how advanced you are with Python programming, so if you need more help, please ask. -- Steve From cs at zip.com.au Tue Dec 1 02:33:34 2015 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 1 Dec 2015 18:33:34 +1100 Subject: [Tutor] Python 3.5 console logging In-Reply-To: References: Message-ID: <20151201073334.GA9247@cskk.homeip.net> On 30Nov2015 16:50, Tyler Smithers wrote: >I am doing a project for my school and i am trying to find out how to make >a event log. But every where i look all it has is just making a text >document and it having in their what they put in their script. That is normally what an event log it; a text file recording significant events. This can be done simply with print() calls or more elaborately via the logging module. >But i cant >find out how to code python into recording everything that happens when i >run the program. And can you please help me soon because i don't have much >time. Thank you! When you say everything, what do you mean? Normally people don't want that ("everything" might mean every python code line traversed, or every internal python opcode executed, etc). Normally that is an insane amount of details, and people normally just want to know significant events (user logged in, did this, was refused that, files opened/closed or stuff like that). You'll need to elaborate a bit more on what you're trying to achieve here. Cheers, Cameron Simpson From turtle at 64.hu Tue Dec 1 02:33:18 2015 From: turtle at 64.hu (=?UTF-8?B?VsOhbGFzIFDDqXRlcg==?=) Date: Tue, 1 Dec 2015 08:33:18 +0100 Subject: [Tutor] Python 3.5 console logging In-Reply-To: References: Message-ID: 2015-11-30 22:50 GMT+01:00 Tyler Smithers : > I am doing a project for my school and i am trying to find out how to make > a event log. But every where i look all it has is just making a text > document and it having in their what they put in their script. But i cant > find out how to code python into recording everything that happens when i > run the program. And can you please help me soon because i don't have much > time. Thank you! > I don't reaaly understand what you mean by "everything" (do you want a keylogger or a complete memory dump?). But the folks at Python.org wrote a nice howto: https://docs.python.org/3/howto/logging.html Does this help? From badwolfwitch at yahoo.com Tue Dec 1 00:04:15 2015 From: badwolfwitch at yahoo.com (jo stone) Date: Tue, 1 Dec 2015 05:04:15 +0000 (UTC) Subject: [Tutor] assignment sign definition References: <319559754.13222113.1448946255094.JavaMail.yahoo.ref@mail.yahoo.com> Message-ID: <319559754.13222113.1448946255094.JavaMail.yahoo@mail.yahoo.com> Hello, I am trying to teach myself Python, and got hung up on the definition of Assignment signs...The explination I have is: "A good way to understand the statement userAge = 0 is to think of it as userAge <- 0." I read this as "userAge is less than minus 0"? ? which make absolutely NO sense to me... Could someone please put this into terms I can understand? Thanks! From alan.gauld at btinternet.com Tue Dec 1 04:58:29 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 Dec 2015 09:58:29 +0000 Subject: [Tutor] assignment sign definition In-Reply-To: <319559754.13222113.1448946255094.JavaMail.yahoo@mail.yahoo.com> References: <319559754.13222113.1448946255094.JavaMail.yahoo.ref@mail.yahoo.com> <319559754.13222113.1448946255094.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 01/12/15 05:04, jo stone via Tutor wrote: > Hello, > I am trying to teach myself Python, and got hung up on the definition of Assignment signs... This is usually only a big problem for those who are strong in mathematics where = means that two things are equal in value and does not mean that either of them is changing value., In programming (in Python and many other languages) it means that the left hand side takes on the value of the right hand side. (For expressing equality we use a double == instead) > The explination I have is: > "A good way to understand the statement userAge = 0 is to think of it as userAge <- 0." > > I read this as "userAge is less than minus 0" which make absolutely NO sense to me... This looks like a classic case of somebody confusing things by trying to explain it :-) The <- is intended to be seen as an arrow pointing from the 0 to the userAge name. It indicates that userAge takes on the value 0. Another way of thinking about it is to read assignments in code as the word "becomes" so you read userAge = 0 as userAge becomes zero. For a different (and slightly more technically correct) explanation of assignment in Python try reading the section on variables in my tutor(see below) in the "Raw Materials" topic. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Tue Dec 1 05:06:22 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 Dec 2015 10:06:22 +0000 Subject: [Tutor] Python 3.5 console logging In-Reply-To: References: Message-ID: On 30/11/15 21:50, Tyler Smithers wrote: > find out how to code python into recording everything that happens when i > run the program. And can you please help me soon because i don't have much > time. Thank you! You need to be a bit more precise about how you define an "event". Everything that happens on your computer even during a few seconds is a vast amount of information(every mouse movement, keystroke, network data arriving/leaving, disk activity, monitor updates etc etc). Even recording everything that your code does is still quite a lot. Normally in an event log you set some values to determine exactly what things you want to record (eg opening a file, reading input from users, changing key variables etc) If you can clarify exactly what you want this event log to look like it will help both you and us figure out how to create it. Try mocking up the expected output and showing us what you'd like to see -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Tue Dec 1 05:16:50 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 Dec 2015 10:16:50 +0000 Subject: [Tutor] Countdown Clock Programming Question In-Reply-To: References: Message-ID: On 30/11/15 19:23, Evan Sommer wrote: > Hello again Alan! > > Do you think you could write a revised code with the modifications that > you suggested? I tried changing the code with your recommendations and I > keep getting syntax errors. My code was just an approximation known as 'pseudo code' you need to translate it into real Python. >> import time >> def count_down(): >> # start with 4 minutes --> 240 seconds >> for t in range(240, 120, -1): >> # format as 2 digit integers, fills with zero to the left >> # divmod() gives minutes, seconds >> sf = "{:01d}:{:02d}".format(*divmod(t, 60)) >> #print(sf) # test >> time_str.set(sf) >> root.update() >> # delay one second >> time.sleep(1)# create root/main window Don't use time.sleep() in a Tkinter program use the after method instead. In this case it will look like root.after(1000, count_down) Also instead of hard coding the 240 and 120 make them parameters of the function like def count_down(start, end): and put those names into your loop: for t in range(start,stop,-1) That way you can call it multiple times with the different values you need and avoid duplicating the for loop below Try those fixes initially and see how you go. >> root = tk.Tk() >> time_str = tk.StringVar() >> # create the time display label, give it a large font >> # label auto-adjusts to the font >> label_font = ('helvetica', 100) >> tk.Label(root, textvariable=time_str, font=label_font, bg='green', >> fg='white', relief='raised', bd=3).pack(fill='x', padx=5, pady=5) >> # start with 2 minutes --> 119 seconds >> for t in range(240, 120, -1): call count_down(240,120) here >> # format as 2 digit integers, fills with zero to the left >> # divmod() gives minutes, seconds >> sf = "{:01d}:{:02d}".format(*divmod(t, 60)) >> #print(sf) # test >> time_str.set(sf) >> root.update() >> # delay one second >> time.sleep(1) >> # create the time display label, give it a large font >> # label auto-adjusts to the font >> label_font = ('helvetica', 100) >> tk.Label(root, textvariable=time_str, font=label_font, bg='yellow', >> fg='white', relief='raised', bd=3).pack(fill='x', padx=5, pady=5) >> # start with 1 minutes --> 59 seconds >> for t in range(120,60, -1): call count_down(120,60) here >> # format as 2 digit integers, fills with zero to the left >> # divmod() gives minutes, seconds >> sf = "{:01d}:{:02d}".format(*divmod(t, 60)) >> #print(sf) # test >> time_str.set(sf) >> root.update() >> # delay one second >> time.sleep(1) >> # create the time display label, give it a large font >> # label auto-adjusts to the font >> label_font = ('helvetica', 100) >> tk.Label(root, textvariable=time_str, font=label_font, bg='red', >> fg='white', relief='raised', bd=3).pack(fill='x', padx=5, pady=5) >> # start with 4 minutes --> 240 seconds >> for t in range(60,-1, -1): call count_down(60,-1) here >> # format as 2 digit integers, fills with zero to the left >> # divmod() gives minutes, seconds >> sf = "{:01d}:{:02d}".format(*divmod(t, 60)) >> #print(sf) # test >> time_str.set(sf) >> root.update() >> # delay one second >> time.sleep(1) >> # start the GUI event loop >> root.mainloop() >> -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From lac at openend.se Tue Dec 1 05:27:02 2015 From: lac at openend.se (Laura Creighton) Date: Tue, 01 Dec 2015 11:27:02 +0100 Subject: [Tutor] assignment sign definition In-Reply-To: <319559754.13222113.1448946255094.JavaMail.yahoo@mail.yahoo.com> References: <319559754.13222113.1448946255094.JavaMail.yahoo.ref@mail.yahoo.com> <319559754.13222113.1448946255094.JavaMail.yahoo@mail.yahoo.com> Message-ID: <201512011027.tB1AR2s2032465@fido.openend.se> In a message of Tue, 01 Dec 2015 05:04:15 +0000, jo stone via Tutor writes: >Hello, >I am trying to teach myself Python, and got hung up on the definition of Assignment signs...The explination I have is: >"A good way to understand the statement userAge = 0 is to think of it as userAge <- 0." > >I read this as "userAge is less than minus 0"? ? which make absolutely NO sense to me... >Could someone please put this into terms I can understand? > >Thanks! The author of that tutorial does not want you to think using thoughts like the word equal. He or she thinks that if you see a line like 'a = 0' you will think 'a is equal to 0' and that is exactly what he or she does not want you to do. 'You had the thought 'equal'. Bad thought. Don't have it!' So he or she thinks that the language would be better if, in using assigments, there was some other symbol to use. He or she would like "a ? 0" instead. That is the unicode symbol U21e6 in there, between the a and the 0. It looks like an arrow that points to the left. But, since the author doesn't have access to unicode for some reason he or she decided to fake an arrow by '<-' which sort of liiks like an arrow in some fonts. Make sense? Laura From lac at openend.se Tue Dec 1 05:31:37 2015 From: lac at openend.se (Laura Creighton) Date: Tue, 01 Dec 2015 11:31:37 +0100 Subject: [Tutor] Python 3.5 console logging In-Reply-To: References: Message-ID: <201512011031.tB1AVbM3032636@fido.openend.se> He may be looking for something like the logging facility of Gnu screen. 'Please capture all the output of my python program and show it to me later'. Of course this will be of little or no use if his program has a GUI. Laura From alan.gauld at btinternet.com Tue Dec 1 12:33:47 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 Dec 2015 17:33:47 +0000 Subject: [Tutor] Countdown Clock Programming Question In-Reply-To: References: Message-ID: On 01/12/15 10:16, Alan Gauld wrote: >>> def count_down(): >>> # start with 4 minutes --> 240 seconds >>> for t in range(240, 120, -1): >>> # format as 2 digit integers, fills with zero to the left >>> # divmod() gives minutes, seconds >>> sf = "{:01d}:{:02d}".format(*divmod(t, 60)) >>> #print(sf) # test >>> time_str.set(sf) >>> root.update() >>> # delay one second >>> time.sleep(1)# create root/main window > > Don't use time.sleep() in a Tkinter program use the after > method instead. In this case it will look like > > root.after(1000, count_down) I just realized my advice is slightly contradictory. If you add parameters to count_down you can't pass it to after() directly. Instead you need to rewrite count_down and use a little trick in after() like this: def count_down(start, stop) sf = "{:01d}:{:02d}".format(*divmod(start, 60)) time_str.set(sf) root.update() if start > stop: root.after(1000, lambda: count_down(start-1,stop) ) Notice it has no loop, instead after() subtracts 1 second from the start value each time it calls count_down. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From cs at zip.com.au Thu Dec 3 20:03:46 2015 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 4 Dec 2015 12:03:46 +1100 Subject: [Tutor] Python 3.5 console logging In-Reply-To: <201512011031.tB1AVbM3032636@fido.openend.se> References: <201512011031.tB1AVbM3032636@fido.openend.se> Message-ID: <20151204010346.GA11157@cskk.homeip.net> On 01Dec2015 11:31, Laura Creighton wrote: >He may be looking for something like the logging facility of Gnu screen. Or the venerable "script" command. But I suspect he wants something else. Cheers, Cameron Simpson The worst tyrannies were the ones where a governance required its own logic on every embedded node. - Vernor Vinge From deepaknedumpilly at gmail.com Sat Dec 5 13:48:46 2015 From: deepaknedumpilly at gmail.com (Deepak Nn) Date: Sun, 6 Dec 2015 00:18:46 +0530 Subject: [Tutor] Please sent me the output of this code .Please include both cases if input correct and if input wrong . Message-ID: # Embedded file name: re4.py import time flag = [102, 108, 97, 103, 123, 112, 121, 116, 104, 111, 110, 95, 114, 111, 99, 107, 115, 125] password = raw_input('Enter secret code to get secret password: ') sleep_hours = 10000 print 'Going to sleep. Will check password after %d hours' % sleep_hours print 'If you want to check password faster, find a way to prevent this sleep' time.sleep(sleep_hours * 60 * 60) if password == 'strongpassword': print 'Correct! The secret password is %s' % ''.join(map(chr, flag)) else: print 'Booo wrong code! No secret password for you' From marc_eymard at hotmail.com Sat Dec 5 08:21:19 2015 From: marc_eymard at hotmail.com (Marc Eymard) Date: Sat, 5 Dec 2015 13:21:19 +0000 Subject: [Tutor] Beginner: Socket object and packets Message-ID: Hi tutor, I am trying to locate the first blank line in the first received packet when pinging an internet server using a socket object. My assumption is there will be a mandatory blank line right after the http headers in accordance with the http protocol. Consider the following: import socket mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mysock.connect( ('www.py4inf.com/code/', 80) ) mysock.send('GET http://www.py4inf.com/code/' + ' HTTP/1.0\n\n') data_str = mysock.recv(700) My question: Why is the following statement False when there is an actual blank line in the received packet: '\n\n' in data The statement 'any_string in data' works fine with any character except the double line drop i.e. '\n\n'. Attached full script for your consideration. Thanks in advance for your guidance, Marc From alan.gauld at btinternet.com Sat Dec 5 17:47:36 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 5 Dec 2015 22:47:36 +0000 Subject: [Tutor] Please sent me the output of this code .Please include both cases if input correct and if input wrong . In-Reply-To: References: Message-ID: On 05/12/15 18:48, Deepak Nn wrote: > # Embedded file name: re4.py If you want to know the output run it. If the output you get is not what you expect tell us what you input, what you got out, what you expec6ed. Also tell us which OS and Python versions you are using. Otherwise all I can tell you is that the output will be some combination of the various print statements depending on what input you provide(assuming there are no code errors). > import time > flag = [102, > 108, > 97, > 103, > 123, > 112, > 121, > 116, > 104, > 111, > 110, > 95, > 114, > 111, > 99, > 107, > 115, > 125] > password = raw_input('Enter secret code to get secret password: ') > sleep_hours = 10000 > print 'Going to sleep. Will check password after %d hours' % sleep_hours > print 'If you want to check password faster, find a way to prevent this > sleep' > time.sleep(sleep_hours * 60 * 60) > if password == 'strongpassword': > print 'Correct! The secret password is %s' % ''.join(map(chr, flag)) > else: > print 'Booo wrong code! No secret password for you' I suspect the question you really want to ask is about how the map() function works? It will apply the chr() function to each number in flags. >>> chr(102),chr(108),chr(97) ('f', 'l', 'a') And so on. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Sat Dec 5 17:56:21 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 5 Dec 2015 22:56:21 +0000 Subject: [Tutor] Beginner: Socket object and packets In-Reply-To: References: Message-ID: On 05/12/15 13:21, Marc Eymard wrote: > Hi tutor, > > I am trying to locate the first blank line in the first received packet > when pinging an internet server using a socket object. You need to be careful with your descriptions. ping is a very specific message and uses ICMP echo rather than TCP/IP and looks nothing like http. In another context it would be OK but when dealing with sockets you need to be precise about what you are actually sending. > My assumption is there will be a mandatory blank line right after the > http headers in accordance with the http protocol. > > Consider the following: > > import socket > mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > mysock.connect( ('www.py4inf.com/code/', 80) ) > mysock.send('GET http://www.py4inf.com/code/' + ' HTTP/1.0\n\n') > data_str = mysock.recv(700) Is there any reason why you are using raw sockets rather than the httplib module which does most of this stuff for you (and probably has useful code you code study if you do want to do it this way)? > My question: > > Why is the following statement False when there is an actual blank line > in the received packet: > '\n\n' in data It looks like you are using Python v3. Remember that most system level IO in v3 uses bytes not strings. You probably need to convert the bytes to a string before looking for blank lines. But that's just a guess. Also did you try using find() or index() rather than in? HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From cs at zip.com.au Sat Dec 5 20:47:15 2015 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 6 Dec 2015 12:47:15 +1100 Subject: [Tutor] Beginner: Socket object and packets In-Reply-To: References: Message-ID: <20151206014715.GA9609@cskk.homeip.net> On 05Dec2015 13:21, Marc Eymard wrote: >Hi tutor, >I am trying to locate the first blank line in the first received packet when >pinging an internet server using a socket object. First up: everything ALan already said. Next: Note that the HTTP response need not all be in a single packet, though that is not your problem. >My assumption is there will be a mandatory blank line right after the >http headers in accordance with the http protocol. There certainly should be. >Consider the following: >import socket >mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >mysock.connect( ('www.py4inf.com/code/', 80) ) >mysock.send('GET http://www.py4inf.com/code/' + ' HTTP/1.0\n\n') >data_str = mysock.recv(700) > >My question: > >Why is the following statement False when there is an actual blank >line in the received packet: > '\n\n' in data 1: You will be getting bytes backup from the server (obviously so in Python 3 and implicitly in Python 2). 2: The HTTP protocol, like most internet text protocols, ends lines with the bytes '\r\n', not just '\n'. Therefore you should expect the bytes '\r\n\r\n' in the response data. However, you should have discovered this already by doing some debugging. Since you're clearly not getting the response you expected, the very first step on your part should be to print our the received data, for example by adding: print(repr(data_str)) after your recv() call. Then you could inspect the received data and probably have seen the '\r' characters. Cheers, Cameron Simpson From huyuehua1106 at sina.com Mon Dec 7 08:12:04 2015 From: huyuehua1106 at sina.com (Yuehua HU) Date: Mon, 7 Dec 2015 21:12:04 +0800 Subject: [Tutor] Tkinter_Entry_tip words Message-ID: <61F8D0F9-17E0-49E3-8243-22979AB12A9D@sina.com> Hi, I want to realise the function below use python, but can?t find the right way. Function description: User input strings in Entry(Tkinter) widget, there are tip words displayed in this Entry widget, when the Entry widget is selected, the tip words are faded, when user begin to entering words into this Entry, the tip words are disappeared. Does anybody know the method to implement it with Entry and Label widget? Or any other method in python? Thank you. Best Regards, Yuehua From alan.gauld at btinternet.com Mon Dec 7 09:23:04 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 7 Dec 2015 14:23:04 +0000 Subject: [Tutor] Tkinter_Entry_tip words In-Reply-To: <61F8D0F9-17E0-49E3-8243-22979AB12A9D@sina.com> References: <61F8D0F9-17E0-49E3-8243-22979AB12A9D@sina.com> Message-ID: On 07/12/15 13:12, Yuehua HU wrote: > Function description: > User input strings in Entry(Tkinter) widget, there are tip words displayed in this Entry widget, > when the Entry widget is selected, the tip words are faded, > when user begin to entering words into this Entry, the tip words are disappeared. > > Does anybody know the method to implement it with Entry and Label widget? Or any other method in python? I'm hoping this is not a homework... Try something like this for Python 2: ###################### import Tkinter as tk top = tk.Tk() e = tk.Entry(top) e.pack() def greyText(ev): e.config(foreground='grey') def startEntry(ev): e.delete(0,tk.END) e.config(foreground='black') e.unbind('') e.insert(tk.END,"Help text") e.bind('', greyText) e.bind('', startEntry) top.mainloop() ########################## You'll need some tweaks to cater for the user changing their mind and just blanking the field. In that case you probably need to reinstate the hint and the key binding. I leave that as an exercise... By coincidence I was doing something very similar to this yesterday! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From wiseilesha at gmail.com Tue Dec 8 02:39:41 2015 From: wiseilesha at gmail.com (Ilesha Wise) Date: Tue, 8 Dec 2015 02:39:41 -0500 Subject: [Tutor] Image MAnipulation Help Message-ID: Hello, I wasnt sure if this is the email address I should be sending this to. I really need help creating codes that will do the following: ? Scanned photos and slides often have dust specs, water marks, scratches etc. Automate their removal as much as possible and/or provide a simple way for the viewer to direct the program as to where to make corrections. ? Images often have a high contrast (bright sky, dark horizon). Help the image by making the sky more blue (with any detectable clouds, birds, etc. remaining) and improve the contrast of the other portion of the image. Additional grading basis: ? The user interface for solving these issues. ? A decent (note, not perfect) improvement in the images. ? Your management of color, averaging, etc. Thank you. From alan.gauld at btinternet.com Tue Dec 8 05:40:07 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Dec 2015 10:40:07 +0000 Subject: [Tutor] Image MAnipulation Help In-Reply-To: References: Message-ID: On 08/12/15 07:39, Ilesha Wise wrote: > Hello, I wasnt sure if this is the email address I should be sending this > to. Its a fair starting point but you will probably get more detailed answers on the PIL/PILLOW forums since those are the packages you will likely be using for this kind of work. (Pillow is for v2/v3, The original PIL for v2 only.) There are some image manipulation packages in the SciPy/Kit bundles too. And of course the venerable ImageMagick modules may help too. Finally the psd-tools package will be useful if you are using Photoshop files. > ? Scanned photos and slides often have dust specs, water marks, scratches > etc. Automate their removal as much as possible and/or provide a simple way > for the viewer to direct the program as to where to make corrections. > ? Images often have a high contrast (bright sky, dark horizon). Help the > image by making the sky more blue (with any detectable clouds, birds, etc. > remaining) and improve the contrast of the other portion of the image. I assume you already have a graphics background and know the theory behind doing all this? ie You are not just a raw beginner? If so then the libraries mentioned above should get you started. > Additional grading basis: > > ? The user interface for solving these issues. Pick a UI framework (there are many) and build it. > ? A decent (note, not perfect) improvement in the images. > ? Your management of color, averaging, etc. You are pretty much on your own for these I suspect ("decent improvement" is of course entirely subjective) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From lac at openend.se Tue Dec 8 06:24:09 2015 From: lac at openend.se (Laura Creighton) Date: Tue, 08 Dec 2015 12:24:09 +0100 Subject: [Tutor] Image MAnipulation Help In-Reply-To: References: Message-ID: <201512081124.tB8BO9nc019665@fido.openend.se> In a message of Tue, 08 Dec 2015 02:39:41 -0500, Ilesha Wise writes: >Hello, I wasnt sure if this is the email address I should be sending this >to. > >I really need help creating codes that will do the following: > >? Scanned photos and slides often have dust specs, water marks, scratches >etc. Automate their removal as much as possible and/or provide a simple way >for the viewer to direct the program as to where to make corrections. > ? Images often have a high contrast (bright sky, dark horizon). Help the >image by making the sky more blue (with any detectable clouds, birds, etc. >remaining) and improve the contrast of the other portion of the image. > >Additional grading basis: > >? The user interface for solving these issues. > ? A decent (note, not perfect) improvement in the images. >? Your management of color, averaging, etc. > > >Thank you. >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >https://mail.python.org/mailman/listinfo/tutor You can do this with the GIMP. http://howto.nicubunu.ro/gimp-remove-watermark/ (actually searching for "GIMP remove watermark" gets you lots of hits.) It is possible to script the GIMP using python, so you could automate some of this. Warning, scripting the GIMP is not a pleasant task, and the python code they use is decidedly weird in places. But it can be done. Laura From alan.gauld at btinternet.com Tue Dec 8 07:54:21 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Dec 2015 12:54:21 +0000 Subject: [Tutor] Image MAnipulation Help In-Reply-To: <201512081124.tB8BO9nc019665@fido.openend.se> References: <201512081124.tB8BO9nc019665@fido.openend.se> Message-ID: On 08/12/15 11:24, Laura Creighton wrote: > You can do this with the GIMP. > http://howto.nicubunu.ro/gimp-remove-watermark/ > (actually searching for "GIMP remove watermark" gets you lots of > hits.) But removing watermarks could get you in lots of legal trouble. The whole point of watermarks is normally to stop you using a commercial image that you should be paying for. Make sure you are not breaking copyright before you start. However, you do say 'water marks' (with a space), which is a different thing entirely and the GIMP could be used for that. > It is possible to script the GIMP using python, so you could > automate some of this. Warning, scripting the GIMP is not a pleasant An understatement IMHO! But that's more to do with scripting GIMP in general than with the Python scripting implementation. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From huyuehua1106 at sina.com Tue Dec 8 10:08:44 2015 From: huyuehua1106 at sina.com (Yuehua HU) Date: Tue, 8 Dec 2015 23:08:44 +0800 Subject: [Tutor] Tkinter_Entry_tip words In-Reply-To: References: <61F8D0F9-17E0-49E3-8243-22979AB12A9D@sina.com> Message-ID: <6B9F776A-4DA3-43D5-B313-1A8A077FBB90@sina.com> Hi Alan, Thank you for your answer, it is really helpful. and it is not a homework :) I?ve tried to write 'user changing their mind and blanking the field? case, but it seems not working? Did I use '? wrong? and another question: Why should we use a parameter in the function 'greyText(e)? ? Here the parameter is ?e?. ####################### import Tkinter def checkEnterStrLen(e): if len(var.get())==0: entry.config(fg= 'grey') entry.insert(0, 'help text') def greyText(e): entry.config(fg = 'grey') def startEntry(e): entry.delete(0,Tkinter.END) entry.config(fg = 'black') entry.unbind('') top = Tkinter.Tk() var = Tkinter.StringVar() entry = Tkinter.Entry(top, textvariable = var) entry.insert(0,'help text') entry.bind('', greyText) entry.bind('',checkEnterStrLen) entry.bind('',startEntry) entry.pack() top.mainloop() ####################### Thank you. B.R. Yuehua > On Dec 7, 2015, at 22:23, Alan Gauld wrote: > > > On 07/12/15 13:12, Yuehua HU wrote: > >> Function description: >> User input strings in Entry(Tkinter) widget, there are tip words displayed in this Entry widget, >> when the Entry widget is selected, the tip words are faded, >> when user begin to entering words into this Entry, the tip words are disappeared. >> >> Does anybody know the method to implement it with Entry and Label widget? Or any other method in python? > > I'm hoping this is not a homework... > > Try something like this for Python 2: > > ###################### > import Tkinter as tk > > top = tk.Tk() > e = tk.Entry(top) > e.pack() > > def greyText(ev): > e.config(foreground='grey') > > def startEntry(ev): > e.delete(0,tk.END) > e.config(foreground='black') > e.unbind('') > > e.insert(tk.END,"Help text") > > e.bind('', greyText) > e.bind('', startEntry) > > top.mainloop() > ########################## > > You'll need some tweaks to cater for the user changing > their mind and just blanking the field. In that case you > probably need to reinstate the hint and the key binding. > I leave that as an exercise... > > By coincidence I was doing something very similar > to this yesterday! :-) > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at btinternet.com Tue Dec 8 14:54:32 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Dec 2015 19:54:32 +0000 Subject: [Tutor] Tkinter_Entry_tip words In-Reply-To: <6B9F776A-4DA3-43D5-B313-1A8A077FBB90@sina.com> References: <61F8D0F9-17E0-49E3-8243-22979AB12A9D@sina.com> <6B9F776A-4DA3-43D5-B313-1A8A077FBB90@sina.com> Message-ID: On 08/12/15 15:08, Yuehua HU wrote: > I?ve tried to write 'user changing their mind and blanking the field? case, but it seems not working? > Did I use '? wrong? Delete is the key that deletes the character to the right of cursor. Did you maybe mean to use <'Keypress-BackSpace'>? Or even both of them? > ...Why should we use a parameter in the function 'greyText(e)? ? Because the bind mechanism passes the event object as an argument and expects the function to accept it even if its not used. [Aside: This is annoying since the command attribute of widgets expects a function with no arguments! To get round that set a default value of None: def aCallBack(event=None):... then you can use aCallBack() in either scenario. ] HTH > ####################### > import Tkinter > > def checkEnterStrLen(e): > if len(var.get())==0: > entry.config(fg= 'grey') > entry.insert(0, 'help text') > > def greyText(e): > entry.config(fg = 'grey') > > def startEntry(e): > entry.delete(0,Tkinter.END) > entry.config(fg = 'black') > entry.unbind('') > > top = Tkinter.Tk() > > var = Tkinter.StringVar() > entry = Tkinter.Entry(top, textvariable = var) > entry.insert(0,'help text') > > entry.bind('', greyText) > entry.bind('',checkEnterStrLen) > entry.bind('',startEntry) > > entry.pack() > > top.mainloop() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From crusier at gmail.com Tue Dec 8 21:01:59 2015 From: crusier at gmail.com (Crusier) Date: Wed, 9 Dec 2015 10:01:59 +0800 Subject: [Tutor] Beautifulsoup Queries Message-ID: Dear All, I am using Python 3.4, I tried to scrap the web and eventually put those data into a database for analysis. While I am using Beautifulsoup to scrap the web, I encountered 2 problems: 1. Using Beautiful Soup, the webmaster on the other end is using the same class, so I got a whole list of information (High, Low Previous Close, Shares Traded, Turnover.....etc) and I really want to divide that up into separate categories. 2. If I input " print(data.string) " for line 27, I will get an error ('ResultSet' object has no attribute 'string'). However, if I input " print(data) ", they print out in span class..... etc... from bs4 import BeautifulSoup import requests import os tryout = ['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010', '0011', '0012', '0014', '0015', '0016', '0017', '0018', '0019', '0020'] url = "https://www.etnet.com.hk/www/eng/stocks/realtime/quote.php?code=" def web_scraper(url): for n in tryout: URL = url + n response = requests.get(URL) html = response.content soup = BeautifulSoup(html,"html.parser") # print (soup.prettify()) Title = soup.find("div", attrs = {"id": "StkQuoteHeader"}) RT_down = soup.find("span", attrs = {"class": "Price down2"}) RT_up = soup.find("span", attrs = {"class": "Price up2"}) RT_unchange = soup.find("span",attrs = {"class" :"Price unchange2"}) change_percent = soup.find("span", attrs = {"class" :"Change"}) Day_High = soup.findAll("span", attrs = {"class" :"Number"}) for data in [Title, RT_down, RT_up, RT_unchange, change_percent, Day_High]: if data: print(data) web_scraper(url) From huyuehua1106 at sina.com Wed Dec 9 06:03:54 2015 From: huyuehua1106 at sina.com (Yuehua HU) Date: Wed, 9 Dec 2015 19:03:54 +0800 Subject: [Tutor] Tkinter_Entry_tip words In-Reply-To: References: <61F8D0F9-17E0-49E3-8243-22979AB12A9D@sina.com> <6B9F776A-4DA3-43D5-B313-1A8A077FBB90@sina.com> Message-ID: Hi Alan, it works using ?BackSpace? and ?Delete?! There is no ?BackSpace? key on Mac, so I didn?t come up with this key before, thanks for your advise and answer :) B.R. Yuehua > On Dec 9, 2015, at 03:54, Alan Gauld wrote: > > On 08/12/15 15:08, Yuehua HU wrote: > >> I?ve tried to write 'user changing their mind and blanking the field? case, but it seems not working? >> Did I use '? wrong? > > Delete is the key that deletes the character to the right of cursor. > Did you maybe mean to use <'Keypress-BackSpace'>? Or even both of them? > >> ...Why should we use a parameter in the function 'greyText(e)? ? > > Because the bind mechanism passes the event object as an argument > and expects the function to accept it even if its not used. > [Aside: This is annoying since the command attribute of widgets expects > a function with no arguments! To get round that set a default value of None: > > def aCallBack(event=None):... > > then you can use aCallBack() in either scenario. > ] > > HTH > >> ####################### >> import Tkinter >> >> def checkEnterStrLen(e): >> if len(var.get())==0: >> entry.config(fg= 'grey') >> entry.insert(0, 'help text') >> >> def greyText(e): >> entry.config(fg = 'grey') >> >> def startEntry(e): >> entry.delete(0,Tkinter.END) >> entry.config(fg = 'black') >> entry.unbind('') >> >> top = Tkinter.Tk() >> >> var = Tkinter.StringVar() >> entry = Tkinter.Entry(top, textvariable = var) >> entry.insert(0,'help text') >> >> entry.bind('', greyText) >> entry.bind('',checkEnterStrLen) >> entry.bind('',startEntry) >> >> entry.pack() >> >> top.mainloop() > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From s.charonis at gmail.com Thu Dec 10 07:38:46 2015 From: s.charonis at gmail.com (Spyros Charonis) Date: Thu, 10 Dec 2015 12:38:46 +0000 Subject: [Tutor] Understanding a linear runtime implementation of anagram detection Message-ID: Dear All, I am learning about analysis of algorithms (python 2.7.6). I am reading a book (Problem solving with Algorithms and Data Structures) where Python is the language used for implementations. The author introduces algorithm analysis in a clear and understandable way, and uses an anagram detection program as a template to compare different runtime implementations (quadratic, log linear, linear). In the linear, and most efficient implementation, the code is as follows (comments added by me): def anagram_test2(s1,s2):""" Checks if two strings are anagrams of each other Runs with O(n) linear complexity """ if (not s1) or (not s2): raise TypeError, "Invalid input: input must be string" return None # Initialize two lists of counters c1 = [0] * 26 c2 = [0] * 26 # Iterate over each string# When a char is encountered, # increment the counter at # its correspoding position for i in range(len(s1)): pos = ord(s1[i]) - ord("a") c1[pos] += 1 for i in range(len(s2)): pos = ord(s2[i]) - ord("a") c2[pos] += 1 j = 0 hit = Truewhile j < 26 and hit: if c1[j] == c2[j]: j += 1 else: hit = False return hit My questions are: 1) Is it computationally more/less/equally efficient to use an explicit while loop as it is to just do "return c1 === c2" (replacing the final code block following the two for loops). I realize that this single line of code performs an implicit for loop over each index to test for equality. My guess is that because in other languages you may not be able to do this simple test, the author wanted to present an example that could be adapted for other languages, unless the explicit while loop is less expensive computationally. 2) How could I go about adapting this algorithm for multiple strings (say I had 20 strings and wanted to check if they are anagrams of one another). def are_anagrams(*args): """ Accepts a tuple of strings and checks if they are anagrams of each other """ # Check that neither of strings are null for i in args: if not i: raise TypeError, "Invalid input" return None # Initialize a list of counters for each string c = ( [] for i in range(len(args) ) ??? Many thanks in advance! From __peter__ at web.de Thu Dec 10 08:45:13 2015 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Dec 2015 14:45:13 +0100 Subject: [Tutor] Understanding a linear runtime implementation of anagram detection References: Message-ID: Spyros Charonis wrote: > Dear All, > > I am learning about analysis of algorithms (python 2.7.6). I am reading a > book (Problem solving with Algorithms and Data Structures) where Python is > the language used for implementations. The author introduces algorithm > analysis in a clear and understandable way, and uses an anagram detection > program as a template to compare different runtime implementations > (quadratic, log linear, linear). In the linear, and most efficient > implementation, the code is as follows (comments added by me): > > def anagram_test2(s1,s2):""" Checks if two strings are anagrams of each > other > Runs with O(n) linear complexity """ > if (not s1) or (not s2): > raise TypeError, "Invalid input: input must be string" > return None > # Initialize two lists of counters > c1 = [0] * 26 > c2 = [0] * 26 > # Iterate over each string# When a char is encountered, # increment > the counter at # its correspoding position for i in range(len(s1)): > pos = ord(s1[i]) - ord("a") > c1[pos] += 1 > for i in range(len(s2)): > pos = ord(s2[i]) - ord("a") > c2[pos] += 1 > > j = 0 > hit = Truewhile j < 26 and hit: > if c1[j] == c2[j]: > j += 1 > else: > hit = False > return hit The code above will make any Python programmer who is past the absolute beginner level cry. Here's a somewhat cleaned-up version: OFFSET = ord("a") def anagram_test3(s1, s2): if len(s1) != len(s2): return False freq1 = [0] * 26 for c in s1: freq1[ord(c) - OFFSET] += 1 freq2 = [0] * 26 for c in s2: freq2[ord(c) - OFFSET] += 1 return freq1 == freq2 When you look a the code you see that almost that the same code appears twice. Let's move it into a separate function: OFFSET = ord("a") def freq(s): freq_table = [0] * 26 for c in s: freq_table[ord(c) - OFFSET] += 1 return freq_table def anagram_test3(s, t): if len(s) != len(t): return False return freq(s) == freq(t) > My questions are: > > 1) > Is it computationally more/less/equally efficient to use an explicit while > loop as it is to just do "return c1 === c2" (replacing the final code > block following the two for loops). I realize that this single line of > code performs an implicit for loop over each index to test for equality. > My guess is that because in other languages you may not be able to do this > simple test, the author wanted to present an example that could be adapted > for other languages, unless the explicit while loop is less expensive > computationally. Yes, while the simple c1 == c2 has the same complexity it should be significantly faster than the loop. The equality check is also easy to read and understand. > 2) > How could I go about adapting this algorithm for multiple strings (say I > had 20 strings and wanted to check if they are anagrams of one another). With the above freq() function you can calculate the frequency table for the first string and then loop over the rest and stop when you encounter one that produces a different frequency table. Somewhat more involved: You might calculate frequency tables for every string and then collect them in a dict. For that to work you have to convert the lists into something hashable -- a tuple will be the obvious choice. The final table will look like this { (1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0): ['jeans'], (1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0): ['stingray', 'straying'], (1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0): ['parleys', 'parsley', 'players', 'replays', 'sparely']} and to find the anagrams you have to pick the lists containing more than one word. From jcgallaher78 at gmail.com Sat Dec 12 02:03:05 2015 From: jcgallaher78 at gmail.com (Jim Gallaher) Date: Sat, 12 Dec 2015 01:03:05 -0600 Subject: [Tutor] Calculation error with a simple program Message-ID: <566BC6A9.6090206@gmail.com> Hi everyone. I'm reading through a beginners Python book and came up with a super simple program. I'm not getting any errors and everything runs through, but there's a logical calculation error. What the program does is take an amount and calculate a couple percentages and add a couple fees. For example, if I put in a value of 1, it will output 752.12 as the sub total and 753.12 as the grand total. It's off by 1 on sub total and 2 on grand total. Thanks in advance! Jim Gallaher # Car Salesman Calculator # User enters the base price of the car and the program adds tax, license, dealer prep, and destination charge. print("Car Sales Calculator") basePrice = int(input("Please enter in the price of the car: ")) # Misc charges to be added to the total cost of the car tax = basePrice * .07 license = basePrice * .05 dealerPrep = basePrice + 500 destinationCharge = basePrice + 250 # Add the total misc charges together subTotal = float(tax + license + dealerPrep + destinationCharge) # Add all the misic charges and include the base price grandTotal = float(subTotal + basePrice) # Display the results print("\nThe sub total is", subTotal) print("\nYour grand Total is", grandTotal) input("\nPress the enter key to close the program.") From alan.gauld at btinternet.com Sat Dec 12 03:04:52 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Dec 2015 08:04:52 +0000 Subject: [Tutor] Calculation error with a simple program In-Reply-To: <566BC6A9.6090206@gmail.com> References: <566BC6A9.6090206@gmail.com> Message-ID: On 12/12/15 07:03, Jim Gallaher wrote: > For example, if I put in a value of 1, it will output 752.12 as the sub > total and 753.12 as the grand total. It's off by 1 on sub total and 2 on > grand total. Are you sure? Lets check the values... > basePrice = int(input("Please enter in the price of the car: ")) => 1 > tax = basePrice * .07 => 0.07 > license = basePrice * .05 => 0.05 > dealerPrep = basePrice + 500 => 501 > destinationCharge = basePrice + 250 => 251 > # Add the total misc charges together > subTotal = float(tax + license + dealerPrep + destinationCharge) => 0.07 + 0.05 + 501 + 251 => 752.12 > # Add all the misic charges and include the base price > grandTotal = float(subTotal + basePrice) => 752.12 + 1 => 753.12 Looks like Python got it right to me? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From lac at openend.se Sat Dec 12 10:07:10 2015 From: lac at openend.se (Laura Creighton) Date: Sat, 12 Dec 2015 16:07:10 +0100 Subject: [Tutor] Calculation error with a simple program In-Reply-To: <566BC6A9.6090206@gmail.com> References: <566BC6A9.6090206@gmail.com> Message-ID: <201512121507.tBCF7AIh011747@fido.openend.se> I haven't verified this, but you are probably up against some problem caused by using floating point to store money. The problem is that, when people see something like the floating point number, 3.15 they think, aha, this is a decimal number just like I learned in school when I was 10 years old. This is 3 plus one-tenth, plus 5 one hundreths. exactly. I know everything about this sort of thing, I learned it when I was 10. In particular, you probably learned this properly of numbers in general. (a + b) + c = a + (b + c) (associative properly of addition) And while you probably had not thought about this property, you definitely exepected it to work with your 3.15 when you want to add it to 2.17 And, herein lies the rub. floating point numbers, despite looking exactly the same as what you learned in school (A terrible design decision, I think that if we wrote them 3_15 or 3#15 we would have many fewer problems now, but it got made before I was born, so .... ) ARE NOT the things you learned in school. Not all decimal numbers are exactly representable in floating point. As a result the law of association fails. The correct result can indeed depend on the order in which you do your operations. You can read more about this here: https://docs.python.org/3.5/faq/design.html#why-are-floating-point-calculations-so-inaccurate and in the tutorial: https://docs.python.org/3.5/tutorial/floatingpoint.html#tut-fp-issues This is also good. http://floating-point-gui.de/ And if you want a more serious, mathematical approach, this ACM reprint is _really good_, but not to everybody's taste. https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html Most of the time, this does not matter, because most of the people using floating point are scientists. Scientists, contrary to popular belief, are not all that concerned with exact accuracy. Their results always come with an error estimate. 'the distance is such and such +/- 10%' or +/- 0.005% or what have you. So, as long as you do your calculations in such a way that the floating point error is covered in the % of uncertainty that you have anyway, your answer is perfectly correct enough for science. And floating calculations are much, much faster than fixed point decimal calculations, which in the old days meant the difference between getting a result for your calculations in a week or in more than a month. No wonder the scientists were happy to trade accuracy which they couldn't use for speed, which they had immediate need for. But once you get to calculations with money, you are suddenly out of the realm of science. (Even if some economists might want to tell you different. :) ) Money is exact. Nobody is willing to accept 10 pounds +/- 10% for a pizza, and allow people to pay anything between 9 pounds and 11 pounds as an ok price. In python we have a fix for this, called the Decimal object. Decimals behave the way you want them to -- i.e. the principle of associaton holds. https://docs.python.org/3.5/library/decimal.html So, if you are just noodling around, playing with things, using floats to store money is ok. It teaches bad habits, but that battle was fought and lost a long time ago. However, if you want to do something serious, like keep track of your own financial affairs with python, ***Don't Use Float For Money***. Please save yourself grief and use the Decimal type instead. Laura From steve at pearwood.info Sat Dec 12 12:00:25 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 13 Dec 2015 04:00:25 +1100 Subject: [Tutor] Calculation error with a simple program In-Reply-To: <566BC6A9.6090206@gmail.com> References: <566BC6A9.6090206@gmail.com> Message-ID: <20151212170025.GK3821@ando.pearwood.info> On Sat, Dec 12, 2015 at 01:03:05AM -0600, Jim Gallaher wrote: > Hi everyone. I'm reading through a beginners Python book and came up > with a super simple program. I'm not getting any errors and everything > runs through, but there's a logical calculation error. What the program > does is take an amount and calculate a couple percentages and add a > couple fees. > > For example, if I put in a value of 1, it will output 752.12 as the sub > total and 753.12 as the grand total. It's off by 1 on sub total and 2 on > grand total. Check your arithmetic -- with a base price of $1, the sub total is $752.12 and the grand total is $753.12, exactly as Python calculates. But I wonder whether you have made a logic mistake in your code. You say: dealerPrep = basePrice + 500 destinationCharge = basePrice + 250 This means that the car will cost more than TRIPLE the base price. Instead of $1, enter a base price of $40,000 and you will see what I mean: now the dealer prep is $40500 and the destination charge is $40250, which added to the base price gives $120750 (plus tax and licence). Surely that's not right, the deal charges more than the cost of the car for preparation? I think what you want is: dealerPrep = 500 destinationCharge = 250 -- Steve From jcgallaher78 at gmail.com Sat Dec 12 12:34:27 2015 From: jcgallaher78 at gmail.com (Jim Gallaher) Date: Sat, 12 Dec 2015 11:34:27 -0600 Subject: [Tutor] Calculation error with a simple program Message-ID: <8774A398-4A0F-41DF-BBD2-941B49A3CC90@gmail.com> Hi Alan, I'm 100 percent sure I'm wrong. :-) I verified it when I fixed the mistake. The problem was it was adding in the basePrice and the fixed rates/percentages each time. So I figured it out when Ian said something about that. Thanks for everyone's help! :-) From todd_purple at yahoo.com Sat Dec 12 08:13:23 2015 From: todd_purple at yahoo.com (Todd Purple) Date: Sat, 12 Dec 2015 08:13:23 -0500 Subject: [Tutor] Calculation error with a simple program In-Reply-To: <566BC6A9.6090206@gmail.com> References: <566BC6A9.6090206@gmail.com> Message-ID: <6EC6D759-3C19-4A6D-8DD7-6EFAE1958CCD@yahoo.com> > On Dec 12, 2015, at 2:03 AM, Jim Gallaher wrote: > > Hi everyone. I'm reading through a beginners Python book and came up with a super simple program. I'm not getting any errors and everything runs through, but there's a logical calculation error. What the program does is take an amount and calculate a couple percentages and add a couple fees. > > For example, if I put in a value of 1, it will output 752.12 as the sub total and 753.12 as the grand total. It's off by 1 on sub total and 2 on grand total. > > Thanks in advance! Jim Gallaher > > # Car Salesman Calculator > > # User enters the base price of the car and the program adds tax, license, dealer prep, and destination charge. > > print("Car Sales Calculator") > basePrice = int(input("Please enter in the price of the car: ")) > > # Misc charges to be added to the total cost of the car > tax = basePrice * .07 > license = basePrice * .05 > dealerPrep = basePrice + 500 > destinationCharge = basePrice + 250 > I think your main problem is right here. Why do dealerPrep and destinationCharge include the basePrice in their equation? This will add the basePrice in multiple times. I would simply set it like this: dealerPrep = 500 destinationCharge = 250 If these charges ever change, you can put in some sort of equation. However, it looks like these are meant to be a flat fee. > # Add the total misc charges together > subTotal = float(tax + license + dealerPrep + destinationCharge) > > # Add all the misic charges and include the base pricem > grandTotal = float(subTotal + basePrice) > > # Display the results > print("\nThe sub total is", subTotal) > print("\nYour grand Total is", grandTotal) > > input("\nPress the enter key to close the program.") > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From kfh777 at earthlink.net Sat Dec 12 12:23:32 2015 From: kfh777 at earthlink.net (Ken Hammer) Date: Sat, 12 Dec 2015 12:23:32 -0500 Subject: [Tutor] Tutor Digest, Vol 142, Issue 10 In-Reply-To: Message-ID: I have a more simple-minded solution. The error appears to occur in testing without revealing the problem by use of $1 base price in the test. Using $10,000 as the base price in the test reveals absurd numbers. I think the real problem lies in the inclusion of base price inappropriately, twice as in: >dealerPrep = basePrice + 500 >destinationCharge = basePrice + 250 "basePrice" has no place in those two lines. 500 and 250 alone express the definition of the challenge. Ken In , on 12/12/15 at 12:00 PM, tutor-request at python.org said: >Send Tutor mailing list submissions to > tutor at python.org >To subscribe or unsubscribe via the World Wide Web, visit > https://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. Calculation error with a simple program (Jim Gallaher) > 2. Re: Calculation error with a simple program (Alan Gauld) > 3. Re: Calculation error with a simple program (Laura Creighton) >---------------------------------------------------------------------- >Message: 1 >Date: Sat, 12 Dec 2015 01:03:05 -0600 >From: Jim Gallaher >To: tutor at python.org >Subject: [Tutor] Calculation error with a simple program >Message-ID: <566BC6A9.6090206 at gmail.com> >Content-Type: text/plain; charset=utf-8; format=flowed >Hi everyone. I'm reading through a beginners Python book and came up with >a super simple program. I'm not getting any errors and everything runs >through, but there's a logical calculation error. What the program does is >take an amount and calculate a couple percentages and add a couple fees. >For example, if I put in a value of 1, it will output 752.12 as the sub >total and 753.12 as the grand total. It's off by 1 on sub total and 2 on >grand total. >Thanks in advance! Jim Gallaher ># Car Salesman Calculator ># User enters the base price of the car and the program adds tax, license, >dealer prep, and destination charge. >print("Car Sales Calculator") >basePrice = int(input("Please enter in the price of the car: ")) ># Misc charges to be added to the total cost of the car >tax = basePrice * .07 >license = basePrice * .05 >dealerPrep = basePrice + 500 >destinationCharge = basePrice + 250 ># Add the total misc charges together >subTotal = float(tax + license + dealerPrep + destinationCharge) ># Add all the misic charges and include the base price >grandTotal = float(subTotal + basePrice) ># Display the results >print("\nThe sub total is", subTotal) >print("\nYour grand Total is", grandTotal) >input("\nPress the enter key to close the program.") >------------------------------ >Message: 2 >Date: Sat, 12 Dec 2015 08:04:52 +0000 >From: Alan Gauld >To: tutor at python.org >Subject: Re: [Tutor] Calculation error with a simple program >Message-ID: >Content-Type: text/plain; charset=utf-8 >On 12/12/15 07:03, Jim Gallaher wrote: >> For example, if I put in a value of 1, it will output 752.12 as the sub >> total and 753.12 as the grand total. It's off by 1 on sub total and 2 on >> grand total. >Are you sure? Lets check the values... >> basePrice = int(input("Please enter in the price of the car: ")) >=> 1 >> tax = basePrice * .07 >=> 0.07 >> license = basePrice * .05 >=> 0.05 >> dealerPrep = basePrice + 500 >=> 501 >> destinationCharge = basePrice + 250 >=> 251 >> # Add the total misc charges together >> subTotal = float(tax + license + dealerPrep + destinationCharge) >=> 0.07 + 0.05 + 501 + 251 => 752.12 >> # Add all the misic charges and include the base price >> grandTotal = float(subTotal + basePrice) >=> 752.12 + 1 => 753.12 >Looks like Python got it right to me? -- ----------------------------------------------------------- K.F.Hammer Associates Ken Hammer management consultations Saint Johnsbury, VT 05819 ----------------------------------------------------------- From crusier at gmail.com Sun Dec 13 02:44:33 2015 From: crusier at gmail.com (Crusier) Date: Sun, 13 Dec 2015 15:44:33 +0800 Subject: [Tutor] Beautiful Soup Message-ID: Dear All, I am trying to scrap the following website, however, I have encountered some problems. As you can see, I am not really familiar with regex and I hope you can give me some pointers to how to solve this problem. I hope I can download all the transaction data into the database. However, I need to retrieve it first. The data which I hope to retrieve it is as follows: " 15:59:59 A 500 6.790 3,395 15:59:53 B 500 6.780 3,390................ Thank you Below is my quote: from bs4 import BeautifulSoup import requests import re url = 'https://bochk.etnet.com.hk/content/bochkweb/eng/quote_transaction_daily_history.php?code=6881&time=F&timeFrom=090000&timeTo=160000&turnover=S&sessionId=44c99b61679e019666f0570db51ad932&volMin=0&turnoverMin=0' def turnover_detail(url): response = requests.get(url) html = response.content soup = BeautifulSoup(html,"html.parser") data = soup.find_all("script") for json in data: print(json) turnover_detail(url) Best Regards, Henry From alan.gauld at btinternet.com Sun Dec 13 04:10:57 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 13 Dec 2015 09:10:57 +0000 Subject: [Tutor] Beautiful Soup In-Reply-To: References: Message-ID: On 13/12/15 07:44, Crusier wrote: > Dear All, > > I am trying to scrap the following website, however, I have > encountered some problems. As you can see, I am not really familiar > with regex and I hope you can give me some pointers to how to solve > this problem. I'm not sure why you mention regex because your script doesn't use regex. And for html that's a good thing. > I hope I can download all the transaction data into the database. > However, I need to retrieve it first. The data which I hope to > retrieve it is as follows: > > " > 15:59:59 A 500 6.790 3,395 > 15:59:53 B 500 6.780 3,390................ > Part of your problem is that the data is not in html format but is in fact part of the Javascript code on the page. And BeautifulSoup is not so good at parsing Javascript. The page code looks like > > > >