Re: [Tutor] Where is win32print in Windows 10 Pro
On 08/12/2016 11:56 PM, eryk sun wrote: On Thu, Aug 11, 2016 at 2:44 PM, Joaquin Alzolawrote: import win32print ImportError: No module named win32print That module doesn't exist on your python path 'pywin32' is its canonical name. http://sourceforge.net/projects/pywin32/ I'm not certain what's meant in the above, but to be clear, PyWin32 installs most of its modules as top-level imports. So `import win32print` is correct. PyWin32 can be pip installed using the "pypiwin32" package: https://pypi.python.org/pypi/pypiwin32 The difference compared to the executable installer is that the wheel package doesn't automatically run the post-install script that copies some DLLs to the System32 directory. Running the post-install script isn't necessary if you just need to call Windows and COM APIs. Thanks for clarifying this more. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Where is win32print in Windows 10 Pro [RESOLVED]
On 08/11/2016 01:19 PM, Alan Gauld via Tutor wrote: On 11/08/16 17:14, Ken G. wrote: Unfortunately, no printing is done yet. Still working on it. Your reference to duckduckgo.com provided a list of useful pywin32 attibutes but no examples was provided. Will keep looking. Thanks. PyWin32 is a very thin layer on top of the Win32/COM API. You probably need to be familiar with printing in Win32 to use PyWin to print, and that's not trivial. If you are already familiar with printing from C/C++ it will be straightforward but otherwise you may be better looking at other options. Finally got it printing. Gosh, it is a whole new ball game in a new whole ball park stadium. Loading up on soda pops and popcorns. Yep, you got it right, absolutely NOT trivial. GRRR. Thanks to all for providing guidance of where to go and look. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Where is win32print in Windows 10 Pro [RESOLVED]
On 08/11/2016 11:34 AM, Steven D'Aprano wrote: On Thu, Aug 11, 2016 at 10:28:44AM -0400, Ken G. wrote: import win32print ImportError: No module named win32print I have searched high and low within my Windows computer and have been unable to find 'win32print'. Any idea of where it is located or where I can obtain same. Thanks. Have you searched the Internet? https://duckduckgo.com/html/?q=win32print+python I'm not really familiar with this specific library, but I think it may be part of PyWin32: https://pypi.python.org/pypi/pywin32 which means if you have pip installed, this *may* work: # run this from your operating system shell (command.com, cmd.exe, Powershell?) pip install pywin32 I'm not an expert on Windows, but I hope this helps. Thanks for the help so far seen here. I already installed pywin32 and no error is encounter in running pywin32 in the python program. Unfortunately, no printing is done yet. Still working on it. Your reference to duckduckgo.com provided a list of useful pywin32 attibutes but no examples was provided. Will keep looking. Thanks. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Where is win32print in Windows 10 Pro
Currently in my Windows 10 Pro, 64-bit operating system, x64-bit based processor, using Python-2.7.12.amd64, I have for the first few lines: ``` import os, sys import win32print ` and get the following error message: ` import win32print ImportError: No module named win32print I have searched high and low within my Windows computer and have been unable to find 'win32print'. Any idea of where it is located or where I can obtain same. Thanks. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Program won't print out in Windows 10
While the following program prints out fine using Python 2.7.6 in Ubuntu 14.04.4 as developed using Geany 1.23.1, same program won't print out to printer under Windows 10 Pro (64 bit). Geany uses there is version 1.28 using Python 2.7.12. I can use CTRL-P to print out the listing. = # hello2.py import os print print "Hello World!" print pr = os.popen("lpr", "w") for i in range(1,8): pr.write("\n") pr.write("\n") pr.write("\t\t01 02 03 04 05") pr.write("\n") pr.close print print("\tPlease wait several moments for printer to catch up.") print === Thanking you readers in advance in resolving this non Windows printing issue. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Quote and double quotes opens up File Explorer in Windows 10 (RESOLVED)
On 07/09/2016 01:02 PM, eryk sun wrote: On Sat, Jul 9, 2016 at 2:22 PM, Ken G. <beachkid...@gmail.com> wrote: Hi: In gradually moving over my Python programs (2.7.6) to Windows 10 and using Geany 1.27 to modify or write up a program there, it is noted that whenever I typed in a quote (') or double quote ("), Windows 10 File Explorer opens up. I end up closing it by typing ALT-F4 to resume typing as before. Is there a way to prevent the File Explorer from opening up whenever I use a quote or double quote? Is there another key(s) that does weird thing in Windows 10? Thanks. The single/double quote key isn't a standard hotkey in any version of Windows. That would be insane. If this is just happening in Geany, check its keybindings preferences. Otherwise, check that you're using the right keyboard layout and that you don't have any programs (or malware) that's registering a global hotkey. For example, here's a simple script that registers the single quote (US keyboard layout) as a global hotkey to open the desktop in Explorer: #! /usr/bin/python3 import os import ctypes from ctypes import wintypes user32 = ctypes.WinDLL('user32') WM_HOTKEY = 0x0312 MOD_NOREPEAT = 0x4000 VK_OEM_7 = 0xDE # US layout, single/double quote hotkey_id = 1 if user32.RegisterHotKey(None, hotkey_id, MOD_NOREPEAT, VK_OEM_7): print('Hotkey "\'" registered.') msg = wintypes.MSG() count = 0 while (count < 3 and user32.GetMessageW(ctypes.byref(msg), None, 0, 0)): if msg.message == WM_HOTKEY and msg.wParam == hotkey_id: count += 1 print('Hotkey received.') os.startfile('shell:Desktop') Thank you for the responses. As it just turned out, it was the keyboard sending out a faulty signal for the quote and double quote to the computer. I switched keyboard and there was no opening of the File Explorer when sending quote and double quote using Geany. Again, thanks. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Quote and double quotes opens up File Explorer in Windows 10
Hi: In gradually moving over my Python programs (2.7.6) to Windows 10 and using Geany 1.27 to modify or write up a program there, it is noted that whenever I typed in a quote (') or double quote ("), Windows 10 File Explorer opens up. I end up closing it by typing ALT-F4 to resume typing as before. Is there a way to prevent the File Explorer from opening up whenever I use a quote or double quote? Is there another key(s) that does weird thing in Windows 10? Thanks. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sorting a list in ascending order [RESOLVED]
On 04/29/2016 07:40 PM, Alan Gauld via Tutor wrote: On 29/04/16 23:58, Ken G. wrote: print ''.join(list1) #making it again as a single string Thanks, Meena, that is great! I changed your last line to: print "".join(list1) and it came out as below: 0511414453 Another quotation mark was needed. No it wasn't. Meena used two single quotes, you used two double quotes. Both will work. But the two single quotes can look like a single double quote depending on your font choices. So double quotes in this case are probably less ambiguous. Gosh, been using double quotes since the late eighties and thus, a hard habit to break when encourage to use single quote mark in Python. Thanks for the reminder of "it" being a possible double single quote when encountering a double quote at various times. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sorting a list in ascending order [RESOLVED]
On 04/29/2016 05:10 PM, Martin A. Brown wrote: Greetings Ken and welcome to Python, Using Linux 2.7.6 in Ubuntu 14.04.4. Thanks. Thank you for this information. I have one tip for you: While Python 2.x will still be around for a while, if you are learning Python today, I'd suggest Python 3.x. You can read more about the differences online (or ask here), if you care. The only syntax difference that usually trips up beginners is the following: print line # Python 2.x print(line)# Python 3.x Though there are other differences, this is one of the most obvious to all Python programmers. With that said, I'll just answer your question using Python 2.x, since everything else in your example will work perfectly the same in either version. I intend to suggest what you should read, and then what you should try to run in order to address your question(s). I will paste my entire interactive Python sessions below. Did you know that you can use the Python interpreter as a shell to test out how things behave? Very handy. Try typing 'python' at the CLI and you should see this: $ python Python 2.7.8 (default, Sep 30 2014, 15:34:38) [GCC] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> So, when you see ">>>" below, that's in the Python shell (2.7.8 in my case, 2.7.6 in yours). In entering five random number, how can I best sort it into ascending order, such as 0511414453? OK, so you have five random numbers, but you seem to want to print them without any visual space between them. A bit strange, but OK! Fragment #1: number01 = "41" number02 = "11" number03 = "05" number04 = "53" number05 = "44" Observation: You define a variable called 'number01', which actually contains a string value. You can call the variable anything you want, but that will not change the type of the object to which your variable name is bound. For example: >>> number01 = "41" >>> type(number01) Suggestion #1, try this instead: >>> number01 = 41 >>> type(number01) Ah-ha! Now, we are dealing with integers (numbers). Fragment #2: line = number01 + number02 + number03 + number04 + number05 Observation: Since all of the variables (named number01, number02, number03, etc) contain strings, you are using string concatenation to create a new string. After the above command executes, you have this: >>> line '4111055344' >>> type(line) Comment: You don't really want a string, do you? Keep reading for a moment, and I'll come back to this. Also, I don't think you really want to add the integers. That would be 41 + 11 + 05 + 53 + 44 = 154. But, you want to keep the numbers and sort them. We will need to keep them in a list. And, Python has a data structure for you...called, obviously enough list(). Fragment #3: print print line line.sort() Traceback (most recent call last): File "Mega_Millions_01_Tickets_Entry_TEST_TEST.py", line 11, in print line.sort() AttributeError: 'str' object has no attribute 'sort' Observation: This message is called an Exception, in Python. There are many different kinds of exceptions--this one is called AttributeError, but the message of the exception is the important part for us here. It doesn't make sense to sort a string. You can sort two strings, of course. But not a single string. Anyway, the important thing about the Exception is it tries to give you a good deal of information about which line of code did something that was problematic, and what code called that code (this is why it's called a "Traceback"). Now, I'll rewind to the beginning and try to go through the problem again, changing a few pieces of your program to get you closer to your solution. First, let's use the right datatype, an int, for each number. Second, let's use a list() to store the numbers (instead of five separate named variables; easy to mistype names). Third, let's sort it. Then, let's print it. >>> nums = [41, 11, 5, 53, 44] # -- create/populate a list >>> nums [41, 11, 5, 53, 44] # -- still looks good >>> nums.sort() # -- sort, in place! >>> nums [5, 11, 41, 44, 53] # -- Ta-da! I'm going to do the same thing a slightly different way, now, so you can see how to add stuff to a list: >>> nums = list() >>> nums.append(41) >>> nums.append(11) >>> nums.append(5) >>> nums.append(53) >>> nums.append(44) >>> nums [41, 11, 5, 53, 44] In each case the variable 'nums' still contains the same data. We just got there in a different series of steps. You may decide which makes more sense to you in any given situation. So, suggestion, play with lists, and see how they work. Now, we have to figure out how to print the contents of the list. Here's one way, but it is not the output you appear to want. >>> print nums [5, 11, 41, 44, 53] I'm guessing you want '05 11 41 44 53'. There are many ways to convert
Re: [Tutor] Sorting a list in ascending order [RESOLVED]
On Fri, Apr 29, 2016 at 3:01 PM, Ken G. <beachkid...@gmail.com <mailto:beachkid...@gmail.com>> wrote: In entering five random number, how can I best sort it into ascending order, such as 0511414453? Using Linux 2.7.6 in Ubuntu 14.04.4. Thanks. number01 = "41" number02 = "11" number03 = "05" number04 = "53" number05 = "44" line = number01 + number02 + number03 + number04 + number05 print print line line.sort() print print line 4111055344 Traceback (most recent call last): File "Mega_Millions_01_Tickets_Entry_TEST_TEST.py", line 11, in print line.sort() AttributeError: 'str' object has no attribute 'sort' On 04/29/2016 04:58 PM, meenu ravi wrote: Hi Ken, As the message clearly says, the string object doesn't have an attribute "sort". You are trying to join the inputs as a single string,"line" and then you are trying to sort it. But, as you want the string in the sorted format, you should sort it first and then convert it into string, as follows. number01 = "41" number02 = "11" number03 = "05" number04 = "53" number05 = "44" list1 = [number01,number02,number03,number04,number05] # Creating a list with the inputs list1.sort() # sorting the input print ''.join(list1) #making it again as a single string Hope this helps. Happy coding. Thanks, Meena Thanks, Meena, that is great! I changed your last line to: print "".join(list1) and it came out as below: 0511414453 Another quotation mark was needed. Again, thanks. Ken I appreciate all of everybody help. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Sorting a list in ascending order
In entering five random number, how can I best sort it into ascending order, such as 0511414453? Using Linux 2.7.6 in Ubuntu 14.04.4. Thanks. number01 = "41" number02 = "11" number03 = "05" number04 = "53" number05 = "44" line = number01 + number02 + number03 + number04 + number05 print print line line.sort() print print line 4111055344 Traceback (most recent call last): File "Mega_Millions_01_Tickets_Entry_TEST_TEST.py", line 11, in print line.sort() AttributeError: 'str' object has no attribute 'sort' ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Best way to install Python 3 onto Windows 10 [RESOLVED]
On 03/15/2016 05:45 PM, Alan Gauld wrote: On 15/03/16 21:31, Ken G. wrote: Having acquired a new laptop yesterday with Windows 10 installed and up-to-date, what would be the best way to install the latest version of Python 3? Personally I always install ActiveState Python on Windows so that I can set up the Pythonwin IDE and use the ActiveState Windows help viewer for the Python docs. The installer should do everything you need for you. (You may have to locate the pyhonwin exe and set up a shortcut - I seem to recall that was not done by the installer for Win 10... Caveat: ActiveState are sometimes a few months behind with their python versions so might not have the very latest build out yet. Thank you Alan. I just could not remember the name of that helpful installer for the Windows system. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Best way to install Python 3 onto Windows 10
Having acquired a new laptop yesterday with Windows 10 installed and up-to-date, what would be the best way to install the latest version of Python 3? The laptop is an Dell Latitude E5500 and I am still learning the bells and whistles of it. I last used Windows XP 3-4 years back so this usage is all new to me. Currently, I am using Python 2.7.6 on a desktop Linux system, Ubuntu 14.04.4 and using Geany as a go to using Python. TIA, Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recommendations for best tool to write/run Python
On 03/02/2016 01:26 PM, Lisa Hasler Waters wrote: Hello everyone, I am new to Python, as are my middle school students. We are using Python 3.5.1 IDLE to write and run our (simple) code. However, this tool does not seem to be the best way to write longer code or to be able to re-edit code that has been saved/closed/reopened. Eventually, we hope to build some projects that we can "use" and share with others. Could you please recommend the best Python tools for writing and running our code for the long term? Also, we are hoping to find free tools! Thanks so very much! Lisa PS We have tried to use Aptana Studio 3 but it is not easy to work in. I have been using Geany as my Python work station in my Ubuntu 14.04.4 desktop operating system. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unable to get out of loop [RESOLVING]
On 02/26/2016 09:26 PM, Steven D'Aprano wrote: On Fri, Feb 26, 2016 at 08:30:19PM -0500, Ken G. wrote: side = "" while side != "0" or side != "1" or side != "2": That will only exit if side == "0", "1" and "2" **at the same time**. Clearly that is impossible, so the condition is always true, and the while loop will never end. Trying to reason about "reversed conditions" like that is hard, much much harder than reasoning about ordinary conditions. You should re-write it in terms of equality, then reverse the condition once: while side not in ("0", "1", "2): ... Thanks Danny and Steven for your response. I will rewrite the code and try again. I had no idea I opened up a can of worms and now, I am putting them back. Thanks! Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Unable to get out of loop
I have been unable to get out of the following loop. No matter what I entered, I can not get get out of the loop. The only way I can stop the routine is CTRL-C. If an entry is either 1, 2 or 3, then I should be able to proceed. I am sure the correct solution is very simple but I don't see it. Thanks. print side = "" while side != "0" or side != "1" or side != "2": print "\t1 = right arm\t2 = left arm\t0 = exit program" print side = raw_input("\t") print print print "\tYou entered", side print ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] OT: Searching Tutor Archives
While searching in Google several months ago, I came across a response addressed to me regarding on how to read, correct and write to the same file at the same time without using a secondary file as a temporary file to hold the corrected entries and rewriting to the original file. The entry was dated back approximately four years ago. I thought I printed it out as that was a new concept to me then. Could someone explain how to found such an article or kindly refresh my memory on how to correct an original file without using a secondary file. Thanks. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT: Searching Tutor Archives
On 08/19/2015 06:09 PM, Ben Finney wrote: Ken G. beachkid...@gmail.com writes: Could someone explain how to found such an article At the end of every message to this forum you'll see this footer: ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor That address, URL:https://mail.python.org/mailman/listinfo/tutor, gives information about the forum, including where to find its archives. You can browse the archives using a web search, for example “site:mail.python.org/pipermail/tutor/ beachkidken” in DuckDuckGo URL:https://duckduckgo.com/?q=site%3Amail.python.org%2Fpipermail%2Ftutor%2F+beachkidken. Wow, thanks. Just took a look and there are some thirty articles. Again, thanks. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT: Searching Tutor Archives
On 08/19/2015 07:34 PM, Alan Gauld wrote: On 19/08/15 18:43, Ken G. wrote: explain how to found such an article or kindly refresh my memory on how to correct an original file without using a secondary file. Thanks. Others have explained the search. Let me just point out that the number of cases where you want to do such a thing is vanishingly small. It's incredibly unreliable and error prone and if you mess it up you will probably screw up the source data such that you can't recover it or re-run it. It's almost never the best way to go about things - much better to fake it safely. Thanks, Alan. Your point is well taken. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reference last email message...
On 04/15/2015 08:21 PM, Alan Gauld wrote: On 16/04/15 00:47, Ken G. wrote: I just emailed that I was unable to correct a message in ModTools so I went to Yahoo and made the change and then approved it. What is ModTools? What kind of message? Where does Yahoo fit in? What does any of it have to do with this list? I'm confused. Again, my apology. Sent to the wrong address. redfaced Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reference last email message...
On 04/15/2015 08:45 PM, Dave Angel wrote: On 04/15/2015 07:47 PM, Ken G. wrote: I just emailed that I was unable to correct a message in ModTools so I went to Yahoo and made the change and then approved it. Noticing it did not appear on the list, I checked the Activity Log in Yahoo and it was marked Bounced! Several days ago, we had another message correction and that too, bounced. It's conceivable that you're referring to: https://pypi.python.org/pypi/modtools/1.0.2 But your message is so garbled that I have no idea how to respond. You have a gmail address, but you're somehow involved with yahoo. You refer to the list, but never say if it's this one. You refer to message correction but there's no standard way to modify a message on python-tutor once it's mailed or posted. So perhaps the message correction and the list you're referring to are somewhere else. Python-tutor is a limited mailing list that only takes messages from those who have subscribed/joined. So perhaps you have two different email addresses and you've registered using gmail, and are trying to post using yahoo. In any case, if it is ModTools, this is the wrong list to post questions. This list is intended for usage of the Python language and the standard library, and while other subjects are permissible, they're not as likely to get good responses. I'd suggest you email to python-l...@python.org a new message, starting a new thread. Be explicit about your question, supplying a URL when you refer to a 3rd party package, and giving python version and OS version. Then show exactly what you've tried and what the result was, posting a full traceback if you got an exception. Oh my! I send this to the wrong address. My apology. redfaced Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Changing a string number to another number [RESOLVED]
On 04/15/2015 08:36 AM, Dave Angel wrote: On 04/15/2015 08:21 AM, Ken G. wrote: When running the following code, I get the following error code: 201504110102030405061 Traceback (most recent call last): File Mega_Millions_Tickets_Change.py, line 11, in module datecode[20:21] = 0 TypeError: 'str' object does not support item assignment A 'str' object is immutable, which means simply that you cannot modify it in place. All you can do is create a new str object, and rebind your variable to that new one. That means that there are a number of things you cannot do directly to a string. One of them is modifying a slice, as you're trying to do. datecode = 201504110102030405061 print datecode if datecode[20:21] == 1: datecode[20:21] = 0 print datecode I can see that the first part of this is probably a standard datetime, and might suggest you convert it to one, and modify that as needed. But you're so far to the right that I have to figure you're doing some custom encoding. If you just want to replace a single character of a string, you could use the construct: datecode = datecode[:20] + 0 + datecode[21:] If you need something fancier, perhaps you can generalize it. Thank you, Dave. That did the trick. You were partly right about the datetime as the first part is a date and following contains the lotto numbers purchased for that date of a drawing. The last number in the string indicates if a bonus multiplier for the ticket was purchased, 0 for no and 1 for yes. Again, thanks. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Changing a string number to another number [RESOLVED]
On 04/15/2015 09:09 AM, Steven D'Aprano wrote: On Wed, Apr 15, 2015 at 08:21:33AM -0400, Ken G. wrote: When running the following code, I get the following error code: 201504110102030405061 Traceback (most recent call last): File Mega_Millions_Tickets_Change.py, line 11, in module datecode[20:21] = 0 TypeError: 'str' object does not support item assignment Try this: datacode = datacode[:20] + 0 + datacode[21:] This is called slicing. We take a slice of the string, from the start up to just before position 20; 0; and a slice from position 21 to the end of the string. The three pieces are then concatenated together, giving a new string. Wow! So darn simple with a good explanation. Thanks! Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Changing a string number to another number
When running the following code, I get the following error code: 201504110102030405061 Traceback (most recent call last): File Mega_Millions_Tickets_Change.py, line 11, in module datecode[20:21] = 0 TypeError: 'str' object does not support item assignment datecode = 201504110102030405061 print datecode if datecode[20:21] == 1: datecode[20:21] = 0 print datecode I have tried using the zero as an integer but still get the same error code. Any suggestion? Thanks in advance, Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Changing a string number to another number [RESOLVED]
On 04/15/2015 08:50 AM, Peter Otten wrote: Ken G. wrote: When running the following code, I get the following error code: 201504110102030405061 Traceback (most recent call last): File Mega_Millions_Tickets_Change.py, line 11, in module datecode[20:21] = 0 TypeError: 'str' object does not support item assignment datecode = 201504110102030405061 print datecode if datecode[20:21] == 1: datecode[20:21] = 0 print datecode I have tried using the zero as an integer but still get the same error code. Any suggestion? Strings in Python are immutable, i. e. you cannot change them once they are created. Instead you have to construct a new string. In the general case you can get the same effect as replacing the character #n of an all-ascii string with s = 01234567890 n = 3 s[:n] + x + s[n+1:] '012x4567890' In your case you want to replace the last character, so s[n+1:] is empty s = 201504110102030405061 n = 20 s[n+1:] '' and just s[:n] + x '20150411010203040506x' is sufficient. A word of warning: as you are using Python 2 you are actually manipulating bytes not characters when using the default string type. This may have ugly consequences: s = ähnlich # I'm using UTF-8 print ae + s[1:] ae�hnlich Here the new string is not valid UTF-8 because in that encoding a-umlaut consists of two bytes and I'm only removing one of them. A partial fix is to use unicode explicitly: s = uähnlich print ae + s[1:] aehnlich But if you are just starting consider switching to Python 3 where unicode is the default string type. Thank you, Peter. That would be something for me to consider. Alas, I am still using Python 2.7.6 but do have it on standby. Again, thanks. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Reference last email message...
I just emailed that I was unable to correct a message in ModTools so I went to Yahoo and made the change and then approved it. Noticing it did not appear on the list, I checked the Activity Log in Yahoo and it was marked Bounced! Several days ago, we had another message correction and that too, bounced. Ken, FreecycleLouisville, KY, USA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Function not returning 05 as string
I am sure there is an simple explanation but when I input 5 (as integer), resulting in 05 (as string), I get zero as the end result. When running the code: START OF PROGRAM: Enter the 1st number: 5 05 0 END OF PROGRAM: START OF CODE: import sys def numberentry(): print number01 = raw_input(Enter the 1st number: ) if number01 == 0: sys.exit() if len(number01) == 1: number01 = 0 + number01 print print number01 return(number01) number01 = 0 numberentry() print print number01 END OF CODE: ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Function not returning 05 as string [SOLVED]
On 04/13/2015 08:56 AM, Steven D'Aprano wrote: On Mon, Apr 13, 2015 at 08:11:46AM -0400, Ken G. wrote: I am sure there is an simple explanation but when I input 5 (as integer), resulting in 05 (as string), I get zero as the end result. When running the code: number01 = 0 Here you set the variable number01 to the int 0. numberentry() Here you call the function. It returns 05, but you don't do anything with it, so it just gets dropped on the floor and thrown away. print print number01 Here you print the variable number01, which is still the int 0, unchanged. I think where you are mislead is that you are not aware, or have forgotten, that global variables and local variables are different. So a variable x outside of a function and a variable x inside a function are different variables. Think of functions being like Los Vegas: what happens in Vegas, stays in Vegas -- function local variables don't leak out and have effects outside of the function except via the return statement, and even then only if the caller assigns the result to another variable: function() # return result is thrown away x = function() # return result is assigned to x The other way to have an effect outside of the function is to use global variables, and the global keyword. This is occasionally necessary, but I strongly recommend against it: it is poor programming practice and a bad habit to get into. Thanks for all the replies. I will keep at it. Again, thanks. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Function not returning 05 as string
On 04/13/2015 08:18 AM, Dave Angel wrote: On 04/13/2015 08:11 AM, Ken G. wrote: I am sure there is an simple explanation but when I input 5 (as integer), resulting in 05 (as string), I get zero as the end result. When running the code: START OF PROGRAM: Enter the 1st number: 5 05 0 END OF PROGRAM: START OF CODE: import sys def numberentry(): print number01 = raw_input(Enter the 1st number: ) if number01 == 0: sys.exit() if len(number01) == 1: number01 = 0 + number01 print print number01 return(number01) number01 = 0 What is this line intended to do? NameError: name 'number01' is not defined numberentry() Where are you intending to store the return value? Currently, you're just throwing it away. I am not sending anything to the def routine but expected an answer in return. print print number01 This variable has no relation to the one in the function. In fact, I'd recommend you use a different name, to make that clear. Do not use return at end of routine? I am lost there. END OF CODE: Thanks for answering. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Rearranging a list of numbers with corresponding index
On 03/13/2015 10:21 AM, Peter Otten wrote: Ken G. wrote: I have been keeping track of numbers drawn in our local lotto drawings into a list format as shown in a short example below. Using such list, I am able to determine how often a number appears within the last 100 plus drawings. The length of my lists range from 5, 15, 35, 59and 75 long. I will give an example of one of my short list. PowerPlay = [0, 0, 61, 32, 11, 14] Disregarding index 0 and 1, I can see and print the following: IndexNumber 2 61 3 32 4 11 5 14 showing that number 2 appears 61 times, number 3 appears 32 times, number 4 appears 11 times and number 5 appears 14 times within last 100 plus drawings. How I best rearrange the numbers from high to low with its corresponding index number such as below: Number Index 612 323 14 5 11 4 showing the number 2 appears 61 times, number 3 appears 32 times, number 5 appears 14 times and number 4 appears 11 times. I know that using MegaBall.reverse() sort the number from high to low but the index numbers still remain in the same positions. Thanks for pointing out the way to do this. The initial list: power_play = [0, 0, 61, 32, 11, 14] Use enumerate() to get index, frequency pairs: list(enumerate(power_play)) [(0, 0), (1, 0), (2, 61), (3, 32), (4, 11), (5, 14)] Sort the pairs: sorted(enumerate(power_play)) [(0, 0), (1, 0), (2, 61), (3, 32), (4, 11), (5, 14)] Provide a key to sort after the second value, i. e. the frequency in the (index, frequency) pairs: def second_value(item): ... return item[1] ... sorted(enumerate(power_play), key=second_value) [(0, 0), (1, 0), (4, 11), (5, 14), (3, 32), (2, 61)] Note that instead of writing your own custom function or lambda you could also use operator.itemgetter(1) from the operator module in the stdlib. Sort in reverse order: sorted(enumerate(power_play), key=second_value, reverse=True) [(2, 61), (3, 32), (5, 14), (4, 11), (0, 0), (1, 0)] Print the output for frequencies 0: pairs = sorted(enumerate(power_play), key=second_value, reverse=True) for index, freq in pairs: ... if freq == 0: ... break ... print(freq, index, sep=\t) ... 61 2 32 3 14 5 11 4 Wow! Thanks! Printing this out and will be studying it completely. Again, thanks. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Rearranging a list of numbers with corresponding index
I have been keeping track of numbers drawn in our local lotto drawings into a list format as shown in a short example below. Using such list, I am able to determine how often a number appears within the last 100 plus drawings. The length of my lists range from 5, 15, 35, 59and 75 long. I will give an example of one of my short list. PowerPlay = [0, 0, 61, 32, 11, 14] Disregarding index 0 and 1, I can see and print the following: IndexNumber 2 61 3 32 4 11 5 14 showing that number 2 appears 61 times, number 3 appears 32 times, number 4 appears 11 times and number 5 appears 14 times within last 100 plus drawings. How I best rearrange the numbers from high to low with its corresponding index number such as below: Number Index 612 323 14 5 11 4 showing the number 2 appears 61 times, number 3 appears 32 times, number 5 appears 14 times and number 4 appears 11 times. I know that using MegaBall.reverse() sort the number from high to low but the index numbers still remain in the same positions. Thanks for pointing out the way to do this. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Rearranging a list of numbers with corresponding index (RESOLVED)
On 03/13/2015 10:38 AM, Dave Angel wrote: On 03/13/2015 09:57 AM, Ken G. wrote: I have been keeping track of numbers drawn in our local lotto drawings into a list format as shown in a short example below. Using such list, I am able to determine how often a number appears within the last 100 plus drawings. The length of my lists range from 5, 15, 35, 59and 75 long. I will give an example of one of my short list. PowerPlay = [0, 0, 61, 32, 11, 14] Disregarding index 0 and 1, I can see and print the following: IndexNumber 2 61 3 32 4 11 5 14 showing that number 2 appears 61 times, number 3 appears 32 times, number 4 appears 11 times and number 5 appears 14 times within last 100 plus drawings. How I best rearrange the numbers from high to low with its corresponding index number such as below: Number Index 612 323 14 5 11 4 showing the number 2 appears 61 times, number 3 appears 32 times, number 5 appears 14 times and number 4 appears 11 times. I know that using MegaBall.reverse() sort the number from high to low but the index numbers still remain in the same positions. Thanks for pointing out the way to do this. Make a list of tuples by doing something like: new_list = [ (cnt, index) for index, cnt in enumerate(power_play) ] to produce: [ (0, 0), (0, 1), (61, 2), (32, 3), (11, 4), (14, 5) ] then sort it with reverse=True. When you print it, just omit the items that have zero as their count. (they'll be at the end, anyway) Lots of other variants, some more concise. And other approaches might be cleaner if we change how we generate the list. (I tried it briefly using Python 3.4) I will be studying this also. I am still using Python 2.7.6 as that is the latest as provided by Ubuntu 14.04.1. With thanks to all, I was able to resolve my request for assistance here in this forum. Thanks Peter. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Rearranging a list
I may have mis-stated my intention. I will rewrite my request for assistance later and resubmit. Thanks, Ken On 02/26/2015 08:04 AM, Peter Otten wrote: Steven D'Aprano wrote: Ah wait, the penny drops! Now I understand what you mean! Glad I'm not the only one ;) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Rearranging a list
Assuming I have the following list and code how do I best be able rearrange the list as stated below: list = [0, 0, 21, 35, 19, 42] Using print list[2:6] resulted in the following: 221 335 419 542 I would like to rearrange the list as follow: 542 335 221 419 I tried using list.reverse() and print list[0,6] and it resulted in: [42, 19, 35, 21, 0, 0] or as printed: 042 119 235 321 40 50 In another words, I would desire to show that: 5 appears 42 times 3 appears 35 times 2 appears 21 times 4 appears 19 times but then I lose my original index of the numbers by reversing. How do I best keep the original index number to the rearrange numbers within a list? Thanking in advance, Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Old popen turned in subprocess...[SOLVED]
I wish to thanks Danny Yoo and Alan Gauld for providing information on using the new subprocess in printing on paper, replacing my old popen which was deprecated since Python 2.6. After some trial and errors, I got my desired output printed. Not looking forward to updating my old programs. Thanks, guys. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Popen was deprecated since Python 2.6, now what?
On 02/16/2015 05:11 PM, Danny Yoo wrote: On Mon, Feb 16, 2015 at 1:26 PM, Ken G. beachkid...@gmail.com wrote: Wow, just found out this morning that the following terms of: import os pr = os.popen(lpr, w) pr.write(month), pr.write( ), pr.write(\t\tLine ) was deprecated. In place there of, there is a subprocess to use. Hi Ken, Yes: subprocess.Popen(), along with Popen.communicate(), are what you want to look at. For your example above, the change is relatively direct: ## import subprocess pr = subprocess.Popen(['lpr', 'w']) pr.communicate(month + ' ' + '\t\tLine ') ## The main difference between this and what you had earlier is that you send all the input at once using Popen.communicate(). There's a quick-and-dirty section in the documentation for converting from the os.popen call to the subprocess equivalents. See: https://docs.python.org/2/library/subprocess.html#replacing-os-popen-os-popen2-os-popen3 . Thank you for helping me get on the road here. I printed out your response and I'll be playing with it. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Popen was deprecated since Python 2.6, now what?
On 02/16/2015 06:26 PM, Alan Gauld wrote: On 16/02/15 21:26, Ken G. wrote: I have not been able to figure out on how to use a subprocess in place of my former popen. I have been reading the new materials on the subprocess all day and it is still not quite understandable. Here is what the docs say: ### 17.5.5.5. Replacing os.popen(), os.popen2(), os.popen3() (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize) == p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdin, child_stdout) = (p.stdin, p.stdout) (child_stdin, child_stdout, child_stderr) = os.popen3(cmd, mode, bufsize) == p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) (child_stdin, child_stdout, child_stderr) = (p.stdin, p.stdout, p.stderr) (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize) == p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) Return code handling translates as follows: pipe = os.popen(cmd, 'w') ... rc = pipe.close() if rc is not None and rc 8: print(There were some errors) == process = Popen(cmd, 'w', stdin=PIPE) ... process.stdin.close() if process.wait() != 0: print(There were some errors) 17.5.5.6. Replacing functions from the popen2 module Note If the cmd argument to popen2 functions is a string, the command is executed through /bin/sh. If it is a list, the command is directly executed. (child_stdout, child_stdin) = popen2.popen2(somestring, bufsize, mode) == p = Popen(somestring, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) (child_stdout, child_stdin) = popen2.popen2([mycmd, myarg], bufsize, mode) == p = Popen([mycmd, myarg], bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) popen2.Popen3 and popen2.Popen4 basically work as subprocess.Popen, except that: Popen raises an exception if the execution fails. the capturestderr argument is replaced with the stderr argument. stdin=PIPE and stdout=PIPE must be specified. popen2 closes all file descriptors by default, but you have to specify close_fds=True with Popen to guarantee this behavior on all platforms or past Python versions. # Which bits of that don't you understand? That way we have something concrete to work with. For example, Your popen program: import os pr = os.popen(lpr, w) pr.write(month), pr.write( ), pr.write(\t\tLine ) Translates according to the above as import subprocess as sub pr = sub.Popen([lpr], stdin = sub.PIPE) pr.stdin.write(month) pr.stdin.write( ) pr.stdin.close() if pr.wait() != 0: print 'Errors!' Now, how can we help further clarify things? Thank for the translation of the hard-to-read docs. Reading the docs threw me for a loop. I printed out your response and will be studying to try best understand it. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Popen was deprecated since Python 2.6, now what?
Wow, just found out this morning that the following terms of: import os pr = os.popen(lpr, w) pr.write(month), pr.write( ), pr.write(\t\tLine ) was deprecated. In place there of, there is a subprocess to use. I have not been able to figure out on how to use a subprocess in place of my former popen. I have been reading the new materials on the subprocess all day and it is still not quite understandable. Is there an easy tutorial of how to replace popen with the subprocess? I am using Python 2.7.6 on an Ubuntu 14.04.1 system. In advance, thanking you all for your assistance. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] RESOLVED: Re: Is there an easily or shorter way?
On 12/15/2014 07:47 PM, Danny Yoo wrote: Thank you but actually whatever number I get from either 1 to 28, each number represent a property name such as Reading Railroad, Judy Avenue, Pacific Gas and Electric, etc., etc. For example: if x = 1 then print Mediterranean Avenue if x = 2 then print Baltic Avenue Ah, cool! Ok, then yes, definitely a list. There's a sequential-ness here that we should take advantage of. PLACES = [Is-there-a-place-when-x-is-zero?, Mediterranean Avenue, Baltic Avenue, ]# and so on ... print PLACES[x] so that all the conditioning dissolves into a single list lookup. There might need to be a few more checks to make sure x is in bounds, but it's worth it here. Thank you, thank you. As I think it over through the night, I had a very faint idea of what you suggested. Again, thank. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Is there an easily or shorter way?
I am sure there is a better way to refine the following lines. Letting x equal a number from 1 to 28, go through 28 separate 'if' statements to print a resulting value that equaled the value of x. For example: x = 8 if x = 1, print 'one' if x = 2, print 'two' ... ... if x = 8, print 'eight' ... ... if x = 28, print 'twenty eight' Would a single line using list or dictionary be shorter? Thanks, Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is there an easily or shorter way?
On 12/15/2014 04:45 PM, Danny Yoo wrote: As a side note: if we were to talk about how we'd do this in a professional context, I think we'd recommend a library such as humanize, which has functions to go from numbers to human-friendly string descriptions. https://pypi.python.org/pypi/humanize Whoops: wrong library. Humanize is a good one, but not exactly the one I was supposed to cite. I should have cited num2words, which is a cardinal number library: https://pypi.python.org/pypi/num2words . Thank you but actually whatever number I get from either 1 to 28, each number represent a property name such as Reading Railroad, Judy Avenue, Pacific Gas and Electric, etc., etc. For example: if x = 1 then print Mediterranean Avenue if x = 2 then print Baltic Avenue ... ... if x = 28 then print Boardwalk Yes, I am using the property names from the game, Monopoly. I am using them in conjunction with of playing a lottery game and using Python to determine if I won anything from the numbers drawn and being compared with what numbers I purchased. Of course, the proper format in Python would be: if x == 01: print Mediterranean Avenue ... ... if x == 28: print Boardwalk Again, thanks for your input. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is there an easily or shorter way?
On 12/15/2014 05:49 PM, Steven D'Aprano wrote: On Mon, Dec 15, 2014 at 04:25:42PM -0500, Ken G. wrote: I am sure there is a better way to refine the following lines. Letting x equal a number from 1 to 28, go through 28 separate 'if' statements to print a resulting value that equaled the value of x. Since you only care about the first 28 values, a list or dict is the way to go. The two look remarkably similar: # Using a dict. Replace the dots ... with the rest of the values. names = {1: one, 2: two, 3: three, ... 28: twenty-eight} print(names[x]) # Using a list. Again, replace the dots. names = [zero, one, two, three, ... twenty-eight] print(names[x]) I stress that neither version *quite* works yet. You have to replace the dots ... with the rest of the values, which is tedious but not hard. In the case of the list version, the reason that I add an entry for zero is that lists are indexed from zero. That is, given the list: L = ['spam', 'eggs', 'cheese', 'toast'] the first entry is written L[0], the second entry L[1] and so forth. Although it takes a bit of getting used to, there actually are good reasons for that. One advantage of dicts over lists is that you can leave gaps while a list must have placeholders for every position: {2: two, 4: four, 8: eight} [, , two, , four, , , , eight] Of course, as Danny suggested, if you're going to be using this seriously for arbitrary numbers, you can't possibly list every single one in advance. What if somebody asks for the name of 9274810276523? In that case, we need a function that turns a number into an name digit by digit: nine trillion, two hundred and seventy-four billion, eight hundred and ten million, two hundred and seventy-six thousand, five hundred and twenty-three Doing this makes a nice little programming exercise, so I will leave it to you :-) Yes, Steven, it would be a 'nice' programming exercise. If I could just find the time...sighs. Thanks, Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is there an easily or shorter way?
On 12/15/2014 05:59 PM, Dave Angel wrote: On 12/15/2014 04:25 PM, Ken G. wrote: I am sure there is a better way to refine the following lines. Letting x equal a number from 1 to 28, go through 28 separate 'if' statements to print a resulting value that equaled the value of x. For example: x = 8 if x = 1, print 'one' if x = 2, print 'two' ... ... if x = 8, print 'eight' ... ... if x = 28, print 'twenty eight' Would a single line using list or dictionary be shorter? If this is an assignment, and you quoted it correctly, then you're required to go through 28 if statements. On the other hand, if that paragraph is just a description of the way you solved it, then yes, it can be improved. Just making all but the first if statement an elif will make it faster, because once it finds a value, it won't continue checking the remaining ones. Still faster would be testing first for fourteen, and making a tree out of the if statements, using and comparisons instead of only == comparisons. Worst case would be about 5 tests. This would not be more compact, just quicker to execute. Faster yet, and somewhat more compact would be to make a tuple or list of 29 items (0 through 28), and just index into it. Slower, but more compact, would be to write the kind of library that Danny pointed you to, or the code that Ken/Bod alluded to. But the real question is what's your goal. Your original code isn't legal Python, so you're presumably in a learning mode. If so, you want to keep it simple, not use 3rd party libraries for something you could do yourself. And when you're given an assignment, you should do it exactly the way they want it, and only after that's correct (and running), do it also in other ways. Those other ways could be to improve performance, reduce size, make it more readable (or less, to enter it in obfuscation contests), to make it independent of any loaded libraries, to look like some sample in another language, ... My second suggestion, untested: if x 14: if x 7: if x 3: if x == 1: print (one) else: print (two) elif x 5: if x == 3: print (three) else: print (four) Oh, it is not an assignment, Dave. It is an actual program I am using for my benefit. I had to figure out on a fly, what is the name of a piece of property that each number represent. I had to reckon something out within a limited amount of time I had. Giving the response given here so far, I could go with a list, dictionary or tuple. Thanks for your input. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] eval use (directly by interpreter vs with in a script)
On 11/03/2014 12:37 AM, Danny Yoo wrote: I use exec to jump to another program within the same directory, such as: execfile(BloodPressure02Sorting.py) and let the program terminate there. Should I do it differently or are you talking about a different horse? This is related. Rather than use execfile, you may want to consider looking into modules. https://docs.python.org/2/tutorial/modules.html By using the module system, you can call the functions of other files. We might think of one of the functions in a file as the main program, in which case you should be able to arrange a module approach that effectively does what you're doing with execfile. Using the module system is often nicer because the functions of another module are still just regular functions: it's easy to pass along Python values as arguments to tell the next process some contextual information. We can contrast this with an execfile approach, where there's not such a nice way of passing on that context to the other program. The module approach also can fail faster, in the case that when we want to use a module, we import it at the head of our main program. So if we got the file name wrong, we get fairly immediate feedback about our mistake. In contrast, the execfile approach defers from touching the secondary program until we're at the point of the execfile call itself. So if we got the filename wrong, we don't see the error as quickly. Wow! Such an interesting response. Much appreciated. Printing this out as a reference. Again, thanks. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] eval use (directly by interpreter vs with in a script)
On 11/02/2014 04:49 PM, Danny Yoo wrote: Hi Alex, Just as a side note, someone has probably already told you something like this, but: I would strongly recommend not to use Python's eval() or exec(). Those language features are dangerous. Every eval() or exec() is a possible vector for injection attacks. This week's injection attack of the week appears to be Drupal: https://www.drupal.org/PSA-2014-003, and it's certainly not going to be the last, but why should we encourage this? In the face of this, we have to admit to ourselves that these features are hard to use. Beginners should certainly give those features a very wide berth. I don't think it's crazy to say that community wisdom is to strongly discourage dynamic code evaluation features unless we have no other choice. Are you just exploring the features of Python, or is there a particular task you're trying to solve with eval or exec()? Perhaps you can accomplish the same goal in another way? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor I use exec to jump to another program within the same directory, such as: execfile(BloodPressure02Sorting.py) and let the program terminate there. Should I do it differently or are you talking about a different horse? Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Error in printing out totalSystolic on paper (1018)
Receiving the following error from the terminal screen: Traceback (most recent call last): File Blood Pressure05Print45.py, line 95, in module pr.write(totalSystolic) TypeError: expected a character buffer object Portion of strip: = pr.write ( ), pr.write (pulse), pr.write (\n) totalSystolic = totalSystolic + int(systolic) totalDiastolic = totalDiastolic + int(diastolic) totalPulse = totalPulse + int(pulse) file1.close() print print totalSystolic, totalDiastolic, totalPulse # sys.exit() pr.write(totalSystolic) # pr.write(totalDiastolic) # pr.write(totalPulse) == I know that totalSystolic is 1018, totalDiastolic is 469 and totalPulse is 465. I can not figure out why pr.write won't print out 1018 on paper. Using Python 2.7 on Ubuntu 12.04.5 and using Geany to process the strip. Thanks for your suggestion. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Error in printing out totalSystolic on paper (1018)
On 08/10/2014 10:38 AM, Alex Kleider wrote: On 2014-08-10 06:41, Ken G. wrote: Receiving the following error from the terminal screen: Traceback (most recent call last): File Blood Pressure05Print45.py, line 95, in module pr.write(totalSystolic) TypeError: expected a character buffer object Portion of strip: = pr.write ( ), pr.write (pulse), pr.write (\n) totalSystolic = totalSystolic + int(systolic) totalDiastolic = totalDiastolic + int(diastolic) totalPulse = totalPulse + int(pulse) file1.close() print print totalSystolic, totalDiastolic, totalPulse # sys.exit() pr.write(totalSystolic) # pr.write(totalDiastolic) # pr.write(totalPulse) == I know that totalSystolic is 1018, totalDiastolic is 469 and totalPulse is 465. I can not figure out why pr.write won't print out 1018 on paper. Using Python 2.7 on Ubuntu 12.04.5 and using Geany to process the strip. Thanks for your suggestion. Ken I'm guessing that you've defined pr.write(string) to take a string object but have fed it an integer- hence type error: try pr.write(str(totalSystolic)) instead of just pr.write(totalSystolic) By the way, those are incredibly high numbers! What units are you using? Thank you, I will try pr.write(str(totalSystolic)). As for the high numbers, they are a total of 8 readings, therefore, Systolic: 1018/8 = 127.25 Diastolic: 469/8 = 58.625 Pulse: 465/8 = 58.125 Again, thanks. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Error in printing out totalSystolic on paper (1018) [SOLVED]
Thanks you to the list for helping me solve my problem. I never had problem using and printing on paper pr.write in my coding until this latest one popped up. Yeah, this old dog is still learning new tricks here. LOL. Again, thanks. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Finding numeric day in a year...
I know the correct answer should be 001, but I keep getting 179 which is the correct answer for June 28, 2014 (I think). I tried using datecode in various places instead of today but I am still getting 179. Currently using Ubuntu 12.04.4 and Python 2.7. Thanks for any feedback and suggestion. PROGRAM DISPLAY: # datefind 03.py import datetime datecode = 20140101 # from database on file month = datecode[4:6] day = datecode[6:8] year = datecode[0:4] datecode = year + - + month + - + day today = datecode print today print print Day of year: , datetime.date.today().strftime(%j) TERMINAL DISPLAY: 2014-01-01 Day of year: 179 -- (program exited with code: 0) Press return to continue ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding numeric day in a year...
On 06/28/2014 02:13 PM, Mark Lawrence wrote: On 28/06/2014 18:59, Ken G. wrote: I know the correct answer should be 001, but I keep getting 179 which is the correct answer for June 28, 2014 (I think). I tried using datecode in various places instead of today but I am still getting 179. Currently using Ubuntu 12.04.4 and Python 2.7. Thanks for any feedback and suggestion. PROGRAM DISPLAY: # datefind 03.py import datetime datecode = 20140101 # from database on file month = datecode[4:6] day = datecode[6:8] year = datecode[0:4] datecode = year + - + month + - + day today = datecode print today print print Day of year: , datetime.date.today().strftime(%j) datetime.date.today() ? :) Thanks but it came out: Day of year: 2014-06-28 What I wanted was 001 for 01-01-2014 as specified in datecode. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding numeric day in a year...
On 06/28/2014 02:20 PM, Albert-Jan Roskam wrote: From: Ken G. beachkid...@gmail.com To: tutor@python.org Sent: Saturday, June 28, 2014 7:59 PM Subject: [Tutor] Finding numeric day in a year... I know the correct answer should be 001, but I keep getting 179 which is the correct answer for June 28, 2014 (I think). I tried using datecode in various places instead of today but I am still getting 179. Currently using Ubuntu 12.04.4 and Python 2.7. Thanks for any feedback and suggestion. PROGRAM DISPLAY: # datefind 03.py import datetime datecode = 20140101 # from database on file month = datecode[4:6] day = datecode[6:8] year = datecode[0:4] datecode = year + - + month + - + day today = datecode print today print print Day of year: , datetime.date.today().strftime(%j) TERMINAL DISPLAY: 2014-01-01 Day of year: 179 -- (program exited with code: 0) Press return to continue Hello, Your variable 'today' and the datetime function 'today()' are not the same thing. You need strptime to parse the date string (and tell it the format is mmdd), then strftime to format it using the day-of-year format '%j' datetime.datetime.strptime(datecode, %Y%m%d).strftime(%j) '001' Thanks! That did the trick. Thank you. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding numeric day in a year...
On 06/28/2014 02:36 PM, Steven D'Aprano wrote: On Sat, Jun 28, 2014 at 01:59:04PM -0400, Ken G. wrote: I know the correct answer should be 001, but I keep getting 179 which is the correct answer for June 28, 2014 (I think). Day 179 of 2014 is June 28 according to my diary, which happens to be today. (Well, I'm in Australia, so for me it is yesterday, but for you it is today.) So when you do this: print Day of year: , datetime.date.today().strftime(%j) it prints the day of the year for *today*. If you try it again tomorrow, it will print 180. If you wait another week, it will print 187. The existence of a variable today is irrelevant and has nothing to do with datetime.date.today. Consider this example: py import datetime py today = the first day of the rest of your life py datetime.date.today # just inspect the method built-in method today of type object at 0x607ac0 py datetime.date.today() # actually call the method datetime.date(2014, 6, 29) py today 'the first day of the rest of your life' I tried using datecode in various places instead of today but I am still getting 179. datecode holds a string, not a date object. To call date methods, you need a date object. py the_day = datetime.date(2014, 1, 1) py the_day.strftime(%j) '001' If you have a date as a string, you can turn it into a date object like this: py the_day = datetime.datetime.strptime('20140101', '%Y%m%d') py the_day.strftime(%j) '001' Thank you. Much appreciated. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding numeric day in a year...[SOLVED]
On 06/28/2014 02:39 PM, Alan Gauld wrote: On 28/06/14 18:59, Ken G. wrote: datecode = 20140101 # from database on file month = datecode[4:6] day = datecode[6:8] year = datecode[0:4] use strptime() to parse dates, its much more reliable. datecode = year + - + month + - + day today = datecode And use strftime() to format them... print today print print Day of year: , datetime.date.today().strftime(%j) This returns todays date whenever you run it. It has nothing to do with the dates above. But if you use strptime() to get the date from your string you should then be able to use strftime to convert it to julian. BTW You say you get it from database on file. Now if that is a real database such as SQLite you will find functions there to convert it to julian at source... which is easier than reading it as a string, parsing it, and then converting it back to a date again... HTH Ah, it is a Python database consisting of year-month-date and past drawn lotto numbers. I have just noticed that I am missing some twice weekly drawing. I am checking which one I am missing so far this year. Thanks to all that helps me solved the puzzle. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding numeric day in a year...[SOLVED]
On 06/28/2014 04:35 PM, Mark Lawrence wrote: On 28/06/2014 19:39, Alan Gauld wrote: On 28/06/14 18:59, Ken G. wrote: BTW You say you get it from database on file. Now if that is a real database such as SQLite you will find functions there to convert it to julian at source... which is easier than reading it as a string, parsing it, and then converting it back to a date again... Well spotted :) Ken G. please see https://docs.python.org/3/library/sqlite3.html#default-adapters-and-converters Thank you. Will take a look at it. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] most useful ide
On 02/02/2014 03:10 PM, Pierre Dagenais wrote: On 14-02-02 01:16 PM, Kodiak Firesmith wrote: Pycharm is nice for bigger projects (since tou can collapse any section); but it's crazy resource intensive. For Linux Gedit can be made very nice I prefer Geany as it will run my code with a click of the mouse. for python, and of course vim in the shell is very nice with the right ~/.vimrc. On Feb 2, 2014 11:20 AM, scurvy scott stopitscu...@gmail.com wrote: Hi Are there any recommendations for python ide's I, too, use Geany to run my Python programs. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Saving files in Python, IDE's editors
For what it may be worth, I use Geany on my Ubuntu OS, 12.04 LTS. I also have IDLE installed and I can use the Terminal Window in running Command Line. Ken On 12/17/2013 09:28 PM, Keith Winston wrote: On Tue, Dec 17, 2013 at 7:26 PM, tutor-requ...@python.org mailto:tutor-requ...@python.org wrote: What else do I need to do to make this version of Python an actually usable programming environment? Chris Acreman Chris, I'm also a noob, but I would recommend you install/use an IDE, such as IDLE which comes free with all (I think) Python installs. An Integrated Development Environment will help with formatting debugging, but the way I like to use IDLE is open up a window on the right side of my screen with the file I'm working on, and whenever I want to run it I save (ctrl-S, or menu) and run (F5, or menu), and then watch it go in the other window. Very efficient. There are quite a few other IDE's, free and not, but I don't really see the value for a beginner (but then, I'm just a beginner!). You didn't mention what operating system (or even what version of Python) you are using, this will likely influence the choices others offer. It is completely possible to do everything without an IDE, though AFAIK most people end up using IDEs or editors that can be set up to recognize (and color-code, etc) programming: VIM and EMACs are big favorites. I can't imagine the learning curve of the latter is worth it at first, if I correctly surmise your relatively noobiness based on the question... IDLE is simple, you already have it installed probably (a little more work if you are on linux), and it's got a GUI interface with drop-down menus and all that good stuff. Hopefully I didn't just start a flame war... -- Keith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Flip the coin 10x and count heads and tails: It works now!
On 05/25/2013 05:25 AM, Rafael Knuth wrote: Gents, thank you all for your help. One of you guys asked me to try out your suggestions and then tell you how it goes. Here we go! First, let me recap briefly what the expected outcome of my program was and which difficulties I encountered at the beginning. I was writing a program in Python 3.3.0 which flips a coin 10 x times and then counts the number of heads and tails. It obviously did something else than I intended: import random print ( This program flips a coin 10 times. It then counts the number of heads and tails. ) flips = 0 heads = 0 tails = 0 while flips 10: flips = flips + 1 if random.randint(1,2) == 1: heads = heads + 1 print(We've got + str(heads) + heads here. if random.randint(1,2) == 2: tails = tails + 1 print(We've got + str(tails) + tails here.) This is what I got as output: This program flips a coin 10 times. It then counts the number of heads and tails. We've got 1 tails here. We've got 1 heads here. We've got 2 tails here. We've got 2 heads here. We've got 3 tails here. We've got 3 heads here. We've got 4 tails here. We've got 5 tails here. We've got 4 heads here. We've got 6 tails here. We've got 7 tails here. We've got 5 heads here. As it turned out, each of your answers was *partially* correct, so I played around with your suggestions until I got my code up and running. Frankly, I did two mistakes: First, I placed the print statement inside the loop instead of outside of it. And second, I mistakenly called the random function two times inside the loop. In order to resolve that issue, I had to modify the heads and tails variables and then add another variable and put it inside the loop: result = random.randint(1,2) Lastly, I figured out that counting the results can be done in a more elegant fashion. Instead of: variable_XYZ = variable_XYZ + 1 … it can be done this way: variable_XYZ += 1 I got so excited when I saw my program run properly that I decided to pimp it a little bit by printing each head and tail with a time delay while the coin got flipped during the run. Here’s what my code looks like now: import random import time print ( This program flips a coin 10 times. It then counts the number of heads and tails. ) time.sleep(1) flips = 0 heads = 0 tails = 0 while flips 10: result = random.randint(1,2) if result == 1: heads += 1 print(head) time.sleep(1) elif result == 2: tails += 1 print(tail) time.sleep(1) flips += 1 print (\nYou've got + str(heads) + heads and + str(tails) + tails.) I have one last question to you: I explained twice in my initial mail what I expect my program to do (“I am writing a program in Python 3.3.0 which flips a coin 10 x times and then counts the number of heads and tails.”). I did that the introduction as well as inside my code. However, almost each of you asked me what I expect my program to do. I was confused about that and I am wondering if any of you can clarify? I just want to make sure I avoid misunderstandings like these in the future. Thank you all again! All the best, Rafael May I suggest that instead of: flips = 0 heads = 0 tails = 0 how about: flips = heads = tails = 0 Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Idle Crashing
On 05/17/2013 02:19 PM, Alan Gauld wrote: On 17/05/13 18:16, bob gailer wrote: On 5/16/2013 8:49 PM, Alan Gauld wrote: don't run programs on real data using IDLE. IDLE is for developing programs not running them. That is really scary. Why do you say that? The IDLE documentation does NOT say that! No, but IDLE is *intended* for development. It is not intended for running programs. You *can* do it but the results may not be what you expect. Lots of beginners seem to think that because they use IDLE to develop code that they must run it from there but its not an effective way of doing things. That's all I was meaning, not that terrible things might happen like the PC crashing or data being deleted. It's just easier and faster and more predictable to run finished code directly in the python interpreter. I use Geany 0.21 as a fast and lightweight IDE for my Python programs. MY OS is Ubuntu 12.04 LTS and currently using Python 2.7.3. I rarely use IDLE v2.7.3. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using a Blackjack Chart...
On 05/23/2012 09:36 PM, Steven D'Aprano wrote: Ken G. wrote: I would like to create a Python program in the manner of an using flash card format. That is, a question is asked and you can respond according and you will be notify if you are correct or incorrect. Is this supposed to be a graphical flashcard program? Or something you run at the terminal, using just text? That's much simpler. Using such format stated above, I would like to create a Blackjack program. I wish to utilize a 'cheat sheet chart' format that provide the proper response. The chart has 10 rows across, being identified as the dealer's up card, from 2 to 10 plus Ace. There are 23 columns indicating the player's cards being shown, such as 8 to 12, 13-16, 17+, A2 to A8 and 2,2 to A,A. Each row and column would indicate either Hit, DD (Double), S (Stand) and SP (Split). There's no need for the 200lb sledgehammer of a database to crack this peanut. Your data structure looks like a table, with a mere 10*23 = 230 cells. Just use a dictionary, with keys (dealer-up-card, player-cards) and values the response: table = { (2, 8): 'H', # dealer's card is 2, player's cards add to 8 (2, 9): 'H', ... (2, 21): 'S', (3, 8): 'H', ... } A text-only flash-card test would look something like this: import random def flash(): # Pick a random cell from the table. cell = random.choice(table.keys()) print The dealer shows, cell[0] print Your hand is, cell[1] response = raw_input(What do you do? ) if response == table[cell]: print Correct else: print The dealer laughs cruelly as he takes your money. def main(): print Blackjack flash-card program print Type Control-C at any time to halt. try: while True: flash() except KeyboardInterrupt: pass main() Thank you Steven for saving me from database hell. LOL. Yes, it would be a text based program. I will start working on this approach today. Again, my thanks. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using a Blackjack Chart...
On 05/24/2012 10:27 AM, Prasad, Ramit wrote: There's no need for the 200lb sledgehammer of a database to crack this peanut. Thank you Steven for saving me from database hell. LOL. Yes, it would be a text based program. I will start working on this approach today. Again, my thanks. This would be good practice as an intro to databases. They are a powerful tool and it would probably beneficial to learn it in the long run. Ramit Thanks. I have a bunch of tutorials printed out to study and learn. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using a Blackjack Chart...
On 05/23/2012 09:56 AM, Prasad, Ramit wrote: How can I best utilize such a chart in the Python program? Lists, Tuples, Dictionary or perhaps, a database format such as SQL? I tried using MySQLdb but was unable to use it since I am using Ubuntu 10.04.4 (Linux) as my main OS. My other OS is Windows XP. As to mysql it works fine on linux. If your system doesn't have mysql you can use synaptic package manager to get it Look for mysql-server, mysql-client and python-mysqldb import MySQLdb as mdb Or even more simply, why not use SQLite? It is built into Python and will be portable for anywhere that Python is. Ramit Thank you. I am looking into SQLite3. It has a steep learning curve for me. I'm still playing with it. Again, thanks. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sqlite3 question
On 05/23/2012 12:51 PM, Joel Goldstick wrote: On Wed, May 23, 2012 at 12:11 PM, Khalid Al-Ghamdiemailkg...@gmail.com wrote: hi all, I'm using Python 3 and have read that you need sqlite to be installed to use the sqlite3 module, but when it is imported it seems to work ok. so, do you need to install it? also, when you create the database where is it saved? thanks Here's one of the top listings from google for sqlite3 python http://greeennotebook.com/2010/06/how-to-use-sqlite3-from-python-introductory-tutorial/ See that the database is kept in the file /home/user/mydatabase.db import sqlite3 mydatabase=/home/user/.mydatabase.db connection=sqlite3.connect(mydatabase) cursor=connection.cursor() cursor.execute('CREATE TABLE mytable (Id INTEGER PRIMARY KEY, Date TEXT, Entry TEXT)') sqlite3.Cursor object at 0xb7cd7140 connection.commit() cursor.close() quit() The file may be hidden due to the dot before the file name and may be located in the home directory of user. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Using a Blackjack Chart...
I would like to create a Python program in the manner of an using flash card format. That is, a question is asked and you can respond according and you will be notify if you are correct or incorrect. Using such format stated above, I would like to create a Blackjack program. I wish to utilize a 'cheat sheet chart' format that provide the proper response. The chart has 10 rows across, being identified as the dealer's up card, from 2 to 10 plus Ace. There are 23 columns indicating the player's cards being shown, such as 8 to 12, 13-16, 17+, A2 to A8 and 2,2 to A,A. Each row and column would indicate either Hit, DD (Double), S (Stand) and SP (Split). How can I best utilize such a chart in the Python program? Lists, Tuples, Dictionary or perhaps, a database format such as SQL? I tried using MySQLdb but was unable to use it since I am using Ubuntu 10.04.4 (Linux) as my main OS. My other OS is Windows XP. Thank you for any suggestions or guidances. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which should it be, lists, tuples, dictionary or files? [SOLVED]
On 01/03/2012 06:28 AM, Alan Gauld wrote: On 03/01/12 07:31, Devin Jeanpierre wrote: It's probably worth mentioning that shelve is not secure; loading a saved shelf can involve executing arbitrary python code embedded inside it. This probably isn't important for this particular project, but maybe in the future, if you consider using shelf for something more security-conscious... A good point, shelve should be treated more like an internal persistence tool than a general purpose database. It's fine if you know what you are storing but if random data is being put into it there could be problems. My thanks to all of those who replied and offered suggestions. I will be looking into every one of those suggestions. Again, my thanks. This is truly a great Python group. Ken, Louisville, KY, USA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Which should it be, lists, tuples, dictionary or files?
I have been using an Open Office Spreadsheet containing basically, the food name, basic serving amount, calories, sodium and carbohydrate. Daily, I entered the servicing amount being eaten and its calculate the amount of calories, sodium and carbohydrate. For some odd reason, I kept losing the spreadsheet and its data. I am interested in keeping track of the number of calories consumed each day. Due to losing the spreadsheet data so frequencies, I decided to use Python in keeping track of the basic information and perhaps, keep track of the calories in a file. Over the last several months, numerous mention is made of lists, tuples and dictionary here. Basically, the format will be as follow: Name of Food Basic Serving Amount Calories per serving Sodium per serving Carbohydrate per serving For example, Name: Hominy, Golden (3.5) Serving Size: 1/2 cup Calories: 100 Sodium: 380 Carbohydrate: 20 The '(3.5)' indicated above is number of servings in a 15.5-ounce can. It will not necessary be indicated. Should the above five elements be stored as a list, tuples, dictionary or file? I am will familiar with files and have some knowledge of using lists and tuples. Not too familiar with dictionary. Thank for any suggestion. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which should it be, lists, tuples, dictionary or files?
On 01/02/2012 05:47 PM, Steven D'Aprano wrote: Ken G. wrote: I have been using an Open Office Spreadsheet containing basically, the food name, basic serving amount, calories, sodium and carbohydrate. Daily, I entered the servicing amount being eaten and its calculate the amount of calories, sodium and carbohydrate. For some odd reason, I kept losing the spreadsheet and its data. I am interested in keeping track of the number of calories consumed each day. Due to losing the spreadsheet data so frequencies, I decided to use Python in keeping track of the basic information and perhaps, keep track of the calories in a file. If you lose the spreadsheets, what makes you think you won't lose the Python files? I am using Open Office and for unknown reason, it does not always open. I am on Ubuntu 10.04.3 OS. I use my Python files every day. [...] Should the above five elements be stored as a list, tuples, dictionary or file? I am will familiar with files and have some knowledge of using lists and tuples. Not too familiar with dictionary. If you to store the data permanently, it has to go into a file. I suggest you learn about INI files to start with. Start by googling for INI file format and see if it sounds like what you could use. Okay, thanks. I will look into it. Have not heard of INI file format. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Weird Error
I have use 'sleep.time(5)' in most of my program but the following error is throwing me for a loss. import time Traceback (most recent call last): File /home/ken/Python2/Blood Glucose/BloodGlucose04ReadingTimed.py, line 63, in module time.sleep(2) AttributeError: 'str' object has no attribute 'sleep' Using the following is okay: import time print Now time.sleep(2) print Later ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Weird Error
On 12/17/2011 10:40 AM, Peter Otten wrote: Ken G. wrote: I have use 'sleep.time(5)' in most of my program but the following error is throwing me for a loss. import time Traceback (most recent call last): File /home/ken/Python2/Blood Glucose/BloodGlucose04ReadingTimed.py, line 63, inmodule time.sleep(2) AttributeError: 'str' object has no attribute 'sleep' Using the following is okay: import time print Now time.sleep(2) print Later Look for an assignment like time = whatever in module BloodGlucose04ReadingTimed.py. Whew! I search for time in the program and yes, I did have time as an assignment in several places in the program prior to using time.sleep. Changed the assigned time to timing. Thanks guys. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Github Pygame Example Repository
The second link should be read as follow: http://flossstuff.wordpress.com/2011/12/17/github-repository-for-pygame-examples/ You had an extra period after http: Ken On 12/17/2011 01:00 PM, ANKUR AGGARWAL wrote: I have created an pygame example repo on github to promote the learning of this API. check this out https://github.com/ankur0890/Pygame-Examples-For-Learning . I created an blog post of the same on my linux blog : http:.//flossstuff.wordpress.com/2011/12/17/github-repository-for-pygame-examples/ . Suggestions and feedback would be great. Looking for contribution too :) Regards Ankur Aggarwal ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File vs. Database (possible off topic)
On 11/22/2011 08:13 AM, Steven D'Aprano wrote: Ken G. wrote: It occurred to me last week while reviewing the files I made in using Python, it could be somewhat similar to a database. What would be a different between a Python files and Python databases? Granted, the access in creating them are different, I really don't see any different in the format of a file and a database. A database is essentially a powerful managed service built on top of one or more files. There's nothing you can do with a database that you can't do with a big set of (say) Windows-style INI files and a whole lot of code to manage them. A database does all the management for you, handling all the complexity, data integrity, and security, so that you don't have to re-invent the wheel. Since database software tends to be big and complicated, there is a lot of wheel to be re-invented. I wish to thank those whom replied to my previous question regarding database vs. file. The responses received was quite useful and helpful. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] File vs. Database (possible off topic)
It occurred to me last week while reviewing the files I made in using Python, it could be somewhat similar to a database. What would be a different between a Python files and Python databases? Granted, the access in creating them are different, I really don't see any different in the format of a file and a database. Again, this may be off topic, but where can I review the basic concepts of creating a database/file. For example, when is a back up file created, after inputting a new value? Is sorting a consider a separate program after inputting a new value? It has been some 30 years since I took a course in basic data processing and I am hazy in trying to remember the basic concepts. If this is off topic, I apologized for posting here. Ken, Kentucky, USA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [off-topic] Any thread for linux troubleshooting
On 12/11/11 17:54, Bikash Sahoo wrote: Can you please refer some threads for linux troubleshooting queries ?? Not so much a thread but the Ubuntu web forum is a good starting place and thereare tons of Linux news groups. Try a search on Google groups as your starting point. Also the Linux Documentation Project www.ldp.org has loads of how-to docs. I've been using Linux on and off since 1993 but only made the total switch to it this July. So far I'm loving it except for the lack of a decent Video editor and Visio clone. Fortunately Serif Movieplus and SmartDraw 6 work under Wine so I'm a happy bunny -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ I checked the above website and I was linked to a foreign political blog. The correct link is: tldp.org/ for The Linux Documentation Project. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginning Python From Perl
Not necessary learning from Perl but I would recommend Alan Gauld's online website for learning Python from scratch: http://www.alan-g.me.uk/ Good luck in learning Python. Ken On 11/08/2011 05:14 PM, Jihad Esmail wrote: Hi! I am new to this list so stick with me. I've recently taken interest in learning Python. I have already learned Perl. How should I go about learning Python from Perl? Please help. Thanks! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] New to programming
You may want to check out a short article entitled Instant Hacking by Magnus Lie Hetland. It is an introduction to programming using Python as an example. In the first paragraph thereby mentioned, there is a link to another easy article titled Instant Python written by the same author. He had already has written three Python books. Ken On 03/18/2011 07:48 PM, Savyn - OpenERP Mail wrote: Dear Everyone I am new to programming (a passion mainly). I have no background in programming. The python.org beginner tutorial seems hard after a few chapters or not sure how to merge requirement with the tutorials. Where and how should I start programming with python for complete beginner? Many thanks Sav ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python printing to LPT
On 02/12/2011 10:14 AM, Bill Allen wrote: Is is possible to print directly to an LPT port printer from Python? --Bill I use the following format in my Ubuntu 10.04 usage. It set up a printing file. import os # declare values month = 02; date = 11; year = 2011 # open up file pr = os.popen(lpr, w) #tab two times before printing string pr.write(\t\tDate of Drawing: ), # print the month on the same line and added a space pr.write(month), pr.write ( ), # print the date on the same line and added a space pr.write(date), pr.write( ), # print the year on the same line and added a space pr.write(year), pr.write( ), # print up two line feeds pr.write(\n), pr.write(\n) # close the print file pr.close() will produce the following: Date of Drawing: 02 11 2011 (start of new line here) Very time consuming and detailing but it work. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python printing to LPT
On 02/12/2011 09:53 PM, Bill Allen wrote: Ken, Thanks for the great info on doing this on a Linux platform. I am sure I will be trying this with Linux sometime and I'll refer back to this. --Bill I discovered some more information on this at the following link: http://mail.python.org/pipermail/tutor/2010-January/073725.html Good luck. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Sorting the Dictionary Set?
Is there a way to sort a dictionary? Assuming I have a dictionary set containing the following: {'02': 1, '03': 1, '12': 1, '15': 2, '14': 2, '04': 3, '05': 1, '19': 1, '32': 1, '28': 1, '27': 1, '17': 2, '25': 1} and using the following code: print ('Printing the result of numbers that are repeated:') print for x, y in counted.items(): if y 1: print Number %s was found %s times. % (x,y) # else: # print Number %s was found %s times. % (x,y) print and the result are: Printing the result of numbers that are repeated: Number 15 was found 2 times. Number 14 was found 2 times. Number 04 was found 3 times. Number 17 was found 2 times. and the question is: How do I sort the dictionary so the numbers listed (15, 14, 04, 17) are listed in sorted ascending order such as: Number 04 was found 3 times. Number 14 was found 2 times. Number 15 was found 2 times. Number 17 was found 2 times. I would appreciate any help, suggestion or hint on how to do achieved the desired result. Thanks, Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Looking for duplicates within a list
I have been working on this problem for several days and I am not making any progress. I have a group of 18 number, in ascending order, within a list. They ranged from 1 to 39. Some numbers are duplicated as much as three times or as few as none. I started with one list containing the numbers. For example, they are listed as like below: a = [1, 2, 3, 3, 4] I started off with using a loop: for j in range (0, 5): x = a[0] # for example, 1 How would I compare '1' with 2, 3, 3, 4? Do I need another duplicated list such as b = a and compare a[0] with either b[0], b[1], b[2], b[3], b[4]? Or do I compare a[0] with a[1], a[2], a[3], a[4]? In any event, if a number is listed more than once, I would like to know how many times, such as 2 or 3 times. For example, '3' is listed twice within a list. TIA, Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for duplicates within a list
vijay wrote: Check out this code l= [1, 2, 3, 3, 4] d={} for item in l: d.setdefaut(item,0) d[item] +=1 print d {1: 1, 2: 1, 3: 2, 4: 1} with regard's vijay Thanks. Very interesting concept. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for duplicates within a list
Alex Hall wrote: On 6/11/10, Ken G. beach...@insightbb.com wrote: I have been working on this problem for several days and I am not making any progress. I have a group of 18 number, in ascending order, within a list. They ranged from 1 to 39. Some numbers are duplicated as much as three times or as few as none. FYI, Python's set data type will let you have a list and never have a repeat. I know that is not your goal now, but if you want to remove duplicates, it seems like a good choice. I started with one list containing the numbers. For example, they are listed as like below: a = [1, 2, 3, 3, 4] I started off with using a loop: for j in range (0, 5): x = a[0] # for example, 1 How would I compare '1' with 2, 3, 3, 4? Do I need another duplicated list such as b = a and compare a[0] with either b[0], b[1], b[2], b[3], b[4]? Or do I compare a[0] with a[1], a[2], a[3], a[4]? A couple points here. First, you will want to make life easier by saying range(0, len(a)) so that the loop will work no matter the size of a. Second, for comparing a list to itself, here is a rather inefficient, though simple, way: for i in range(0, len(a)): x=a[i] for j in range(0, len(a)): y=a[j] if(x==y and i!=j): #match since a[i]==a[j] and i and j are not the same index of a In any event, if a number is listed more than once, I would like to know how many times, such as 2 or 3 times. For example, '3' is listed twice within a list. Do not quote me here, but I think sets may be able to tell you that as well. TIA, Ken Thank you for your contribution. As seen here, I have much to learn. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for duplicates within a list [SOLVED]
Sander Sweers wrote: On 11 June 2010 15:57, Ken G. beach...@insightbb.com wrote: In any event, if a number is listed more than once, I would like to know how many times, such as 2 or 3 times. For example, '3' is listed twice within a list. If you do not have top keep the order of the number this will work. a = [1, 2, 3, 3, 4] counted = {} for n in a: if not n in counted: counted[n] = 1 else: counted[n] += 1 counted {1: 1, 2: 1, 3: 2, 4: 1} for x, y in counted.items(): if y 1: print Number %s was found %s times % (x, y) else: print Number %s was found %s time % (x, y) Number 1 was found 1 time Number 2 was found 1 time Number 3 was found 2 times Number 4 was found 1 time Greets Sander That works great! Thanks! Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for duplicates within a list [SOLVED]
Jose Amoreira wrote: On Friday, June 11, 2010 02:57:34 pm Ken G. wrote: I have been working on this problem for several days and I am not making any progress. I have a group of 18 number, in ascending order, within a list. They ranged from 1 to 39. Some numbers are duplicated as much as three times or as few as none. I started with one list containing the numbers. For example, they are listed as like below: a = [1, 2, 3, 3, 4] I started off with using a loop: for j in range (0, 5): x = a[0] # for example, 1 How would I compare '1' with 2, 3, 3, 4? Do I need another duplicated list such as b = a and compare a[0] with either b[0], b[1], b[2], b[3], b[4]? Or do I compare a[0] with a[1], a[2], a[3], a[4]? In any event, if a number is listed more than once, I would like to know how many times, such as 2 or 3 times. For example, '3' is listed twice within a list. TIA, I would do it with a dictionary: def reps(lst): dict = {} for item in lst: if item in dict: dict[item] += 1 else: dict[item] = 1 return dict This function returns a dictionary with of the number of times each value in the list is repeated. Even shorter using dict.setdefault: def reps(lst): dict={} for item in lst: dict[item] = dict.setdefault(item,0) + 1 return dict For instance, if lst=[1,2,2,2,4,4,5], then reps(lst) returns {1: 1, 2: 3, 4: 2, 5: 1} Using the fact that the list is ordered, one can design a more efficient solution (go through the list; if this item is equal to the previous, then it is repeated, else, it is a new value). But you list is short enough for this direct approach to work. Hope this helps. Cheers, Jose Thanks. I will be studying your approach. Thanks all. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for duplicates within a list [SOLVED]
Alan Gauld wrote: Ken G. beach...@insightbb.com wrote In any event, if a number is listed more than once, I would like to know how many times, such as 2 or 3 times. For example, '3' is listed twice within a list. Have you looked at the count method of lists? Something like: counts = set(( item, mylist.count(item)) for item in mylist if mylist.count(item) 1) Seems to work... HTH, Whee, this is great! I learned a lot today. Back to playing and studying. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for duplicates within a list [SOLVED]
Dave Angel wrote: Ken G. wrote: I have been working on this problem for several days and I am not making any progress. I have a group of 18 number, in ascending order, within a list. They ranged from 1 to 39. Some numbers are duplicated as much as three times or as few as none. I started with one list containing the numbers. For example, they are listed as like below: a = [1, 2, 3, 3, 4] I started off with using a loop: for j in range (0, 5): x = a[0] # for example, 1 How would I compare '1' with 2, 3, 3, 4? Do I need another duplicated list such as b = a and compare a[0] with either b[0], b[1], b[2], b[3], b[4]? Or do I compare a[0] with a[1], a[2], a[3], a[4]? In any event, if a number is listed more than once, I would like to know how many times, such as 2 or 3 times. For example, '3' is listed twice within a list. TIA, Ken I'm a bit surprised nobody has mentioned the obvious solution -- another list of size 40, each of which represents the number of times a particular number has appeared. (Untested) a = [1, 2, 3, 3, 4] counts = [0] * 40 for item in a: counts[item] += 1 Now, if you want to know how many times 3 appears, simply print counts[3] The only downside to this is if the range of possible values is large, or non-numeric. In either of those cases, go back to the default dictionary. DaveA This will be look into. Mucho thanks. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for duplicates within a list [SOLVED]
Steven D'Aprano wrote: On Sat, 12 Jun 2010 12:58:19 am Alan Gauld wrote: Have you looked at the count method of lists? Something like: counts = set(( item, mylist.count(item)) for item in mylist if mylist.count(item) 1) That's a Shlemiel the Painter algorithm. http://www.joelonsoftware.com/articles/fog000319.html Seems to work... You say that now, but one day you will use it on a list of 100,000 items, and you'll wonder why it takes 45 minutes to finish, and curse Python for being slow. Hee, hee. Will investigate further. Thanks. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for duplicates within a list [SOLVED]
Hugo Arts wrote: On 11 jun 2010, at 17:49, Steven D'Aprano st...@pearwood.info wrote: On Sat, 12 Jun 2010 12:58:19 am Alan Gauld wrote: Have you looked at the count method of lists? Something like: counts = set(( item, mylist.count(item)) for item in mylist if mylist.count(item) 1) That's a Shlemiel the Painter algorithm. http://www.joelonsoftware.com/articles/fog000319.html It is, but it's also very elegant and simple to understand. And it works fine on small inputs. Everything is fast for small n. Seems to work... You say that now, but one day you will use it on a list of 100,000 items, and you'll wonder why it takes 45 minutes to finish, and curse Python for being slow. Actually, now that you know it is a shlemiel the painter's algorithm, you won't have to wonder anymore. And you'll just say: well, this piece of code might need to handle huge lists someday, I'll use a dictionary. I guess what I'm trying to say is: using code that performs bad in situations that won't be encountered anyway is not inherently bad. Otherwise, we'd all still be writing everything in C. The corrolary, of course, is that you should always know what the performance characteristics of your code are, and what kind of data it will handle. Hugo I appreciate your input. Thanks! Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for duplicates within a list [SOLVED]
davidheise...@gmail.com wrote: How about this? List = [1, 2, 3, 3, 3, 4, 5, 5] for Item in list(set(List)): print Item, List.count(Item) - Original Message - *From:* Ken G. mailto:beach...@insightbb.com *To:* Steven D'Aprano mailto:st...@pearwood.info *Cc:* tutor@python.org mailto:tutor@python.org *Sent:* Friday, June 11, 2010 9:09 AM *Subject:* Re: [Tutor] Looking for duplicates within a list [SOLVED] Steven D'Aprano wrote: On Sat, 12 Jun 2010 12:58:19 am Alan Gauld wrote: Have you looked at the count method of lists? Something like: counts = set(( item, mylist.count(item)) for item in mylist if mylist.count(item) 1) That's a Shlemiel the Painter algorithm. http://www.joelonsoftware.com/articles/fog000319.html Seems to work... You say that now, but one day you will use it on a list of 100,000 items, and you'll wonder why it takes 45 minutes to finish, and curse Python for being slow. Hee, hee. Will investigate further. Thanks. Ken ___ Oh, a nice one. Many thanks. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Finding duplicates entry in file
What is a method I can use to find duplicated entry within a sorted numeric file? I was trying to read a file reading two lines at once but apparently, I can only read one line at a time. Can the same file be opened and read two times within a program? For example, a file has: 1 2 2 3 4 4 5 6 6 The newly revised file should be: 1 2 3 4 5 6 Again, thanking the group for their input, Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding duplicates entry in file
Thanks for the info. I already adopted a program from another person and it works like a charm. As for your question, I had no idea of if I had duplicate or more as there was some 570 line items. I whittled it down to 370 line entries. Whew. Ken Luke Paireepinart wrote: On Sat, Mar 20, 2010 at 11:34 AM, Ken G. beach...@insightbb.com mailto:beach...@insightbb.com wrote: What is a method I can use to find duplicated entry within a sorted numeric file? I was trying to read a file reading two lines at once but apparently, I can only read one line at a time. Can the same file be opened and read two times within a program? For example, a file has: 1 2 2 3 4 4 5 6 6 The newly revised file should be: 1 2 3 4 5 6 Again, thanking the group for their input, One-liner: open(output.txt, w).write(\n.join(sorted(set([i.strip() for i in open(input.txt)] Just for fun :) also, in your algorithm, why are you assuming there are at most 1 extra entries in the case of a duplicate? Why not generalize it for all duplicates? -Luke ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding duplicates entry in file
Thanks for letting me know. Corrective actions taken. Ken Luke Paireepinart wrote: On Sat, Mar 20, 2010 at 4:50 PM, Ken G. beach...@insightbb.com mailto:beach...@insightbb.com wrote: Thanks for the info. I already adopted a program from another person and it works like a charm. As for your question, I had no idea of if I had duplicate or more as there was some 570 line items. I whittled it down to 370 line entries. Whew. Can you please try to post to the list in plain-text rather than HTML? it is very hard to read your font on my system. Thanks, -Luke ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First program
I am using Ubuntu 9.04 and I have versions 2.6.2 and 3.0.1+ installed. Look for IDLE in Add/Remove Applications. Perhaps, you may have a different version of Ubuntu. Ken Ray Parrish wrote: Yes, I'm using 2.45.2 as that is the highest version available in the Ubuntu repositories, and I'd like to keep it simple for users of programs i write. If I install a higher version from somewhere other than the repositories it will force users of my programs to do the same, and the repositories are the trusted source of software for Ubuntu, and other Linux users. Thanks for being so observant. Later, Ray Parrish ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Changing the value in a list
If the following program change list[2] to 2010, replacing 1997 (and it does), why doesn't the second program work in changing line[ 9:11] to 20 from 08? FIRST PROGRAM: list = ['physics', 'chemistry', 1997, 2000] print list[2] list[2] = 2010 print list[2] OUTPUT: 1997 2010 SECOND PROGRAM: line = [2010020820841134] if line[ 9:11] == 08: line[ 9:11] = 20 print line[ 9:11] OUTPUT: TypeError: 'str' object does not support item assignment. Thanking you all in advance, Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Changing the value in a list
Okay, now, it is understood. Thanks. Ken Andre Engels wrote: On Thu, Mar 11, 2010 at 4:32 PM, Ken G. beach...@insightbb.com wrote: If the following program change list[2] to 2010, replacing 1997 (and it does), why doesn't the second program work in changing line[ 9:11] to 20 from 08? FIRST PROGRAM: list = ['physics', 'chemistry', 1997, 2000] print list[2] list[2] = 2010 print list[2] OUTPUT: 1997 2010 SECOND PROGRAM: line = [2010020820841134] if line[ 9:11] == 08: line[ 9:11] = 20 print line[ 9:11] OUTPUT: TypeError: 'str' object does not support item assignment. Thanking you all in advance, First, you seem to have made a mistake in copying your programs: In the second program to get your error message, line = [2010020820841134] should read line = 2010020820841134 As for your question: The error message already says it better than I do: If x is a string, then x[9] = something is not allowed, nor is x[9:11] = something. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Changing the value in a list
Okay, I understand now. Thanks! Ken Steve Willoughby wrote: On Thu, Mar 11, 2010 at 10:32:45AM -0500, Ken G. wrote: list = ['physics', 'chemistry', 1997, 2000] This is a list of 4 elements, and lists allow elements to be changed, so list[2] = 2010 Will change the value of list to be ['physics','chemistry',1997,2010] line = [2010020820841134] Is this one right, or did you mean '2010020820841134'? What is shown is a list of one element. Assuming you meant it to be a string, that would give the error you quote below. Strings are immutable objects, meaning that once they are created you can't change them, although you can construct new strings from them, so if you wanted to make a string which had characters 9 and 10 replaced with 08 you could say: line = line[:9]+08+line[11:] ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Bowing out
Thanks for helping out. I enjoyed readying your posts. Good luck on your future endeavors. Ken Kent Johnson wrote: Hi all, After six years of tutor posts my interest and energy have waned and I'm ready to move on to something new. I'm planning to stop reading and contributing to the list. I have handed over list moderation duties to Alan Gauld and Wesley Chun. Thanks to everyone who contributes questions and answers. I learned a lot from my participation here. So long and keep coding! Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] rstrip in list?
I printed out some random numbers to a list and use 'print mylist' and they came out like this: ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n'] I was using 'print mylist.rstrip()' to strip off the '\n' but kept getting an error of : AttributeError: 'list' object has no attribute 'rstrip' My memory must be hazy but I thought I had it working several months ago. Any idea or suggestion? TIA, Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] rstrip in list?
Kent Johnson wrote: On Tue, Feb 9, 2010 at 10:28 AM, Ken G. beach...@insightbb.com wrote: I printed out some random numbers to a datafile and use 'print mylist' and they came out like this: ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n'] How are you generating this list? You should be able to create it without the \n. That would be better than stripping them out. I inputting some random numbers into a database and then created a list and appended the list as it read the database. I was using 'print mylist.rstrip()' to strip off the '\n' but kept getting an error of : AttributeError: 'list' object has no attribute 'rstrip' My memory must be hazy but I thought I had it working several months ago. Any idea or suggestion? Use a list comprehension or map(): In [1]: l = ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n'] In [2]: [ i.rstrip() for i in l ] Out[2]: ['102', '231', '463', '487', '555', '961'] In [3]: map(str.rstrip, l) Out[3]: ['102', '231', '463', '487', '555', '961'] Kent My database file has numbers of the same exact length that need to be sorted. I am using 'mylist.sort()' as one of the command. Actually, I will be using 'mylist.reverse' after that command. I am still in a learning mode. Thanks. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] rstrip in list? (SOLVED)
There was so many different solutions presented here to me. Thanks to all. By adding '.strip('\n') to the last two lines below, it came out: Sorted List ['102', '231', '463', '487', '555', '961'] for line in file.readlines(): print line.strip('\n'), mylist.append(line.strip('\n')) Further work and studying needed here. LOL. Ken Steven D'Aprano wrote: On Wed, 10 Feb 2010 02:28:43 am Ken G. wrote: I printed out some random numbers to a list and use 'print mylist' and they came out like this: ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n'] I was using 'print mylist.rstrip()' to strip off the '\n' but kept getting an error of : AttributeError: 'list' object has no attribute 'rstrip' You have to apply rstrip to each item in the list, not the list itself. Here are two ways to do it: #1: modify the list in a for-loop for i, item in enumerate(mylist): mylist[i] = item.rstrip() #2: make a new list with a list comprehension mylist = [item.rstrip() for item in mylist] Of the two, I prefer the second. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Embarrassed...
I am a little embarrassed. I just happen to found a program I wrote in December that create random numbers into a file, copy the numbers into a list, print the numbers unsorted and sorted from the list without printing '\n'. Nevertheless, I do thanks you all for trying to help me out. Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Future Appointments...
Below is a program to determine when my next appointment is. Line numbers are provided for reference only. 01 import time, datetime, sys 02 from datetime import date 03 today = date.today() 04 print 05 print Today date is:, today 06 todaystr = str(today) 07 print 08 print Corrected date format is:, 09 print todaystr[ 5: 7], todaystr[ 8:10], todaystr[ 0: 4] 10 print 11 future = raw_input(Next appointment is in how many days? ), 12 print 13 difference1 = datetime.timedelta(days=1) 14 datestring = str(today + difference1) 15 print Next appointment after that is:,datestring 16 print 17 print Corrected date format for next appointment is:, 18 print datestring[ 5: 7], datestring[ 8:10], datestring[ 0: 4] 19 sys.exit() In answering the question in line 11 as to when is my next appointment, I would answer 3 (for 2/3/2010) but how do I change days=1 at end of line 13 to days=3 so that datestring would read 2010-02-03 instead of 2010-02-01 as presented above? TIA, Ken ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor