From chris_roysmith at internode.on.net Sun Jul 1 01:32:59 2018 From: chris_roysmith at internode.on.net (Chris Roy-Smith) Date: Sun, 1 Jul 2018 15:32:59 +1000 Subject: [Tutor] how to change the command "string" on a tkinter Button? In-Reply-To: References: <140dc3c6-2150-737a-fc09-df458a769833@internode.on.net> Message-ID: <1cf7d268-1eb8-55c7-872e-6ca28ad7ba2e@internode.on.net> On 01/07/18 02:17, Alan Gauld via Tutor wrote: > On 30/06/18 03:55, Chris Roy-Smith wrote: > >> I am trying to change the command of a tkinter Button in my program. >> Eventually I want to be able to do this to many buttons. > Since I'm not 100% sure if you mean the command or the label or both > here is a simple example that does both... > > ############################################ > import tkinter as tk > > def cmd1(): print('This is command 1') > > def cmd2(): print('This is number 2') > > def swapCmd(): > c = b1['command'] > # kluge to get the function name from Tcl id > if str(c).endswith("cmd1"): > b1['command'] = cmd2 > else: > b1['command'] = cmd1 > > def swapText(): > t = b1['text'] > if t == "Cool": > b1['text'] = "Hot" > else: > b1['text'] = "Cool" > > # make GUI > top = tk.Tk() > win = tk.Frame(top) > win.pack() > b1 = tk.Button(win,text="Cool", command=cmd1) > b1.pack() > b2 = tk.Button(win, text="Swap text", command=swapText) > b2.pack() > b3 = tk.Button(win, text="Swap cmd", command=swapCmd) > b3.pack() > > top.mainloop() > ########################################### > > Thank you Alan, you have covered what I think I wanted to achieve. For me, programming is a continual learning experience, unfortunately I seem to forget nearly as much as I learn, Python is the first language I have attempted since macro assembler for CP/M. Python seems to be another world. It appears that I broke the code I started experimenting with, to try? changing the command, and that may have added to my confusion. I'll play with your example to try an understand what is going on. Regards, Chris Roy-Smith From steve at pearwood.info Sun Jul 1 05:19:34 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 1 Jul 2018 19:19:34 +1000 Subject: [Tutor] how to change the command "string" on a tkinter Button? In-Reply-To: <1cf7d268-1eb8-55c7-872e-6ca28ad7ba2e@internode.on.net> References: <140dc3c6-2150-737a-fc09-df458a769833@internode.on.net> <1cf7d268-1eb8-55c7-872e-6ca28ad7ba2e@internode.on.net> Message-ID: <20180701091934.GW14437@ando.pearwood.info> On Sun, Jul 01, 2018 at 03:32:59PM +1000, Chris Roy-Smith wrote: > Python is the first language I have > attempted since macro assembler for CP/M. Python seems to be another world. Yes indeed, high-level languages like Python *are* a radically different programming experience than low-level languages like assembler. The fundamental execution and data models of the languages are *very* different: - assembler lives in a universe of bytes and words; there are few abstractions and you are dealing (very nearly) with the lowest level of flipping bits in hardware, or at least of moving bytes. - Python lives in a world of big, complex abstractions like dicts and Unicode text and even objects as complex as "web server", and the fundamental operations are multiple layers away from moving bytes. It's not surprising that this may require some re-adjustment of your mental model of how to program. > It appears that I broke the code I started experimenting with, to try? > changing the command, and that may have added to my confusion. "Save As..." before engaging in big changes is your friend :-) Even better would be to learn a form of VCS (version control system) such as Mercurial (hg) or git. Depending on the text editor you are using, it may have VCS integration available. Off-topic: I see you are a fellow Internode user, like me. Which part of Australia are you in, and is your internet connection giving you as much grief as mine is? I'm pretty sure that Internode is *grossly* oversubscribed. E.g. when I try doing a google search, I'll usually get "Waiting for www.google.com..." which then times out about six or twelve times on average before succeeding to connect, after which it is damn near instantaneous. I downloaded 2 GB of data in about ten minutes yesterday, not long followed by a 2K email that took *three hours* to leave my computer because the connection to Internode's mail server kept timing out. -- Steve From chris_roysmith at internode.on.net Sun Jul 1 04:15:32 2018 From: chris_roysmith at internode.on.net (Chris Roy-Smith) Date: Sun, 1 Jul 2018 18:15:32 +1000 Subject: [Tutor] how to change the command "string" on a tkinter Button? In-Reply-To: References: <140dc3c6-2150-737a-fc09-df458a769833@internode.on.net> Message-ID: <422b4f32-9325-2d64-8082-ee55f66ac39e@internode.on.net> On 01/07/18 02:17, Alan Gauld via Tutor wrote: > On 30/06/18 03:55, Chris Roy-Smith wrote: > >> I am trying to change the command of a tkinter Button in my program. >> Eventually I want to be able to do this to many buttons. > Since I'm not 100% sure if you mean the command or the label or both > here is a simple example that does both... > > ############################################ > import tkinter as tk > > def cmd1(): print('This is command 1') > > def cmd2(): print('This is number 2') I was hoping eventually to generate the command form the results of a database query, not knowing? the exact command until run time. Perhaps what I was trying to achieve is too close to self modifying code, I was warned off this when I used to dabble in assembler. Does the same advice hold for python? > > def swapCmd(): > c = b1['command'] > # kluge to get the function name from Tcl id > if str(c).endswith("cmd1"): > b1['command'] = cmd2 > else: > b1['command'] = cmd1 I never thought to try anything like this, I was thinking more along the lines for how to change the text of a Labe.l > def swapText(): > t = b1['text'] > if t == "Cool": > b1['text'] = "Hot" > else: > b1['text'] = "Cool" > > # make GUI > top = tk.Tk() > win = tk.Frame(top) > win.pack() > b1 = tk.Button(win,text="Cool", command=cmd1) > b1.pack() > b2 = tk.Button(win, text="Swap text", command=swapText) > b2.pack() > b3 = tk.Button(win, text="Swap cmd", command=swapCmd) > b3.pack() > > top.mainloop() > ########################################### > Thank you again Alan, While your solution works, it's not how I imagined in terms of approach. Eventually I wanted to change the command of a variable number of buttons with the actual command depending on the results of a database query. I am unable to see how I can manage this in your solution style ( predetermined commands) might be difficult to achieve ( with my limited programming skills ).? Your solution made me rethink what I was attempting to do, and found with a slightly modified database query, I didn't need to change the command at all. The rest of this bit of program I have already solved. Now I just have to learn a lot more about classes, and objects. again, thank you Alan. Regards, Chris Roy-Smith From chris_roysmith at internode.on.net Sun Jul 1 06:33:27 2018 From: chris_roysmith at internode.on.net (Chris Roy-Smith) Date: Sun, 1 Jul 2018 20:33:27 +1000 Subject: [Tutor] how to change the command "string" on a tkinter Button? In-Reply-To: <20180701091934.GW14437@ando.pearwood.info> References: <140dc3c6-2150-737a-fc09-df458a769833@internode.on.net> <1cf7d268-1eb8-55c7-872e-6ca28ad7ba2e@internode.on.net> <20180701091934.GW14437@ando.pearwood.info> Message-ID: <86947ac6-440f-cd2d-9c18-500587e391bc@internode.on.net> On 01/07/18 19:19, Steven D'Aprano wrote: > On Sun, Jul 01, 2018 at 03:32:59PM +1000, Chris Roy-Smith wrote: > >> Python is the first language I have >> attempted since macro assembler for CP/M. Python seems to be another world. > Yes indeed, high-level languages like Python *are* a radically different > programming experience than low-level languages like assembler. The > fundamental execution and data models of the languages are *very* > different: > > - assembler lives in a universe of bytes and words; there are few > abstractions and you are dealing (very nearly) with the lowest > level of flipping bits in hardware, or at least of moving bytes. > > - Python lives in a world of big, complex abstractions like dicts > and Unicode text and even objects as complex as "web server", > and the fundamental operations are multiple layers away from > moving bytes. > > It's not surprising that this may require some re-adjustment of your > mental model of how to program. those big complex bits cut down on the amount of code needed to achieve a given task. :-) > > >> It appears that I broke the code I started experimenting with, to try >> changing the command, and that may have added to my confusion. > "Save As..." before engaging in big changes is your friend :-) yes, was supposed to be a quick experiment to test idea ;) > > Even better would be to learn a form of VCS (version control system) > such as Mercurial (hg) or git. Depending on the text editor you are > using, it may have VCS integration available. I don't know anything about these tools, I use Kate as my editor for my programming. I usually give a new number to separate versions, I'm sure there are better ways, I just haven't gone looking for them yet. Idle only looks useful for CLI stuff. > > Off-topic: > > I see you are a fellow Internode user, like me. Which part of Australia > are you in, and is your internet connection giving you as much grief as > mine is? I have had little trouble with Internode over the last 13 years or so. The other day is the first time I had a really slow download, went to another mirror in Western Australia, and all went as fast as I'm supposed to get (I have the slowest option of NBN, ( bronze 100) which I have never NEEDED extra bandwidth, it might be nice, but I don't use the sort of service which depends on good bandwidth, downloads can go all night for all I care). I'm not greedy though it's all very fast compared to dial up, or packet radio > > I'm pretty sure that Internode is *grossly* oversubscribed. E.g. when I > try doing a google search, I'll usually get "Waiting for > www.google.com..." which then times out about six or twelve times on > average before succeeding to connect, after which it is damn near > instantaneous. I search with DuckDuckGo, and rarely have any response issue with my searches. I don't think they sell my search data. > > I downloaded 2 GB of data in about ten minutes yesterday, not long > followed by a 2K email that took *three hours* to leave my computer > because the connection to Internode's mail server kept timing out. Your connection is a bit faster than mine. I've not experienced any speed issues with the email server. Regards, Chris Roy-Smith From sydney.shall at kcl.ac.uk Sun Jul 1 05:50:46 2018 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Sun, 1 Jul 2018 11:50:46 +0200 Subject: [Tutor] RAD GUI Development (like Visual Studio/VBA) Message-ID: <5597cc4f-800a-1a57-8f0b-ca019263d8a6@kcl.ac.uk> On 30/06/2018 19:21, Alan Gauld via Tutor wrote: > On 30/06/18 11:50, Shall, Sydney wrote: > >>> And if you want to try using Jython or MacPython(?) >>> you can use the native GUI builders for those: >>> - Eclipse/Netbeans (Java) >>> - XDeveloper (MacOS) - I tried this once and it kind of works... >>> >> Alan, >> >> Could you expand a bit on the use of XDeveloper. >> I have need of some such utility for my project and I use a MAC OS X. > I've only gone through the tutorial and made some tweaks > to the resulting code but it seemed to work pretty much > as usual for Cocoa projects using Objective C. > > You layout the UI then connect the widgets to your code > (which is in Python of course). > > The PyObjC project is here: > > https://pythonhosted.org/pyobjc/ > > The tutorial I used is here: > > https://pythonhosted.org/pyobjc/tutorials/firstapp.html > > Note that it is old, but I only have an iBook from 2001 > running MacOS Lion, so age wasn't an issue for me! > Thank you. I shall spend some time studying the two sites and see what I can make of it. Sydney _________ Professor Sydney Shall Department of Haematology/Oncology Phone: +(0)2078489200 E-Mail: sydney.shall [Correspondents outside the College should add @kcl.ac.uk] From alan.gauld at yahoo.co.uk Sun Jul 1 15:07:17 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 1 Jul 2018 20:07:17 +0100 Subject: [Tutor] how to change the command "string" on a tkinter Button? In-Reply-To: <422b4f32-9325-2d64-8082-ee55f66ac39e@internode.on.net> References: <140dc3c6-2150-737a-fc09-df458a769833@internode.on.net> <422b4f32-9325-2d64-8082-ee55f66ac39e@internode.on.net> Message-ID: On 01/07/18 09:15, Chris Roy-Smith wrote: >> def cmd2(): print('This is number 2') > I was hoping eventually to generate the command form the results of a > database query, not knowing? the exact command until run time. Perhaps > what I was trying to achieve is too close to self modifying code, I was > warned off this when I used to dabble in assembler. Does the same advice > hold for python? writing sel;f modifying code is so difficult to get right and so easy to be catastrophically wrong that its best avoided in any language. Even guru level programmers get that stuff wrong. But it sounds like you probably want data driven code which is (still tricky but) a lot easier. Tell us more with some examples of the data and we can probably help. > While your solution works, it's not how I imagined in terms of approach. > Eventually I wanted to change the command of a variable number of > buttons with the actual command depending on the results of a database > query. Sure, but the actual changing of the command will still look like my code I suspect. The tricky bit is creating the appropriate function object so that you can assign it,. The number of widgets is just a matter of a list and an iterator.... And remember, in a GUI everyting is event driven so you need to think about what event will trigger this reassignment of commands. You need the GUI in place and some kind of event catcher (button?, timer?) to handle the changeover. > attempting to do, and found with a slightly modified database query, I > didn't need to change the command at all. The rest of this bit of > program I have already solved. > Now I just have to learn a lot more about classes, and objects. OK, Glad you avoided the tricky stiff. Its very rarely needed. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Sun Jul 1 18:34:32 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 1 Jul 2018 23:34:32 +0100 Subject: [Tutor] how to change the command "string" on a tkinter Button? In-Reply-To: <86947ac6-440f-cd2d-9c18-500587e391bc@internode.on.net> References: <140dc3c6-2150-737a-fc09-df458a769833@internode.on.net> <1cf7d268-1eb8-55c7-872e-6ca28ad7ba2e@internode.on.net> <20180701091934.GW14437@ando.pearwood.info> <86947ac6-440f-cd2d-9c18-500587e391bc@internode.on.net> Message-ID: On 01/07/18 11:33, Chris Roy-Smith wrote: >> Even better would be to learn a form of VCS (version control system) > I don't know anything about these tools, VCS store versions of a file. You can check for differences between versions, restore previous versions, even merge different versions. Modst also allow you to freeze a collection of file versions for a release so that you can restore a previous version of your project. They are what all professional programmers use on big projects. One of the oldest and simplest VCS tools is RCS (Revision Control System). It basically has 2 commands: ci - checkin a file. co - check out a version. So you create a file and get it working. Create a folder in your project folder called RCS Check it in and keep a copy for editing ci -l myfile.py Now make changes until you have a new version check it in ci -l myfile.py Realize that you made a mistake, get the original version back co -l -v1.1 myfile.py and so on. At each check in the system will ask you to describe your changes There are other commands you can use to query the versions etc. The system only stores the differences between versions so doesn't use a huge amount of storage. https://www.gnu.org/software/rcs/ More recent systems work on servers across a network and tend to operate at the project/folder level rather than individual files, but the basic ideas remain the same. Steven mentioned Mercurial and Git, there is also Subversion(SVN) and CVS(based on RCS and by the same team). There are also commercial tools, some costing up to $1000 per seat! Its big business. One of the best is ClearCase (now owned by IBM?), nearly magical in its capabilities but very expensive! Some editors will have menu commands to automatically do the check in/out operations for you once you configure the tool and paths in the properties. > I use Kate as my editor Perfectly fine tool, no need to change unless you want to. > ...Idle only looks useful for CLI stuff. Not at all it has a full file editor and integrated interpreter so you can save your file and hit F5 to run the code with the output in the "shell window" (which is what appears at startup) Even better is IDLEX which has a lot of extra features such as tabbed editing windows, code folding, line numbering, intelligent paste from the shell, etc etc... Many IDLEX features are planned for future IDLE releases, but the approval process takes time. Meanwhile IDLEX is available here: http://idlex.sourceforge.net/features.html And all written in Python/Tkinter so a great place to learn Tkinter tricks! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From chris_roysmith at internode.on.net Sun Jul 1 21:54:08 2018 From: chris_roysmith at internode.on.net (Chris Roy-Smith) Date: Mon, 2 Jul 2018 11:54:08 +1000 Subject: [Tutor] why can use a widget assigned to a variable or just use it on it's own? Message-ID: <274d9715-ccb4-32a0-95ad-c1b3d13f1db1@internode.on.net> Hi, I'm trying to understand working with objects. If I have grasped things correctly a widget is an object. So why can I assign the widget, or use it stand alone? See sample code below ===================== #!/usr/bin/python3 from tkinter import * main=Tk() # as I understand it this will create an instance of the button widget called b1 b1=Button(main, text='instantce', command= lambda b='goodbye' : print(b)).grid(row=1, column=0) # but here I haven't made an instance, but all seems well Button(main, text='test1', command=lambda a='hello' :print(a)).grid(row=0, column=0) main.mainloop() ======================= any explanation gratefully recieved Regards, Chris ROy-Smith From timomlists at gmail.com Mon Jul 2 03:24:44 2018 From: timomlists at gmail.com (Timo) Date: Mon, 2 Jul 2018 09:24:44 +0200 Subject: [Tutor] why can use a widget assigned to a variable or just use it on it's own? In-Reply-To: <274d9715-ccb4-32a0-95ad-c1b3d13f1db1@internode.on.net> References: <274d9715-ccb4-32a0-95ad-c1b3d13f1db1@internode.on.net> Message-ID: Op 02-07-18 om 03:54 schreef Chris Roy-Smith: > Hi, > > I'm trying to understand working with objects. > > If I have grasped things correctly a widget is an object. So why can I > assign the widget, or use it stand alone? See sample code below > > ===================== > > #!/usr/bin/python3 > from tkinter import * > main=Tk() > > # as I understand it this will create an instance of the button widget > called b1 > b1=Button(main, text='instantce', command= lambda b='goodbye' : > print(b)).grid(row=1, column=0) > > > # but here I haven't made an instance, but all seems well > Button(main, text='test1', command=lambda a='hello' > :print(a)).grid(row=0, column=0) > You still create an instance, but don't assign it to a variable. See following example: class Foo: ??? def __init__(self): ??????? print("Instance created") f = Foo()? # prints "Instance created" Foo()? # print "Instance created" Two instances are created, just that the second one isn't accessible. Timo > main.mainloop() > > > ======================= > > any explanation gratefully recieved > > Regards, Chris ROy-Smith > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at yahoo.co.uk Mon Jul 2 03:40:19 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 2 Jul 2018 08:40:19 +0100 Subject: [Tutor] why can use a widget assigned to a variable or just use it on it's own? In-Reply-To: <274d9715-ccb4-32a0-95ad-c1b3d13f1db1@internode.on.net> References: <274d9715-ccb4-32a0-95ad-c1b3d13f1db1@internode.on.net> Message-ID: On 02/07/18 02:54, Chris Roy-Smith wrote: > If I have grasped things correctly a widget is an object. Every value in Python is an object. numbers, strings, lists, functions, instances of classes. All are objects. You can see that by using the dir() function on them: >>> dir(5) ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] >>> dir(print) ['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__'] >>> Those are all the attributes and methods/operations that you can access for a number and a function. And so, yes, widgets are also objects...They are instances of classes. > from tkinter import * > main=Tk() main is now a reference to an instance of the top level Tkinter class, Tk. > # as I understand it this will create an instance of the button widget > called b1 > b1=Button(main, text='instantce', command= lambda b='goodbye' : > print(b)).grid(row=1, column=0) No, this will create an instance of the Button class but it will not be called b1. You call grid() on your instance and grid always returns None. So b1 stores a reference to None. (Note that None is also an object!) > # but here I haven't made an instance, but all seems well > Button(main, text='test1', command=lambda a='hello' > :print(a)).grid(row=0, column=0) You have made an instance, exactly like before. The instance is created by you calling the class: Button(.....) # creates an instance b = Button(.....) ' creates instance and stores a reference in b b = Button(...).grid() # creates instance and # calls its grid method returning None to b Everything works because when you create a widget instance the first argument is always the parent widget. Inside the widget __init__() method the code looks something like this: def __init__(...): parent.children.append(self) .... So one of the first things the widget does is add itself to its parent's list of child widgets. That means that there is a reference to the widget inside parent whether you store a local reference or not. As a result the widget is not immediately destroyed. > any explanation gratefully received Hopefully that helps. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Mon Jul 2 03:47:09 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 2 Jul 2018 08:47:09 +0100 Subject: [Tutor] how to change the command "string" on a tkinter Button? In-Reply-To: References: <140dc3c6-2150-737a-fc09-df458a769833@internode.on.net> <1cf7d268-1eb8-55c7-872e-6ca28ad7ba2e@internode.on.net> <20180701091934.GW14437@ando.pearwood.info> <86947ac6-440f-cd2d-9c18-500587e391bc@internode.on.net> Message-ID: On 01/07/18 23:34, Alan Gauld via Tutor wrote: > Realize that you made a mistake, get the original > version back > > co -l -v1.1 myfile.py Oops, a bit rusty. The command should be: co -l1.1 myfile.py -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Mon Jul 2 07:21:04 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 2 Jul 2018 21:21:04 +1000 Subject: [Tutor] why can use a widget assigned to a variable or just use it on it's own? In-Reply-To: <274d9715-ccb4-32a0-95ad-c1b3d13f1db1@internode.on.net> References: <274d9715-ccb4-32a0-95ad-c1b3d13f1db1@internode.on.net> Message-ID: <20180702112104.GA14437@ando.pearwood.info> On Mon, Jul 02, 2018 at 11:54:08AM +1000, Chris Roy-Smith wrote: > Hi, > > I'm trying to understand working with objects. > > If I have grasped things correctly a widget is an object. In Python, all values are objects. (That's not the case in all languages.) > So why can I > assign the widget, or use it stand alone? See sample code below That depends on the object, but in general, you can use any object you like even if it doesn't survive the experience. Python knows enough to only access objects which are still alive. That's *incredibly common* for small, lightweight values like floats and strings. We might say: print(math.sin(1.3*math.pi) + 1) which creates (and then destroys) the following transient objects: * the float 1.3 * then the float 4.084070449666731 (multiplying the above by pi) * then the float -0.8090169943749473 (calling sin on the above) * then 0.19098300562505266 (adding 1) none of which survive more than a few microseconds. By the time the final value is printed, all of those transient objects will have been reclaimed for recycling by the garbage collector, their memory ready for re-use. The same applies for big, complex objects. But under normal circumstances, the bigger and more complex, the more unlikely you are to treat it as a transient, disposable object. (Creating lightweight objects is cheap, but the bigger the object, the less cheap it is.) In the case of tkinter, things are even more murky. Like many (all?) GUI frameworks, tkinter does a lot of behind the scenes clever stuff that makes it easier to use at the cost of being less comprehensible. And so: > # as I understand it this will create an instance of the button widget > called b1 > b1=Button(main, text='instantce', command= lambda b='goodbye' : > print(b)).grid(row=1, column=0) Actually, no, if you print the value of b1 -- or print its repr, print(repr(b1)) -- you might be in for a surprise. Your b1 is not actually the button, but the None object. But don't worry, the button object itself is safely attached to the TK main window, as if by magic. (That's tkinter's magic: the first argument to the Button constructor is the window to attach it to.) > # but here I haven't made an instance, but all seems well > Button(main, text='test1', command=lambda a='hello' > :print(a)).grid(row=0, column=0) Indeed. You don't have to hold onto the button, because the main window does it for you. -- Steve From luizgustavo at luizgustavo.pro.br Mon Jul 2 12:48:01 2018 From: luizgustavo at luizgustavo.pro.br (Luiz Gustavo S. Costa) Date: Mon, 2 Jul 2018 17:48:01 +0100 Subject: [Tutor] Pip install and Ipv6 Message-ID: Hello, Is anyone else here having problems using Pip repository with ipv6? If I try to install something with pip, I get this: (python2) lgcosta:api/ $ pip install falcon Collecting falcon Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', error(104, 'Connection reset by peer'))': /simple/falcon/ and it does not work ... but, I discovered this: (python2) lgcosta:api/ $ curl -I https://pypi.python.org/ curl: (35) gnutls_handshake() failed: Error in the pull function. (python2) lgcosta:api/ $ host pypi.python.org pypi.python.org is an alias for dualstack.python.map.fastly.net. dualstack.python.map.fastly.net has address 151.101.16.223 dualstack.python.map.fastly.net has IPv6 address 2a04:4e42:4::223 My default output is ipv6, so if I force it out by ipv4, it works: (python2) lgcosta:api/ $ curl -I -4 https://pypi.python.org/ HTTP/1.1 301 Redirect to Primary Domain Server: Varnish Retry-After: 0 Location: https://pypi.org/ Content-Type: text/html; charset=UTF-8 Content-Length: 122 .... output over ipv6, the repository does not work, only for ipv4. I did not find the option to force ipv4 on the pip. Does anyone have any notice or similar reports? Thanks ! -- Luiz Gustavo Costa (Powered by BSD) *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+ ICQ: 2890831 / Gtalk: gustavo.bsd at gmail.com Blog: http://www.luizgustavo.pro.br From darylheppner at gmail.com Mon Jul 2 16:06:47 2018 From: darylheppner at gmail.com (Daryl Heppner) Date: Mon, 2 Jul 2018 16:06:47 -0400 Subject: [Tutor] Need all values from while loop - only receiving one Message-ID: Hi folks, I'm trying to calculate the amount of rent per lease for the life of the lease, by month. The following code provides the correct results except for the monthnum and billper. Monthnum is intended to show the month within the lease and the billper should list each date for rent billing. For example, if the lease commences May 1, 2018 for a 60 month term, 2018-05-01 is monthnum = 1 and the billper = 2018-05-01. The following 59 rows needs to increment the monthnum and billper values by 1. The while loop (below) returns the first value correctly but stops without continuing through the rest of the True matches. Code (see below for results): import xml.etree.ElementTree as ET import pyodbc import dateutil.relativedelta as rd import dateutil.parser as pr tree = ET.parse('DealData.xml') root = tree.getroot() for deal in root.findall("Deals"): for dl in deal.findall("Deal"): dealid = dl.get("DealID") for dts in dl.findall("DealTerms/DealTerm"): dtid = dts.get("ID") dstart = pr.parse(dts.find("CommencementDate").text) dterm = dts.find("LeaseTerm").text darea = dts.find("RentableArea").text for brrent in dts.findall("BaseRents/BaseRent"): brid = brrent.get("ID") begmo = int(brrent.find("BeginIn").text) if brrent.find("Duration").text is not None: duration = int(brrent.find("Duration").text) else: duration = 0 brentamt = brrent.find("Rent").text brper = brrent.find("Period").text perst = dstart + rd.relativedelta(months=begmo-1) perend = perst + rd.relativedelta(months=duration-1) billmocount = begmo while billmocount < duration: monthnum = billmocount billmocount += 1 billmo = perst while billmo < perend: billper = billmo billmo += rd.relativedelta(months=1) if dealid == "706880": print(dealid, dtid, brid, begmo, dstart, dterm, darea, brentamt, brper, duration, perst, perend, \ monthnum, billper) Results: 706880 4278580 45937180 1 2018-01-01 00:00:00 60 6200 15.0 rsf/year 36 2018-01-01 00:00:00 2020-12-01 00:00:00 35 2020-11-01 00:00:00 706880 4278580 45937181 37 2018-01-01 00:00:00 60 6200 18.0 rsf/year 24 2021-01-01 00:00:00 2022-12-01 00:00:00 35 2022-11-01 00:00:00 Any help is appreciated! Thank you, Daryl From alan.gauld at yahoo.co.uk Mon Jul 2 17:51:06 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 2 Jul 2018 22:51:06 +0100 Subject: [Tutor] Need all values from while loop - only receiving one In-Reply-To: References: Message-ID: On 02/07/18 21:06, Daryl Heppner wrote: > I'm trying to calculate the amount of rent per lease for the life of > the lease, by month. The following code provides the correct results > except for the monthnum and billper. > The while loop (below) returns the first value correctly but stops > without continuing through the rest of the True matches. Which whiole loop? There are two. > for dl in deal.findall("Deal"): > dealid = dl.get("DealID") > for dts in dl.findall("DealTerms/DealTerm"): > dtid = dts.get("ID") > dstart = pr.parse(dts.find("CommencementDate").text) > dterm = dts.find("LeaseTerm").text > darea = dts.find("RentableArea").text I'm a bit confused by this loop. You go round and round overwriting the same values but not doing anything with them? They eventually wind up weith the last value read. Is that really what you want? > for brrent in dts.findall("BaseRents/BaseRent"): > brid = brrent.get("ID") > begmo = int(brrent.find("BeginIn").text) > if brrent.find("Duration").text is not None: > duration = int(brrent.find("Duration").text) > else: > duration = 0 > brentamt = brrent.find("Rent").text > brper = brrent.find("Period").text > perst = dstart + rd.relativedelta(months=begmo-1) > perend = perst + rd.relativedelta(months=duration-1) > billmocount = begmo This is basically the same in that only the last value will be stored because you overwrite the same variables each time. > while billmocount < duration: > monthnum = billmocount > billmocount += 1 And this too is odd. You set monthnum to billmocount Then you increment billmocount Then you go round and do the same until billmocount equals duration(or somehow is slightly greater than), at which point monthnum is one less than billmo. So, assuming integer values are used, you could replace the loop with: billmocount = duration monthnum = billmocount -1 If it's floats then its only slightly more complex to work out the values directly. > billmo = perst > while billmo < perend: > billper = billmo > billmo += rd.relativedelta(months=1) And again here. billmo winds up equal or greater than perend and billper has the value billmo - rd.relativedelta(months=1) It would be more efficient to write billmo = perst delta = rd.relativedelta(months=1) while billmo < perend: billmo += delta billper = billmo - delta > if dealid == "706880": > print(dealid, dtid, brid, begmo, dstart, dterm, > darea, brentamt, brper, duration, perst, perend, \ > monthnum, billper) > I'm not clear what you think you are doing but it looks fundamentally flawed to me. I think you need a rethink of your design. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From jonesadam581 at gmail.com Tue Jul 3 01:23:49 2018 From: jonesadam581 at gmail.com (Adam Jones) Date: Tue, 3 Jul 2018 07:23:49 +0200 Subject: [Tutor] Help Message-ID: Good day, I am currently checking a piece of arcpy code. Where a point is shifted within a set distance to protect the privacy of said point. Please see the code below, and please advise me or correct the code where it is needed # Step 11 - SELECT By Attributes -> where FID == FID_1, export to new Feature Class # ------------------------------------------------------------------------------------------------------------------ # Make a layer from the feature class arcpy.MakeFeatureLayer_management(in_features="RDiff_AreaIntersect_Dissolve", out_layer="lyr_eaten", where_clause="", workspace="", field_info= "OBJECTID OBJECTID VISIBLE NONE", "Shape Shape VISIBLE NONE", "ORIG_FID ORIG_FID VISIBLE NONE", "FIRST_Join_Count FIRST_Join_Count VISIBLE NONE" FIRST_OBJECTID_1 (VISIBLE NONE;FIRST_gps_latitu FIRST_gps_latitu VISIBLE NONE; FIRST_gps_longit; FIRST_gps_longit VISIBLE NONE;FIRST_OBJECTID FIRST_OBJECTID VISIBLE NONE; FIRST_R1 FIRST_R1 VISIBLE NONE;FIRST_ORIG_FID FIRST_ORIG_FID VISIBLE NONE;Shape_Length Shape_Length VISIBLE NONE; Shape_Area Shape_Area VISIBLE NONE) # SELECT by attribute arcpy.SelectLayerByAttribute_management(in_layer_or_view="lyr_eaten", selection_type="NEW_SELECTION", where_clause="FID_RDiffBuffer = ORIG_FID") # Write the selected features to a new featureclass arcpy.CopyFeatures_management(in_features="lyr_eaten",out_feature_class="C:/Users/Claudinho/Desktop/2016/ GIS_702/COPC_DATA/Altered_Data_sets/702.gdb/DonutFile", config_keyword="", spatial_grid_1="0", spatial_grid_2="0", spatial_grid_3="0") # ------------------------------------------------------------------------------------------------------------------ # Step 12 - CreateRandomPoint constrained by DonutFile # ------------------------------------------------------------------------------------------------------------------ arcpy.CreateRandomPoints_management(out_path="C:/Users/Claudinho/Desktop/2016/GIS_702/COPC_DATA/ Altered_Data_sets/702.gdb", out_name="RandomFile", constraining_feature_class="DonutFile", constraining_extent="0 0 250 250", number_of_points_or_field="1", minimum_allowed_distance="0 Meters", create_multipoint_output="POINT", multipoint_size="0") # JOIN RandomFile (CID) to DonutFile (OBJECTID) arcpy.JoinField_management(in_data="RandomFile", in_field="CID", join_table="DonutFile", join_field="OBJECTID", fields="") # DELETE unnecessary fields in RandomFile arcpy.DeleteField_management(in_table="RandomFile", drop_field="FIRST_OBJECTID_1;FIRST_FID_RDiffBuffer; FIRST_gps_latitu;FIRST_gps_longit;") Regards Adam From alan.gauld at yahoo.co.uk Tue Jul 3 03:55:00 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 3 Jul 2018 08:55:00 +0100 Subject: [Tutor] Help In-Reply-To: References: Message-ID: On 03/07/18 06:23, Adam Jones wrote: > Good day, I am currently checking a piece of arcpy code. Where a point is > shifted within a set distance to protect the privacy of said point. Please > see the code below, and please advise me or correct the code where it is > needed It would help us to help you if you explain what the problem is. Do you get an error message(if so include it). Is the data wrong (if so tell us what you expected and what you got) Do not assume we know much about arcpy, that's not part of standard Python, so you need to tell us what you are doing with it. > # Step 11 - SELECT By Attributes -> where FID == FID_1, export to new > Feature Class > # > ------------------------------------------------------------------------------------------------------------------ > # Make a layer from the feature class > arcpy.MakeFeatureLayer_management(in_features="RDiff_AreaIntersect_Dissolve", > out_layer="lyr_eaten", > where_clause="", > workspace="", > field_info= "OBJECTID OBJECTID VISIBLE NONE", "Shape Shape VISIBLE NONE", > "ORIG_FID ORIG_FID VISIBLE NONE", "FIRST_Join_Count FIRST_Join_Count > VISIBLE NONE" > FIRST_OBJECTID_1 (VISIBLE NONE;FIRST_gps_latitu FIRST_gps_latitu VISIBLE > NONE; > FIRST_gps_longit; FIRST_gps_longit VISIBLE NONE;FIRST_OBJECTID > FIRST_OBJECTID VISIBLE NONE; > FIRST_R1 FIRST_R1 VISIBLE NONE;FIRST_ORIG_FID FIRST_ORIG_FID VISIBLE > NONE;Shape_Length Shape_Length VISIBLE NONE; > Shape_Area Shape_Area VISIBLE NONE) I would expect the above to give a syntax error because it doesn't look like valid Python. It starts out as a sequence of arguments but then semi colons start appearing in strange places amid a function call. And the parens don't seem to match either. All very odd. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Tue Jul 3 03:42:20 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 3 Jul 2018 08:42:20 +0100 Subject: [Tutor] Need all values from while loop - only receiving one In-Reply-To: References: Message-ID: <9565a845-caec-bdea-965a-939b871aa858@yahoo.co.uk> On 02/07/18 23:52, Daryl Heppner wrote: > The two While Loops are the part I'm struggling with. The goal is to > list each bill month number and date for each month in the term. When you need multiple values you need to use a collection type such as a list or tuple. Your problem is that you are using single valued variables to collect data but as you go round the loops (not just the while loops) you are throwing away the data you have already collected so that when the loop ends you only have the last set of values. > this example, I'm trying to return 36 rows, listed from 1-36 instead > of one row followed by 24 rows numbered 37 to 60. Personally I'd create a dictionary per row and store those dictionaries in a list. (You could use a class instead of a dictionary but I'm guessing that might be too big a step for a beginner.) I'd also put all the parsing code into a function so that you pass it the raw xml and get back the row dictionary. That should simplify the structure of your code significantly and make it easier to see what's going on. It should also be easier to test the function on its own with some sample xml. If you need more help with that let us know. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From bellamybaron87 at gmail.com Tue Jul 3 09:48:03 2018 From: bellamybaron87 at gmail.com (Bellamy Baron) Date: Tue, 3 Jul 2018 15:48:03 +0200 Subject: [Tutor] C++ or Python? Message-ID: Hi, I have heard C++ is faster than python and I have a few questions 1.Is there a way to make python run just as fast 2.can I get in a serious game making team like 343 by using python 3. if C++ is better where can I get good 3d model libraries and libraries that make coding in C++ faster 4. Is there a way to transfer python files to C++ Thanks -- -------------------------------------------------------------------------------------------------------- Bellamy iWYZE https://www.iwyze.co.za/products/car-insurance From howardbandy at gmail.com Tue Jul 3 13:06:21 2018 From: howardbandy at gmail.com (Howard B) Date: Tue, 3 Jul 2018 10:06:21 -0700 Subject: [Tutor] C++ or Python? In-Reply-To: References: Message-ID: Greetings -- Faster to do what? Develop faster? Run faster? Debug faster? In my experience, making the development and eventual debugging of programs as easy and quick as possible is very important. My experience and advice has been to design a clear algorithm, then program it in as clear and straightforward a manner as possible in a language that has good support. Test the program for correctness. After it works as hoped, test it for speed. Only then, and only if necessary, analyze, profile, and optimize the code for speed. Keep in mind that modifying the program to increase speed will make it less clear and will probably make it more difficult to maintain, even by its original programmer. That said, Python is much easier to code and to debug than C++ (I have considerable experience with both). When necessary, identify the portions of the program that are the bottleneck and optimize them in a step-by-step manner -- most constricting bottleneck first, then reevaluate, etc. That optimization may be as simple as replacing Python routines with Cython routines. http://cython.readthedocs.io/en/latest/src/tutorial/cython_tutorial.html Best, Howard (50 years in computing, including commercial programming and university professor) On Tue, Jul 3, 2018 at 9:26 AM Bellamy Baron wrote: > Hi, > > I have heard C++ is faster than python and I have a few questions > 1.Is there a way to make python run just as fast > 2.can I get in a serious game making team like 343 by using python > 3. if C++ is better where can I get good 3d model libraries and libraries > that make coding in C++ faster > 4. Is there a way to transfer python files to C++ > > Thanks > > -- > > -------------------------------------------------------------------------------------------------------- > Bellamy > iWYZE > https://www.iwyze.co.za/products/car-insurance > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From leamhall at gmail.com Tue Jul 3 13:24:41 2018 From: leamhall at gmail.com (Leam Hall) Date: Tue, 3 Jul 2018 13:24:41 -0400 Subject: [Tutor] C++ or Python? In-Reply-To: References: Message-ID: Howard is right. You will produce actual code doing actual stuff much faster with Python than with C++. There are ways to resolve performance bottlenecks but most people don't actually hit those sorts of issues. Leam On 07/03/2018 01:06 PM, Howard B wrote: > Greetings -- > > Faster to do what? Develop faster? Run faster? Debug faster? > > In my experience, making the development and eventual debugging of programs > as easy and quick as possible is very important. My experience and advice > has been to design a clear algorithm, then program it in as clear and > straightforward a manner as possible in a language that has good support. > Test the program for correctness. After it works as hoped, test it for > speed. Only then, and only if necessary, analyze, profile, and optimize > the code for speed. Keep in mind that modifying the program to increase > speed will make it less clear and will probably make it more difficult to > maintain, even by its original programmer. > > That said, Python is much easier to code and to debug than C++ (I have > considerable experience with both). When necessary, identify the portions > of the program that are the bottleneck and optimize them in a step-by-step > manner -- most constricting bottleneck first, then reevaluate, etc. That > optimization may be as simple as replacing Python routines with Cython > routines. > http://cython.readthedocs.io/en/latest/src/tutorial/cython_tutorial.html > > Best, Howard (50 years in computing, including commercial programming > and university professor) > > > On Tue, Jul 3, 2018 at 9:26 AM Bellamy Baron > wrote: > >> Hi, >> >> I have heard C++ is faster than python and I have a few questions >> 1.Is there a way to make python run just as fast >> 2.can I get in a serious game making team like 343 by using python >> 3. if C++ is better where can I get good 3d model libraries and libraries >> that make coding in C++ faster >> 4. Is there a way to transfer python files to C++ >> >> Thanks >> >> -- >> >> -------------------------------------------------------------------------------------------------------- >> Bellamy >> iWYZE >> https://www.iwyze.co.za/products/car-insurance >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From alan.gauld at yahoo.co.uk Tue Jul 3 13:58:51 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 3 Jul 2018 18:58:51 +0100 Subject: [Tutor] C++ or Python? In-Reply-To: References: Message-ID: On 03/07/18 14:48, Bellamy Baron wrote: > I have heard C++ is faster than python and I have a few questions > 1.Is there a way to make python run just as fast Kind of. Nearly. But its limited to specific types of program. The most common approach is to identify the slow bits and rewrite them in C++ then expose that code to python as a library. You then call the C++ code from your Python program. That's how most of the core libraries are written. Most programs only need C++ speed for a tiny part of their functionality. Python is about speed of development not speed of execution. For most programming tasks modern computers mean that Python is fast enough. But games (or certain types of games) are one of the exceptions to that generalisation. > 2.can I get in a serious game making team like 343 by using python No idea, never even heard of them. But in general games programmers tend to favour C++. > 3. if C++ is better where can I get good 3d model libraries and libraries > that make coding in C++ faster You'd need to ask C++ programmers, and probably more specifically other games programmers. Gamers have very unique programming needs which is why many universities teach games programming as a separate course. The graphics libraries they use are likely to be different from the ones used by, for example, Adobe to create Photoshop... > 4. Is there a way to transfer python files to C++ If you mean convert then no, not directly. But projects like Cython allow you to write Python-like code that turns into C code eventually. Its very clever but not likely what you are looking for. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From darylheppner at gmail.com Tue Jul 3 15:39:08 2018 From: darylheppner at gmail.com (Daryl Heppner) Date: Tue, 3 Jul 2018 15:39:08 -0400 Subject: [Tutor] Need all values from while loop - only receiving one In-Reply-To: <9565a845-caec-bdea-965a-939b871aa858@yahoo.co.uk> References: <9565a845-caec-bdea-965a-939b871aa858@yahoo.co.uk> Message-ID: Again thank you so much! I truly appreciate your direction! The idea of a class is something I'd unsuccessfully tried but I'm up for the challenge! I'm very comfortable in Transact SQL but OOP is new to me. Here's my updated code with a sample XML. The full XML file is over 600K rows. I'd appreciate any feedback. Daryl import xml.etree.ElementTree as ET import pyodbc import dateutil.relativedelta as rd import dateutil.parser as pr from dateutil.rrule import rrule, MONTHLY tree = ET.parse(r'\\DealData.xml') root = tree.getroot() class BillDate: def __init__(self, begin, end): self.current = begin self.end = end def __iter__(self): return self def __next__(self): if self.current < self.end: billmo = self.current self.current += rd.relativedelta(months=1) return billmo else: raise StopIteration for deal in root.findall("Deals"): for dl in deal.findall("Deal"): dealid = dl.get("DealID") for dts in dl.findall("DealTerms/DealTerm"): dtid = dts.get("ID") dstart = pr.parse(dts.find("CommencementDate").text) dterm = int(dts.find("LeaseTerm").text) darea = dts.find("RentableArea").text for brrent in dts.findall("BaseRents/BaseRent"): brid = brrent.get("ID") begmo = int(brrent.find("BeginIn").text) if brrent.find("Duration").text is not None: duration = int(brrent.find("Duration").text) else: duration = 0 brentamt = brrent.find("Rent").text brper = brrent.find("Period").text perst = dstart + rd.relativedelta(months=begmo-1) perend = perst + rd.relativedelta(months=duration-1) months = [dt.strftime("%Y-%m-%d") for dt in rrule(MONTHLY, dtstart=perst, until=perend)] for billdt in BillDate(perst, perend): billdt if dealid == "706880": print(dealid, dtid, brid, begmo, dstart, dterm, darea, brentamt, brper, duration, perst, \ perend, billdt) c03528f241fdc8e4 12345_Place - Bldg 1 2015-10-28T04:09:07Z 2018-04-24T21:56:25Z SourceID 12345~12345
Calgary AB 1234 5 Ave S.W. T3P 0N7 Canada
800 11225 8 7 2016-04-20T13:47:13Z 2017-10-02T09:17:20Z SourceID 800
new 2017-12-20T22:36:21Z 2017-06-06T15:09:35Z dead_deal 0 2017-12-01 Office Tenant Name financial services 1013325 6000 7000 proposal 2017-06-06T15:09:35Z 2017-06-06T15:09:22Z 2017-06-06T15:09:22Z 2017-12-20 197 17699 Jessica Rabbit jessica.rabbit at themovie.com dead_deal 2017-12-20T22:36:01Z 2017-12-20T22:36:01Z 2017-12-20T22:36:01Z 2017-12-20 0 24934 Leigh Vaughan leigh.vaughan at emails.com dead_deal 2017-12-20T22:36:21Z 2017-12-20T22:36:21Z 2017-12-20T22:36:21Z 169 price 24934 Leigh Vaughan leigh.vaughan at emails.com landlord 0.08 6200 triple net 60 2018-01-01 2017-06-06T15:16:23Z 20714.1144670763 2017-06-06 7.45 103367.15936951 640876388.09096 642137720.0 502200.0 64480.0 1 true 1 15.0 rsf/year 36 37 18.0 rsf/year 24 landlord Company1 2.9 rsf landlord Company2 7.5 rsf 186607 2017-06-06 ReimbursableExpenseCam 12.87 net 12.87 RealEstateTax 7.45 net 7.45
On Tue, Jul 3, 2018 at 3:42 AM Alan Gauld wrote: > > On 02/07/18 23:52, Daryl Heppner wrote: > > The two While Loops are the part I'm struggling with. The goal is to > > list each bill month number and date for each month in the term. > When you need multiple values you need to use a collection > type such as a list or tuple. Your problem is that you are using > single valued variables to collect data but as you go round the > loops (not just the while loops) you are throwing away the data > you have already collected so that when the loop ends you only > have the last set of values. > > > > this example, I'm trying to return 36 rows, listed from 1-36 instead > > of one row followed by 24 rows numbered 37 to 60. > > Personally I'd create a dictionary per row and store those > dictionaries in a list. (You could use a class instead of a dictionary > but I'm guessing that might be too big a step for a beginner.) > > I'd also put all the parsing code into a function so that you > pass it the raw xml and get back the row dictionary. > > That should simplify the structure of your code significantly > and make it easier to see what's going on. It should also be > easier to test the function on its own with some sample xml. > > If you need more help with that let us know. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > From noflaco at gmail.com Tue Jul 3 12:30:21 2018 From: noflaco at gmail.com (Carlton Banks) Date: Tue, 3 Jul 2018 18:30:21 +0200 Subject: [Tutor] C++ or Python? In-Reply-To: References: Message-ID: tir. 3. jul. 2018 18.25 skrev Bellamy Baron : > Hi, > > I have heard C++ is faster than python and I have a few questions > 1.Is there a way to make python run just as fast > Look Up cpython might be a bit faster 2.can I get in a serious game making team like 343 by using python > No > 3. if C++ is better where can I get good 3d model libraries and libraries > that make coding in C++ faster > Unity Maybe? > 4. Is there a way to transfer python files to C++ > What files? - they use different compilers.. > > Thanks > Np :) > -- > > -------------------------------------------------------------------------------------------------------- > Bellamy > iWYZE > https://www.iwyze.co.za/products/car-insurance > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From alan.gauld at yahoo.co.uk Tue Jul 3 20:08:36 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 4 Jul 2018 01:08:36 +0100 Subject: [Tutor] Need all values from while loop - only receiving one In-Reply-To: References: <9565a845-caec-bdea-965a-939b871aa858@yahoo.co.uk> Message-ID: On 03/07/18 20:39, Daryl Heppner wrote: > The idea of a class is something I'd unsuccessfully tried but I'm up > for the challenge! I'm very comfortable in Transact SQL but OOP is > new to me. OK, What I meant by using a class was to define one (or more?) that encompassed all the data in one Deal. Then have the init method take a row of XML and populate all the fields. Something like this (Note this is not pretending to be correct, its just your own code reformed slightly): class DealTerm: def __init__(self,xml_dt): self.id = xml_dt.get("ID") self.start = pr.parse(dts.find("CommencementDate").text) self.term = int(xml_dt.find("LeaseTerm").text) self.area = xml_dt.find("RentableArea").text self.baseRents = [BaseRent(br) for br in xml_dt.findall("BaseRents/BaseRent")] class BaseRent: def __init__(self, xml_br): self.id = xml_br.get("ID") self.begmo = int(xml_br.find("BeginIn").text) if xml_br.find("Duration").text is not None: duration = int(xml_br.find("Duration").text) else: duration = 0 self.amt = xml_br.find("Rent").text self.per = xml_br.find("Period").text self.perst = dstart + rd.relativedelta(months=begmo-1) self.perend = perst + rd.relativedelta(months=duration-1) self.months = [dt.strftime("%Y-%m-%d") for dt in rrule(MONTHLY, dtstart=perst, until=perend)] class Deal: def __init__(self, dl): # use XT to parse the xml string self.id = dl.get("DealID") self.terms = [DealTerm(dts) for dts in dl.findall("DealTerms/DealTerm")] for billdt in BillDate(perst, perend): billdt def __str__(self): # returns string for print() etc ''' only uses first term value for convenience''' return self.id + terms[0].id + terms[0].baseRents[0].id + ... # The billdt line above makes no sense since it will do nothing. # Although in the >>> interpreter it would display the value # in a script it will do nothing. # I'm also not sure if the loop should be part of the # BaseRent or the DealTerm or the Deal. I suspect it # should be in BaseRent but I've left it where it was for now! # Now the main code just needs the outer loops: tree = ET.parse(r'\\DealData.xml') root = tree.getroot() deals = [] for deal in root.findall("Deals"): for dl in deal.findall("Deal"): deals.append( Deal(dl) ) if dl.id == "706880": print(dl) #uses __str__() to create string Hopefully you can see how, by putting the xml parsing into the classes that represent the actual real-world data objects that you are dealing with you simplify the logic of the higher level code and make it clearer what is being read and where? Notice also that in Deal I'm using a list to hold the DealTerms. And in DealTerm I use a list to hold the BaseRents. That way we don't just throw away the early values as your code currently does. You can extend this to cover the other data blocks in your XML if necessary, eg. Commission, Tenant, User etc. > Here's my updated code with a sample XML. The full XML > file is over 600K rows. > > I'd appreciate any feedback. > > Daryl > > import xml.etree.ElementTree as ET > import pyodbc > import dateutil.relativedelta as rd > import dateutil.parser as pr > from dateutil.rrule import rrule, MONTHLY > > tree = ET.parse(r'\\DealData.xml') > root = tree.getroot() > > class BillDate: > def __init__(self, begin, end): > self.current = begin > self.end = end > > def __iter__(self): > return self > > def __next__(self): > if self.current < self.end: > billmo = self.current > self.current += rd.relativedelta(months=1) > return billmo > else: > raise StopIteration Since this acts like a virtual collection you should probably call it BillDates - plural. Then the for loop reads more naturally as for date in BillDates(start, end): # do something with each date > > > for deal in root.findall("Deals"): > for dl in deal.findall("Deal"): > dealid = dl.get("DealID") > for dts in dl.findall("DealTerms/DealTerm"): > dtid = dts.get("ID") > dstart = pr.parse(dts.find("CommencementDate").text) > dterm = int(dts.find("LeaseTerm").text) > darea = dts.find("RentableArea").text > for brrent in dts.findall("BaseRents/BaseRent"): > brid = brrent.get("ID") > begmo = int(brrent.find("BeginIn").text) > if brrent.find("Duration").text is not None: > duration = int(brrent.find("Duration").text) > else: > duration = 0 > brentamt = brrent.find("Rent").text > brper = brrent.find("Period").text > perst = dstart + rd.relativedelta(months=begmo-1) > perend = perst + rd.relativedelta(months=duration-1) > months = [dt.strftime("%Y-%m-%d") for dt in rrule(MONTHLY, > dtstart=perst, until=perend)] > for billdt in BillDate(perst, perend): > billdt > > if dealid == "706880": > print(dealid, dtid, brid, begmo, dstart, dterm, darea, > brentamt, brper, duration, perst, \ > perend, billdt) > > > > c03528f241fdc8e4 > > > > > 12345_Place - Bldg 1 > 2015-10-28T04:09:07Z > 2018-04-24T21:56:25Z > > SourceID > 12345~12345 > >
> Calgary > AB > 1234 5 Ave S.W. > T3P 0N7 > Canada >
> > > 800 > 11225 > 8 > 7 > > > 2016-04-20T13:47:13Z > 2017-10-02T09:17:20Z > > SourceID > 800 > > > >
>
> new > 2017-12-20T22:36:21Z > 2017-06-06T15:09:35Z > dead_deal > 0 > > > 2017-12-01 > Office > > Tenant Name > financial services > > > 1013325 > > > > > 6000 > 7000 > > > > > > proposal > 2017-06-06T15:09:35Z > 2017-06-06T15:09:22Z > 2017-06-06T15:09:22Z > 2017-12-20 > 197 > > > 17699 > Jessica > Rabbit > jessica.rabbit at themovie.com > > > > > > > > dead_deal > 2017-12-20T22:36:01Z > 2017-12-20T22:36:01Z > 2017-12-20T22:36:01Z > 2017-12-20 > 0 > > > 24934 > Leigh > Vaughan > leigh.vaughan at emails.com > > > > > > > > dead_deal > 2017-12-20T22:36:21Z > 2017-12-20T22:36:21Z > 2017-12-20T22:36:21Z > 169 > > price > > > 24934 > Leigh > Vaughan > leigh.vaughan at emails.com > > > > > > > > > > > landlord > 0.08 > 6200 > triple net > 60 > 2018-01-01 > > > > 2017-06-06T15:16:23Z > > > 20714.1144670763 > > > 2017-06-06 > > > > > > > > > > > 7.45 > > > > > > > 103367.15936951 > 640876388.09096 > > > 642137720.0 > 502200.0 > 64480.0 > 1 > > > true > > > 1 > 15.0 > rsf/year > 36 > > > 37 > 18.0 > rsf/year > 24 > > > > > > > landlord > Company1 > 2.9 > rsf > > > landlord > Company2 > 7.5 > rsf > > > > 186607 > 2017-06-06 > > > ReimbursableExpenseCam > 12.87 > net > 12.87 > > > > RealEstateTax > 7.45 > net > 7.45 > > > > > > > > >
>
>
-- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Tue Jul 3 20:15:40 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 4 Jul 2018 01:15:40 +0100 Subject: [Tutor] Need all values from while loop - only receiving one In-Reply-To: References: <9565a845-caec-bdea-965a-939b871aa858@yahoo.co.uk> Message-ID: On 04/07/18 01:08, Alan Gauld via Tutor wrote: > # Now the main code just needs the outer loops: > tree = ET.parse(r'\\DealData.xml') > root = tree.getroot() > deals = [] > for deal in root.findall("Deals"): > for dl in deal.findall("Deal"): > deals.append( Deal(dl) ) > > if dl.id == "706880": > print(dl) #uses __str__() to create string Sorry, that last loop should be like this: for xml_dl in deal.findall("Deal"): theDeal = Deal(xml_dl) deals.append( theDeal ) if theDeal.id == "706880": print(theDeal) #uses __str__() to create string -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From breamoreboy at gmail.com Wed Jul 4 04:29:55 2018 From: breamoreboy at gmail.com (Mark Lawrence) Date: Wed, 4 Jul 2018 09:29:55 +0100 Subject: [Tutor] C++ or Python? In-Reply-To: References: Message-ID: On 03/07/18 17:30, Carlton Banks wrote: > tir. 3. jul. 2018 18.25 skrev Bellamy Baron : > >> Hi, >> >> I have heard C++ is faster than python and I have a few questions >> 1.Is there a way to make python run just as fast >> > Look Up cpython might be a bit faster > Really, or did you mean cython? :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From darylheppner at gmail.com Wed Jul 4 07:08:17 2018 From: darylheppner at gmail.com (Daryl Heppner) Date: Wed, 4 Jul 2018 07:08:17 -0400 Subject: [Tutor] Need all values from while loop - only receiving one In-Reply-To: References: <9565a845-caec-bdea-965a-939b871aa858@yahoo.co.uk> Message-ID: Hi Alan, Extremely valuable guidance - thank you! I will be adapting my script once I get to the office but at a first glance, this appears to be exactly what we need! I'll confirm once I've had a chance to implement this. If you have any suggestions for continued self-learning (books, courses, etc.) I'd appreciate any tips. A bit of context, in case you're curious - we're parsing the XML for load into a T SQL database for reporting purposes which is why I've parsed each value to a unique "cell". The print statement is merely a QA step before ultimately making use of the pyodbc method. For our Base Rent table, the final Python statement reads as: x.execute("Insert into dealbaserents (dealid, dtermid, brentid, \ brbegin, brentamt, brentperiod, brentdur) values \ (?, ?, ?, ?, ?, ?, ?)", \ (dealid, dtid, brid, begmo, brentamt, brper, duration)) con.commit() The need to extrapolate the full rent schedule is to address a few reporting needs. Free Rent, where applicable, is not expressed as a dollar value with a specific date. Rather, it is described as a percentage of Base Rent with a reference to the month in which it applies. A lease can have multiple Free Rent periods which may or may not be consecutive and there are several examples where a Free Rent is applied in the 2nd month and again in the 14th month which means that the dollar value of the Free Rent could be different if a rent step occurs at the end of the first year. We will also be calculating Net Present Value which will be much easier to deal with using normalized data. There are four scenarios for calculating base rent - per square foot per month, per square foot per year, monthly amount and annual amount. Regards, Daryl On Tue, Jul 3, 2018 at 8:16 PM Alan Gauld via Tutor wrote: > > On 04/07/18 01:08, Alan Gauld via Tutor wrote: > > > # Now the main code just needs the outer loops: > > tree = ET.parse(r'\\DealData.xml') > > root = tree.getroot() > > deals = [] > > for deal in root.findall("Deals"): > > for dl in deal.findall("Deal"): > > deals.append( Deal(dl) ) > > > > if dl.id == "706880": > > print(dl) #uses __str__() to create string > > Sorry, that last loop should be like this: > > for xml_dl in deal.findall("Deal"): > theDeal = Deal(xml_dl) > deals.append( theDeal ) > > if theDeal.id == "706880": > print(theDeal) #uses __str__() to create string > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From noflaco at gmail.com Wed Jul 4 06:57:10 2018 From: noflaco at gmail.com (Carlton Banks) Date: Wed, 4 Jul 2018 12:57:10 +0200 Subject: [Tutor] C++ or Python? In-Reply-To: References: Message-ID: Yes i meant cython.. can see that my phone autocorrects to cpython for some reason.. ons. 4. jul. 2018 10.33 skrev Mark Lawrence : > On 03/07/18 17:30, Carlton Banks wrote: > > tir. 3. jul. 2018 18.25 skrev Bellamy Baron : > > > >> Hi, > >> > >> I have heard C++ is faster than python and I have a few questions > >> 1.Is there a way to make python run just as fast > >> > > Look Up cpython might be a bit faster > > > > Really, or did you mean cython? :) > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From alan.gauld at yahoo.co.uk Wed Jul 4 10:53:36 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 4 Jul 2018 15:53:36 +0100 Subject: [Tutor] Need all values from while loop - only receiving one In-Reply-To: References: <9565a845-caec-bdea-965a-939b871aa858@yahoo.co.uk> Message-ID: On 04/07/18 12:08, Daryl Heppner wrote: > If you have any suggestions for continued self-learning (books, > courses, etc.) I'd appreciate any tips. So far as OOP goes you can't go far wrong with the latest version of Grady Booch's OOAD book. I've read both the previous versions and the latest update is the best yet. > A bit of context, in case you're curious - we're parsing the XML for > load into a T SQL database for reporting purposes which is why I've > parsed each value to a unique "cell". The print statement is merely a > QA step before ultimately making use of the pyodbc method. I guessed as much. As for the database inserts I'd consider making them part of the class init method, so once you create the new class instance it automatically saves itself (or updates if the ID already exists?) > The need to extrapolate the full rent schedule is to address a few > reporting needs. Free Rent, where applicable, is not expressed as a > dollar value with a specific date. Rather, it is described as a > percentage of Base Rent with a reference to the month in which it > applies. A lease can have multiple Free Rent periods which may or may > not be consecutive and there are several examples where a Free Rent is > applied in the 2nd month and again in the 14th month which means that > the dollar value of the Free Rent could be different if a rent step > occurs at the end of the first year. Put the calculations as methods into the corresponding classes. If necessary break them up so each class does only its own bit of the calculation. Remember the adage that "objects do things to themselves". If an object owns a piece of data it should be the thing that operates (including doing calculations) on that data. Calculations are operations on objects not objects in their own right. (Unless you are building a calculation framework, like Matlab say...) One of the most common OOP anti-patterns is having some kind of calculator object that fetches data from all the surrounding objects, does a complex calculation then stores the result into some other object. Instead the calculation should commence in the target object and it should ask each of the supplier objects to do their own bits only returning to the target the end result of their subcalculation. The target object should, in turn, only be performing calculations on the results returned plus the data actually stored in the target itself. Of course it is not always that clean but if the object data is partitioned well it should be pretty close. But it takes most non-OOP programmers a little time to turn their thinking inside out like that. So don't sweat if it feels unnatural to start with. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From matthew.hlavin at nasa.gov Thu Jul 5 12:03:00 2018 From: matthew.hlavin at nasa.gov (Hlavin, Matthew (GSFC-5460)[GSFC INTERNS]) Date: Thu, 5 Jul 2018 16:03:00 +0000 Subject: [Tutor] Using pip Message-ID: <2C06B1693101D9499488A64A2B771A5801083173@NDJSMBX102.ndc.nasa.gov> I just downloaded Python to work on a project at work. I'm writing a pretty simple program for data collection for an experiment. In order to get the data, though I need to install PyVISA. The website for PyVISA says I can install the library using the line: $ pip install -U pyvisa When I type this line, I get a syntax error for using the $, and when I remove the $, I get a syntax error for using the word install. I even tried just using the word pip and an error said 'pip' is not defined. I'm not sure if I'm not using some syntax wrong, or if its a completely different issue. Thanks for any help and insight Matt Hlavin From alan.gauld at yahoo.co.uk Thu Jul 5 13:08:38 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 5 Jul 2018 18:08:38 +0100 Subject: [Tutor] Using pip In-Reply-To: <2C06B1693101D9499488A64A2B771A5801083173@NDJSMBX102.ndc.nasa.gov> References: <2C06B1693101D9499488A64A2B771A5801083173@NDJSMBX102.ndc.nasa.gov> Message-ID: On 05/07/18 17:03, Hlavin, Matthew (GSFC-5460)[GSFC INTERNS] wrote: > install the library using the line: > $ pip install -U pyvisa > When I type this line, I get a syntax error The most common reason is that you are trying to type it at the Python >>> prompt. It should be typed at the OS prompt. The $ is the traditional *nix prompt. In Windows it will be something like C:\WINDOWS> It's not at all obvious that pip is an OS level tool, they need to improve/clarify the docs to make that clear - as does every site that uses pip! Its a very common error. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From eire1130 at gmail.com Thu Jul 5 13:11:21 2018 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 5 Jul 2018 13:11:21 -0400 Subject: [Tutor] Using pip In-Reply-To: <2C06B1693101D9499488A64A2B771A5801083173@NDJSMBX102.ndc.nasa.gov> References: <2C06B1693101D9499488A64A2B771A5801083173@NDJSMBX102.ndc.nasa.gov> Message-ID: On Thu, Jul 5, 2018 at 12:55 PM Hlavin, Matthew (GSFC-5460)[GSFC INTERNS] < matthew.hlavin at nasa.gov> wrote: > I just downloaded Python to work on a project at work. I'm writing a > pretty simple program for data collection for an experiment. In order to > get the data, though I need to install PyVISA. The website for PyVISA says > I can install the library using the line: > $ pip install -U pyvisa > When I type this line, I get a syntax error for using the $, and when I > remove the $, I get a syntax error for using the word install. I even tried > just using the word pip and an error said 'pip' is not defined. I'm not > sure if I'm not using some syntax wrong, or if its a completely different > issue. > > Thanks for any help and insight > Matt Hlavin > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor What version of Python did you install and what operating system are you using? the $ is just a command prompt and it isn't used for the above command. The important bit from your message is the "I even tried just using the word pip and an error said 'pip' is not defined". This means either A.) You have pip installed, but it's not on your path or B.) You don't have pip installed. If you installed latest python (which is 3.7), then you can can create a virtual env directly and just use that, which contains pip as well. (this all assumes that python is on your path already) python -m venv env this will create a virtual environment called "env". After you create your virtual environment, you activate it ". env/bin/activate". If you are windows it would be "env\Scripts\activate" Once activated, you can install your package like: pip install pyvisa you may also enjoy using ipython (pip install ipython) for this kind of use case. James From jf_byrnes at comcast.net Thu Jul 5 13:13:53 2018 From: jf_byrnes at comcast.net (Jim) Date: Thu, 5 Jul 2018 12:13:53 -0500 Subject: [Tutor] Using pip In-Reply-To: <2C06B1693101D9499488A64A2B771A5801083173@NDJSMBX102.ndc.nasa.gov> References: <2C06B1693101D9499488A64A2B771A5801083173@NDJSMBX102.ndc.nasa.gov> Message-ID: On 07/05/2018 11:03 AM, Hlavin, Matthew (GSFC-5460)[GSFC INTERNS] wrote: > I just downloaded Python to work on a project at work. I'm writing a pretty simple program for data collection for an experiment. In order to get the data, though I need to install PyVISA. The website for PyVISA says I can install the library using the line: > $ pip install -U pyvisa > When I type this line, I get a syntax error for using the $, and when I remove the $, I get a syntax error for using the word install. I even tried just using the word pip and an error said 'pip' is not defined. I'm not sure if I'm not using some syntax wrong, or if its a completely different issue. > > Thanks for any help and insight > Matt Hlavin It sounds like you are trying to install it from inside python. First make sure that pip is installed on your OS. Then install PyVISA from your commandline/terminal (which ever your OS provides). Also depending on which version of python you are using (2 or 3) you may have to type pip3 instead of just pip. regards, Jim From steve at pearwood.info Thu Jul 5 13:27:39 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 6 Jul 2018 03:27:39 +1000 Subject: [Tutor] Using pip In-Reply-To: <2C06B1693101D9499488A64A2B771A5801083173@NDJSMBX102.ndc.nasa.gov> References: <2C06B1693101D9499488A64A2B771A5801083173@NDJSMBX102.ndc.nasa.gov> Message-ID: <20180705172737.GC7318@ando.pearwood.info> On Thu, Jul 05, 2018 at 04:03:00PM +0000, Hlavin, Matthew (GSFC-5460)[GSFC INTERNS] wrote: > I just downloaded Python to work on a project at work. I'm writing a > pretty simple program for data collection for an experiment. In order > to get the data, though I need to install PyVISA. The website for > PyVISA says I can install the library using the line: > > $ pip install -U pyvisa > > When I type this line, I get a syntax error for using the $, and when > I remove the $, I get a syntax error for using the word install. I > even tried just using the word pip and an error said 'pip' is not > defined. I'm not sure if I'm not using some syntax wrong, or if its a > completely different issue. My crystal ball tells me you're using the Python interactive intepreter :-) (By the way, in the future, please always copy and paste the full error messages you see. Don't use a screen shot.) Does the line start with a prompt >>> ? Then you're already running inside Python. The above command is assumed to be inside a Linux "bash" shell. Type Ctrl-D or enter the command "quit()" (with the parentheses, but not the quotes) to exit. The command "exit()" will also work. This should return you to the standard terminal shell, which on Linux is probably bash. You should see a $ (dollar sign) prompt. If you do, then you can try running: pip install -U pyvisa at the dollar sign prompt (don't retype the $) but don't be surprised if it fails again. pip is a great tool, *once you get it working right*, but getting it working is often a dozen kinds of pain. If it works, GREAT! But if you get an error, please copy and paste all the output and we'll see what we can see. All of the above assume you are running Linux. If you're on Windows, the commands needed will be slightly different. Let's start with: - what OS are you running? Windows, Linux, Mac OS, something else? - do you have sudo/root/Administrator privileges on that machine? - what version of Python are you running? - what command or action do you use to start Python? If you're running Linux or Mac OS, you can also run this command at the dollar sign $ prompt: which pip and see what it says. -- Steve From mats at wichmann.us Thu Jul 5 13:28:04 2018 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 5 Jul 2018 11:28:04 -0600 Subject: [Tutor] Using pip In-Reply-To: References: <2C06B1693101D9499488A64A2B771A5801083173@NDJSMBX102.ndc.nasa.gov> Message-ID: <406b6e5c-09e8-f69d-c917-6a88a12d211f@wichmann.us> On 07/05/2018 11:11 AM, James Reynolds wrote: > On Thu, Jul 5, 2018 at 12:55 PM Hlavin, Matthew (GSFC-5460)[GSFC INTERNS] < > matthew.hlavin at nasa.gov> wrote: > >> I just downloaded Python to work on a project at work. I'm writing a >> pretty simple program for data collection for an experiment. In order to >> get the data, though I need to install PyVISA. The website for PyVISA says >> I can install the library using the line: >> $ pip install -U pyvisa >> When I type this line, I get a syntax error for using the $, and when I >> remove the $, I get a syntax error for using the word install. I even tried >> just using the word pip and an error said 'pip' is not defined. I'm not >> sure if I'm not using some syntax wrong, or if its a completely different >> issue. These days, it is suggested not to use pip as if it were a command by itself, but as a module. This is because many systems have more than one python version installed, and it's not clear if you'll get the version of pip that matches the version of python you'll be using. To make that more simple, suggest using **at a command prompt** as others have said: python -m pip install -U pyvisa rather than pip install -U pyvisa If you are using Windows, even if you've added python to your PATH, pip may not be in the path, as it lives in the scripts subdirectory of the place python was installed. This is another reason the "python -m pip" way of calling may be easier to deal with. Virtualenv instructions below are good by the way, as it's usually not a great idea to install into "system locations" with pip. That's actually what the "-U" in the invocation above is for - it means to not install the new module in the system paths, but in a user-specific path. > What version of Python did you install and what operating system are you > using? > > the $ is just a command prompt and it isn't used for the above command. > > The important bit from your message is the "I even tried just using the > word pip and an error said 'pip' is not defined". > > This means either A.) You have pip installed, but it's not on your path or > B.) You don't have pip installed. > > If you installed latest python (which is 3.7), then you can can create a > virtual env directly and just use that, which contains pip as well. > > (this all assumes that python is on your path already) > > python -m venv env > > this will create a virtual environment called "env". > > After you create your virtual environment, you activate it ". > env/bin/activate". If you are windows it would be "env\Scripts\activate" > > Once activated, you can install your package like: pip install pyvisa > > you may also enjoy using ipython (pip install ipython) for this kind of use > case. > > James > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From mats at wichmann.us Fri Jul 6 11:09:01 2018 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 6 Jul 2018 09:09:01 -0600 Subject: [Tutor] Pip install and Ipv6 In-Reply-To: References: Message-ID: <0f31f8ad-cbb7-c3ab-68f3-ee522b5a62e3@wichmann.us> On 07/02/2018 10:48 AM, Luiz Gustavo S. Costa wrote: > Hello, > > Is anyone else here having problems using Pip repository with ipv6? > > If I try to install something with pip, I get this: > > (python2) lgcosta:api/ $ pip install falcon > Collecting falcon Retrying (Retry(total=4, connect=None, read=None, > redirect=None, status=None)) after connection broken by > 'ProtocolError('Connection aborted.', error(104, 'Connection reset by > peer'))': /simple/falcon/ > > and it does not work ... but, I discovered this: > > (python2) lgcosta:api/ $ curl -I https://pypi.python.org/ > curl: (35) gnutls_handshake() failed: Error in the pull function. > > (python2) lgcosta:api/ $ host pypi.python.org > pypi.python.org is an alias for dualstack.python.map.fastly.net. > dualstack.python.map.fastly.net has address 151.101.16.223 > dualstack.python.map.fastly.net has IPv6 address 2a04:4e42:4::223 > > My default output is ipv6, so if I force it out by ipv4, it works: > > (python2) lgcosta:api/ $ curl -I -4 https://pypi.python.org/ > HTTP/1.1 301 Redirect to Primary Domain > Server: Varnish Retry-After: 0 > Location: https://pypi.org/ > Content-Type: text/html; charset=UTF-8 > Content-Length: 122 > .... > > output over ipv6, the repository does not work, only for ipv4. > > I did not find the option to force ipv4 on the pip. > > Does anyone have any notice or similar reports? Given the lack of responses, probably you should try poking around the issue tracker for pip: https://github.com/pypa/pip/issues or some of the other resources listed on the main page there (click the Code tab from the Issue page to see) Best of luck! From darylheppner at gmail.com Sat Jul 7 13:46:52 2018 From: darylheppner at gmail.com (Daryl Heppner) Date: Sat, 7 Jul 2018 13:46:52 -0400 Subject: [Tutor] Need all values from while loop - only receiving one In-Reply-To: References: <9565a845-caec-bdea-965a-939b871aa858@yahoo.co.uk> Message-ID: Hi Alan, A lot of great guidance here! I'm stepping back to simply return the DealID from the XML using the concept of a class. My code results in exit code 0 but doesn't print any results. Could you give me a hint where I'm missing something? Thank you, Daryl root = tree.getroot() class Deal: def __init__(self, rt): for deal in rt.findall("Deals/Deal"): self.dealID = deal.get("DealID") def __str__(self): return self.dealID def __iter__(self): return self.dealID def __next__(self): if self.dealID is not None: print(self.dealID) else: raise StopIteration Deal(root) On Wed, Jul 4, 2018 at 10:53 AM Alan Gauld via Tutor wrote: > > On 04/07/18 12:08, Daryl Heppner wrote: > > > If you have any suggestions for continued self-learning (books, > > courses, etc.) I'd appreciate any tips. > > So far as OOP goes you can't go far wrong with the latest version > of Grady Booch's OOAD book. I've read both the previous versions > and the latest update is the best yet. > > > A bit of context, in case you're curious - we're parsing the XML for > > load into a T SQL database for reporting purposes which is why I've > > parsed each value to a unique "cell". The print statement is merely a > > QA step before ultimately making use of the pyodbc method. > > I guessed as much. > > As for the database inserts I'd consider making them part of the > class init method, so once you create the new class instance > it automatically saves itself (or updates if the ID already > exists?) > > > The need to extrapolate the full rent schedule is to address a few > > reporting needs. Free Rent, where applicable, is not expressed as a > > dollar value with a specific date. Rather, it is described as a > > percentage of Base Rent with a reference to the month in which it > > applies. A lease can have multiple Free Rent periods which may or may > > not be consecutive and there are several examples where a Free Rent is > > applied in the 2nd month and again in the 14th month which means that > > the dollar value of the Free Rent could be different if a rent step > > occurs at the end of the first year. > > Put the calculations as methods into the corresponding classes. > If necessary break them up so each class does only its own bit > of the calculation. Remember the adage that "objects do things to > themselves". If an object owns a piece of data it should be the > thing that operates (including doing calculations) on that data. > Calculations are operations on objects not objects in their > own right. (Unless you are building a calculation framework, > like Matlab say...) > > One of the most common OOP anti-patterns is having some kind of > calculator object that fetches data from all the surrounding > objects, does a complex calculation then stores the result > into some other object. > > Instead the calculation should commence in the target object and it > should ask each of the supplier objects to do their own bits only > returning to the target the end result of their subcalculation. > The target object should, in turn, only be performing calculations > on the results returned plus the data actually stored in the > target itself. Of course it is not always that clean but if > the object data is partitioned well it should be pretty close. > > But it takes most non-OOP programmers a little time to turn their > thinking inside out like that. So don't sweat if it feels > unnatural to start with. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at yahoo.co.uk Sat Jul 7 17:35:39 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 7 Jul 2018 22:35:39 +0100 Subject: [Tutor] Need all values from while loop - only receiving one In-Reply-To: References: <9565a845-caec-bdea-965a-939b871aa858@yahoo.co.uk> Message-ID: On 07/07/18 18:46, Daryl Heppner wrote: > I'm stepping back to simply return the DealID from the XML using the > concept of a class. My code results in exit code 0 but doesn't print > any results. Could you give me a hint where I'm missing something? You have an issue which has shown up in several of the code samples you have sent in that you don't assign values to variables. In your code below Deal is a class. To use it you must create an instance, which you do at the bottom. But the methods defined in the class do not execute until you call them from the instance. So in your code below you create an instance, but because it is not stored anywhere (with a variable) you do not execute any of its methods (except init) and Python, seeing that it is unassigned, immediately deletes the object. To use an object you must store it someplace; either by assigning it to a variable or inserting it into some kind of collection > root = tree.getroot() > > class Deal: > def __init__(self, rt): > for deal in rt.findall("Deals/Deal"): > self.dealID = deal.get("DealID") > > def __str__(self): > return self.dealID > You only need the iter/next stuff if you are creating an iterator which usually means a collection of some kind. Since your class only represents one deal object you almost certainly don't need iter/next and they just add confusion. You can add them back in later if you find you do need them. > Deal(root) This line should look like: testDeal = Deal(root) print (testDeal) Which should print the DealId via the __str__() method which is called implicitly by the print() function. However, there is one other issue that I think you need to address. You call findall() which implies that it returns some kind of collection of deals, not just one. You are iterating over that list assigning self.DealID each time. That means that you are only storing the last ID. For testing things you can probably just go with the first one, like so: allDeals = rt.findall("Deals/Deal"): self.dealID = allDeals[0].get("DealID") HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From mats at wichmann.us Sun Jul 8 12:42:21 2018 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 8 Jul 2018 10:42:21 -0600 Subject: [Tutor] Need all values from while loop - only receiving one In-Reply-To: References: <9565a845-caec-bdea-965a-939b871aa858@yahoo.co.uk> Message-ID: <5233b9bc-c26d-c713-c580-016ea14a7875@wichmann.us> On 07/07/2018 03:35 PM, Alan Gauld via Tutor wrote: > On 07/07/18 18:46, Daryl Heppner wrote: > >> I'm stepping back to simply return the DealID from the XML using the >> concept of a class. My code results in exit code 0 but doesn't print >> any results. Could you give me a hint where I'm missing something? > > You have an issue which has shown up in several of the code > samples you have sent in that you don't assign values to variables. > In your code below Deal is a class. To use it you must create an > instance, which you do at the bottom. > > But the methods defined in the class do not execute until > you call them from the instance. So in your code below you > create an instance, but because it is not stored anywhere > (with a variable) you do not execute any of its methods > (except init) and Python, seeing that it is unassigned, > immediately deletes the object. To use an object you must > store it someplace; either by assigning it to a variable > or inserting it into some kind of collection I don't know if this is preaching about something you already understand very well; if so, sorry, just ignore this. It's not always instantly obvious that in Python operations create objects. This is not quite the same as the Object Oriented Programming description of an object, which might tell you "an object is an instance of a class". From the surface viewpoint, anyway, Python has objects that don't look like class instances - at least, not instances of classes which you are aware of being classes, or which use the class-calling syntax like Foo() to create them. To do anything with an object, you need a reference to it, so you assign a name, store it in a collection, etc. A simple numeric operation creates an object, you can see its "identifier" with the id() function (btw the value returned by id() is not intrinsically meaningful, but it does show you when names refer to the same or different objects): >>> x = 2 + 7 >>> id(x) 93975971883992 You can assign additional names for objects: >>> y = x >>> id(y) 93975971883992 that object, which has a value of 9, now has two references. A function definition creates an object, and assigns the name from the definition to the object: >>> def foo(q): ... print(id(q)) ... >>> id(foo) 140534881482704 You can make additional names for a function object as well, it's just an object: >>> z = foo >>> id(z) 140534881482704 It's callable by either name: >>> foo(x) 93975971883992 >>> z(x) 93975971883992 The same is true of a class definition, it creates an object and binds the name to it. When you call the class object, it creates an instance object. As Alan says, Python reference-counts objects, so you need to hold on to at least one reference as long as you want the object to live. From jf_byrnes at comcast.net Tue Jul 10 22:46:57 2018 From: jf_byrnes at comcast.net (Jim) Date: Tue, 10 Jul 2018 21:46:57 -0500 Subject: [Tutor] Need help combining elements of a list of lists Message-ID: Say I have a list like ltrs and I want to print out all the possible 3 letter combinations. I want to combine letters from each inner list but not combine any letters within the inner list itself. So ACF and ADF would be ok but ABC would not. I can lay it out manually and see the pattern, I cannot figure out how to do it programically. Just in case this looks like homework it is not. It's a small test case I devised to try to figure it out so I can apply it to a bigger real world problem I am working on. ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']] print(ltrs[0][0]+ltrs[1][0]+ltrs[2][0]) #ACF print(ltrs[0][0]+ltrs[1][1]+ltrs[2][0]) #ADF print(ltrs[0][0]+ltrs[1][2]+ltrs[2][0]) #AEF print(ltrs[0][0]+ltrs[1][0]+ltrs[2][1]) #ACG print(ltrs[0][0]+ltrs[1][1]+ltrs[2][1]) #ADG print(ltrs[0][0]+ltrs[1][2]+ltrs[2][1]) #AEG . . . print(ltrs[0][1]+ltrs[1][2]+ltrs[2][3]) #BEI thanks, Jim From david at graniteweb.com Tue Jul 10 23:04:08 2018 From: david at graniteweb.com (David Rock) Date: Tue, 10 Jul 2018 22:04:08 -0500 Subject: [Tutor] Need help combining elements of a list of lists In-Reply-To: References: Message-ID: <24FF9644-17D5-4EDF-9411-CCA57A11E44A@graniteweb.com> > On Jul 10, 2018, at 21:46, Jim wrote: > > ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']] A fairly straightforward way is to use nested loops: >>> for l in ltrs[0]: ... for j in ltrs[1]: ... for k in ltrs[2]: ... print l,j,k A C F A C G A C H A C I A D F A D G A D H A D I A E F A E G A E H A E I B C F B C G B C H B C I B D F B D G B D H B D I B E F B E G B E H B E I Not the most elegant, but probably the easiest to follow. ? David Rock david at graniteweb.com From steve at pearwood.info Tue Jul 10 23:09:39 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 11 Jul 2018 13:09:39 +1000 Subject: [Tutor] Need help combining elements of a list of lists In-Reply-To: References: Message-ID: <20180711030938.GP7318@ando.pearwood.info> On Tue, Jul 10, 2018 at 09:46:57PM -0500, Jim wrote: > Say I have a list like ltrs and I want to print out all the possible 3 > letter combinations. I want to combine letters from each inner list but > not combine any letters within the inner list itself. So ACF and ADF > would be ok but ABC would not. > > I can lay it out manually and see the pattern, I cannot figure out how > to do it programically. Just in case this looks like homework it is not. > It's a small test case I devised to try to figure it out so I can apply > it to a bigger real world problem I am working on. > > ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']] If you know that there are just three sublists, then you can do this: for a in ltrs[0]: for b in ltrs[1]: for c in ltrs[2]: print(a + b + c) I trust that's easy enough to understand. But here's a more general technique, where you don't need to know up front how many nested lists there are: from itertools import product # short for "Cartesian Product" for s in product(*ltrs): print(''.join(s)) The *ltrs syntax might be a bit mysterious: it is called "sequence unpacking", and tells the interpreter to use each item from ltrs as a separate argument: product(*ltrs) => product(ltrs[0], ltrs[1], ltrs[2]) -- Steve From david at graniteweb.com Tue Jul 10 23:09:56 2018 From: david at graniteweb.com (David Rock) Date: Tue, 10 Jul 2018 22:09:56 -0500 Subject: [Tutor] Need help combining elements of a list of lists In-Reply-To: <24FF9644-17D5-4EDF-9411-CCA57A11E44A@graniteweb.com> References: <24FF9644-17D5-4EDF-9411-CCA57A11E44A@graniteweb.com> Message-ID: <99629C42-5927-4F99-A9BC-77D1DA6ED420@graniteweb.com> > On Jul 10, 2018, at 22:04, David Rock wrote: > >> On Jul 10, 2018, at 21:46, Jim wrote: >> >> ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']] > > A fairly straightforward way is to use nested loops: > >>>> for l in ltrs[0]: > ... for j in ltrs[1]: > ... for k in ltrs[2]: > ... print l,j,k > Sorry, let?s try to make that a little cleaner-looking for x in ltrs[0]: for y in ltrs[1]: for z in ltrs[2]: print x,y,z ? David Rock david at graniteweb.com From mats at wichmann.us Wed Jul 11 00:03:53 2018 From: mats at wichmann.us (Mats Wichmann) Date: Tue, 10 Jul 2018 22:03:53 -0600 Subject: [Tutor] Need help combining elements of a list of lists In-Reply-To: <20180711030938.GP7318@ando.pearwood.info> References: <20180711030938.GP7318@ando.pearwood.info> Message-ID: <2d767f73-b21e-e9fe-e32d-19e5181e2135@wichmann.us> On 07/10/2018 09:09 PM, Steven D'Aprano wrote: > On Tue, Jul 10, 2018 at 09:46:57PM -0500, Jim wrote: > >> Say I have a list like ltrs and I want to print out all the possible 3 >> letter combinations. I want to combine letters from each inner list but >> not combine any letters within the inner list itself. So ACF and ADF >> would be ok but ABC would not. >> >> I can lay it out manually and see the pattern, I cannot figure out how >> to do it programically. Just in case this looks like homework it is not. >> It's a small test case I devised to try to figure it out so I can apply >> it to a bigger real world problem I am working on. >> >> ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']] > > If you know that there are just three sublists, then you can do this: > > for a in ltrs[0]: > for b in ltrs[1]: > for c in ltrs[2]: > print(a + b + c) > > I trust that's easy enough to understand. > > But here's a more general technique, where you don't need to know up > front how many nested lists there are: > > > from itertools import product # short for "Cartesian Product" > for s in product(*ltrs): > print(''.join(s)) This is one of those cases where: if it's homework, getting the nested loops right is almost certainly the way to go. If it isn't, then itertools (that is, "using an available library solution") is almost certainly the way to go :) If the eventual case is not just "letters", and a list of combined lists is the eventual goal, then the concise stanza is: prods = list(product(*ltrs)) print(prods) then gives you: [('a', 'c', 'f'), ('a', 'c', 'g'), ('a', 'c', 'h'), ('a', 'c', 'i'), ('a', 'd', 'f'), ('a', 'd', 'g'), ('a', 'd', 'h'), ('a', 'd', 'i'), ('a', 'e', 'f'), ('a', 'e', 'g'), ('a', 'e', 'h'), ('a', 'e', 'i'), ('b', 'c', 'f'), ('b', 'c', 'g'), ('b', 'c', 'h'), ('b', 'c', 'i'), ('b', 'd', 'f'), ('b', 'd', 'g'), ('b', 'd', 'h'), ('b', 'd', 'i'), ('b', 'e', 'f'), ('b', 'e', 'g'), ('b', 'e', 'h'), ('b', 'e', 'i')] if you want them concatenated, then of course join is the way to do that. From jf_byrnes at comcast.net Wed Jul 11 11:47:55 2018 From: jf_byrnes at comcast.net (Jim) Date: Wed, 11 Jul 2018 10:47:55 -0500 Subject: [Tutor] Need help combining elements of a list of lists In-Reply-To: <99629C42-5927-4F99-A9BC-77D1DA6ED420@graniteweb.com> References: <24FF9644-17D5-4EDF-9411-CCA57A11E44A@graniteweb.com> <99629C42-5927-4F99-A9BC-77D1DA6ED420@graniteweb.com> Message-ID: On 07/10/2018 10:09 PM, David Rock wrote: > >> On Jul 10, 2018, at 22:04, David Rock wrote: >> >>> On Jul 10, 2018, at 21:46, Jim wrote: >>> >>> ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']] >> >> A fairly straightforward way is to use nested loops: >> >>>>> for l in ltrs[0]: >> ... for j in ltrs[1]: >> ... for k in ltrs[2]: >> ... print l,j,k >> > > Sorry, let?s try to make that a little cleaner-looking > > for x in ltrs[0]: > for y in ltrs[1]: > for z in ltrs[2]: > print x,y,z > Seeing it in front of me it does look straight forward, I was having difficulty visualizing how to solve it. thanks, Jim From jf_byrnes at comcast.net Wed Jul 11 12:09:57 2018 From: jf_byrnes at comcast.net (Jim) Date: Wed, 11 Jul 2018 11:09:57 -0500 Subject: [Tutor] Need help combining elements of a list of lists In-Reply-To: <2d767f73-b21e-e9fe-e32d-19e5181e2135@wichmann.us> References: <20180711030938.GP7318@ando.pearwood.info> <2d767f73-b21e-e9fe-e32d-19e5181e2135@wichmann.us> Message-ID: On 07/10/2018 11:03 PM, Mats Wichmann wrote: > On 07/10/2018 09:09 PM, Steven D'Aprano wrote: >> On Tue, Jul 10, 2018 at 09:46:57PM -0500, Jim wrote: >> >>> Say I have a list like ltrs and I want to print out all the possible 3 >>> letter combinations. I want to combine letters from each inner list but >>> not combine any letters within the inner list itself. So ACF and ADF >>> would be ok but ABC would not. >>> >>> I can lay it out manually and see the pattern, I cannot figure out how >>> to do it programically. Just in case this looks like homework it is not. >>> It's a small test case I devised to try to figure it out so I can apply >>> it to a bigger real world problem I am working on. >>> >>> ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']] >> >> If you know that there are just three sublists, then you can do this: >> >> for a in ltrs[0]: >> for b in ltrs[1]: >> for c in ltrs[2]: >> print(a + b + c) >> >> I trust that's easy enough to understand. >> >> But here's a more general technique, where you don't need to know up >> front how many nested lists there are: >> >> >> from itertools import product # short for "Cartesian Product" >> for s in product(*ltrs): >> print(''.join(s)) > > This is one of those cases where: if it's homework, getting the nested > loops right is almost certainly the way to go. If it isn't, then > itertools (that is, "using an available library solution") is almost > certainly the way to go :) > > If the eventual case is not just "letters", and a list of combined lists > is the eventual goal, then the concise stanza is: > > prods = list(product(*ltrs)) > > print(prods) then gives you: > > [('a', 'c', 'f'), ('a', 'c', 'g'), ('a', 'c', 'h'), ('a', 'c', 'i'), > ('a', 'd', 'f'), ('a', 'd', 'g'), ('a', 'd', 'h'), ('a', 'd', 'i'), > ('a', 'e', 'f'), ('a', 'e', 'g'), ('a', 'e', 'h'), ('a', 'e', 'i'), > ('b', 'c', 'f'), ('b', 'c', 'g'), ('b', 'c', 'h'), ('b', 'c', 'i'), > ('b', 'd', 'f'), ('b', 'd', 'g'), ('b', 'd', 'h'), ('b', 'd', 'i'), > ('b', 'e', 'f'), ('b', 'e', 'g'), ('b', 'e', 'h'), ('b', 'e', 'i')] > > if you want them concatenated, then of course join is the way to do that. > > > Steven & Mats thanks for your replies. It is more that just letters. I was reading Al Sweigart's book Cracking Codes with Python. I got to the chapter on substitution cyphers and wondered if his program could solve the daily Crypto Quips in the newspaper. Turns out it did not do a very good job because the quips were to short. It did produce a dictionary where the keys are the letters of the alphabet and the items are a list of possible letters to substitute. If a key has no possible letters it is ignored, if a key has only one possible letter it considered a solution and plugged into the cypher. the keys with multiple possible letters are ones I am interested in. I know you cannot brute force a substitution cypher but maybe I could loop over and combine the possible substitution letters and crack it that way. That's why I made up the letter problem, I wanted to see how to do it on a simple data set before attempting much more complex one. It looks like the library solution is the way for me to try. Regards, Jim From anilduggirala at fastmail.fm Wed Jul 11 09:55:06 2018 From: anilduggirala at fastmail.fm (Anil Duggirala) Date: Wed, 11 Jul 2018 08:55:06 -0500 Subject: [Tutor] learn python to build payment processor Message-ID: <1531317306.3795999.1437284528.5F6393C5@webmail.messagingengine.com> hello, I would like to ask what for recommendations on books/resources to learn python to build a payment processor. I need to understand how python works with databases, user authentication and how a user can have an account page to view all his details; something like you would see when you login to your Paypal account. I am building a payment processor for cryptocurrencies. I am a newbie, but know very basic Python, applied to math. Should I learn to use Django to do this project, is it necessary? thanks a lot, From alan.gauld at yahoo.co.uk Wed Jul 11 14:28:37 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 11 Jul 2018 19:28:37 +0100 Subject: [Tutor] learn python to build payment processor In-Reply-To: <1531317306.3795999.1437284528.5F6393C5@webmail.messagingengine.com> References: <1531317306.3795999.1437284528.5F6393C5@webmail.messagingengine.com> Message-ID: On 11/07/18 14:55, Anil Duggirala wrote: > I would like to ask what for recommendations on > books/resources to learn python to build a payment processor. You don;t tell us your experience level. If you can already program in any other language then just use the standard Python tutorial on python.org. Then progress to the Django tutorial on their web site. That should be sufficient, however.... If you are a complete beginner you should start with one of the non-programmers tutorials linked on the python.org site (or try mine from the link below). Any of them will get you to a basic standard with the language. You then probably need to learn the basics of SQL - there are many SQL tutorials (including mine :-) Finally you cn try Django... > I need to understand how python works with databases, > user authentication and how a user can have an account>page to view all his details; Django can do a lot of that for you. (as can many other web frameworks, but Django is well supported so a good place to start. > I am a newbie, but know very basic Python, applied to math. > Should I learn to use Django to do this project, is it necessary? As I said, there are other web frameworks, so you could use any of then, but Django has a proven track record for this kind of task, has a large user community, many web resources for learning and is not so complex that the learning curve is too steep (think Zope!) But you do need a good knowledge of Python so going through the full official tutorial is probably a good idea - it should only take a day or so. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From anilduggirala at fastmail.fm Wed Jul 11 17:41:24 2018 From: anilduggirala at fastmail.fm (Anil Duggirala) Date: Wed, 11 Jul 2018 16:41:24 -0500 Subject: [Tutor] learn python to build payment processor In-Reply-To: References: <1531317306.3795999.1437284528.5F6393C5@webmail.messagingengine.com> Message-ID: <1531345284.2435855.1437793840.1AE240A4@webmail.messagingengine.com> > You don;t tell us your experience level. Im not a complete newbie, I understand basic programming. > If you can already program in any other language then just > use the standard Python tutorial on python.org. I will do this, thanks! >Then progress > to the Django tutorial on their web site. That should > be sufficient, however.... Will do as well, thanks a lot. > Any of them will get you to a basic standard with the language. > You then probably need to learn the basics of SQL - there are > many SQL tutorials (including mine :-) Will the Django tutorial guide me toward connecting Python and SQL? Could you share a link to your SQL tutorial or provide a specific one? Will these (SQL tutorials) pertain specifically to Python? Thanks a lot Alan. From alan.gauld at yahoo.co.uk Wed Jul 11 18:08:55 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 11 Jul 2018 23:08:55 +0100 Subject: [Tutor] learn python to build payment processor In-Reply-To: <1531345284.2435855.1437793840.1AE240A4@webmail.messagingengine.com> References: <1531317306.3795999.1437284528.5F6393C5@webmail.messagingengine.com> <1531345284.2435855.1437793840.1AE240A4@webmail.messagingengine.com> Message-ID: On 11/07/18 22:41, Anil Duggirala wrote: > Will the Django tutorial guide me toward connecting > Python and SQL? Yes, Django has its own mechanism for doing that and the tutorials will cover it. > Could you share a link to your SQL tutorial See the signature. On the left hand contents frame you'll find a database topic. It covers basic raw SQL then the second half shows how to access that from standard Python. But, as noted, Django wraps its own layer of abstraction around SQL so mostly you'll just use Django. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From mats at wichmann.us Wed Jul 11 22:00:12 2018 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 11 Jul 2018 20:00:12 -0600 Subject: [Tutor] learn python to build payment processor In-Reply-To: <1531317306.3795999.1437284528.5F6393C5@webmail.messagingengine.com> References: <1531317306.3795999.1437284528.5F6393C5@webmail.messagingengine.com> Message-ID: On 07/11/2018 07:55 AM, Anil Duggirala wrote: > hello, > I would like to ask what for recommendations on books/resources to learn python to build a payment processor. I need to understand how python works with databases, user authentication and how a user can have an account page to view all his details; something like you would see when you login to your Paypal account. I am building a payment processor for cryptocurrencies. I am a newbie, but know very basic Python, applied to math. Should I learn to use Django to do this project, is it necessary? > thanks a lot, Hi Anil. Python has a kind of motto: "There should be one-- and preferably only one --obvious way to do it." (see https://www.python.org/dev/peps/pep-0020/) The thing is, when "it" is a complex concept -- and "payment processing" certainly is that (you've listed several high-level issues already) -- you end up not being able to simply apply that. There are a lot of ways to deal with the payment processing topic. Normally the advice would be to decompose your problem into rather distinct chunks, and see what looks like a good choice for each (including the "build or buy" decision, although here by "buy" I only mean pick up some existing implementation). You listed some of those - database, auth, web interface, account managment, but probably need to break it down further. Django is a powerful and wonderful system; however the one time I worked with it on a paid project where a book author wanted a system to order and sell her book, the existing payment-processing modules nearly drove me insane with all the quirks I ran into. Since then I've spewed a good amount of possible unjustified hate for Django. If you've done this many times it's probably a trivial exercise. Probably today's code is more mature when I did this. etc. All I'm saying is Django may, or may not, be your magic bullet. Or it may be overkill for what you need - we can't tell. There's a Udemy course on this topic - I don't know if it's of interest to pay a bit of money to look at it and see if there's a fit based on what they have to present (I'm sure there are many other options, some not pay-for): https://www.udemy.com/learn-django-code-accept-payments-with-stripe/ Meanwhile, it turns out I have Jeff Knupp's site bookmarked because I like the way he explains at least some of the topics he takes on, and he's got one on payment processing too: https://jeffknupp.com/blog/2014/01/18/python-and-flask-are-ridiculously-powerful/ I've mentioned three scenarios here because (a) I fell in this hole myself once, and (b) I happen to have seen the two links in the course of other searching. I bet there's a ton of resources for this on the Internet because, well, there are an awful lot of people who want to figure out how to get paid without irritating their customers in the process! The bottom line is... there's probably not one place you can go which will teach you exactly what you need to know for this idea, and nothing more. But there are a ton of resources that will edge you in that direction. Including this list - if you get to the point where you have specific Python questions to ask. Best of luck! From robertvstepp at gmail.com Wed Jul 11 22:34:00 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Wed, 11 Jul 2018 21:34:00 -0500 Subject: [Tutor] learn python to build payment processor In-Reply-To: References: <1531317306.3795999.1437284528.5F6393C5@webmail.messagingengine.com> Message-ID: On Wed, Jul 11, 2018 at 9:01 PM Mats Wichmann wrote: From: > (see https://www.python.org/dev/peps/pep-0020/) It says: "Abstract Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down." What is the unwritten twentieth aphorism? If this is a joke or pun, I'm missing it. -- boB From anilduggirala at fastmail.fm Wed Jul 11 20:56:10 2018 From: anilduggirala at fastmail.fm (Anil Duggirala) Date: Wed, 11 Jul 2018 19:56:10 -0500 Subject: [Tutor] learn python to build payment processor In-Reply-To: References: <1531317306.3795999.1437284528.5F6393C5@webmail.messagingengine.com> <1531345284.2435855.1437793840.1AE240A4@webmail.messagingengine.com> Message-ID: <1531356970.2483891.1437942320.61EE706B@webmail.messagingengine.com> I appreciate your help very much Alan, I have homework to do now, thanks again, From leamhall at gmail.com Thu Jul 12 04:55:23 2018 From: leamhall at gmail.com (Leam Hall) Date: Thu, 12 Jul 2018 04:55:23 -0400 Subject: [Tutor] learn python to build payment processor In-Reply-To: <1531345284.2435855.1437793840.1AE240A4@webmail.messagingengine.com> References: <1531317306.3795999.1437284528.5F6393C5@webmail.messagingengine.com> <1531345284.2435855.1437793840.1AE240A4@webmail.messagingengine.com> Message-ID: On 07/11/2018 05:41 PM, Anil Duggirala wrote: >> You don;t tell us your experience level. > > Im not a complete newbie, I understand basic programming. Anil, if you are doing this for a class project, or as a way to learn Python, then I applaud you! It will take time and be difficult but you will learn a lot. However, if you are actually thinking about using this to process payments, please stop. Don't do that. Not because you're not smart enough but because none of us is smart enough. Companies have entire teams writing this sort of code and other teams reviewing the code. Even then, there are significant security risks. Financial transaction code that has flaws can ruin people's lives. I've already had my card misused this year, it took me a week of effort to recover. That was much less than it would have been if we didn't have stringent controls in place. Please code responsibly. Leam From mats at wichmann.us Thu Jul 12 10:55:06 2018 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 12 Jul 2018 08:55:06 -0600 Subject: [Tutor] learn python to build payment processor In-Reply-To: References: <1531317306.3795999.1437284528.5F6393C5@webmail.messagingengine.com> Message-ID: <92786fbc-880d-f612-89b2-72824c45a549@wichmann.us> On 07/11/2018 08:34 PM, boB Stepp wrote: > On Wed, Jul 11, 2018 at 9:01 PM Mats Wichmann wrote: > > From: >> (see https://www.python.org/dev/peps/pep-0020/) > It says: > > "Abstract > Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding > principles for Python's design into 20 aphorisms, only 19 of which > have been written down." > > What is the unwritten twentieth aphorism? If this is a joke or pun, > I'm missing it. That's been speculated on for years :) The top-voted answer here suggests there really isn't one: https://stackoverflow.com/questions/4504487/the-zen-of-python-distils-the-guiding-principles-for-python-into-20-aphorisms-bu From anilduggirala at fastmail.fm Thu Jul 12 08:35:29 2018 From: anilduggirala at fastmail.fm (Anil Duggirala) Date: Thu, 12 Jul 2018 07:35:29 -0500 Subject: [Tutor] learn python to build payment processor In-Reply-To: References: <1531317306.3795999.1437284528.5F6393C5@webmail.messagingengine.com> <1531345284.2435855.1437793840.1AE240A4@webmail.messagingengine.com> Message-ID: <1531398929.2661039.1438445840.5968B1F4@webmail.messagingengine.com> > Not because you're not smart > enough but because none of us is smart enough. You sound like my brother. From tkoch1 at hwemail.com Fri Jul 13 13:42:11 2018 From: tkoch1 at hwemail.com (Talia Koch) Date: Fri, 13 Jul 2018 17:42:11 +0000 Subject: [Tutor] changing font Message-ID: <3972394225124eee8a12bb5fd9c9067a@hwemail.com> Hi, I am trying to figure out a code that would change my text output to 'Arial' font. How would I do this? Thanks. From cs at cskk.id.au Fri Jul 13 18:30:18 2018 From: cs at cskk.id.au (Cameron Simpson) Date: Sat, 14 Jul 2018 08:30:18 +1000 Subject: [Tutor] changing font In-Reply-To: <3972394225124eee8a12bb5fd9c9067a@hwemail.com> References: <3972394225124eee8a12bb5fd9c9067a@hwemail.com> Message-ID: <20180713223018.GA192@cskk.homeip.net> On 13Jul2018 17:42, Talia Koch wrote: >Hi, I am trying to figure out a code that would change my text output to 'Arial' font. How would I do this? Thanks. You will need to provide far more context for this question. What are you using to display your text? HTML (eg a web browser)? Then the tag might help you. Some other document format such as roff or LaTeX? A terminal? If this is possible it will be entirely terminal dependent. A GUI of some kind, such as Tk or Qt? You will need to consult its documentation for its text widgets. Cheers, Cameron Simpson (formerly cs at zip.com.au) in rec.moto, jsh wrote: > Dan Nitschke wrote: > > Ged Martin wrote: > > > On Sat, 17 May 1997 16:53:33 +0000, Dan Nitschke scribbled: > > > >(And you stay *out* of my dreams, you deviant little > > > >weirdo.) > > > Yeah, yeah, that's what you're saying in _public_.... > > Feh. You know nothing of my dreams. I dream entirely in text (New Century > > Schoolbook bold oblique 14 point), and never in color. I once dreamed I > > was walking down a flowchart of my own code, and a waterfall of semicolons > > was chasing me. (I hid behind a global variable until they went by.) > You write code in a proportional serif? No wonder you got extra > semicolons falling all over the place. No, I *dream* about writing code in a proportional serif font. It's much more exciting than my real life. /* dan: THE Anti-Ged -- Ignorant Yank (tm) #1, none-%er #7 */ Dan Nitschke peDANtic at best.com nitschke at redbrick.com From alan.gauld at yahoo.co.uk Fri Jul 13 18:32:24 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 13 Jul 2018 23:32:24 +0100 Subject: [Tutor] changing font In-Reply-To: <3972394225124eee8a12bb5fd9c9067a@hwemail.com> References: <3972394225124eee8a12bb5fd9c9067a@hwemail.com> Message-ID: On 13/07/18 18:42, Talia Koch via Tutor wrote: > Hi, I am trying to figure out a code that would change my text output to 'Arial' It all depends on how you are displaying your text. If it is in a GUI such as Tkinter or WxPython you can change the font in yor program. But the technique is completely different in each GUI toolkit. For example here is how to set it in Tkinter: (Using Pyton 2.7...) import Tkinter as tk sans = "SansSerif 10" serif = "Garamond 12 italic" top = tk.Tk() tk.Label(top, text="Hello", font=sans).pack() tk.Label(top, text="Hello", font=serif).pack() top.mainloop() Note, I'm on Linux so can't use Arial, but you should be able to change the font line to suit your OS... Whereas here is how to do it in wxPython: import wx # --- Define a custom Frame, this will become the main window --- class FontsFrame(wx.Frame): def __init__(self, parent, id, title, pos, size): wx.Frame.__init__(self,parent, id, title, pos, size) # wxPython defines its own system dependant fonts sans = wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL) serif = wx.Font(12, wx.ROMAN, wx.ITALIC, wx.NORMAL) panel = wx.Panel(self) t1 = wx.StaticText(panel, -1, "Hello", (10,10)) t1.SetFont(sans) t2 = wx.StaticText(panel, -1, "Hello", (10, 30)) t2.SetFont(serif) class HelloApp(wx.App): def OnInit(self): frame = FontsFrame(None, -1, "Hello", (50,50), (80,90) ) frame.Show(True) self.SetTopWindow(frame) return True # create instance and start the event loop HelloApp().MainLoop() As you see its completely different and much more work. But if you are not using a GUI then its not something you as a programmer can do (at least not easily). The font the console window uses depends on your users settings, not on your program. You may be able to control things like underline, bold, italic etc, but even that depends on the terminal emulator in use. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From robertvstepp at gmail.com Sat Jul 14 17:51:38 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 14 Jul 2018 16:51:38 -0500 Subject: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19 Message-ID: I have finally taken the plunge and abandoned Windows for Linux Mint 19. I had been doing a dual-boot, but I found I spent most of my time where I was comfortable -- Windows 7 -- and mostly avoided my Linux installation. So I took my pacifier away and went for it! Linux Mint 19 comes with Python 3.6.5 pre-installed. However, my son and I are working on a couple of things together, and decided to use the latest bugfix releases of Python 3.6 for them. I would not think that upgrading from 3.6.5 to 3.6.6 would break anything in my system Python 3. But after much searching I cannot find an _easy_ way to do this upgrade. I would rather delay the learning experience of compiling Python from source if I can. Is there any _easy_ way to upgrade the system Python 3.6.5 to 3.6.6 (Without wreaking system-wide havoc)? -- boB From alan.gauld at yahoo.co.uk Sat Jul 14 19:42:48 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 15 Jul 2018 00:42:48 +0100 Subject: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19 In-Reply-To: References: Message-ID: On 14/07/18 22:51, boB Stepp wrote: > Linux Mint 19 comes with Python 3.6.5 pre-installed. However, my son > and I are working on a couple of things together, and decided to use > the latest bugfix releases of Python 3.6 for them. I would not think > that upgrading from 3.6.5 to 3.6.6 would break anything in my system Probably not but do you really need that last dot release? Do you know for sure there is anything in it that will affect your code? If not I'd just stay on 3.6.5.... Personally, although I have 3.6.5 installed, my default v3 is 3.5.4. If you really need 3.6.6 then your best bet is to locate a deb package that somebody has created, otherwise building from source is about the only option. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From jf_byrnes at comcast.net Sat Jul 14 21:17:52 2018 From: jf_byrnes at comcast.net (Jim) Date: Sat, 14 Jul 2018 20:17:52 -0500 Subject: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19 In-Reply-To: References: Message-ID: On 07/14/2018 06:42 PM, Alan Gauld via Tutor wrote: > On 14/07/18 22:51, boB Stepp wrote: > >> Linux Mint 19 comes with Python 3.6.5 pre-installed. However, my son >> and I are working on a couple of things together, and decided to use >> the latest bugfix releases of Python 3.6 for them. I would not think >> that upgrading from 3.6.5 to 3.6.6 would break anything in my system > > Probably not but do you really need that last dot release? > Do you know for sure there is anything in it that will affect > your code? If not I'd just stay on 3.6.5.... > > Personally, although I have 3.6.5 installed, my default v3 > is 3.5.4. > > If you really need 3.6.6 then your best bet is to locate a > deb package that somebody has created, otherwise building > from source is about the only option. > Bob, If you look you might find a PPA that has packaged it. I installed python 3.6.5 (no help to you) on Mint 18 from here: https://launchpad.net/~jonathonf/+archive/ubuntu/python-3.6'. Maybe you can find one that does 3.6.6 or ask Jonathon if he intends to package 3.6.6. Whatever you do I would suggest you install it in a virtual environment, especially if you are going to be experimenting with a lot of libraries. If you use a virtual environment you don't have to worry about breaking your system python. regards, Jim From mats at wichmann.us Sat Jul 14 21:22:46 2018 From: mats at wichmann.us (Mats Wichmann) Date: Sat, 14 Jul 2018 19:22:46 -0600 Subject: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19 In-Reply-To: References: Message-ID: <7FCE64F2-31C3-4985-87F8-D640C062205E@wichmann.us> take a look at pyenv. should make it fairly easy. https://github.com/pyenv/pyenv On July 14, 2018 7:17:52 PM MDT, Jim wrote: >On 07/14/2018 06:42 PM, Alan Gauld via Tutor wrote: >> On 14/07/18 22:51, boB Stepp wrote: >> >>> Linux Mint 19 comes with Python 3.6.5 pre-installed. However, my >son >>> and I are working on a couple of things together, and decided to use >>> the latest bugfix releases of Python 3.6 for them. I would not >think >>> that upgrading from 3.6.5 to 3.6.6 would break anything in my system >> >> Probably not but do you really need that last dot release? >> Do you know for sure there is anything in it that will affect >> your code? If not I'd just stay on 3.6.5.... >> >> Personally, although I have 3.6.5 installed, my default v3 >> is 3.5.4. >> >> If you really need 3.6.6 then your best bet is to locate a >> deb package that somebody has created, otherwise building >> from source is about the only option. >> > >Bob, > >If you look you might find a PPA that has packaged it. I installed >python 3.6.5 (no help to you) on Mint 18 from here: >https://launchpad.net/~jonathonf/+archive/ubuntu/python-3.6'. > >Maybe you can find one that does 3.6.6 or ask Jonathon if he intends to > >package 3.6.6. Whatever you do I would suggest you install it in a >virtual environment, especially if you are going to be experimenting >with a lot of libraries. If you use a virtual environment you don't >have >to worry about breaking your system python. > >regards, Jim > > >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >https://mail.python.org/mailman/listinfo/tutor -- Sent from my Android device with K-9 Mail. Please excuse my brevity. From robertvstepp at gmail.com Sat Jul 14 21:30:06 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 14 Jul 2018 20:30:06 -0500 Subject: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19 In-Reply-To: References: Message-ID: On Sat, Jul 14, 2018 at 8:18 PM Jim wrote: > If you look you might find a PPA that has packaged it. I installed > python 3.6.5 (no help to you) on Mint 18 from here: > https://launchpad.net/~jonathonf/+archive/ubuntu/python-3.6'. That is an interesting thought. My only concern is how does one choose a "safe" PPA? With the recent security breaches of Gentoo and Arch Linux repositories, nothing seems safe nowadays, and PPAs seem dependent on trusting someone apart from the official Linux distribution. However, when I was doing my searching, this particular PPA came up more than once, so I imagine he is reliable. > Maybe you can find one that does 3.6.6 or ask Jonathon if he intends to > package 3.6.6. Whatever you do I would suggest you install it in a > virtual environment, especially if you are going to be experimenting > with a lot of libraries. If you use a virtual environment you don't have > to worry about breaking your system python. Your advice is very solid. Alas! I was hoping to delay getting intimate with virtual environments, but based on my own searches, your advice and Alan's it appears to me that I have three obvious choices: (1) Just stick with the current system Python 3 until an issue comes up that 3.6.6 fixes. (2) Wait on the system Python 3 to provide an update to Python 3.6.6. (3) Install into a virtual environment -- either compiling from source or the PPA route. Thanks, Jim! -- boB From robertvstepp at gmail.com Sat Jul 14 21:43:40 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 14 Jul 2018 20:43:40 -0500 Subject: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19 In-Reply-To: <7FCE64F2-31C3-4985-87F8-D640C062205E@wichmann.us> References: <7FCE64F2-31C3-4985-87F8-D640C062205E@wichmann.us> Message-ID: On Sat, Jul 14, 2018 at 8:23 PM Mats Wichmann wrote: > > take a look at pyenv. should make it fairly easy. > > https://github.com/pyenv/pyenv This does look interesting. On the linked page, after installing and configuring pyenv, it says to install Python as follows giving a 2.7.8 example: $ pyenv install 2.7.8 Where and how does it get its Python installation? boB From robertvstepp at gmail.com Sun Jul 15 00:52:04 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 14 Jul 2018 23:52:04 -0500 Subject: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19 In-Reply-To: References: <7FCE64F2-31C3-4985-87F8-D640C062205E@wichmann.us> Message-ID: On Sat, Jul 14, 2018 at 8:43 PM boB Stepp wrote: > > On Sat, Jul 14, 2018 at 8:23 PM Mats Wichmann wrote: > > > > take a look at pyenv. should make it fairly easy. > > > > https://github.com/pyenv/pyenv > > This does look interesting. On the linked page, after installing and > configuring pyenv, it says to install Python as follows giving a 2.7.8 > example: > > $ pyenv install 2.7.8 > > Where and how does it get its Python installation? After a lot of searching, I'm still not sure how pyenv is working its magic. On https://github.com/pyenv/pyenv/wiki it says: "pyenv will try its best to download and compile the wanted Python version, ..." This suggests that it is getting the source from somewhere (python.org/downloads ?) and then compiling it locally. Is this what it actually does? boB -- boB From robertvstepp at gmail.com Sun Jul 15 02:38:52 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 15 Jul 2018 01:38:52 -0500 Subject: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19 In-Reply-To: References: <7FCE64F2-31C3-4985-87F8-D640C062205E@wichmann.us> Message-ID: On Sat, Jul 14, 2018 at 11:52 PM boB Stepp wrote: > > On Sat, Jul 14, 2018 at 8:43 PM boB Stepp wrote: > > > > On Sat, Jul 14, 2018 at 8:23 PM Mats Wichmann wrote: > > > > > > take a look at pyenv. should make it fairly easy. > > > > > > https://github.com/pyenv/pyenv > > > > This does look interesting. On the linked page, after installing and > > configuring pyenv, it says to install Python as follows giving a 2.7.8 > > example: > > > > $ pyenv install 2.7.8 > > > > Where and how does it get its Python installation? > > After a lot of searching, I'm still not sure how pyenv is working its > magic. On https://github.com/pyenv/pyenv/wiki it says: > > "pyenv will try its best to download and compile the wanted Python version, ..." > > This suggests that it is getting the source from somewhere > (python.org/downloads ?) and then compiling it locally. Is this what > it actually does? After too much fruitless searching I finally found a more direct confirmation of what I was suspecting to be true at "In contrast, with PyEnv, you install a Python. This can be a version of CPython, PyPy, IronPython, Jython, Pyston, stackless, miniconda, or even Anaconda. It downloads the sources from the official repos, and compiles them on your machine [1]. Plus, it provides an easy and transparent way of switching between installed versions (including any system-installed versions). After that, you use Python's own venv and pip." This sounds like exactly what I need! Thanks for this, Mats!! I will give it a whirl later today after I wake up. -- boB From robertvstepp at gmail.com Sun Jul 15 02:47:12 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 15 Jul 2018 01:47:12 -0500 Subject: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19 In-Reply-To: References: <7FCE64F2-31C3-4985-87F8-D640C062205E@wichmann.us> Message-ID: On Sun, Jul 15, 2018 at 1:38 AM boB Stepp wrote: > > On Sat, Jul 14, 2018 at 11:52 PM boB Stepp wrote: > > > > On Sat, Jul 14, 2018 at 8:43 PM boB Stepp wrote: > > > > > > On Sat, Jul 14, 2018 at 8:23 PM Mats Wichmann wrote: > > > > > > > > take a look at pyenv. should make it fairly easy. > > > > > > > > https://github.com/pyenv/pyenv > > > > > > This does look interesting. On the linked page, after installing and > > > configuring pyenv, it says to install Python as follows giving a 2.7.8 > > > example: > > > > > > $ pyenv install 2.7.8 > > > > > > Where and how does it get its Python installation? > > > > After a lot of searching, I'm still not sure how pyenv is working its > > magic. On https://github.com/pyenv/pyenv/wiki it says: > > > > "pyenv will try its best to download and compile the wanted Python version, ..." > > > > This suggests that it is getting the source from somewhere > > (python.org/downloads ?) and then compiling it locally. Is this what > > it actually does? > > After too much fruitless searching I finally found a more direct > confirmation of what I was suspecting to be true at Oops! Too sleepy. Forgot to paste the link where I found the below info. It's at: https://bastibe.de/2017-11-20-pyenv.html > "In contrast, with PyEnv, you install a Python. This can be a version > of CPython, PyPy, IronPython, Jython, Pyston, stackless, miniconda, or > even Anaconda. It downloads the sources from the official repos, and > compiles them on your machine [1]. Plus, it provides an easy and > transparent way of switching between installed versions (including any > system-installed versions). After that, you use Python's own venv and > pip." > > This sounds like exactly what I need! Thanks for this, Mats!! I will > give it a whirl later today after I wake up. > > -- > boB -- boB From mats at wichmann.us Sun Jul 15 11:24:22 2018 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 15 Jul 2018 09:24:22 -0600 Subject: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19 In-Reply-To: References: <7FCE64F2-31C3-4985-87F8-D640C062205E@wichmann.us> Message-ID: <57da55b8-7827-464e-f33d-63d0f874cbed@wichmann.us> On 07/15/2018 12:38 AM, boB Stepp wrote: > On Sat, Jul 14, 2018 at 11:52 PM boB Stepp wrote: >> >> On Sat, Jul 14, 2018 at 8:43 PM boB Stepp wrote: >>> >>> On Sat, Jul 14, 2018 at 8:23 PM Mats Wichmann wrote: >>>> >>>> take a look at pyenv. should make it fairly easy. >>>> >>>> https://github.com/pyenv/pyenv >>> >>> This does look interesting. On the linked page, after installing and >>> configuring pyenv, it says to install Python as follows giving a 2.7.8 >>> example: >>> >>> $ pyenv install 2.7.8 >>> >>> Where and how does it get its Python installation? >> >> After a lot of searching, I'm still not sure how pyenv is working its >> magic. On https://github.com/pyenv/pyenv/wiki it says: >> >> "pyenv will try its best to download and compile the wanted Python version, ..." >> >> This suggests that it is getting the source from somewhere >> (python.org/downloads ?) and then compiling it locally. Is this what >> it actually does? > > After too much fruitless searching I finally found a more direct > confirmation of what I was suspecting to be true at > > "In contrast, with PyEnv, you install a Python. This can be a version > of CPython, PyPy, IronPython, Jython, Pyston, stackless, miniconda, or > even Anaconda. It downloads the sources from the official repos, and > compiles them on your machine [1]. Plus, it provides an easy and > transparent way of switching between installed versions (including any > system-installed versions). After that, you use Python's own venv and > pip." > > This sounds like exactly what I need! Thanks for this, Mats!! I will > give it a whirl later today after I wake up. > Right... sorry for not following up sooner, it tries to download and build a Python from sources, while not messing with the system-installed Python. From adeadmarshal at gmail.com Sun Jul 15 15:44:33 2018 From: adeadmarshal at gmail.com (Ali M) Date: Mon, 16 Jul 2018 00:14:33 +0430 Subject: [Tutor] putting accent on letters while user is typing in Entrybox (Tkinter) Message-ID: Hi. I want to write these (?, ?, ?, ?, ?, ?) accented letters when the user types (gx, cx, jx, ux, cx). when user types 'gx' for example i want to remove that x and replace it with the accent. how should i do that? and how should i specify which accent goes above which letter? thanks. From carroll at tjc.com Sun Jul 15 15:37:26 2018 From: carroll at tjc.com (Terry Carroll) Date: Sun, 15 Jul 2018 15:37:26 -0400 (EDT) Subject: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19 In-Reply-To: References: Message-ID: On Sat, 14 Jul 2018, boB Stepp wrote: > Linux Mint 19 comes with Python 3.6.5 pre-installed.... > But after much searching I cannot find an _easy_ way to do > this upgrade. Unlike many distributions, Mint's philosophy is *not* to install most updates by default, on the "if it's not broken, don't fix it" theory. That being said, if you do want to update to the latest version available for Mint, this command should do it for you: sudo apt-get install --only-upgrade python3 If Mint doesn't have a vetted 3.6.6 yet, I would leave it alone. -- Terry Carroll carroll at tjc.com From robertvstepp at gmail.com Sun Jul 15 17:04:06 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 15 Jul 2018 16:04:06 -0500 Subject: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19 In-Reply-To: References: Message-ID: On Sun, Jul 15, 2018 at 3:30 PM Terry Carroll wrote: > That being said, if you do want to update to the latest version available > for Mint, this command should do it for you: > > sudo apt-get install --only-upgrade python3 > > If Mint doesn't have a vetted 3.6.6 yet, I would leave it alone. This is what led me to my question, I could not find a "vetted 3.6.6". However, I will keep your suggested command in mind for the future. I have decided I am going to try out Mats' suggestion of pyenv. It seems clean, flexible, and does not mess with the system Python. Thanks! -- boB From tingqu at gmail.com Sun Jul 15 17:19:13 2018 From: tingqu at gmail.com (Ting Qu) Date: Sun, 15 Jul 2018 14:19:13 -0700 Subject: [Tutor] =?utf-8?b?5ZOmemR0emV3c3N3enpz?= Message-ID: From tingqu at gmail.com Sun Jul 15 17:20:10 2018 From: tingqu at gmail.com (Ting Qu) Date: Sun, 15 Jul 2018 14:20:10 -0700 Subject: [Tutor] =?utf-8?b?5L2g?= Message-ID: ??S???z C x x z c z xs From tingqu at gmail.com Sun Jul 15 17:20:27 2018 From: tingqu at gmail.com (Ting Qu) Date: Sun, 15 Jul 2018 14:20:27 -0700 Subject: [Tutor] ze Message-ID: From tingqu at gmail.com Sun Jul 15 17:21:31 2018 From: tingqu at gmail.com (Ting Qu) Date: Sun, 15 Jul 2018 14:21:31 -0700 Subject: [Tutor] =?utf-8?b?6I2J5Lit5b+D5Li75Lu7Y2N0dGZ6?= Message-ID: From robertvstepp at gmail.com Sun Jul 15 19:38:32 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 15 Jul 2018 18:38:32 -0500 Subject: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19 In-Reply-To: <7FCE64F2-31C3-4985-87F8-D640C062205E@wichmann.us> References: <7FCE64F2-31C3-4985-87F8-D640C062205E@wichmann.us> Message-ID: On Sat, Jul 14, 2018 at 8:23 PM Mats Wichmann wrote: > > take a look at pyenv. should make it fairly easy. > > https://github.com/pyenv/pyenv I just completed getting access to Python 3.6.6 using pyenv, so I guess I'll post my experience for future searchers. It was not totally painless, and I am still pondering whether I used "sudo" inappropriately or not. Recall I am on Linux Mint 19 Cinnamon edition. First, the page Mats linked to mentioned an automatic installer for pyenv in another GitHub project of the author's, so I used that. It was here: https://github.com/pyenv/pyenv-installer I used the recommended "GitHub way" instead of the PyPi way which apparently is still in development and doesn't work for Python 3 anyway. So I ran: $ curl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash Then I added to the end of my .bashrc: export PATH="/home/bob/.pyenv/bin:$PATH" eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" This apparently allows pyenv's "shims" to take precedence in the search path for Python versions. Warning: On the page Mats linked there are some reports of getting into an infinite search loop if these lines are added to .bashrc. After pondering the specifics I did not think it would affect me, so I went ahead with what I did. I then did the suggested restart of my shell with: $ exec "$SHELL" pyenv seemed to be successfully installed. I ran $ pyenv update just to be sure I had the latest, greatest, which I did. I then ran $pyenv install --list to see if Python 3.6.6 was available. It was and the list of available versions is HUGE running from 2.1.3 to 3.8-dev to Active Python versions to Anaconda versions, IronPython, Jython, MiniConda, PyPy, Stackless, etc. So I thought I was ready to download and install Python 3.6.6 with $ pyenv install 3.6.6 It *did* download from https://www.python.org/ftp/python/3.6.6/Python-3.6.6.tar.xz, something you could tell I was concerned about from my earlier posts. Unfortunately I got: Installing Python-3.6.6... BUILD FAILED (LinuxMint 19 using python-build 20180424) So I went to https://github.com/pyenv/pyenv/wiki/Common-build-problems, which at the very top of the page recommended running this: $ sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev \ libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev \ xz-utils tk-dev libffi-dev So without pausing for further thought I did run it, but now wonder if this will cause me future consequences with system stuff as later I read on the FAQ page a similar command without granting sudo privileges. So I jumped into the fire on this one without fully understanding what I was doing. But after doing this I was able to get 3.6.6, but there was still one more thing to do and that was to run $ pyenv global 3.6.6 because I did want to be able to type python3 in the shell and get specifically 3.6.6 as my default version -- for now at least. I probably did not do everything like I should, but maybe this will help someone down the line do better. So far I seem to have everything working and doing what I had hoped for. pyenv looks like a fine tool for managing as many Python versions as one wants to play around with, and does seem to support virtual environments with a plugin. boB From alan.gauld at yahoo.co.uk Sun Jul 15 19:42:29 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 16 Jul 2018 00:42:29 +0100 Subject: [Tutor] putting accent on letters while user is typing in Entrybox (Tkinter) In-Reply-To: References: Message-ID: On 15/07/18 20:44, Ali M wrote: > Hi. I want to write these (?, ?, ?, ?, ?, ?) accented letters when the user > types (gx, cx, jx, ux, cx). > > when user types 'gx' for example i want to remove that x and replace it > with the accent. how should i do that? and how should i specify which > accent goes above which letter? thanks. You need to replace the two characters with a single unicode character representing the accented character. But you also need to be displaying your output on a device or terminal capable of displaying the unicode characters. Mapping a pair of characters to a single unicode one is not particularly difficult, although not trivial either. But its rarely necessary. If we knew more about what you really want to do rather tan what you think is the solution we might be able to offer more specific help. Where are you reading the input from? Where are you displaying the output? How do you read the input? How do you display the output? Why can the user not just type the accented code into the input? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From adeadmarshal at gmail.com Mon Jul 16 13:29:55 2018 From: adeadmarshal at gmail.com (Ali M) Date: Mon, 16 Jul 2018 21:59:55 +0430 Subject: [Tutor] putting accent on letters while user is typing in Entrybox (Tkinter) Message-ID: The accents which i want to be automatically converted and put upon letters is circumflex and another one which shape is like the opposite of circumflex. the user types in entrybox and it searches in db which i've created before and has no problem. the words in my db have unicode characters and they are accented. the user himself can type accented characters too, but i want to make it automatically converted so the user doesn't have to have a special keyboard to write. when x is pressed after these letters (g,j,c,h,u), i want that x to be removed and replaced with a circumflex above those letters. here is the full code if needed: import sqlite3 as sqlite import tkinter as tk from tkinter import ttk #GUI Widgets class EsperantoDict: def __init__(self, master): master.title("EsperantoDict") master.iconbitmap("Esperanto.ico") master.resizable(False, False) master.configure(background='#EAFFCD') self.style = ttk.Style() self.search_var = tk.StringVar() self.search_var.trace("w", lambda name, index, mode: self.update_list()) self.style = ttk.Style() self.style.configure("TFrame", background='#EAFFCD') self.style.configure("TButton", background='#C6FF02') self.style.configure("TLabel", background='#EAFFCD') self.frame_header = ttk.Frame(master, relief=tk.FLAT) self.frame_header.config(style="TFrame") self.frame_header.pack(side=tk.TOP, padx=5, pady=5) self.logo = tk.PhotoImage(file=r'C:\EsperantoDict\eo.png') self.small_logo = self.logo.subsample(10, 10) ttk.Label(self.frame_header, image=self.small_logo).grid(row=0, column=0, stick="ne", padx=5, pady=5, rowspan=2) ttk.Label(self.frame_header, text='EsperantoDict', font=('Arial', 18, 'bold')).grid(row=0, column=1) self.frame_content = ttk.Frame(master) self.frame_content.config(style="TFrame") self.frame_content.pack() self.entry_search = ttk.Entry(self.frame_content, textvariable=self.search_var, width=30) self.entry_search.bind('', self.entry_delete) self.entry_search.bind('', self.entry_insert) self.entry_search.grid(row=0, column=0, padx=5) self.entry_search.focus() self.button_search = ttk.Button(self.frame_content, text="Search") self.photo_search = tk.PhotoImage(file=r'C:\EsperantoDict\search.png') self.small_photo_search = self.photo_search.subsample(3, 3) self.button_search.config(image=self.small_photo_search, compound=tk.LEFT, style="TButton") self.button_search.grid(row=0, column=2, columnspan=1, sticky='nw', padx=5) self.listbox = tk.Listbox(self.frame_content, height=30, width=30) self.listbox.grid(row=1, column=0, padx=5) self.scrollbar = ttk.Scrollbar(self.frame_content, orient=tk.VERTICAL, command=self.listbox.yview) self.scrollbar.grid(row=1, column=1, sticky='nsw') self.listbox.config(yscrollcommand=self.scrollbar.set) self.listbox.bind('<>', self.enter_meaning) self.textbox = tk.Text(self.frame_content, relief=tk.GROOVE, width=60, height=30, borderwidth=2) self.textbox.config(wrap='word') self.textbox.grid(row=1, column=2, sticky='w', padx=5) # SQLite self.db = sqlite.connect(r'C:\EsperantoDict\test.db') self.cur = self.db.cursor() self.cur.execute('SELECT Esperanto FROM Words') for row in self.cur: self.listbox.insert(tk.END, row) for row in range(0, self.listbox.size(), 2): self.listbox.itemconfigure(row, background="#f0f0ff") self.update_list() def update_list(self): search_term = self.search_var.get() for item in self.listbox.get(0, tk.END): if search_term.lower() in item: self.listbox.delete(0, tk.END) self.listbox.insert(tk.END, item) # SQLite def enter_meaning(self, tag): for index in self.listbox.curselection(): esperanto = self.listbox.get(index) results = self.cur.execute("SELECT English FROM Words WHERE Esperanto = ?", (esperanto)) for row in results: self.textbox.delete(1.0, tk.END) self.textbox.insert(tk.END, row) def entry_delete(self, tag): self.entry_search.delete(0, tk.END) return None def entry_insert(self, tag): self.entry_search.delete(0, tk.END) self.entry_search.insert(0, "Type to Search") return None def main(): root = tk.Tk() esperantodict = EsperantoDict(root) root.mainloop() if __name__ == '__main__': main() From cfrommert at gmail.com Mon Jul 16 18:28:37 2018 From: cfrommert at gmail.com (Crystal Frommert) Date: Mon, 16 Jul 2018 17:28:37 -0500 Subject: [Tutor] help with reading a string? Message-ID: Hi, I am a beginner comp sci teacher at an all-girls high school. The girls are learning how to read from a txt file and search for a string. Here is a sample of text from the txt file: TX,F,1910,Mary,895 TX,F,1910,Ruby,314 TX,F,1910,Annie,277 TX,F,1910,Willie,260 TX,F,1910,Ruth,252 TX,F,1910,Gladys,240 TX,F,1910,Maria,223 TX,F,1910,Frances,197 TX,F,1910,Margaret,194 How do they read the number after a certain searched name and then add up the numbers after each time the name occurs? I would really like to help them with this code but I am at a loss. Thank you, Crystal From alan.gauld at yahoo.co.uk Mon Jul 16 19:37:31 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 17 Jul 2018 00:37:31 +0100 Subject: [Tutor] help with reading a string? In-Reply-To: References: Message-ID: On 16/07/18 23:28, Crystal Frommert wrote: > are learning how to read from a txt file and search for a string. > > Here is a sample of text from the txt file: > TX,F,1910,Mary,895 > TX,F,1910,Ruby,314 > TX,F,1910,Annie,277 > > How do they read the number after a certain searched name and then add up > the numbers after each time the name occurs? > > I would really like to help them with this code but I am at a loss. Which bit are you at a loss over? The general approach is: open the file for reading read each line. search the line for your target string extract the number at the end of the file add the number to the running total None of those are intrinsically difficult, so which bit are you having problems with? Have you got any code that you tried and it didn't work? That would be most helpful in determining where you need to adjust your approach. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Mon Jul 16 19:46:36 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 17 Jul 2018 00:46:36 +0100 Subject: [Tutor] putting accent on letters while user is typing in Entrybox (Tkinter) In-Reply-To: References: Message-ID: On 16/07/18 18:29, Ali M wrote: > The accents which i want to be automatically converted and put upon letters > is circumflex and another one which shape is like the opposite of > circumflex. It doesn't really matter what the shapes are provided the result is a unicode character. You just want to substitute one character for another > def update_list(self): > search_term = self.search_var.get() You have the string of characters here so you need to scan the string and detect the special character pairs, do a look up and swap in the unicode chars you want. I strongly suggest you do that in a method def edit_input(self, input) for index,char in enumerate(input) .... return result You can then proceed to process the new string as required. search_term = self.edit_input(search_term) > for item in self.listbox.get(0, tk.END): > if search_term.lower() in item: > self.listbox.delete(0, tk.END) > self.listbox.insert(tk.END, item) > -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Mon Jul 16 20:06:49 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 17 Jul 2018 10:06:49 +1000 Subject: [Tutor] help with reading a string? In-Reply-To: References: Message-ID: <20180717000647.GQ7318@ando.pearwood.info> Hi Crystal, and welcome! My response is further below, after your question. On Mon, Jul 16, 2018 at 05:28:37PM -0500, Crystal Frommert wrote: > Hi, I am a beginner comp sci teacher at an all-girls high school. The girls > are learning how to read from a txt file and search for a string. > > Here is a sample of text from the txt file: > TX,F,1910,Mary,895 > TX,F,1910,Ruby,314 > TX,F,1910,Annie,277 > TX,F,1910,Willie,260 > TX,F,1910,Ruth,252 > TX,F,1910,Gladys,240 > TX,F,1910,Maria,223 > TX,F,1910,Frances,197 > TX,F,1910,Margaret,194 > > How do they read the number after a certain searched name and then add up > the numbers after each time the name occurs? Which version of Python are you using? The answer may depend on the exact version, but something like this ought to be good: # Code below is not tested, please forgive any bugs when you try it... # Process the lines of some text file. total = 0 with open("path to the file.txt", "r") as f: # Read the file line-by-line. for line in f: # Split each record into five fields. # Please pick more meaningful field names for a, b, c! a, b, c, name, score = line.split(",") # Choose only records for a specific person. # Here I hard-code the person's name, in practice # you ought to use a variable. if name == "Sarah": # Convert the score from a string to an int, # and add it to total. total = total + int(score) # Dropping back to the extreme left automatically closes # the file. print(total) Remember that in Python, indentation is not optional. Some extra features: * You can re-write the line "total = total + int(score)" using the more compact notation "total += int(score)" * Instead of the "with open(...) as f", you can do it like this: f = open("path to the file.txt") # the "r" parameter is optional for line in f: # copy for loop from above to here # (don't forget to reduce the indentation by one level) ... # Explicitly close the file. f.close() # A common error is to forget the parentheses! # And finally print the total. print(total) Hope this helps, and please don't hesitate to ask if you have any questions. Keep your replies on the mailing list so others may contribute answers and learn from the responses. Regards, Steve From jaruiz at comcast.net Tue Jul 17 02:26:37 2018 From: jaruiz at comcast.net (Jeanne Ruiz) Date: Mon, 16 Jul 2018 23:26:37 -0700 (PDT) Subject: [Tutor] Does Python 2.7 bdist_wininst perform checksum verification? Message-ID: <1419271307.525192.1531808797398@connect.xfinity.com> Hello, I can't seem to find documentation in docs.python.org that talks about whether or not the Python Build Distribution command, bdist_wininst performs checksum verification upon installing a Windows executable *.exe. I would think that it does but I need a reference(s) that describes this - can someone point me to a description of how checksums are used to verify the integrity of the installed software? Any help would be appreciated - thanks! From alan.gauld at yahoo.co.uk Tue Jul 17 12:33:27 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 17 Jul 2018 17:33:27 +0100 Subject: [Tutor] Does Python 2.7 bdist_wininst perform checksum verification? In-Reply-To: <1419271307.525192.1531808797398@connect.xfinity.com> References: <1419271307.525192.1531808797398@connect.xfinity.com> Message-ID: On 17/07/18 07:26, Jeanne Ruiz wrote: > I can't seem to find documentation in docs.python.org that talks > about whether or not the Python Build Distribution command, > bdist_wininst performs checksum verification upon installing > a Windows executable *.exe. That's probably a bit off topic for the tutor list, we focus on beginner to python type stuff. Language issues and standard library usage. I'd try the main Python mailing list for more likelihood of a response. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From mats at wichmann.us Tue Jul 17 12:45:09 2018 From: mats at wichmann.us (Mats Wichmann) Date: Tue, 17 Jul 2018 10:45:09 -0600 Subject: [Tutor] Does Python 2.7 bdist_wininst perform checksum verification? In-Reply-To: References: <1419271307.525192.1531808797398@connect.xfinity.com> Message-ID: On 07/17/2018 10:33 AM, Alan Gauld via Tutor wrote: > On 17/07/18 07:26, Jeanne Ruiz wrote: > >> I can't seem to find documentation in docs.python.org that talks > about whether or not the Python Build Distribution command, >> bdist_wininst performs checksum verification upon installing >> a Windows executable *.exe. > > That's probably a bit off topic for the tutor list, we focus on > beginner to python type stuff. Language issues and standard > library usage. > > I'd try the main Python mailing list for more likelihood of > a response. > Or the source code! From matthew.polack at htlc.vic.edu.au Tue Jul 17 19:52:24 2018 From: matthew.polack at htlc.vic.edu.au (Matthew Polack) Date: Wed, 18 Jul 2018 09:52:24 +1000 Subject: [Tutor] Stuck on some basics re floats Message-ID: Hi, I'm a teacher trying to learn Python with my students. I am trying to make a very simple 'unit calculator' program...but I get an error ..I think python is treating my num1 variable as a text string...not an integer. How do I fix this? Thanks! - Matt print ("How many inches would you like to convert? ") num1 = input('Enter inches here') print ("You have entered",num1, "inches") convert = num1 * 2.54 print ("This is", convert, "centimetres") Traceback (most recent call last): File "convert.py", line 10, in convert = num1 * 2.54 TypeError: can't multiply sequence by non-int of type 'float' Matthew Polack | Teacher [image: Emailbanner3.png] Trinity Drive | PO Box 822 Horsham Victoria 3402 p. 03 5382 2529 m. 0402456854 e. matthew.polack at htlc.vic.edu.au w. www.htlc.vic.edu.au -- **Disclaimer: *Whilst every attempt has been made to ensure that material contained in this email is free from computer viruses or other defects, the attached files are provided, and may only be used, on the basis that the user assumes all responsibility for use of the material transmitted. This email is intended only for the use of the individual or entity named above and may contain information that is confidential and privileged. If you are not the intended recipient, please note that any dissemination, distribution or copying of this email is strictly prohibited. If you have received this email in error, please notify us immediately by return email or telephone +61 3 5382 2529**?and destroy the original message.* From alan.gauld at yahoo.co.uk Wed Jul 18 03:28:12 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 18 Jul 2018 08:28:12 +0100 Subject: [Tutor] Stuck on some basics re floats In-Reply-To: References: Message-ID: On 18/07/18 00:52, Matthew Polack wrote: > Hi, > > I'm a teacher trying to learn Python with my students. > > I am trying to make a very simple 'unit calculator' program...but I get an > error ..I think python is treating my num1 variable as a text string...not > an integer. You are correct. > How do I fix this? Convert the string to a float: f = float(s) > print ("How many inches would you like to convert? ") > num1 = input('Enter inches here') In Python 3 input() always returns a string. In python 2 input() returns an evaluated version of the string, so if a number was entered Python returned a number. This was a serious security risk however, so input() was removed in Python 3 and the old raw_input() was renamed as input(). > print ("You have entered",num1, "inches") > convert = num1 * 2.54 convert = float(num1) * 2.54 > print ("This is", convert, "centimetres") HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Wed Jul 18 03:34:40 2018 From: __peter__ at web.de (Peter Otten) Date: Wed, 18 Jul 2018 09:34:40 +0200 Subject: [Tutor] Stuck on some basics re floats References: Message-ID: Matthew Polack wrote: > Hi, > > I'm a teacher trying to learn Python with my students. > > I am trying to make a very simple 'unit calculator' program...but I get an > error ..I think python is treating my num1 variable as a text string...not > an integer. > > How do I fix this? > > Thanks! > > - Matt > > print ("How many inches would you like to convert? ") > num1 = input('Enter inches here') As you have guessed, at this point num1 is a string. You can convert it to a float with num1 = float(num1) > print ("You have entered",num1, "inches") > convert = num1 * 2.54 > print ("This is", convert, "centimetres") > > > Traceback (most recent call last): > File "convert.py", line 10, in > convert = num1 * 2.54 > TypeError: can't multiply sequence by non-int of type 'float' Note that int is mentioned here because Python can multiply int with str, though the result might surprise you: >>> "spam" * 3 'spamspamspam' So * also works as the repetition-operator just like + is also used to concat strings. From ben+python at benfinney.id.au Wed Jul 18 04:07:51 2018 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 18 Jul 2018 18:07:51 +1000 Subject: [Tutor] Stuck on some basics re floats References: Message-ID: <854lgx7yqw.fsf@benfinney.id.au> Matthew Polack writes: > I'm a teacher trying to learn Python with my students. Wonderful! Thank you for choosing Python for teaching your students. > I am trying to make a very simple 'unit calculator' program...but I get an > error ..I think python is treating my num1 variable as a text string...not > an integer. Yes. You are using the ?input? function, built in to Python 3 . Read the documentation for that function; when successful, it returns text (?a string?). If you want an integer, you will need to explicitly tell Python to convert the text to an integer value. To create a new object, a general way is to use the type as a constructor. The type you want is ?int?, so use that as the constructor, and you will (if it succeeds) get a new integer as the return value:: response = input("Enter inches here: ") inches = int(response) You will also need to learn about handling conversion errors: Try entering something that is *not* a representation of an integer and see what happens. How to handle the error is up to you. -- \ ?Yesterday I parked my car in a tow-away zone. When I came back | `\ the entire area was missing.? ?Steven Wright | _o__) | Ben Finney From sydney.shall at kcl.ac.uk Wed Jul 18 09:46:20 2018 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Wed, 18 Jul 2018 15:46:20 +0200 Subject: [Tutor] Everything in one file? Message-ID: <12b49285-0c95-f5c8-019b-7f10faa9fdc6@kcl.ac.uk> On 24/05/2018 03:27, Steven D'Aprano wrote: > On Tue, May 22, 2018 at 03:46:50PM +0530, aishwarya selvaraj wrote: >> Dear all, >> I have created 2 classes in 2 separate files. > > If you have learned the bad habit from Java of putting every class in a > separate file, you should unlearn that habit for your Python code. There > is no need to put every class in a separate file, and it usually leads > to complicated dependencies and circular imports. > > I am an slightly more than a beginner. I have not met this advice from Steven D'Aprano before, so I have some questions. I have constructed a program which has a parent class and a child class and I have them in two different files. I import the parent class into the child class and create instances with the child class. This works fine. But, would it be better to have both classes in one file? Would then the child class 'know' that the parent class is in the file? And further. I have a function which sets up all the suitable data structures into which this function will put the information supplied by the user. I import this file too into both the parent and the child class. Would the instances with which I actually work, 'know' that this function is there if it is simply present in the same file? -- Sydney From steve at pearwood.info Wed Jul 18 11:52:07 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 19 Jul 2018 01:52:07 +1000 Subject: [Tutor] Everything in one file? In-Reply-To: <12b49285-0c95-f5c8-019b-7f10faa9fdc6@kcl.ac.uk> References: <12b49285-0c95-f5c8-019b-7f10faa9fdc6@kcl.ac.uk> Message-ID: <20180718155206.GT7318@ando.pearwood.info> Comments below. On Wed, Jul 18, 2018 at 03:46:20PM +0200, Shall, Sydney wrote: > On 24/05/2018 03:27, Steven D'Aprano wrote: > > On Tue, May 22, 2018 at 03:46:50PM +0530, aishwarya selvaraj wrote: > >> Dear all, > >> I have created 2 classes in 2 separate files. > > > > If you have learned the bad habit from Java of putting every class in a > > separate file, you should unlearn that habit for your Python code. There > > is no need to put every class in a separate file, and it usually leads > > to complicated dependencies and circular imports. > > > > > > I am an slightly more than a beginner. > I have not met this advice from Steven D'Aprano before, so I have some > questions. Note that I said there is no *need* to put each class in a separate file, not that one should "never" split classes into separate files. > I have constructed a program which has a parent class and a child class > and I have them in two different files. I import the parent class into > the child class and create instances with the child class. This works fine. > But, would it be better to have both classes in one file? Probably. Even better, why do you have two classes if you only ever use one? If Parent is never used on its own, and you only use Child, why bother with Parent? Put everything into one class. > Would then the > child class 'know' that the parent class is in the file? If you write this: class Parent: pass class Child(Parent): pass then it will work fine, for *exactly* the same reasons that this works: x = 99 y = x + 1 # x is already defined But if you try this instead: # Stop! This won't work! class Child(Parent): # NameError: unknown Parent pass class Parent: pass it won't work for exactly the same reason you can't write this: y = x + 1 # NameError: unknown x x = 99 > And further. I have a function which sets up all the suitable data > structures into which this function will put the information supplied by > the user. I import this file too into both the parent and the child class. > Would the instances with which I actually work, 'know' that this > function is there if it is simply present in the same file? Every line of Python code "knows" whatever variables and names exist at the moment that line of code is executed. That usually means variables, classes and functions which are defined *above* it in the file. Whether those variables are defined in place: x = 99 or imported from somewhere else: from module import x makes no difference. -- Steve From alan.gauld at yahoo.co.uk Wed Jul 18 12:00:55 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 18 Jul 2018 17:00:55 +0100 Subject: [Tutor] Everything in one file? In-Reply-To: <12b49285-0c95-f5c8-019b-7f10faa9fdc6@kcl.ac.uk> References: <12b49285-0c95-f5c8-019b-7f10faa9fdc6@kcl.ac.uk> Message-ID: On 18/07/18 14:46, Shall, Sydney wrote: > > is no need to put every class in a separate file, and it usually leads > > to complicated dependencies and circular imports. > I have constructed a program which has a parent class and a child class > and I have them in two different files. I import the parent class into > the child class and create instances with the child class. This works fine. > But, would it be better to have both classes in one file? Probably if you know when writing them that you will need to import parent to use child and especially if you are unlikely to ever use parent without child(or some other child class). > Would then the > child class 'know' that the parent class is in the file? Python visibility is controlled by the scope rules (and some other magic stuff that applies to packages but needn't concern us here!) The scope that we are concerned with is module scope, sometimes called global scope, but not in the normal sense that global has in other languages. Module or global scope means that everything inside a module is visible to everything else inside the same module. So yes you child class can see the parent class if it is in the same file (aka module). # myfile.py ########## class Parent: pass class Child(Parent): pass # EOF ############# So Parent is visible to the child definition without any extra work. Now consider the 2 file option: # parent.py ##### class Parent: pass # EOF ###### # child.py ### import parent class Child(parent.Parent): pass # EOF ###### Now the child class must import parent and dereference Parent within its module. (ie use parent.Parent) So two classes is more work for you and more work for the interpreter. > And further. I have a function which sets up all the suitable data > structures into which this function will put the information supplied by > the user. I import this file too into both the parent and the child class. > Would the instances with which I actually work, 'know' that this > function is there if it is simply present in the same file? Yes, again the function definition would have module/global scope so the classes can see the function with no extra work. The instances don;t see the function idf they are in a separate file but they do see their class definition which includes all the methods. And those methods see the function. Like so: # myfile2.py ########## def myFunc(): return (1,2,3) # some data structure... class Parent: pass class Child(Parent): def __init__(self): self.data = myFunc() # access the function # EOF ############# # myinstance.py ### import myfile2 instance = myfile2.Child() print(instance.data) # -> (1,2,3) # EOF #### So it works. But it's probably bad practice. Classes should do all their own data maniplulation. Having a function outside the class preparing data structures for use by a class is bad OOP practice. Much better to prepare the data structures inside the class - maybe as a method of Parent? Remember classes are data structures too. That's why its called object oriented programming - you define objects and pass the objects around. You don't pass data between objects. You pass objects. Objects are data, and they know how to process their own data - so nobody else should need to. That's called encapsulation and is the basis of all things OOP. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Wed Jul 18 12:05:31 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 18 Jul 2018 17:05:31 +0100 Subject: [Tutor] Stuck on some basics re floats In-Reply-To: References: Message-ID: On 18/07/18 14:10, Matthew Polack wrote: > Thanks for the reply Alan. > > I found another fix where I could just use this: > > num1 =int(input('Ener inches here?: ')) > > > but a lot of people like yourself.... seem to be recommending this > 'float' method. It all depends whether your input is a float or an integer. If it will always be a whole number of inches then use int(). If it will be a floating point value then you need to use float(). In your example I'd have thought it reasonable to allow conversions of, say, 11.5 inches... I meant to add that its generally considered good practice to do the conversion as early as possible unless you plan on using the string version later. So wrapping the input() call inside the int or float call is good. You can then wrap that inside a try/except and get the user to re-try if they type invalid data - if you so wish... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Wed Jul 18 12:14:11 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 18 Jul 2018 17:14:11 +0100 Subject: [Tutor] Everything in one file? In-Reply-To: References: <12b49285-0c95-f5c8-019b-7f10faa9fdc6@kcl.ac.uk> Message-ID: On 18/07/18 17:00, Alan Gauld via Tutor wrote: > Now the child class must import parent and dereference > Parent within its module. (ie use parent.Parent) > > So two classes is more work for you and more work > for the interpreter. Oops, that should be two *files* is more work... sorry, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From mats at wichmann.us Wed Jul 18 13:42:50 2018 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 18 Jul 2018 11:42:50 -0600 Subject: [Tutor] Everything in one file? In-Reply-To: References: <12b49285-0c95-f5c8-019b-7f10faa9fdc6@kcl.ac.uk> Message-ID: <528c2621-7c7c-167e-2803-daf7de350265@wichmann.us> On 07/18/2018 10:00 AM, Alan Gauld via Tutor wrote: > On 18/07/18 14:46, Shall, Sydney wrote: > >> > is no need to put every class in a separate file, and it usually leads >> > to complicated dependencies and circular imports. > >> I have constructed a program which has a parent class and a child class >> and I have them in two different files. I import the parent class into >> the child class and create instances with the child class. This works fine. >> But, would it be better to have both classes in one file? > > Probably if you know when writing them that you will need to > import parent to use child and especially if you are unlikely > to ever use parent without child(or some other child class). > >> Would then the >> child class 'know' that the parent class is in the file? I had been writing something here and then saw Alan and Steven had already sent pretty much what I was trying to say! > Python visibility is controlled by the scope rules (and some other magic > stuff that applies to packages but needn't concern us here!) > > The scope that we are concerned with is module scope, > sometimes called global scope, but not in the normal sense > that global has in other languages. Module or global scope > means that everything inside a module is visible to > everything else inside the same module. > > So yes you child class can see the parent class if > it is in the same file (aka module). A couple of extra points... first, in standard Python, function and class definitions are runnable statements which are evaluated when encountered (this sometimes surprises new developers), creating objects which are then available to use when it comes time to call them. So "order matters" as Steven was saying, class Child(Parent): pass class Parent: pass fails on the Child class definition because there is not yet a class object named Parent that Child can inherit from. In compiled languages the compiler can figure it all out since it processes it all up front before anything is run, but may still require "forward declarations" to make its life simpler, so it's not so different after all. second, Python creates namespaces - C++ developers, say, may be used to declaring their own namespace, and being able to split those namespaces across multiple files, but Python tends to use a module-based approach. If you just write a single Python file, and run it, Python considers that to be a module named __main__ (stick the line print(__name__) in a python file and run it to see, or use the interpreter), and that has its own set of symbols, called globals but really just module-global. If you want to get the symbols from another module, you need to "import" them, and they appear in a namespace matching that module name. So, # assume module foo defines function bar import foo # makes available the symbols from foo # your module can call foo as foo.bar() but also: from foo import bar # makes available that symbol in _your_ namespace # your module can now call bar as bar(). These are really just symbol-visibility tricks, so you can do both if you have any desire to do so: import foo from foo import bar bar() foo.bar() maybe that's drifting off-topic, so I'll stop now :) From ahubbard at umn.edu Tue Jul 24 15:55:50 2018 From: ahubbard at umn.edu (Aimee Hubbard) Date: Tue, 24 Jul 2018 14:55:50 -0500 Subject: [Tutor] Getting started with Python Message-ID: Hi, I have done some introductory courses with Python, but they did not cover how to get Python (3.7 version 64 bit) up and running on my own computer. I have it downloaded on my Windows 10 computer and made sure in my "Environment Variables" that it has the path (C:\Users\aimee6\AppData\Local\Programs\Python\Python37\lib\site-packages). But whenever I try to run any commands like "python --version" I get this error: Traceback (most recent call last): File "", line 1, in python NameError: name 'python' is not defined I am just not sure what step I am missing. Any help you can offer would be greatly appreciated. Thank you so much and I hope you are having a great night! Best, Aimee -- *Aimee Hubbard M.S.* Editorial Assistant, *Journal of Marital & Family Therapy* Doctoral Student, Family Social Science-Couple & Family Therapy University of Minnesota ahubbard at umn.edu From mats at wichmann.us Tue Jul 24 16:38:21 2018 From: mats at wichmann.us (Mats Wichmann) Date: Tue, 24 Jul 2018 14:38:21 -0600 Subject: [Tutor] Getting started with Python In-Reply-To: References: Message-ID: On 07/24/2018 01:55 PM, Aimee Hubbard wrote: > Hi, > I have done some introductory courses with Python, but they did not cover > how to get Python (3.7 version 64 bit) up and running on my own computer. I > have it downloaded on my Windows 10 computer and made sure in my > "Environment Variables" that it has the path > (C:\Users\aimee6\AppData\Local\Programs\Python\Python37\lib\site-packages). > But whenever I try to run any commands like "python --version" I get this > error: > Traceback (most recent call last): > File "", line 1, in > python > NameError: name 'python' is not defined > > I am just not sure what step I am missing. Any help you can offer would be > greatly appreciated. Thank you so much and I hope you are having a great > night! you are typing the command _inside_ the python shell. The command you are trying is intended to be typed to a command shell (outside python) to get the version from inside python type these: import sys print(sys.version) From BeckC21 at duchesne.org Wed Jul 25 13:36:53 2018 From: BeckC21 at duchesne.org (Beck, Caroline) Date: Wed, 25 Jul 2018 17:36:53 +0000 Subject: [Tutor] images In-Reply-To: References: Message-ID: Hi! I am a student working on a game in which I am trying to use a gif as my turtle. Currently, the turtle moves around the screen with the arrow keys, but the gif does not move with it. Below is how I have tried to tell the code that the gif is the turtle, but the code is not reading that the gif is my turtle. I was wondering if I could have some help with making the gif in my code to read as my turtle. Thank you! Here is my code so far: import random import turtle as t screen = t.Screen() screen.setup(1250,900) screen.bgpic("newbackground.gif") screen.addshape("shark.gif") t.shape("shark.gif") shark = t.Turtle() shark.speed(0) shark.penup() shark.hideturtle() leaf = t.Turtle() leaf_shape = ((0,0), (14,2), (18,6), (20,20),(6,18), (2,14)) t.register_shape('leaf', leaf_shape) leaf.shape('leaf') leaf.color('orange') leaf.penup() leaf.hideturtle() leaf.speed(0) game_started = False text_turtle = t.Turtle() text_turtle.write('Press SPACE to start', align='center', font=('Arial',16,'bold')) text_turtle.hideturtle() score_turtle = t.Turtle() score_turtle.hideturtle() score_turtle.speed(0) def outside_window(): left_wall = -t.window_width() / 2 right_wall = t.window_width() / 2 top_wall = t.window_height() / 2 bottom_wall = -t.window_height() / 2 (x,y) = t.pos() outside = \ x< left_wall or \ x> right_wall or \ y< bottom_wall or \ y> top_wall return outside def game_over(): t.penup() t.hideturtle() t.write('GAME OVER!', align='center', font=('Arial', 30, 'normal')) def display_score(current_score): score_turtle.clear() score_turtle.penup() x = (t.window_width()/2) - 50 y = (t.window_height()/2) - 50 score_turtle.setpos(x, y) score_turtle.write(str(current_score), align='right',font=('Arial', 40, 'bold')) def place_leaf(): leaf.ht() leaf.setx(random.randint(-200,200)) leaf.sety(random.randint(-200,200)) leaf.st() def start_game(): global game_started if game_started: return game_started = True score=0 text_turtle.clear shark_speed = 2 shark_length = 3 shark.shapesize(1, shark_length,1) shark.showturtle() display_score(score) place_leaf() while True: shark.forward(shark_speed) if shark.distance(leaf) < 20: place_leaf() #shark_length=t_length + 1 #shark.shapesize(1, t_length, 1) shark_speed=shark_speed + 1 score = score + 10 display_score(score) if outside_window(): game_over() break def move_up(): if shark.heading() == 0 or shark.heading() == 180: shark.setheading(90) def move_down(): if shark.heading() == 0 or shark.heading() == 180: shark.setheading(270) def move_left(): if shark.heading() == 90 or shark.heading() == 270: shark.setheading(180) def move_right(): if shark.heading() == 90 or shark.heading() == 270: shark.setheading(0) t.onkey(start_game, 'space') t.onkey(move_up, 'Up') t.onkey(move_right, 'Right') t.onkey(move_down, 'Down') t.onkey(move_left, 'Left') t.listen() t.mainloop() From: Crystal Frommert Sent: Tuesday, July 24, 2018 1:11 PM To: Beck, Caroline Subject: images Try a gif image instead of png From jf_byrnes at comcast.net Wed Jul 25 19:50:56 2018 From: jf_byrnes at comcast.net (Jim) Date: Wed, 25 Jul 2018 18:50:56 -0500 Subject: [Tutor] How can I find a group of characters in a list of strings? Message-ID: Linux mint 18 and python 3.6 I have a list of strings that contains slightly more than a million items. Each item is a string of 8 capital letters like so: ['MIBMMCCO', 'YOWHHOY', ...] I need to check and see if the letters 'OFHCMLIP' are one of the items in the list but there is no way to tell in what order the letters will appear. So I can't just search for the string 'OFHCMLIP'. I just need to locate any strings that are made up of those letters no matter their order. I suppose I could loop over the list and loop over each item using a bunch of if statements exiting the inner loop as soon as I find a letter is not in the string, but there must be a better way. I'd appreciate hearing about a better way to attack this. thanks, Jim From mats at wichmann.us Wed Jul 25 20:23:11 2018 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 25 Jul 2018 18:23:11 -0600 Subject: [Tutor] How can I find a group of characters in a list of strings? In-Reply-To: References: Message-ID: <2fc9bd07-3e5c-5bc6-eae2-7a707de98267@wichmann.us> On 07/25/2018 05:50 PM, Jim wrote: > Linux mint 18 and python 3.6 > > I have a list of strings that contains slightly more than a million > items. Each item is a string of 8 capital letters like so: > > ['MIBMMCCO', 'YOWHHOY', ...] > > I need to check and see if the letters 'OFHCMLIP' are one of the items > in the list but there is no way to tell in what order the letters will > appear. So I can't just search for the string 'OFHCMLIP'. I just need to > locate any strings that are made up of those letters no matter their order. > > I suppose I could loop over the list and loop over each item using a > bunch of if statements exiting the inner loop as soon as I find a letter > is not in the string, but there must be a better way. > > I'd appreciate hearing about a better way to attack this. It's possible that the size of the biglist and the length of the key has enough performance impacts that a quicky (untested because I don't have your data) solution is unworkable for performance reasons. But a quicky might be to take these two steps: 1. generate a list of the permutations of the target 2. check if any member of the target-permutation-list is in the biglist. Python sets are a nice way to check membership. from itertools import permutations permlist = [''.join(p) for p in permutations('MIBMMCCO', 8)] if not set(permlist).isdisjoint(biglist): print("Found a permutation of MIBMMCCO") From steve at pearwood.info Wed Jul 25 20:43:56 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 26 Jul 2018 10:43:56 +1000 Subject: [Tutor] How can I find a group of characters in a list of strings? In-Reply-To: References: Message-ID: <20180726004355.GL8744@ando.pearwood.info> On Wed, Jul 25, 2018 at 06:50:56PM -0500, Jim wrote: [...] > I need to check and see if the letters 'OFHCMLIP' are one of the items > in the list but there is no way to tell in what order the letters will > appear. So I can't just search for the string 'OFHCMLIP'. I just need to > locate any strings that are made up of those letters no matter their order. data = ['MIBMMCCO', 'YOWHHOY', 'ABCDEFG', 'HCMLIPOF', 'TUVWXYZ'] target = sorted('OFHCMLIP') for pos, item in enumerate(data): if sorted(item) == target: print("found", pos, item) break -- Steve From martin at linux-ip.net Wed Jul 25 20:29:27 2018 From: martin at linux-ip.net (Martin A. Brown) Date: Wed, 25 Jul 2018 17:29:27 -0700 Subject: [Tutor] How can I find a group of characters in a list of strings? In-Reply-To: References: Message-ID: > I have a list of strings that contains slightly more than a > million items. Each item is a string of 8 capital letters like so: > > ['MIBMMCCO', 'YOWHHOY', ...] > > I need to check and see if the letters 'OFHCMLIP' are one of the items in the > list but there is no way to tell in what order the letters will appear. So I > can't just search for the string 'OFHCMLIP'. I just need to locate any strings > that are made up of those letters no matter their order. > > I suppose I could loop over the list and loop over each item using a bunch of > if statements exiting the inner loop as soon as I find a letter is not in the > string, but there must be a better way. > > I'd appreciate hearing about a better way to attack this. > > thanks, Jim If I only had to do this once, over only a million items (given today's CPU power), so I'd probably do something like the below using sets. I couldn't tell from your text whether you wanted to see all of the entries in 'OFHCMLIP' in each entry or if you wanted to see only that some subset were present. So, here's a script that will produce a partial match and exact match. Note, I made a 9-character string, too because you had a 7-character string as your second sample -- mostly to point out that the 9-character string satisfies an exact match although it sports an extra character. farm = ['MIBMMCCO', 'YOWHHOY', 'OFHCMLIP', 'OFHCMLIPZ', 'FHCMLIP', 'NEGBQJKR'] needle = set('OFHCMLIP') for haystack in farm: partial = needle.intersection(haystack) exact = needle.intersection(haystack) == needle print(haystack, exact, ''.join(sorted(partial))) On the other hand, there are probably lots of papers on how to do this much more efficiently. -Martin MIBMMCCO False CIMO YOWHHOY False HO OFHCMLIP True CFHILMOP OFHCMLIPZ True CFHILMOP FHCMLIP False CFHILMP NEGBQJKR False -- Martin A. Brown http://linux-ip.net/ From jf_byrnes at comcast.net Wed Jul 25 21:36:41 2018 From: jf_byrnes at comcast.net (Jim) Date: Wed, 25 Jul 2018 20:36:41 -0500 Subject: [Tutor] How can I find a group of characters in a list of strings? In-Reply-To: <20180726004355.GL8744@ando.pearwood.info> References: <20180726004355.GL8744@ando.pearwood.info> Message-ID: On 07/25/2018 07:43 PM, Steven D'Aprano wrote: > On Wed, Jul 25, 2018 at 06:50:56PM -0500, Jim wrote: > [...] >> I need to check and see if the letters 'OFHCMLIP' are one of the items >> in the list but there is no way to tell in what order the letters will >> appear. So I can't just search for the string 'OFHCMLIP'. I just need to >> locate any strings that are made up of those letters no matter their order. > > data = ['MIBMMCCO', 'YOWHHOY', 'ABCDEFG', 'HCMLIPOF', 'TUVWXYZ'] > > target = sorted('OFHCMLIP') > for pos, item in enumerate(data): > if sorted(item) == target: > print("found", pos, item) > break Stephen, Perfect, thank you. I did remove the break because I thought I would get more than one hit. I got 196, more that I hoped for but now I have a better idea of what I am working with. Regards, Jim From jf_byrnes at comcast.net Wed Jul 25 21:40:15 2018 From: jf_byrnes at comcast.net (Jim) Date: Wed, 25 Jul 2018 20:40:15 -0500 Subject: [Tutor] How can I find a group of characters in a list of strings? In-Reply-To: References: Message-ID: On 07/25/2018 07:29 PM, Martin A. Brown wrote: > >> I have a list of strings that contains slightly more than a >> million items. Each item is a string of 8 capital letters like so: >> >> ['MIBMMCCO', 'YOWHHOY', ...] >> >> I need to check and see if the letters 'OFHCMLIP' are one of the items in the >> list but there is no way to tell in what order the letters will appear. So I >> can't just search for the string 'OFHCMLIP'. I just need to locate any strings >> that are made up of those letters no matter their order. >> >> I suppose I could loop over the list and loop over each item using a bunch of >> if statements exiting the inner loop as soon as I find a letter is not in the >> string, but there must be a better way. >> >> I'd appreciate hearing about a better way to attack this. >> >> thanks, Jim > > If I only had to do this once, over only a million items (given > today's CPU power), so I'd probably do something like the below > using sets. I couldn't tell from your text whether you wanted to > see all of the entries in 'OFHCMLIP' in each entry or if you wanted > to see only that some subset were present. So, here's a script that > will produce a partial match and exact match. > > Note, I made a 9-character string, too because you had a 7-character > string as your second sample -- mostly to point out that the > 9-character string satisfies an exact match although it sports an > extra character. Sorry, that was a typo, they are all 8 characters in length. > farm = ['MIBMMCCO', 'YOWHHOY', 'OFHCMLIP', 'OFHCMLIPZ', 'FHCMLIP', 'NEGBQJKR'] > needle = set('OFHCMLIP') > for haystack in farm: > partial = needle.intersection(haystack) > exact = needle.intersection(haystack) == needle > print(haystack, exact, ''.join(sorted(partial))) > > On the other hand, there are probably lots of papers on how to do > this much more efficiently. > > -Martin Thanks for your help. Steven came up with a solution that works well for me. Regards, Jim From steve at pearwood.info Thu Jul 26 01:57:44 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 26 Jul 2018 15:57:44 +1000 Subject: [Tutor] How can I find a group of characters in a list of strings? In-Reply-To: References: Message-ID: <20180726055744.GQ8744@ando.pearwood.info> On Wed, Jul 25, 2018 at 05:29:27PM -0700, Martin A. Brown wrote: > If I only had to do this once, over only a million items (given > today's CPU power), so I'd probably do something like the below > using sets. The problem with sets is that they collapse multiple instances of characters to a single one, so that 'ABC' will match 'ABBBCC'. There's no indication that is what is required. -- Steve From matt.ruffalo at gmail.com Wed Jul 25 20:42:58 2018 From: matt.ruffalo at gmail.com (Matt Ruffalo) Date: Wed, 25 Jul 2018 20:42:58 -0400 Subject: [Tutor] How can I find a group of characters in a list of strings? In-Reply-To: <2fc9bd07-3e5c-5bc6-eae2-7a707de98267@wichmann.us> References: <2fc9bd07-3e5c-5bc6-eae2-7a707de98267@wichmann.us> Message-ID: <1c725f91-0918-24fd-6ada-8d1b9e2aaeb3@gmail.com> On 2018-07-25 20:23, Mats Wichmann wrote: > On 07/25/2018 05:50 PM, Jim wrote: >> Linux mint 18 and python 3.6 >> >> I have a list of strings that contains slightly more than a million >> items. Each item is a string of 8 capital letters like so: >> >> ['MIBMMCCO', 'YOWHHOY', ...] >> >> I need to check and see if the letters 'OFHCMLIP' are one of the items >> in the list but there is no way to tell in what order the letters will >> appear. So I can't just search for the string 'OFHCMLIP'. I just need to >> locate any strings that are made up of those letters no matter their order. >> >> I suppose I could loop over the list and loop over each item using a >> bunch of if statements exiting the inner loop as soon as I find a letter >> is not in the string, but there must be a better way. >> >> I'd appreciate hearing about a better way to attack this. > It's possible that the size of the biglist and the length of the key has > enough performance impacts that a quicky (untested because I don't have > your data) solution is unworkable for performance reasons. But a quicky > might be to take these two steps: > > 1. generate a list of the permutations of the target > 2. check if any member of the target-permutation-list is in the biglist. > > Python sets are a nice way to check membership. > > from itertools import permutations > permlist = [''.join(p) for p in permutations('MIBMMCCO', 8)] > > if not set(permlist).isdisjoint(biglist): > print("Found a permutation of MIBMMCCO") > I would *strongly* recommend against keeping a list of all permutations of the query string; though there are only 8! = 40320 permutations of 8 characters, suggesting anything with factorial runtime should be done only as a last resort. This could pretty effectively be solved by considering each string in the list as a set of characters for query purposes, and keeping a set of those, making membership testing constant-time. Note that the inner sets will have to be frozensets because normal sets aren't hashable. For example: """ In [1]: strings = ['MIBMMCCO', 'YOWHHOY'] In [2]: query = 'OFHCMLIP' In [3]: search_db = {frozenset(s) for s in strings} In [4]: frozenset(query) in search_db Out[4]: False In [5]: frozenset('MMCOCBIM') in search_db # permutation of first string Out[5]: True """ MMR... From robertvstepp at gmail.com Fri Jul 27 00:34:11 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Thu, 26 Jul 2018 23:34:11 -0500 Subject: [Tutor] Questions about the formatting of docstrings Message-ID: I am near the end of reading "Documenting Python Code: A Complete Guide" by James Mertz, found at https://realpython.com/documenting-python-code/ This has led me to a few questions: (1) The author claims that reStructuredText is the official Python documentation standard. Is this true? If yes, is this something I should be doing for my own projects? (2) How would type hints work with this reStructuredText formatting? In part of the author's reStructuredText example he has: [...] :param file_loc: The file location of the spreadsheet :type file_loc: str [...] It seems to me that if type hinting is being used, then the ":type" info is redundant, so I wonder if special provision is made for avoiding this redundancy when using type hinting? TIA! -- boB From steve at pearwood.info Fri Jul 27 01:49:31 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 27 Jul 2018 15:49:31 +1000 Subject: [Tutor] Questions about the formatting of docstrings In-Reply-To: References: Message-ID: <20180727054931.GB22554@ando.pearwood.info> On Thu, Jul 26, 2018 at 11:34:11PM -0500, boB Stepp wrote: > I am near the end of reading "Documenting Python Code: A Complete > Guide" by James Mertz, found at > https://realpython.com/documenting-python-code/ This has led me to a > few questions: > > (1) The author claims that reStructuredText is the official Python > documentation standard. Is this true? If yes, is this something I > should be doing for my own projects? Yes, it is true. If you write documentation for the Python standard library, they are supposed to be in ReST. Docstrings you read in the interactive interpreter often aren't, but the documentation you read on the web page has all been automatically generated from ReST text files. As for your own projects... *shrug*. Are you planning to automatically build richly formatted PDF and HTML files from plain text documentation? If not, I wouldn't worry too much. On the other hand, if your documentation will benefit from things like: Headings ======== * lists of items * with bullets Definition a concise explanation of the meaning of a word then you're probably already using something close to ReST. > (2) How would type hints work with this reStructuredText formatting? Before Python 3 introduced syntax for type hints: def func(arg: int) -> float: ... there were a number of de facto conventions for coding that information into the function doc string. Being plain text, the human reader can simply read it, but being a standard format, people can write tools to extract that information and process it. Well I say standard format, but in fact there were a number of slightly different competing formats. > In part of the author's reStructuredText example he has: > > [...] > :param file_loc: The file location of the spreadsheet > :type file_loc: str > [...] As far as I remember, that's not part of standard ReST, but an extension used by the Sphinx restructured text tool. I don't know what it does with that information, but being a known format, any tool can parse the docstring, extract out the parameters and their types, and generate documentation, do type checking (either statically or dynamically) or whatever else you want to do. > It seems to me that if type hinting is being used, then the ":type" > info is redundant, so I wonder if special provision is made for > avoiding this redundancy when using type hinting? No. You can use one, or the other, or both, or neither, whatever takes your fancy. I expect that as Python 2 fades away, it will eventually become common practice to document types using a type hint rather than in the docstring and people will simply stop writing things like ":type file_loc: str" in favour of using def func(file_loc: str). -- Steve From robertvstepp at gmail.com Fri Jul 27 13:23:00 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 27 Jul 2018 12:23:00 -0500 Subject: [Tutor] Questions about the formatting of docstrings In-Reply-To: <20180727054931.GB22554@ando.pearwood.info> References: <20180727054931.GB22554@ando.pearwood.info> Message-ID: On Fri, Jul 27, 2018 at 12:50 AM Steven D'Aprano wrote: > > On Thu, Jul 26, 2018 at 11:34:11PM -0500, boB Stepp wrote: > > (1) The author claims that reStructuredText is the official Python > > documentation standard. Is this true? If yes, is this something I > > should be doing for my own projects? > > Yes, it is true. If you write documentation for the Python standard > library, they are supposed to be in ReST. Docstrings you read in > the interactive interpreter often aren't, but the documentation you read > on the web page has all been automatically generated from ReST text > files. What tool is being used to generate the documentation from the ReST text files? Thanks! boB From mats at wichmann.us Fri Jul 27 13:29:41 2018 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 27 Jul 2018 11:29:41 -0600 Subject: [Tutor] Questions about the formatting of docstrings In-Reply-To: References: <20180727054931.GB22554@ando.pearwood.info> Message-ID: <61e885a5-1523-a2d3-3432-1ded37ac5550@wichmann.us> On 07/27/2018 11:23 AM, boB Stepp wrote: > On Fri, Jul 27, 2018 at 12:50 AM Steven D'Aprano wrote: >> >> On Thu, Jul 26, 2018 at 11:34:11PM -0500, boB Stepp wrote: > >>> (1) The author claims that reStructuredText is the official Python >>> documentation standard. Is this true? If yes, is this something I >>> should be doing for my own projects? >> >> Yes, it is true. If you write documentation for the Python standard >> library, they are supposed to be in ReST. Docstrings you read in >> the interactive interpreter often aren't, but the documentation you read >> on the web page has all been automatically generated from ReST text >> files. > > What tool is being used to generate the documentation from the ReST text files? I'm not sure if Python is still using it, but Sphinx is a popular choice, originally written to handle the Python docs. From sydney.shall at kcl.ac.uk Fri Jul 27 06:55:16 2018 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Fri, 27 Jul 2018 12:55:16 +0200 Subject: [Tutor] how to change the command "string" on a tkinter Button? In-Reply-To: <20180701091934.GW14437@ando.pearwood.info> References: <140dc3c6-2150-737a-fc09-df458a769833@internode.on.net> <1cf7d268-1eb8-55c7-872e-6ca28ad7ba2e@internode.on.net> <20180701091934.GW14437@ando.pearwood.info> Message-ID: <5f675f1d-f811-7b09-1d86-b3f178992a84@kcl.ac.uk> On 01/07/2018 11:19, Steven D'Aprano wrote: > On Sun, Jul 01, 2018 at 03:32:59PM +1000, Chris Roy-Smith wrote: >> > "Save As..." before engaging in big changes is your friend :-) > > Even better would be to learn a form of VCS (version control system) > such as Mercurial (hg) or git. Depending on the text editor you are > using, it may have VCS integration available. > Does Spyder have a VCS? Could you list a few text-editors that do have VCS, please. -- _________ Professor Sydney Shall Department of Haematology/Oncology Phone: +(0)2078489200 E-Mail: sydney.shall [Correspondents outside the College should add @kcl.ac.uk] From valerio at pbds.eu Fri Jul 27 08:56:46 2018 From: valerio at pbds.eu (Valerio Pachera) Date: Fri, 27 Jul 2018 14:56:46 +0200 (CEST) Subject: [Tutor] Do something on list elements Message-ID: <1854107779.11.1532696206426.JavaMail.zimbra@pbds.eu> Hi all, I started studying python and I hope you may help me getting better. Let's start with the first question. Consider this example --- #!/usr/bin/python3 l = ['unoX', 'dueX'] c = 0 for n in l: l[c] = l[c].replace('X','') c = c + 1 print (l) --- it works but I wonder if there's a better way to achieve the same. From alan.gauld at yahoo.co.uk Fri Jul 27 17:40:10 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 27 Jul 2018 22:40:10 +0100 Subject: [Tutor] how to change the command "string" on a tkinter Button? In-Reply-To: <5f675f1d-f811-7b09-1d86-b3f178992a84@kcl.ac.uk> References: <140dc3c6-2150-737a-fc09-df458a769833@internode.on.net> <1cf7d268-1eb8-55c7-872e-6ca28ad7ba2e@internode.on.net> <20180701091934.GW14437@ando.pearwood.info> <5f675f1d-f811-7b09-1d86-b3f178992a84@kcl.ac.uk> Message-ID: On 27/07/18 11:55, Shall, Sydney wrote: > On 01/07/2018 11:19, Steven D'Aprano wrote: >> Even better would be to learn a form of VCS (version control system) >> such as Mercurial (hg) or git. Depending on the text editor you are >> using, it may have VCS integration available. > > Does Spyder have a VCS? Dunno, sorry... > Could you list a few text-editors that do have VCS, please. It's not so much that they have a VCS but that they integrate with an existing VCS. So they will typically have menu options for checking in/out a file or locking/unlocking it. Typically you can configure which VCS they use from a list of common options, in some cases you can define the command line to use for each menu action. vim, emacs, Eclipse, Netbeans, VisualStudio etc all support VCS to varying degrees. But you still need to install and configure a VCS engine such as CVS, SVN, Hg or git etc. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Jul 27 18:06:55 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 27 Jul 2018 23:06:55 +0100 Subject: [Tutor] Do something on list elements In-Reply-To: <1854107779.11.1532696206426.JavaMail.zimbra@pbds.eu> References: <1854107779.11.1532696206426.JavaMail.zimbra@pbds.eu> Message-ID: On 27/07/18 13:56, Valerio Pachera wrote: > l = ['unoX', 'dueX'] > c = 0 > for n in l: > l[c] = l[c].replace('X','') > c = c + 1 > print (l) > --- > > it works but I wonder if there's a better way to achieve the same. Yes, a much better way. for index, s in l: l[index] = s.replace('X','') print(l) But better still is a list comprehension: l = [s.replace('X','') for s in l) print(l) In Python you very rarely need to resort to using indexes to process the members of a collection. And even more rarely do you need to manually increment the index. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From cs at cskk.id.au Fri Jul 27 18:32:18 2018 From: cs at cskk.id.au (Cameron Simpson) Date: Sat, 28 Jul 2018 08:32:18 +1000 Subject: [Tutor] Do something on list elements In-Reply-To: References: Message-ID: <20180727223218.GA4536@cskk.homeip.net> On 27Jul2018 23:06, Alan Gauld wrote: >On 27/07/18 13:56, Valerio Pachera wrote: > >> l = ['unoX', 'dueX'] >> c = 0 >> for n in l: >> l[c] = l[c].replace('X','') >> c = c + 1 >> print (l) >> >> it works but I wonder if there's a better way to achieve the same. > >Yes, a much better way. > >for index, s in l: > l[index] = s.replace('X','') >print(l) I think you meant: for index, s in enumerate(l): >But better still is a list comprehension: > >l = [s.replace('X','') for s in l) >print(l) > >In Python you very rarely need to resort to using indexes >to process the members of a collection. And even more rarely >do you need to manually increment the index. I use indices when I need to modify the elements of a list in place. The list comprehension makes a shiny new list. That is usually fine, but not always what is required. I also have (rare) occasions where an item wants know its own index. In that case one wants the index floating around so it can be attached to the item. The other place I use enumerate in a big way is to track line numbers in files, as context for error messages (either now or later). For example: with open(filename) as f: for lineno, line in enumerate(f, 1): if badness: print("%s:%d: badness happened" % (filename, lineno), file=sys.stderr) continue ... process good lines ... Cheers, Cameron Simpson From alan.gauld at yahoo.co.uk Fri Jul 27 19:24:41 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 28 Jul 2018 00:24:41 +0100 Subject: [Tutor] Do something on list elements In-Reply-To: <20180727223218.GA4536@cskk.homeip.net> References: <20180727223218.GA4536@cskk.homeip.net> Message-ID: On 27/07/18 23:32, Cameron Simpson wrote: >> for index, s in l: >> l[index] = s.replace('X','') >> print(l) > > I think you meant: > > for index, s in enumerate(l): Oops, yes. Sorry. >> In Python you very rarely need to resort to using indexes >> to process the members of a collection. And even more rarely >> do you need to manually increment the index. > > I use indices when I need to modify the elements of a list in place. Yes, that's probably the most common use case, and enumerate is the best way to do that. > comprehension makes a shiny new list. That is usually fine, but not always what > is required. >From a purist point of view its usually preferable but in practice making copies of large data structures is usually a bad idea. In that case you are forced to resort to enumerate, I agree. > The other place I use enumerate in a big way is to track line numbers in files, > as context for error messages (either now or later). For example: Yes, but then you don't use the index to access/process the data. Its just providing context. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From mats at wichmann.us Fri Jul 27 20:28:10 2018 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 27 Jul 2018 18:28:10 -0600 Subject: [Tutor] Do something on list elements In-Reply-To: <20180727223218.GA4536@cskk.homeip.net> References: <20180727223218.GA4536@cskk.homeip.net> Message-ID: <880f822a-f761-b0e8-9d54-d5f423b18af9@wichmann.us> On 07/27/2018 04:32 PM, Cameron Simpson wrote: > On 27Jul2018 23:06, Alan Gauld wrote: >> In Python you very rarely need to resort to using indexes >> to process the members of a collection. And even more rarely >> do you need to manually increment the index. I think this was an important point: use a list index only when the actual value of the index is important, otherwise use the fact that a list is iterable by just looping over the list itself without bothering with indices... it's a powerful enough idea that C++. C# and other languages picked it up. > I use indices when I need to modify the elements of a list in place. The > list comprehension makes a shiny new list. That is usually fine, but not > always what is required. True indeed, but in this case since the elements being modified are strings, which are immutable and thus "modifying" a string creates a new string, we're not really buying anything by not creating a new list of those new strings along the way... From sjeik_appie at hotmail.com Sat Jul 28 09:47:29 2018 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Sat, 28 Jul 2018 13:47:29 +0000 Subject: [Tutor] Questions about the formatting of docstrings In-Reply-To: Message-ID: On 27 Jul 2018 06:34, boB Stepp wrote: I am near the end of reading "Documenting Python Code: A Complete Guide" by James Mertz, found at https://realpython.com/documenting-python-code/ This has led me to a few questions: (1) The author claims that reStructuredText is the official Python documentation standard. Is this true? If yes, is this something I should be doing for my own projects? (2) How would type hints work with this reStructuredText formatting? In part of the author's reStructuredText example he has: [...] :param file_loc: The file location of the spreadsheet :type file_loc: str [...] Hi Bob, Have a look at numpydoc, which works with Sphinx. Numpydoc makes it much easier to read and write docstrings, while they can still be converted into nice looking docs, e.g html. See: https://codeandchaos.wordpress.com/2012/08/09/sphinx-and-numpydoc/ Albert-Jan From sydney.shall at kcl.ac.uk Sat Jul 28 06:15:42 2018 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Sat, 28 Jul 2018 12:15:42 +0200 Subject: [Tutor] how to change the command "string" on a tkinter Button? In-Reply-To: References: <140dc3c6-2150-737a-fc09-df458a769833@internode.on.net> <1cf7d268-1eb8-55c7-872e-6ca28ad7ba2e@internode.on.net> <20180701091934.GW14437@ando.pearwood.info> <5f675f1d-f811-7b09-1d86-b3f178992a84@kcl.ac.uk> Message-ID: <29a561f0-5a95-53d1-743d-6ffe6a94d588@kcl.ac.uk> On 27/07/2018 23:40, Alan Gauld via Tutor wrote: > On 27/07/18 11:55, Shall, Sydney wrote: >> On 01/07/2018 11:19, Steven D'Aprano wrote: >>> Even better would be to learn a form of VCS (version control system) >>> such as Mercurial (hg) or git. Depending on the text editor you are >>> using, it may have VCS integration available. >> >> Does Spyder have a VCS? > > Dunno, sorry... > >> Could you list a few text-editors that do have VCS, please. > > It's not so much that they have a VCS but that they integrate > with an existing VCS. So they will typically have menu options > for checking in/out a file or locking/unlocking it. Typically > you can configure which VCS they use from a list of common > options, in some cases you can define the command line to > use for each menu action. > > vim, emacs, Eclipse, Netbeans, VisualStudio etc all > support VCS to varying degrees. > > But you still need to install and configure a VCS > engine such as CVS, SVN, Hg or git etc. > Thanks, that clarifies it for me. I shall learn to use GIT. Sydney From sunil.techspk at gmail.com Mon Jul 30 09:20:59 2018 From: sunil.techspk at gmail.com (Sunil Tech) Date: Mon, 30 Jul 2018 18:50:59 +0530 Subject: [Tutor] Python Memory Allocation -- deep learning Message-ID: Hi Team, I am investigating how the memory allocation happens in Python For Eg: *Case 1:* >>> a = 10 >>> b = 10 >>> c = 10 >>> id(a), id(b), id(c) (140621897573616, 140621897573616, 140621897573616) >>> a += 1 >>> id(a) 140621897573592 *Case 2:* >>> x = 500 >>> y = 500 >>> id(x) 4338740848 >>> id(y) 4338741040 *Case 3:* >>> s1 = 'hello' >>> s2 = 'hello' >>> id(s1), id(s2) (4454725888, 4454725888) >>> s1 == s2 True >>> s1 is s2 True >>> s3 = 'hello, world!' >>> s4 = 'hello, world!' >>> id(s3), id(s4) (4454721608, 4454721664) >>> s3 == s4 True >>> s3 is s4 False Python memory allocation is varying in all these use cases. Please help me understand. Thanks, Sunil. G From joel.goldstick at gmail.com Mon Jul 30 11:09:55 2018 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 30 Jul 2018 11:09:55 -0400 Subject: [Tutor] Python Memory Allocation -- deep learning In-Reply-To: References: Message-ID: On Mon, Jul 30, 2018 at 9:20 AM, Sunil Tech wrote: > Hi Team, > > I am investigating how the memory allocation happens in Python > For Eg: > *Case 1:* > >>>> a = 10 >>>> b = 10 >>>> c = 10 >>>> id(a), id(b), id(c) > (140621897573616, 140621897573616, 140621897573616) >>>> a += 1 >>>> id(a) > 140621897573592 > > > *Case 2:* > >>>> x = 500 >>>> y = 500 >>>> id(x) > 4338740848 >>>> id(y) > 4338741040 > > > *Case 3:* > >>>> s1 = 'hello' >>>> s2 = 'hello' >>>> id(s1), id(s2) > (4454725888, 4454725888) >>>> s1 == s2 > True >>>> s1 is s2 > True >>>> s3 = 'hello, world!' >>>> s4 = 'hello, world!' >>>> id(s3), id(s4) > (4454721608, 4454721664) >>>> s3 == s4 > True >>>> s3 is s4 > False > > Python memory allocation is varying in all these use cases. Please help me > understand. > > Thanks, > Sunil. G > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor An id is not guaranteed to be a memory address. In the cases you cited, your version of python caches small integers, and apparently small strings because its convenient and efficient to do so. Other implementations of python may take a different approach. I think it would be unwise to ever assume that a value is cached in your day to day programming -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays From mats at wichmann.us Mon Jul 30 11:21:01 2018 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 30 Jul 2018 09:21:01 -0600 Subject: [Tutor] Python Memory Allocation -- deep learning In-Reply-To: References: Message-ID: <94cec0f1-5aaa-0840-12dd-8b673fc54076@wichmann.us> On 07/30/2018 07:20 AM, Sunil Tech wrote: > Hi Team, > > I am investigating how the memory allocation happens in Python There are several things going on here, but the main thing to know is: but Python language _implementations_ optimize when they can and think it makes sense. So don't draw too many conclusions from this experiment... The python.org Python only creates one copy of small integer objects, I think I've read somewhere the range is -5 to 256. Strings get some kind of the same treatement - short strings may get entries in the bytecode generated (.pyc files) allowing references to be to the same id (id does not necessarily mean memory location, by the way) Pretty much, don't count on this behavior. Other Pythons may not do the same things. There is some control over whether strings are interned, see sys.intern() > For Eg: > *Case 1:* > >>>> a = 10 >>>> b = 10 >>>> c = 10 >>>> id(a), id(b), id(c) > (140621897573616, 140621897573616, 140621897573616) >>>> a += 1 >>>> id(a) > 140621897573592 > > > *Case 2:* > >>>> x = 500 >>>> y = 500 >>>> id(x) > 4338740848 >>>> id(y) > 4338741040 > > > *Case 3:* > >>>> s1 = 'hello' >>>> s2 = 'hello' >>>> id(s1), id(s2) > (4454725888, 4454725888) >>>> s1 == s2 > True >>>> s1 is s2 > True >>>> s3 = 'hello, world!' >>>> s4 = 'hello, world!' >>>> id(s3), id(s4) > (4454721608, 4454721664) >>>> s3 == s4 > True >>>> s3 is s4 > False > > Python memory allocation is varying in all these use cases. Please help me > understand. > > Thanks, > Sunil. G > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From steve at pearwood.info Mon Jul 30 12:58:56 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 31 Jul 2018 02:58:56 +1000 Subject: [Tutor] Python Memory Allocation -- deep learning In-Reply-To: References: Message-ID: <20180730165855.GA22431@ando.pearwood.info> On Mon, Jul 30, 2018 at 06:50:59PM +0530, Sunil Tech wrote: > Hi Team, > > I am investigating how the memory allocation happens in Python You cannot investigate memory allocation in Python code, because the Python execution model does not give you direct access to memory. What you can investigate is: - when the particular interpreter you are using creates a new object, or re-uses an existing object; - when the particular interpreter you are using re-uses an object ID; - the *approximate* size of an object in bytes. Your example #1: > >>> a = 10 > >>> b = 10 > >>> c = 10 > >>> id(a), id(b), id(c) > (140621897573616, 140621897573616, 140621897573616) tells you that the particular interpreter you are using happens to re-use the int object 10. This is a version-specific, interpreter-specific implementation detail, not a language feature. Your example #2: > >>> x = 500 > >>> y = 500 > >>> id(x) > 4338740848 > >>> id(y) > 4338741040 shows us that the particular interpreter you are using happens to *not* re-use the int object 500, but create a new object each time it is required. Again, this is not a language feature. Your example #3: > >>> s1 = 'hello' > >>> s2 = 'hello' > >>> id(s1), id(s2) > (4454725888, 4454725888) tells us that the particular interpreter you are using happens to re-use the string object "hello", rather than create two different string objects. Again, this is an implementation feature, not a language feature. Another interpreter, or a different version, might behave differently. > >>> s3 = 'hello, world!' > >>> s4 = 'hello, world!' > >>> id(s3), id(s4) > (4454721608, 4454721664) And this tells us that the particular interpreter you are using *doesn't* re-use the string object "hello, world!" in this context. *Everything* you have seen in these examples, with one exception, are implementation-specific and depend on the interpreter and the version you use, and could change without notice. The *only* thing you have seen which is a language feature is this rule: - if two objects, a and b, have the same ID *at the same time*, then "a is b" will be true; - if "a is b" is false, then a and b must have different IDs. In practice, most interpreters will follow rules something like this: - small integers up to some convenient limit, like 20 or 100 or 256, will be cached and re-used; - integers larger than that will be created as needed; - small strings that look like identifiers may be cached and re-used; - large strings and those containing punctuation or spaces probably won't be cached and re-used; - the interpreter has the right and the ability to change these rules any time it likes. For example: py> x = 1.5 py> y = 1.5 py> x is y # the float object *is not* re-used False py> x = 1.5; y = 1.5 py> x is y # the float object *is* re-used True > Python memory allocation is varying in all these use cases. Nothing in any of those examples shows you anything about memory allocation. It only shows you the existence of objects, -- Steve From matthew.polack at htlc.vic.edu.au Mon Jul 30 03:24:27 2018 From: matthew.polack at htlc.vic.edu.au (Matthew Polack) Date: Mon, 30 Jul 2018 17:24:27 +1000 Subject: [Tutor] How to add an Image in Grid mode with Python and Tkinter? Message-ID: Hi, Steadily trying to learn Python and Tkinter here with our students... Am working on a simple 'Price of Cereal Crop' calculator....and have made a start with the code below... I'm trying to simply add an image to our program to make the GUI more interesting...but most of the tutorials describe using the 'Pack' method.... not the grid method of layout... and apparently you cannot use 'Pack' and 'Grid' in the one program... Can anyone explain how I could add an image to this program? Or show me an example of a simple program that lets someone simply add an image and use the grid layout in combination. Thanks for any clues at all! - Matt from tkinter import * root = Tk("Crop Calculator") # abutton = Button(root, text="Crop Prices in Australia") #Main Heading Labels croplabel = Label(root, text="Crop Prices in Australia", fg="white", bg= "green") instruction = Label(root, text="Please select from the following crops", fg= "green", bg="white") blanklabel = Label(root, text="", fg="green", bg="white") blanklabel2 = Label(root, text="", fg="green", bg="white") statusbar = Label(root, text="Copyright 2018", fg="white", bg="black", relief='sunken') #Answerlabel answerlabel=Label(root, text="wheatwords") # abutton.pack(side='left', fill='both', expand=True) croplabel.grid(columnspan=12, sticky='ew') instruction.grid(row=1, columnspan=12, sticky='ew') blanklabel.grid(row=2, columnspan=12, sticky='ew') statusbar.grid(row=12, columnspan=12, sticky='ew') blanklabel2.grid(row=11, columnspan=12, sticky='ew') #List of Crops wheatlabel = Button(root, text="Wheat", fg="black", bg="yellow") peaslabel = Button(root, text="Peas", fg="white", bg="green") lupenslabel = Button(root, text="Lupens", fg="white", bg="brown") barleylabel = Button(root, text="Barley", fg="white", bg="orange") canolalabel = Button(root, text="Canola", fg="white", bg="red") sorghumlabel = Button(root, text="Sorghum", fg="white", bg="ivory3") # Grid positioning of crops. wheatlabel.grid(row=4, column=1, sticky='ew') peaslabel.grid(row=4, column=7, sticky='ew') lupenslabel.grid(row=5, column=1, sticky='ew') barleylabel.grid(row=5, column=7, sticky='ew') canolalabel.grid(row=6, column=1, sticky='ew') sorghumlabel.grid(row=6, column=7, sticky='ew') # Definitions def wheatwords(): print("Button one was pushed") wheatlabel.configure(command=wheatwords) root.mainloop() -- **Disclaimer: *Whilst every attempt has been made to ensure that material contained in this email is free from computer viruses or other defects, the attached files are provided, and may only be used, on the basis that the user assumes all responsibility for use of the material transmitted. This email is intended only for the use of the individual or entity named above and may contain information that is confidential and privileged. If you are not the intended recipient, please note that any dissemination, distribution or copying of this email is strictly prohibited. If you have received this email in error, please notify us immediately by return email or telephone +61 3 5382 2529**?and destroy the original message.* From max at zettlmeissl.de Mon Jul 30 09:38:35 2018 From: max at zettlmeissl.de (=?UTF-8?Q?Max_Zettlmei=C3=9Fl?=) Date: Mon, 30 Jul 2018 15:38:35 +0200 Subject: [Tutor] Python Memory Allocation -- deep learning In-Reply-To: References: Message-ID: On Mon, Jul 30, 2018 at 3:20 PM, Sunil Tech wrote: > Python memory allocation is varying in all these use cases. Please help me > understand. CPython is interning small integers and small strings as a form of optimisation. "The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object." For integers see https://docs.python.org/2/c-api/int.html for Python 2 or https://docs.python.org/3/c-api/long.html for Python 3. For strings see https://hg.python.org/cpython/file/3.5/Objects/codeobject.c#l51 From steve at pearwood.info Mon Jul 30 13:10:28 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 31 Jul 2018 03:10:28 +1000 Subject: [Tutor] Python Memory Allocation -- deep learning In-Reply-To: <94cec0f1-5aaa-0840-12dd-8b673fc54076@wichmann.us> References: <94cec0f1-5aaa-0840-12dd-8b673fc54076@wichmann.us> Message-ID: <20180730171028.GB22431@ando.pearwood.info> On Mon, Jul 30, 2018 at 09:21:01AM -0600, Mats Wichmann wrote: > (id does not necessarily mean memory location, by the way) id() *never* means memory location in Python. id() *always* returns an opaque integer ID number which has no promised meaning except to be unique while the object is alive. The interpreter has to generate an ID somehow. In Jython and IronPython, the interpreter keeps a counter, and IDs are allocated as consecutive numbers 1, 2, 3, 4, ... etc. In CPython, the object's memory address is used to generate the ID, but the ID does not mean "memory address". If the ID happens to match the memory address, that's an accident, not a feature of the language. -- Steve From valerio at pbds.eu Mon Jul 30 06:37:04 2018 From: valerio at pbds.eu (Valerio Pachera) Date: Mon, 30 Jul 2018 12:37:04 +0200 (CEST) Subject: [Tutor] Do something on list elements In-Reply-To: References: <1854107779.11.1532696206426.JavaMail.zimbra@pbds.eu> Message-ID: <645930693.26.1532947024607.JavaMail.zimbra@pbds.eu> ----- Messaggio originale ----- > Da: "Tutor Python" > A: "Tutor Python" > Inviato: Sabato, 28 luglio 2018 0:06:55 > Oggetto: Re: [Tutor] Do something on list elements > But better still is a list comprehension: > > l = [s.replace('X','') for s in l) > print(l) Thank you all for the answers. List comprehension is what I was looking for. Here's almost the same example that I made up to summarize: >>> l = ['one ', 'two ', 'three '] >>> print(l) ['one ', 'two ', 'three '] >>> l = [ s.strip() for s in l] >>> print(l) ['one', 'two', 'three'] I create a new list with the same name so I don't need to have another list. From valerio at pbds.eu Mon Jul 30 08:40:45 2018 From: valerio at pbds.eu (Valerio Pachera) Date: Mon, 30 Jul 2018 14:40:45 +0200 (CEST) Subject: [Tutor] Dictionary viceversa Message-ID: <1062877654.45.1532954445827.JavaMail.zimbra@pbds.eu> Hi all, consider this dictionary users = {'user1':['office-a', 'office-b'], 'user2':['office-b'], 'user3':['office-a','office-c']} It's a list of users. For each user there's a list of room it can access to. Generalizing, a dictionary with a list for each element. d = {k:list} I wish to get the same info but "sorted" by room. In other words, a dictionary that has rooms as keys. For each room there's a list of users that can access the room. I've been able to achieve that by for user in users: for room in users[user]: if room in users_by_room: users_by_room[room].append(user) else: users_by_room[room] = [] users_by_room[room].append(user) And i generalized it in a function like this: def viceversa(d): new_d = dict() for k in d: for e in d[k]: if e in new_d: new_d[e].append(k) else: new_d[e] = [] new_d[e].append(k) return(new_d) My question is: is there a better way to that? Maybe by list comprehension? I was looking to substiture the cicle for e in new_d like this: [ new_d[e].append(k) if e in new_d else new_d[e].append(k) for e in d[k] ] but it can't work because 'new_d[e] = []' is missing. From zachary.ware+pytut at gmail.com Mon Jul 30 13:28:05 2018 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Mon, 30 Jul 2018 12:28:05 -0500 Subject: [Tutor] Dictionary viceversa In-Reply-To: <1062877654.45.1532954445827.JavaMail.zimbra@pbds.eu> References: <1062877654.45.1532954445827.JavaMail.zimbra@pbds.eu> Message-ID: On Mon, Jul 30, 2018 at 12:20 PM Valerio Pachera wrote: > I was looking to substiture the cicle for e in new_d like this: > [ new_d[e].append(k) if e in new_d else new_d[e].append(k) for e in d[k] ] > but it can't work because 'new_d[e] = []' is missing. Have a look at `dict.setdefault` and play around with it; I think it will help you do what you want. -- Zach From __peter__ at web.de Mon Jul 30 13:45:36 2018 From: __peter__ at web.de (Peter Otten) Date: Mon, 30 Jul 2018 19:45:36 +0200 Subject: [Tutor] Dictionary viceversa References: <1062877654.45.1532954445827.JavaMail.zimbra@pbds.eu> Message-ID: Zachary Ware wrote: > On Mon, Jul 30, 2018 at 12:20 PM Valerio Pachera wrote: >> I was looking to substiture the cicle for e in new_d like this: >> [ new_d[e].append(k) if e in new_d else new_d[e].append(k) for e in >> [ d[k] ] >> but it can't work because 'new_d[e] = []' is missing. > > Have a look at `dict.setdefault` and play around with it; I think it > will help you do what you want. Either that, or use a defaultdict: >>> import collections >>> room_access = collections.defaultdict(list) >>> for user, rooms in users.items(): ... for room in rooms: ... room_access[room].append(user) ... >>> room_access defaultdict(, {'office-c': ['user3'], 'office-b': ['user2', 'user1'], 'office-a': ['user3', 'user1']}) From alan.gauld at yahoo.co.uk Mon Jul 30 14:06:10 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 30 Jul 2018 19:06:10 +0100 Subject: [Tutor] Dictionary viceversa In-Reply-To: <1062877654.45.1532954445827.JavaMail.zimbra@pbds.eu> References: <1062877654.45.1532954445827.JavaMail.zimbra@pbds.eu> Message-ID: On 30/07/18 13:40, Valerio Pachera wrote: > users = {'user1':['office-a', 'office-b'], > 'user2':['office-b'], > 'user3':['office-a','office-c']} > > It's a list of users. > For each user there's a list of room it can access to. > > I wish to get the same info but "sorted" by room. Remember that dicts are not sorted. You can create a dictionary keyed by room but not sorted by room. (You can however get a list of sorted keys but that's different, and you can use a collections.OrderedDict) > And i generalized it in a function like this: > > def viceversa(d): > new_d = dict() > for k in d: > for e in d[k]: > if e in new_d: > new_d[e].append(k) > else: > new_d[e] = [] > new_d[e].append(k) > return(new_d) > > My question is: is there a better way to that? There are lots of options including those suggested elsewhere. Another involves using get() which makes your function look like: def viceversa(d): new_d = dict() for k in d: for e in d[k]: new_d[e] = new_d.get(e,[]).append(k) return(new_d) > Maybe by list comprehension? I can't think of a reasonable way of doing that but a generator may work. Another option would be to build a set of the original rooms then iterate over the data, collecting the keys which have those rooms. But that would be pretty inefficient... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From zachary.ware+pytut at gmail.com Mon Jul 30 14:11:43 2018 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Mon, 30 Jul 2018 13:11:43 -0500 Subject: [Tutor] Dictionary viceversa In-Reply-To: References: <1062877654.45.1532954445827.JavaMail.zimbra@pbds.eu> Message-ID: On Mon, Jul 30, 2018 at 1:08 PM Alan Gauld via Tutor wrote: > There are lots of options including those suggested elsewhere. > Another involves using get() which makes your function > look like: > > def viceversa(d): > new_d = dict() > for k in d: > for e in d[k]: > new_d[e] = new_d.get(e,[]).append(k) Note that this will set each entry to `None` as returned by `list.append`. -- Zach From __peter__ at web.de Mon Jul 30 14:12:53 2018 From: __peter__ at web.de (Peter Otten) Date: Mon, 30 Jul 2018 20:12:53 +0200 Subject: [Tutor] How to add an Image in Grid mode with Python and Tkinter? References: Message-ID: Matthew Polack wrote: > Hi, > > Steadily trying to learn Python and Tkinter here with our students... > > Am working on a simple 'Price of Cereal Crop' calculator....and have made > a start with the code below... > > I'm trying to simply add an image to our program to make the GUI more > interesting...but most of the tutorials describe using the 'Pack' > method.... not the grid method of layout... Open the image with PIL, and then put the image into a Label or Button. What layout manager you use for that widget afterwords doesn't really matter. > and apparently you cannot use 'Pack' and 'Grid' in the one program... > > Can anyone explain how I could add an image to this program? Or show me an > example of a simple program that lets someone simply add an image and use > the grid layout in combination. Let's assume you want to show a picture stored in the file "wheat.jpg" on the button with the -- misleading! -- name wheatlabel. Then > from tkinter import * from PIL import Image, ImageTk > root = Tk("Crop Calculator") # The line above produced an exception over here; I think you wanted root = Tk() root.title("Crop Calculator") > # abutton = Button(root, text="Crop Prices in Australia") > > #Main Heading Labels > croplabel = Label(root, text="Crop Prices in Australia", fg="white", bg= > "green") > instruction = Label(root, text="Please select from the following crops", > fg= "green", bg="white") > blanklabel = Label(root, text="", fg="green", bg="white") > blanklabel2 = Label(root, text="", fg="green", bg="white") > statusbar = Label(root, text="Copyright 2018", fg="white", bg="black", > relief='sunken') > > #Answerlabel > answerlabel=Label(root, text="wheatwords") > > # abutton.pack(side='left', fill='both', expand=True) > croplabel.grid(columnspan=12, sticky='ew') > instruction.grid(row=1, columnspan=12, sticky='ew') > blanklabel.grid(row=2, columnspan=12, sticky='ew') > statusbar.grid(row=12, columnspan=12, sticky='ew') > blanklabel2.grid(row=11, columnspan=12, sticky='ew') > > > #List of Crops wheat_image = Image.open("wheat.jpg") wheat_photo = ImageTk.PhotoImage(wheat_image) wheatlabel = Button(root, image=wheat_photo, fg="black", bg="yellow") > peaslabel = Button(root, text="Peas", fg="white", bg="green") > lupenslabel = Button(root, text="Lupens", fg="white", bg="brown") > barleylabel = Button(root, text="Barley", fg="white", bg="orange") > canolalabel = Button(root, text="Canola", fg="white", bg="red") > sorghumlabel = Button(root, text="Sorghum", fg="white", bg="ivory3") > > # Grid positioning of crops. > wheatlabel.grid(row=4, column=1, sticky='ew') > peaslabel.grid(row=4, column=7, sticky='ew') > lupenslabel.grid(row=5, column=1, sticky='ew') > barleylabel.grid(row=5, column=7, sticky='ew') > canolalabel.grid(row=6, column=1, sticky='ew') > sorghumlabel.grid(row=6, column=7, sticky='ew') > > # Definitions > > def wheatwords(): > print("Button one was pushed") > > wheatlabel.configure(command=wheatwords) > > > root.mainloop() > From alan.gauld at yahoo.co.uk Mon Jul 30 14:26:13 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 30 Jul 2018 19:26:13 +0100 Subject: [Tutor] How to add an Image in Grid mode with Python and Tkinter? In-Reply-To: References: Message-ID: On 30/07/18 08:24, Matthew Polack wrote: > I'm trying to simply add an image to our program to make the GUI more > interesting...but most of the tutorials describe using the 'Pack' > method.... not the grid method of layout... That's completely irrelevant since you can add images to widgets regardless of the layout manager used. In most cases you will want to use a PhotoImage widget to do it though. > and apparently you cannot use 'Pack' and 'Grid' in the one program... Yes you can just not in the same container. For example a common strategy for building forms based apps is to have a menubar on top with a toolbar frame packed below with a data frame packed below that and finally a status bar frame packed at the bottom. Within those frames you use the packer for the toolbar buttons, and for the status bar text. Then you use the grid layout manager to display the data entry widgets in the centre panel. So at each container(usually a Frame) level you can only have a single layout manager, but inside each nested container you can choose to use the same or a different manager. And remember there are more than just pack and grid, there are also place and form(in Tix) (and you can write your own if you are really keen!) > Can anyone explain how I could add an image to this program? Or show me an > example of a simple program that lets someone simply add an image and use > the grid layout in combination. import tkinter as tk top = tk.Tk() tk.Label(image = "foo.img").grid(row=0,column=0) top.mainloop)() Thats about as simple as it gets. But the img file must be in Tk compatible format. More generally, use a PhotoImage: import tkinter as tk top = tk.Tk() lbl = tk.Label() lbl.grid(row=0,column=0) #could as easily use pack() or place() img = tk.PhotoImage(file="/path/to/myimg.gif") lbl['image'] = img top.mainloop)() But to get more sophisticated you really want to look into the PIL/Pillow library and its integration with Tkinter via the image class. Also look at how the Text and Canvas widgets deal with images because its slightly more complex than a simple Label or Button. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Mon Jul 30 14:36:49 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 30 Jul 2018 19:36:49 +0100 Subject: [Tutor] Dictionary viceversa In-Reply-To: References: <1062877654.45.1532954445827.JavaMail.zimbra@pbds.eu> Message-ID: On 30/07/18 19:11, Zachary Ware wrote: > On Mon, Jul 30, 2018 at 1:08 PM Alan Gauld via Tutor wrote: >> There are lots of options including those suggested elsewhere. >> Another involves using get() which makes your function >> look like: >> >> def viceversa(d): >> new_d = dict() >> for k in d: >> for e in d[k]: >> new_d[e] = new_d.get(e,[]).append(k) > > Note that this will set each entry to `None` as returned by `list.append`. Oops, yes. You need an intermediate variable: for e in d[k]: data = new_d.get(e,[]) data.append(k) new_d[e] = data Or use addition: for e in d[k]: new_d[e] = new_d.get(e,[]) + [k] -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Mon Jul 30 19:33:40 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 31 Jul 2018 09:33:40 +1000 Subject: [Tutor] Python Memory Allocation -- deep learning In-Reply-To: <20180730165855.GA22431@ando.pearwood.info> References: <20180730165855.GA22431@ando.pearwood.info> Message-ID: <20180730233340.GD22431@ando.pearwood.info> On Tue, Jul 31, 2018 at 02:58:56AM +1000, Steven D'Aprano wrote: > The *only* thing you have seen which is a language feature is this rule: > > - if two objects, a and b, have the same ID *at the same time*, then > "a is b" will be true; > > - if "a is b" is false, then a and b must have different IDs. Sorry, I forgot to mention that for both of those, the reverse applies as well. Perhaps a better way to put it is this: - if "a is b", then a and b must have the same ID, and vice versa. - if "a is not b", then a and b must have different IDs, and vice versa. -- Steve From matthew.polack at htlc.vic.edu.au Mon Jul 30 19:26:41 2018 From: matthew.polack at htlc.vic.edu.au (Matthew Polack) Date: Tue, 31 Jul 2018 09:26:41 +1000 Subject: [Tutor] How to add an Image in Grid mode with Python and Tkinter? In-Reply-To: References: Message-ID: Thanks Alan and Peter for the comprehensive replies...that gives me some good 'homework' to do and clarity on how to go about it. Much appreciated....will spend some time now getting my head around it. Thanks so much. - Matthew Polack Matthew Polack | Teacher [image: Emailbanner3.png] Trinity Drive | PO Box 822 Horsham Victoria 3402 p. 03 5382 2529 m. 0402456854 e. matthew.polack at htlc.vic.edu.au w. www.htlc.vic.edu.au On Tue, Jul 31, 2018 at 4:26 AM, Alan Gauld via Tutor wrote: > On 30/07/18 08:24, Matthew Polack wrote: > > > I'm trying to simply add an image to our program to make the GUI more > > interesting...but most of the tutorials describe using the 'Pack' > > method.... not the grid method of layout... > > That's completely irrelevant since you can add images to widgets > regardless of the layout manager used. In most cases you will > want to use a PhotoImage widget to do it though. > > > and apparently you cannot use 'Pack' and 'Grid' in the one program... > > Yes you can just not in the same container. > For example a common strategy for building forms based apps > is to have a menubar on top with a toolbar frame packed below > with a data frame packed below that and finally a status > bar frame packed at the bottom. > > Within those frames you use the packer for the toolbar buttons, > and for the status bar text. Then you use the grid layout > manager to display the data entry widgets in the centre panel. > > So at each container(usually a Frame) level you can only have > a single layout manager, but inside each nested container > you can choose to use the same or a different manager. > > And remember there are more than just pack and grid, there > are also place and form(in Tix) (and you can write your own > if you are really keen!) > > > Can anyone explain how I could add an image to this program? Or show me > an > > example of a simple program that lets someone simply add an image and use > > the grid layout in combination. > import tkinter as tk > > top = tk.Tk() > tk.Label(image = "foo.img").grid(row=0,column=0) > > top.mainloop)() > > > Thats about as simple as it gets. But the img file must > be in Tk compatible format. > > More generally, use a PhotoImage: > > import tkinter as tk > > top = tk.Tk() > lbl = tk.Label() > lbl.grid(row=0,column=0) #could as easily use pack() or place() > > img = tk.PhotoImage(file="/path/to/myimg.gif") > lbl['image'] = img > > top.mainloop)() > > But to get more sophisticated you really want to look > into the PIL/Pillow library and its integration with > Tkinter via the image class. Also look at how the Text > and Canvas widgets deal with images because its slightly > more complex than a simple Label or Button. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- **Disclaimer: *Whilst every attempt has been made to ensure that material contained in this email is free from computer viruses or other defects, the attached files are provided, and may only be used, on the basis that the user assumes all responsibility for use of the material transmitted. This email is intended only for the use of the individual or entity named above and may contain information that is confidential and privileged. If you are not the intended recipient, please note that any dissemination, distribution or copying of this email is strictly prohibited. If you have received this email in error, please notify us immediately by return email or telephone +61 3 5382 2529**?and destroy the original message.* From mehrotra.saket at gmail.com Mon Jul 30 22:52:12 2018 From: mehrotra.saket at gmail.com (Saket Mehrotra) Date: Tue, 31 Jul 2018 08:22:12 +0530 Subject: [Tutor] SSL Error Message-ID: Hi I am trying to run import requests in a py file but I am getting below error ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD, AttributeError: module 'ssl' has no attribute 'PROTOCOL_SSLv23' >>> I tried to execute below from the terminal but it still remains unresolved. sudo easy_install --upgrade pip I've also had to run: sudo pip uninstall pyopenssl sudo pip install mozdownload Can you please help me . Thanks & Regards Saket Mehrotra From marc.tompkins at gmail.com Tue Jul 31 12:58:27 2018 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 31 Jul 2018 09:58:27 -0700 Subject: [Tutor] SSL Error In-Reply-To: References: Message-ID: This is a general Python tutor group; I'm not sure anybody here can help you with the OpenSSL package (I've definitely never used it myself.) We're all willing to help, but this might not be the right place to ask this question. More to the point, though, when you ask questions on this list it's best to just cut and paste BOTH your code and the actual error message/traceback; from the bit that you've posted, it sounds like it might be as simple as a typo, but we can't really tell without seeing your code. On Mon, Jul 30, 2018 at 7:52 PM, Saket Mehrotra wrote: > Hi > > I am trying to run import requests in a py file but I am getting below > error ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD, > AttributeError: module 'ssl' has no attribute 'PROTOCOL_SSLv23' > >>> > > I tried to execute below from the terminal but it still remains unresolved. > > sudo easy_install --upgrade pip > > I've also had to run: > > sudo pip uninstall pyopenssl > > sudo pip install mozdownload > > > Can you please help me . > > Thanks & Regards > Saket Mehrotra > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From alan.gauld at yahoo.co.uk Tue Jul 31 13:03:49 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 31 Jul 2018 18:03:49 +0100 Subject: [Tutor] SSL Error In-Reply-To: References: Message-ID: On 31/07/18 03:52, Saket Mehrotra wrote: > error ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD, > AttributeError: module 'ssl' has no attribute 'PROTOCOL_SSLv23' Are you sure you spelled the attribute correctly? Have you tried >>> import ssl >>> dir(ssl) Top see what the attribute names look like? Is PROTOCOL_SSLv23 one of them? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From zachary.ware+pytut at gmail.com Tue Jul 31 13:16:30 2018 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Tue, 31 Jul 2018 12:16:30 -0500 Subject: [Tutor] SSL Error In-Reply-To: References: Message-ID: On Tue, Jul 31, 2018 at 12:06 PM Alan Gauld via Tutor wrote: > > On 31/07/18 03:52, Saket Mehrotra wrote: > > > error ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD, > > AttributeError: module 'ssl' has no attribute 'PROTOCOL_SSLv23' > > Are you sure you spelled the attribute correctly? > > Have you tried > > > >>> import ssl > >>> dir(ssl) > > Top see what the attribute names look like? > Is PROTOCOL_SSLv23 one of them? Also check `ssl.__file__` and make sure it is the standard library's `ssl.py` (/usr/lib/python3.6/ssl.py or similar) and not a local file of yours named `ssl.py`. -- Zach From marc.tompkins at gmail.com Tue Jul 31 13:19:32 2018 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 31 Jul 2018 10:19:32 -0700 Subject: [Tutor] SSL Error In-Reply-To: References: Message-ID: On Tue, Jul 31, 2018 at 10:03 AM, Alan Gauld via Tutor wrote: > On 31/07/18 03:52, Saket Mehrotra wrote: > > > error ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD, > > AttributeError: module 'ssl' has no attribute 'PROTOCOL_SSLv23' > > Are you sure you spelled the attribute correctly? > > Have you tried > > > >>> import ssl > >>> dir(ssl) > > Top see what the attribute names look like? > Is PROTOCOL_SSLv23 one of them? > > What I was getting at earlier: it isn't clear, without seeing his code, whether he's directly asking for PROTOCOL_SSLv23, or whether it's an internal result of a call he made. If it's the first, then the problem is with his code; if it's the second, it's a problem with how the package is built on his machine. Really can't tell without context. From __peter__ at web.de Tue Jul 31 13:28:39 2018 From: __peter__ at web.de (Peter Otten) Date: Tue, 31 Jul 2018 19:28:39 +0200 Subject: [Tutor] SSL Error References: Message-ID: Saket Mehrotra wrote: > Hi > > I am trying to run import requests in a py file but I am getting below > error ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD, > AttributeError: module 'ssl' has no attribute 'PROTOCOL_SSLv23' If you start the Python interpreter and execute >>> import ssl >>> ssl.__file__ '/usr/lib/python3.4/ssl.py' does it print something suspicious? You might be hiding the standard ssl.py with one you created yourself: # touch ssl.py $ python3 Python 3.4.3 (default, Nov 28 2017, 16:41:13) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import ssl >>> ssl.__file__ '/home/peter/mystuff/ssl.py' In that case just rename the offending file (if you are using Python 2 remember to remove the corresponding ssl.pyc). >>>> > > I tried to execute below from the terminal but it still remains > unresolved. > > sudo easy_install --upgrade pip > > I've also had to run: > > sudo pip uninstall pyopenssl > > sudo pip install mozdownload > > > Can you please help me . > > Thanks & Regards > Saket Mehrotra > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor