From atesfalem at gmail.com Sun Nov 1 14:09:50 2020 From: atesfalem at gmail.com (Tesfalem Abraham) Date: Sun, 1 Nov 2020 20:09:50 +0100 Subject: [Tutor] Python library Message-ID: Hello, i am beginner her and wants to get all python libraries and built-in function. Any website or anything you may suggest me. I don't know really wherein to start.? Best From mats at wichmann.us Sun Nov 1 18:12:02 2020 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 1 Nov 2020 16:12:02 -0700 Subject: [Tutor] Python library In-Reply-To: References: Message-ID: <55553adc-887c-20bd-b359-dcf729710d46@wichmann.us> On 11/1/20 12:09 PM, Tesfalem Abraham wrote: > Hello, i am beginner her and wants to get all python libraries and built-in > function. Any website or anything you may suggest me. > > I don't know really wherein to start.? You already have all the built-ins. Python likes to say about itself that it's batteries included. As to "all libraries" - you really don't want that, there are hundreds of thousands. You can browse a bit at https://pypi.org for ones you can install using pip. There will be some lists of top Python modules on the internet you might read up on. From alan.gauld at yahoo.co.uk Sun Nov 1 18:37:33 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 1 Nov 2020 23:37:33 +0000 Subject: [Tutor] Python library In-Reply-To: References: Message-ID: On 01/11/2020 19:09, Tesfalem Abraham wrote: > Hello, i am beginner her and wants to get all python libraries and built-in > function. Any website or anything you may suggest me. The standard library is described on the python.org website. The Pypi site has a lot of the 3rd party libraries. But there are new libraries being added all the time. And nobody uses all of them, many are highly specialized. If you are keen on science you can install Anaconda which includes the standard library and most of the SciPy catalog of packages and modules too. But there are far too many library packages for one person to ever explore thoroughly in their entire life. For example my book "Python Projects" provides a very high level introduction to over 60 of the standard library modules in around 400 pages. That's about 30% of the total library that ships with every copy of Python. But the standard library probably accounts for less than 5% of the total python catalog. So to give a general intro to all of them would take around 20,000 pages of documentation! This is both a blessing and a curse. It's a blessing because pretty much anything you want to do probably has a module somewhere that will get you going. But it's a curse because for most things there will be a choice and finding the exact right module in the flood of options can be a real challenge! -- 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 phillor9 at gmail.com Sun Nov 1 20:24:21 2020 From: phillor9 at gmail.com (Phil) Date: Mon, 2 Nov 2020 11:24:21 +1000 Subject: [Tutor] Two dimensional lists Message-ID: <9cb39aa0-8fd5-d198-56f2-94982f746b4c@gmail.com> I have some C++ code that I wrote some time ago and, just as an exercise, I'm converting it to Python. I've come to a standstill because of arrays. If I use a numpy array as follows then I can use that array in exactly the same way as a C++ array even though I don't understand the syntax of it. I used the trial_and_error method to create it. self.board = numpy.zeros((board_size_x, board_size_y), dtype=numpy.bool) self.next_board = numpy.zeros((board_size_x, board_size_y), numpy.bool) Python lists, if I understand this correctly, can be used in the same way as arrays. However, I've made little progress. Is there a list equivalent to this? b = [5] , [5] # a square array of size 5 b[3][2] = 9 In Python, b = [[5,5],[5,5]] looked promising but I'm still greeted with a list out of range error. I've read through several Python tutorials and I've tried append and even though there isn't an error the result doesn't make sense. No doubt the solution is straight forward but this poor old duffer cannot see it. -- Regards, Phil From cs at cskk.id.au Sun Nov 1 23:46:41 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Mon, 2 Nov 2020 15:46:41 +1100 Subject: [Tutor] Two dimensional lists In-Reply-To: <9cb39aa0-8fd5-d198-56f2-94982f746b4c@gmail.com> References: <9cb39aa0-8fd5-d198-56f2-94982f746b4c@gmail.com> Message-ID: <20201102044641.GA19930@cskk.homeip.net> On 02Nov2020 11:24, Phil wrote: >I have some C++ code that I wrote some time ago and, just as an >exercise, I'm converting it to Python. I've come to a standstill >because of arrays. If I use a numpy array as follows then I can use >that array in exactly the same way as a C++ array even though I don't >understand the syntax of it. I used the trial_and_error method to >create it. This can be deceptive. Read the documentation. (Disclaimer: I know nothing about numpy.) >Python lists, if I understand this correctly, can be used in the same >way as arrays. Linear arrays yes. Anything else you need to build. >However, I've made little progress. Is there a list equivalent to this? > >b = [5] , [5] # a square array of size 5 > >b[3][2] = 9 For the syntax you show above, the direct Python equivalent is a 5 element list, each element of which is a 5 element list. So: b = [ [ 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0 ], ] The syntax you use "b[3][2]" fetches element 3 (the fourth element, since lists count from 0), and then fetches element 2 from _that_. So the third element of the fourth list. Depending on you needs, something basic like that will do. For large arrays you want something sparse (not a fully filled out list of lists) or something fast (maybe a single flat list, eg 25 elements in the example above, and an indexing approach to turn a pair of coordinates into the right flat index). Finally, since you're fond of syntactic experiment, note that Python has a convenient replication syntax. It does not do what you would first expect: You can make a 5 element list like this: l5 = [0] * 5 but note that is a 5 element list, each of whose elements is the _same_ object (an int of value 0 in this case). For ints that's fine, the small ones are immutable singletons anyway - changes involve making new ints. But you might be tempted to do this: l5 = [0] * 5 l55 = l5 * 5 like this: >>> l5 [0, 0, 0, 0, 0] >>> l55 = l5 * 5 >>> l55 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] Whoops. Better do that correctly: >>> l55 = [l5] * 5 >>> l55 [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] That looks like our first example, but it is not. Watch: >>> l55[3][2] = 7 >>> l55 [[0, 0, 7, 0, 0], [0, 0, 7, 0, 0], [0, 0, 7, 0, 0], [0, 0, 7, 0, 0], [0, 0, 7, 0, 0]] Why? Because l55 is a list of 5 elements, each of which is a reference to the _same_ 5 element list we made as "l5": >>> l5 [0, 0, 7, 0, 0] Cheers, Cameron Simpson From phillor9 at gmail.com Mon Nov 2 01:25:06 2020 From: phillor9 at gmail.com (Phil) Date: Mon, 2 Nov 2020 16:25:06 +1000 Subject: [Tutor] Two dimensional lists In-Reply-To: <20201102044641.GA19930@cskk.homeip.net> References: <9cb39aa0-8fd5-d198-56f2-94982f746b4c@gmail.com> <20201102044641.GA19930@cskk.homeip.net> Message-ID: <4abda1b7-dc29-4bb5-ce6f-5a71039d75ca@gmail.com> On 2/11/20 2:46 pm, Cameron Simpson wrote: Thank you Cameron for your insightful reply. For the syntax you show above, the direct Python equivalent is a 5 > element list, each element of which is a 5 element list. > > So: > > b = [ > [ 0, 0, 0, 0, 0 ], > [ 0, 0, 0, 0, 0 ], > [ 0, 0, 0, 0, 0 ], > [ 0, 0, 0, 0, 0 ], > [ 0, 0, 0, 0, 0 ], > ] > > The syntax you use "b[3][2]" fetches element 3 (the fourth element, > since lists count from 0), and then fetches element 2 from _that_. So > the third element of the fourth list. That's what I expected as well, however, this is the result; >>> >>> b = [5],[5] >>> b[3][2] = 9 Traceback (most recent call last): ? File "", line 1, in IndexError: tuple index out of range >>> print(b[3][2]) Traceback (most recent call last): ? File "", line 1, in IndexError: tuple index out of range I'd spent the last 3 or 4 hours experimenting with this but have not achieved anything useful. I also had a play with the array module and I had another look at numpy and have decided that's the way to go. Still, I'm a little disappointed that this has defeated me. -- Regards, Phil From cs at cskk.id.au Mon Nov 2 02:22:01 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Mon, 2 Nov 2020 18:22:01 +1100 Subject: [Tutor] Two dimensional lists In-Reply-To: <4abda1b7-dc29-4bb5-ce6f-5a71039d75ca@gmail.com> References: <4abda1b7-dc29-4bb5-ce6f-5a71039d75ca@gmail.com> Message-ID: <20201102072201.GA49871@cskk.homeip.net> On 02Nov2020 16:25, Phil wrote: >On 2/11/20 2:46 pm, Cameron Simpson wrote: >Thank you Cameron for your insightful reply. Remarks below. >For the syntax you show above, the direct Python equivalent is a 5 >>element list, each element of which is a 5 element list. >> >>So: >> >> b = [ >> [ 0, 0, 0, 0, 0 ], >> [ 0, 0, 0, 0, 0 ], >> [ 0, 0, 0, 0, 0 ], >> [ 0, 0, 0, 0, 0 ], >> [ 0, 0, 0, 0, 0 ], >> ] >> >>The syntax you use "b[3][2]" fetches element 3 (the fourth element, >>since lists count from 0), and then fetches element 2 from _that_. So >>the third element of the fourth list. > >That's what I expected as well, however, this is the result; > >>>> b = [5],[5] >>>> b[3][2] = 9 >Traceback (most recent call last): >? File "", line 1, in >IndexError: tuple index out of range >>>> print(b[3][2]) >Traceback (most recent call last): >? File "", line 1, in >IndexError: tuple index out of range But what you wrote is not what I wrote. I've explicitly laid out a list of lists. You've laid out a 2-tuple of 1 element lists: b = [5],[5] Perhaps I should note here that you don't "declare" Python variables, so the above is not a declaration of some kind of array, it is an assignment of a little tuple, containing 2 lists. The above may make more sense to you as this: b = ([5], [5]) Does that loook more obvious? Had I written it out as in my original example it would look like this: b = ( [ 5 ], [ 5 ], ) If not, consider: x = [5] makes a _single_ element list, whose sole element is the value 5. It does not create a 5 element list. This: x = [1, 2] makes a 2 element list, and this: x = (1, 2) makes a 2 element tuple (effectively an immutable fixed length list, semanticly, but that immutability bring other features, irrelevant here). Now, the brackets are not part of Python's tuple syntax - they're only needed for disambiguation. This still makes a 2 element tuple: x = 1, 2 Is it now evident why your: b = [5],[5] does not make 2 dimensional list/array, it makes a little tuple of 1-element lists? >I'd spent the last 3 or 4 hours experimenting with this but have not >achieved anything useful. I also had a play with the array module and >I had another look at numpy and have decided that's the way to go. For many purposes, that is probably true. Numpy is explicitly desogned to bring bulk numeric computation to Python, and that often involves matrices etc. The array module is probably less useful, but it is designed for compact allocation of bulk objects in memory, IIRC. >Still, I'm a little disappointed that this has defeated me. You're defeated because you're coming in reading: b = [5],[5] as an array declaration, which it is not. Clear that away and things should make more sense. Then come back when you're having trouble making the data structures you actually need, and we'll see how one would approach that in Python. Cheers, Cameron Simpson From phillor9 at gmail.com Mon Nov 2 03:36:39 2020 From: phillor9 at gmail.com (Phil) Date: Mon, 2 Nov 2020 18:36:39 +1000 Subject: [Tutor] Two dimensional lists In-Reply-To: <20201102072201.GA49871@cskk.homeip.net> References: <4abda1b7-dc29-4bb5-ce6f-5a71039d75ca@gmail.com> <20201102072201.GA49871@cskk.homeip.net> Message-ID: <9160747a-f280-396b-ca3e-e24766b9c589@gmail.com> On 2/11/20 5:22 pm, Cameron Simpson wrote: I've explicitly laid out a list of lists. Thank you again Cameron. I left a pair of square brackets off my previous reply. It's been a long day and this is what I meant in my reply: >>> b = [[5],[5]] >>> b[3][2] = 9 Traceback (most recent call last): ? File "", line 1, in IndexError: list index out of range I know there's still a problem there, I'll look into it tomorrow. -- Regards, Phil From cs at cskk.id.au Mon Nov 2 03:53:39 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Mon, 2 Nov 2020 19:53:39 +1100 Subject: [Tutor] Two dimensional lists In-Reply-To: <9160747a-f280-396b-ca3e-e24766b9c589@gmail.com> References: <9160747a-f280-396b-ca3e-e24766b9c589@gmail.com> Message-ID: <20201102085339.GA62118@cskk.homeip.net> On 02Nov2020 18:36, Phil wrote: >On 2/11/20 5:22 pm, Cameron Simpson wrote: >I've explicitly laid out a list of lists. > >Thank you again Cameron. You said you had some C++ code, so I'm going to provide some C code below to show some mechanism in a form I hope you're already familiar with. >I left a pair of square brackets off my previous reply. It's been a >long day and this is what I meant in my reply: > >>>> b = [[5],[5]] This implements a 2x1 list of lists and assigns a reference to it to "b". >>>> b[3][2] = 9 >Traceback (most recent call last): >? File "", line 1, in >IndexError: list index out of range Thus the index errors: you have a 2x1 data structure, not a 5x5 data structure. >I know there's still a problem there, I'll look into it tomorrow. I think you're still conflating declarations and assignments. In C one might write: int aa[5][5]; That _declares_ a 5x5 array of ints and implicitly fills it with zeroes. In Python you don't declare variables. A variable is just a reference to an object (a list is an object, so is an int). They are not pointers, but if you think of them as pointers it will be useful for your mental model. So, here's your b= _assignment_: b = [5], [5] which is a 2-tuple if 1-lists. This is _similar_ to this piece of C: int l1[1] = { 5 }; int l2[1] = { 5 }; int *b[2] = { l1, l2 }; It is not a perfect metaphor, because lists are resizeable, so a closer analogy might be this: int *l1 = malloc(1 * sizeof(int)); l1[0] = 5; int *l2 = malloc(1 * sizeof(int)); l2[0] = 5; int *b[2] = { l1, l2 }; So malloc() a resizable piece of memory holding 1 int and keep a pointer to it in l1. Repeat for l2. Then allocate a fixed size 2-element array of int* to point at l1 and l2. Now, that is for: b = [5], [5] which is equivalent to: b = ( [5], [5] ) i.e. that makes "b" refer to a 2-tuple. With your missing square brackets: b = [ [5], [5] ] you're making a 2-list instead of a 2-tuple: the real different is that a list can be mmodified. So this is like this C code: int *l1 = malloc(1 * sizeof(int)); l1[0] = 5; int *l2 = malloc(1 * sizeof(int)); l2[0] = 5; int **b = malloc(2 * sizeof(int*)); b[0] = l1; b[1] = l2; So "b" now points at a resizable piece of memory holding 2 pointers instead of a fixed size piece of memory. Cheers, Cameron Simpson From phillor9 at gmail.com Mon Nov 2 04:33:10 2020 From: phillor9 at gmail.com (Phil) Date: Mon, 2 Nov 2020 19:33:10 +1000 Subject: [Tutor] Two dimensional lists In-Reply-To: <20201102085339.GA62118@cskk.homeip.net> References: <9160747a-f280-396b-ca3e-e24766b9c589@gmail.com> <20201102085339.GA62118@cskk.homeip.net> Message-ID: On 2/11/20 6:53 pm, Cameron Simpson wrote: > You said you had some C++ code, so I'm going to provide some C code > below to show some mechanism in a form I hope you're already familiar > with. OK Cameron thank you, I've got it now. Declaring a two dimensional array in C takes one line of code, e.g. int b[5][5]. The equivalent in Python takes 7 lines or one long line: b = [ ??? [0] * 5, ??? [0] * 5, ??? [0] * 5, ??? [0] * 5, ??? [0] * 5, ??? ] My array is [30] [25] which means many lines of code, something I want to avoid. Creating a numpy array is also one line of code. Anyway Cameron I appreciate the time that you've devoted to this. -- Regards, Phil From alan.gauld at yahoo.co.uk Mon Nov 2 05:08:44 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 2 Nov 2020 10:08:44 +0000 Subject: [Tutor] Two dimensional lists In-Reply-To: References: <9160747a-f280-396b-ca3e-e24766b9c589@gmail.com> <20201102085339.GA62118@cskk.homeip.net> Message-ID: On 02/11/2020 09:33, Phil wrote: > > Declaring a two dimensional array in C takes one line of code, e.g. int > b[5][5]. > > The equivalent in Python takes 7 lines or one long line: > > b = [ > ??? [0] * 5, > ??? [0] * 5, > ??? [0] * 5, > ??? [0] * 5, > ??? [0] * 5, > ??? ] > > My array is [30] [25] which means many lines of code, something I want > to avoid. Creating a numpy array is also one line of code. The point is that you don;t in general declare arrays in Python. You build them as needed. So to build the array above you would more likely writer: b = [[0]*5 for row in range(5)] Which creates a list b that contains 5 rows each of which is a list of 5 zeros. If you need to initialize an X by Y table then you would do it: xy = [[0]*X for row in range(Y)] Still one line and flexible enough to cope with any sizes. And you can extend that technique to as many dimensions as you need. But its fairly unusual that you need to create ;large lists before using them. You can usually build them by adding the elements as required. That sometimes requires a different approach to accessing the data. Also lists are often not the best option, you can use dictionaries (C++ maps) and access them with tuples as keys. mymap = {} item = mymap[x,y] = 42 print(mymap[x,y]) There is a;so a get() that can return a default value: val = mypmap.get((5,5),0)? # return 0 since 5,5 isn't there yet This is probably closest to your original style example. -- 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 Mon Nov 2 01:07:26 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Mon, 2 Nov 2020 06:07:26 +0000 Subject: [Tutor] Two dimensional lists In-Reply-To: <9cb39aa0-8fd5-d198-56f2-94982f746b4c@gmail.com> References: <9cb39aa0-8fd5-d198-56f2-94982f746b4c@gmail.com> Message-ID: On 02/11/2020 01:24, Phil wrote: > I have some C++ code that I wrote some time ago and, just as an > exercise, I'm converting it to Python. I've come to a standstill because > of arrays. If I use a numpy array as follows then I can use that array > in exactly the same way as a C++ array even though I don't understand > the syntax of it. I used the trial_and_error method to create it. > > self.board = numpy.zeros((board_size_x, board_size_y), dtype=numpy.bool) > self.next_board = numpy.zeros((board_size_x, board_size_y), numpy.bool) > > Python lists, if I understand this correctly, can be used in the same > way as arrays. However, I've made little progress. Is there a list > equivalent to this? > > b = [5] , [5] # a square array of size 5 > > b[3][2] = 9 > > In Python, b = [[5,5],[5,5]] looked promising but I'm still greeted with > a list out of range error. I've read through several Python tutorials > and I've tried append and even though there isn't an error the result > doesn't make sense. > > No doubt the solution is straight forward but this poor old duffer > cannot see it. > I'm too tired to type much so start here https://stackoverflow.com/questions/12791501/python-initializing-a-list-of-lists as it's an obvious pitfall :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at gmail.com Mon Nov 2 01:58:03 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Mon, 2 Nov 2020 06:58:03 +0000 Subject: [Tutor] Two dimensional lists In-Reply-To: <4abda1b7-dc29-4bb5-ce6f-5a71039d75ca@gmail.com> References: <9cb39aa0-8fd5-d198-56f2-94982f746b4c@gmail.com> <20201102044641.GA19930@cskk.homeip.net> <4abda1b7-dc29-4bb5-ce6f-5a71039d75ca@gmail.com> Message-ID: On 02/11/2020 06:25, Phil wrote: > On 2/11/20 2:46 pm, Cameron Simpson wrote: > > Thank you Cameron for your insightful reply. > > For the syntax you show above, the direct Python equivalent is a 5 >> element list, each element of which is a 5 element list. >> >> So: >> >> ???? b = [ >> ?????????? [ 0, 0, 0, 0, 0 ], >> ?????????? [ 0, 0, 0, 0, 0 ], >> ?????????? [ 0, 0, 0, 0, 0 ], >> ?????????? [ 0, 0, 0, 0, 0 ], >> ?????????? [ 0, 0, 0, 0, 0 ], >> ???????? ] >> >> The syntax you use "b[3][2]" fetches element 3 (the fourth element, >> since lists count from 0), and then fetches element 2 from _that_. So >> the third element of the fourth list. > > That's what I expected as well, however, this is the result; > > >>> > >>> b = [5],[5] > >>> b[3][2] = 9 > Traceback (most recent call last): > ? File "", line 1, in > IndexError: tuple index out of range > >>> print(b[3][2]) > Traceback (most recent call last): > ? File "", line 1, in > IndexError: tuple index out of range You might like to try things with the interactive interpreter. >>> b = [5],[5] >>> type(b) >>> b ([5], [5]) >>> b[0] [5] >>> b[1] [5] >>> b[2] Traceback (most recent call last): File "", line 1, in IndexError: tuple index out of range >>> b[0][1] Traceback (most recent call last): File "", line 1, in IndexError: list index out of range So you have a tuple of two lists each of which contains one element. The fact that a comma creates a tuple catches a lot of people :) > > I'd spent the last 3 or 4 hours experimenting with this but have not > achieved anything useful. I also had a play with the array module and I > had another look at numpy and have decided that's the way to go. > > Still, I'm a little disappointed that this has defeated me. > -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From jasmineroyer1 at gmail.com Mon Nov 2 02:55:30 2020 From: jasmineroyer1 at gmail.com (jasmine) Date: Mon, 2 Nov 2020 15:55:30 +0800 Subject: [Tutor] python question Message-ID: Hi, How do I allow a user to input an arbitrary number of names? From jasmineroyer1 at gmail.com Mon Nov 2 02:58:37 2020 From: jasmineroyer1 at gmail.com (jasmine) Date: Mon, 2 Nov 2020 15:58:37 +0800 Subject: [Tutor] Python question Message-ID: Hi, I was wondering how can I allow a user to input an arbitrary number of names? (im using the version 2020.2.1) thank you. From alan.gauld at yahoo.co.uk Mon Nov 2 05:32:01 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 2 Nov 2020 10:32:01 +0000 Subject: [Tutor] Python question In-Reply-To: References: Message-ID: On 02/11/2020 07:58, jasmine wrote: > Hi, > I was wondering how can I allow a user to input an arbitrary number of > names? (im using the version 2020.2.1) I have no idea what version that refers to but you can see the python version when you start the interpreter: Python 3.8.5 (default, Jul 28 2020, 12:59:40) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> So I am using version 3.8.5 That will be more helpful to us than specifying the date. -- 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 Mon Nov 2 05:44:54 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Mon, 2 Nov 2020 10:44:54 +0000 Subject: [Tutor] Python question In-Reply-To: References: Message-ID: On 02/11/2020 07:58, jasmine wrote: > Hi, > I was wondering how can I allow a user to input an arbitrary number of > names? (im using the version 2020.2.1) > thank you. > As we don't write your code you'll need to read the names and append them to a list. From the index here https://docs.python.org/3/genindex.html you should be able to find 'input', 'while' and 'list'. You're not using Python 2020.2.1 as the latest version is 3.9.0, I'd guess that's your IDE you're referring to. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From alan.gauld at yahoo.co.uk Mon Nov 2 07:06:26 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 2 Nov 2020 12:06:26 +0000 Subject: [Tutor] Fwd: Re: python question In-Reply-To: References: Message-ID: <428a6aa9-39dc-2c54-87be-19c145098065@yahoo.co.uk> Don't know what's up with my network but this is my third attempt to send this. Sorry if you wind up with multiple copies! On 02/11/2020 07:55, jasmine wrote: > Hi, > How do I allow a user to input an arbitrary number of names? Just get them to enter a string then you have to break that string into it's elements. s = input("Enter some names: ") names = s.split() # assuming names are separated by whitespace names = s.split(',') # assuming they are separated by commas names = s.split(',:;. ') # assuming separated by any of specified chars 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 Mon Nov 2 08:56:25 2020 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 2 Nov 2020 06:56:25 -0700 Subject: [Tutor] Two dimensional lists In-Reply-To: References: <9160747a-f280-396b-ca3e-e24766b9c589@gmail.com> <20201102085339.GA62118@cskk.homeip.net> Message-ID: <2e8ec6f0-b328-bb54-f638-b0cca1773071@wichmann.us> On 11/2/20 3:08 AM, Alan Gauld via Tutor wrote: > > On 02/11/2020 09:33, Phil wrote: >> >> Declaring a two dimensional array in C takes one line of code, e.g. int >> b[5][5]. >> >> The equivalent in Python takes 7 lines or one long line: >> >> b = [ >> ??? [0] * 5, >> ??? [0] * 5, >> ??? [0] * 5, >> ??? [0] * 5, >> ??? [0] * 5, >> ??? ] >> >> My array is [30] [25] which means many lines of code, something I want >> to avoid. Creating a numpy array is also one line of code. > > The point is that you don;t in general declare arrays in Python. You > build them as needed. > > So to build the array above you would more likely writer: > > > b = [[0]*5 for row in range(5)] > > Which creates a list b that contains 5 rows each of which is a list of 5 > zeros. > > If you need to initialize an X by Y table then you would do it: > > xy = [[0]*X for row in range(Y)] > > Still one line and flexible enough to cope with any sizes. > > And you can extend that technique to as many dimensions as you need. The useful itertools module also has something to help with this (repeat). In general, you have to be a little careful when constructing lists-of-lists when the members are mutable objects, rather than ints as here. But perhaps that's for a little later on in the learning journey... From psimon at sonic.net Mon Nov 2 17:50:55 2020 From: psimon at sonic.net (Paul Simon) Date: Mon, 2 Nov 2020 14:50:55 -0800 Subject: [Tutor] Python3 install windows 10 Message-ID: I have been having trouble installing python 3.9. I already have 2.7 installed and running. Python 2.7 is installed in a directory under c:\ but 3.9 is installed in an odd location under AppData? Aside from having a unicode issue my script cannot find downloaded modules like seaborn and matplotlib. They have been imported with pip3 into python 3.9. Do I have to make a change to a path somewhere? Some instructions? Where can I find info on adapting text from python 2 to unicode python3? Thanks, Paul Simon From mats at wichmann.us Mon Nov 2 18:16:45 2020 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 2 Nov 2020 16:16:45 -0700 Subject: [Tutor] Python3 install windows 10 In-Reply-To: References: Message-ID: <5fce7445-3e4e-027b-46af-0c81e97e4fbe@wichmann.us> On 11/2/20 3:50 PM, Paul Simon wrote: > I have been having trouble installing python 3.9.? I already have 2.7 > installed and running.? Python 2.7 is installed in a directory under c:\ > but 3.9 is installed in an odd location under AppData? That's the default location (AppData/Local/Programs/Python*) if you select a user install, which I think is the default checkbox setting in the installer; if you "install for all users" it goes to the root directory, but that's not an ideal place because you probably then don't have rights to modify it (e.g. install modules via pip), that's why you'll normally get it in your own directory under AppData. > Aside from > having a unicode issue my script cannot find downloaded modules like > seaborn and matplotlib.? They have been imported with pip3 into python 3.9. > > Do I have to make a change to a path somewhere?? Some instructions? Well, failure to import something you know is installed is _always_ a path problem. But probably they didn't install where you thought they installed. Instructions? General ones here: https://docs.python.org/3/using/windows.html Usually, if you get the Python you want working, then use that same Python to install. So if "py" (the Python launcher) finds the Python you want, then use: py -m pip install seaborn By the way, a bunch of modules that have binary bits haven't been made available for 3.9 yet (that's normal for Python minor-version bumps). For example: https://pypi.org/project/matplotlib/#files there are no "cp39" versions there yet. You may want to stick with 3.8 for a while longer. > > Where can I find info on adapting text from python 2 to unicode python3? this is one of the best descriptions I've read: http://python-notes.curiousefficiency.org/en/latest/python3/text_file_processing.html From david at graniteweb.com Mon Nov 2 21:56:56 2020 From: david at graniteweb.com (David Rock) Date: Mon, 2 Nov 2020 20:56:56 -0600 Subject: [Tutor] Python question In-Reply-To: References: Message-ID: <7A82FC4D-AD4B-4BA0-90BB-033508C59AC2@graniteweb.com> > On Nov 2, 2020, at 04:44, Mark Lawrence wrote: > > On 02/11/2020 07:58, jasmine wrote: >> Hi, >> I was wondering how can I allow a user to input an arbitrary number of >> names? (im using the version 2020.2.1) >> thank you. > > As we don't write your code you'll need to read the names and append them to a list. From the index here https://docs.python.org/3/genindex.html you should be able to find 'input', 'while' and 'list'. You're not using Python 2020.2.1 as the latest version is 3.9.0, I'd guess that's your IDE you're referring to. 2020.2.1 sounds like the version of PyCharm. As Mark suggests, you will want to investigate using a loop to repeatedly ask for names and append them to a list that you can work with after you break out of the loop. That may not be the best solution, depending on your needs, but it?s a good place to start. ? David Rock david at graniteweb.com From manpritsinghece at gmail.com Tue Nov 3 02:18:00 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Tue, 3 Nov 2020 12:48:00 +0530 Subject: [Tutor] A problem involving exception handling, need suggestions to improve further Message-ID: Dear sir , I have written a program using functions, that print a sum of series upto n terms : The Series will be as follows : a + aa + aaa + aaaa + ------------ upto n terms output will be sum(9 + 99 +999 + 9999) if the series is made up of integer 9 and up to 4 terms. Now clearly for values of n(number of terms) below 1, i need to raise an exception as for values of n < 1 there will be no valid series and no output should be there . in that situation i have to print "Wrong value of order entered". The program is written below: def ser_gen(x, n): try: if n < 1: raise ValueError except ValueError: print("Wrong value of order entered") else: l1 = [x] for i in range(1, n): l1.append(l1[-1]*10 + x) print(sum(l1)) ser_gen(9, 4) will print 11106 which is right answer ser_gen(9, -1) will print 'Wrong value of order entered" Need your suggestions to improve Regards Manprit Singh From alan.gauld at yahoo.co.uk Tue Nov 3 04:47:31 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 3 Nov 2020 09:47:31 +0000 Subject: [Tutor] A problem involving exception handling, need suggestions to improve further In-Reply-To: References: Message-ID: On 03/11/2020 07:18, Manprit Singh wrote: > Now clearly for values of n(number of terms) below 1, i need to raise an > exception as for values of n < 1 there will be no valid series and no > output should be there . in that situation i have to print "Wrong value of > order entered". The program is written below: > > def ser_gen(x, n): > try: > if n < 1: > raise ValueError > except ValueError: > print("Wrong value of order entered") This is completely pointless and extremely inefficient. All you need here is if n < 1: print(....) But better would be: if n < 1: raise ValueError("n must be greater than 1") Why is it better? Because: 1) it removes any printing from the function - you should avoid mixing logic/processing with display. 2) The error message tells the user what was wrong not just that something was wrong. 3) By raising the exception to the user of the function there is some possibility that they can fix the problem rather than being stuck with a printed message. 4) By raising an exception the user of the function will get a stack trace that will enable (or at least help) them to figure out where the error was introduced. > else: > l1 = [x] > for i in range(1, n): > l1.append(l1[-1]*10 + x) > print(sum(l1)) See point 1 above. The code that does the processing should *return* the value not print it. Also, for your own sanity avoid mixing i,l and 1 in variable names. They all look so similar that it's very easy to make mistakes and finding the mistake becomes a visual nightmare! Finally, try to name your functions to reflect what they do. ser_gen() suggests that this function returns a generated series. In fact it returns a total. So call the function sum_ser() or something similar. It's all about making your code readable. -- 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.Flynn at capita.com Tue Nov 3 04:21:23 2020 From: Steve.Flynn at capita.com (Flynn, Stephen (Life & Pensions)) Date: Tue, 3 Nov 2020 09:21:23 +0000 Subject: [Tutor] A problem involving exception handling, need suggestions to improve further In-Reply-To: References: Message-ID: > ser_gen(9, 4) will print 11106 which is right answer > ser_gen(9, -1) will print 'Wrong value of order entered" > Need your suggestions to improve Is the exercise to actually use a try/except block as it's entirely superfluous. Why not: def ser_gen(x, n): if n < 1: print("Wrong value of order entered") raise ValueError else: l1 = [x] for i in range(1, n): l1.append(l1[-1]*10 + x) print(sum(l1)) This email is security checked and subject to the disclaimer on web-page: https://www.capita.com/email-disclaimer.aspx From eryksun at gmail.com Tue Nov 3 18:51:26 2020 From: eryksun at gmail.com (Eryk Sun) Date: Tue, 3 Nov 2020 17:51:26 -0600 Subject: [Tutor] Python3 install windows 10 In-Reply-To: <5fce7445-3e4e-027b-46af-0c81e97e4fbe@wichmann.us> References: <5fce7445-3e4e-027b-46af-0c81e97e4fbe@wichmann.us> Message-ID: On 11/2/20, Mats Wichmann wrote: > On 11/2/20 3:50 PM, Paul Simon wrote: >> I have been having trouble installing python 3.9. I already have 2.7 >> installed and running. Python 2.7 is installed in a directory under c:\ >> but 3.9 is installed in an odd location under AppData? > > That's the default location (AppData/Local/Programs/Python*) if you > select a user install, which I think is the default checkbox setting in > the installer; if you "install for all users" it goes to the root > directory The following are the default installation paths used for version 3.x: per-user interpreter: %LocalAppData%\Programs\Python\Python3[-32] per-machine interpreter: %ProgramFiles%\Python3 or %ProgramFiles(x86)%\Python3-32 per-user launcher: %LocalAppData%\Programs\Python\Launcher per-machine launcher: %SystemRoot% "" is the minor version number, and "[-32]" means that "-32" is appended to the name for a 32-bit installation. For example: "Python39-32". The installation path of the interpreter can be configured. Some people install for all users in the root directory, but I recommend against this in general, especially if the interpreter will ever run as an administrator. Scripts that need administrator access should be executed by an interpreter that's installed in a secure location, such as %ProgramFiles%. Directories created in the root directory inherit file security that allows code running with authenticated credentials (i.e. any normal logon session) to modify them. This means that unprivileged malware can infect the installation. Subsequently if the interpreter is run as an administrator, it can infect the entire machine. This applies equally to a per-user installation. Programs installed per-user are low-hanging fruit that's ripe for the picking. A qualified exception for 'per-user' (unprivileged) installation, if one is careful about using virtual environments, is the app distribution of Python from the Microsoft Store. UWP apps are installed into "%ProgramFiles%\WindowsApps", a directory that's even more secure than %ProgramFiles%. If you need to run a script as an administrator, just create a virtual environment and harden the security on the directory to protect it from unprivileged malware. Set a [H]igh integrity level that's inheritable, e.g. `icacls.exe "path\to\env" /setintegritylevel (CI)(OI)H`. This sets a no-write-up rule in the mandatory access-control label of all files and directories in the tree, so code that's running at a lower integrity level (medium is the standard level) is denied data and metadata write access. From manpritsinghece at gmail.com Wed Nov 4 09:42:34 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Wed, 4 Nov 2020 20:12:34 +0530 Subject: [Tutor] A problem involving exception handling, need suggestions to improve further In-Reply-To: References: Message-ID: Dear sir , In the below written mail , we are only raising an exception . I need to make a program that can end normally while displaying a message "Wrong value of order entered" without error if a user provides inappropriate input in a function call like ser_gen(9, -1). Regards Manprit Singh On Tue, Nov 3, 2020 at 8:14 PM Flynn, Stephen (Life & Pensions) < Steve.Flynn at capita.com> wrote: > > ser_gen(9, 4) will print 11106 which is right answer > > > ser_gen(9, -1) will print 'Wrong value of order entered" > > > > Need your suggestions to improve > > Is the exercise to actually use a try/except block as it's entirely > superfluous. Why not: > > def ser_gen(x, n): > if n < 1: > print("Wrong value of order entered") > raise ValueError > else: > l1 = [x] > for i in range(1, n): > l1.append(l1[-1]*10 + x) > print(sum(l1)) > > > This email is security checked and subject to the disclaimer on web-page: > https://www.capita.com/email-disclaimer.aspx > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From mats at wichmann.us Wed Nov 4 09:45:47 2020 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 4 Nov 2020 07:45:47 -0700 Subject: [Tutor] A problem involving exception handling, need suggestions to improve further In-Reply-To: References: Message-ID: <3bee05bc-98cd-be86-c845-fbe3692912ea@wichmann.us> On 11/4/20 7:42 AM, Manprit Singh wrote: > Dear sir , > > In the below written mail , we are only raising an exception . I need to > make a program that can end normally while displaying a message "Wrong > value of order entered" without error if a user provides inappropriate > input in a function call like ser_gen(9, -1). You wrap the call to the function in a try block, and handle the exception the way you want it. In this case you should remove the prints in the function and instead print after calling the function. > > Regards > Manprit Singh > > On Tue, Nov 3, 2020 at 8:14 PM Flynn, Stephen (Life & Pensions) < > Steve.Flynn at capita.com> wrote: > >>> ser_gen(9, 4) will print 11106 which is right answer >> >>> ser_gen(9, -1) will print 'Wrong value of order entered" >> >> >>> Need your suggestions to improve >> >> Is the exercise to actually use a try/except block as it's entirely >> superfluous. Why not: >> >> def ser_gen(x, n): >> if n < 1: >> print("Wrong value of order entered") >> raise ValueError >> else: >> l1 = [x] >> for i in range(1, n): >> l1.append(l1[-1]*10 + x) >> print(sum(l1)) From cs at cskk.id.au Wed Nov 4 16:15:23 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Thu, 5 Nov 2020 08:15:23 +1100 Subject: [Tutor] A problem involving exception handling, need suggestions to improve further In-Reply-To: <3bee05bc-98cd-be86-c845-fbe3692912ea@wichmann.us> References: <3bee05bc-98cd-be86-c845-fbe3692912ea@wichmann.us> Message-ID: <20201104211523.GA50362@cskk.homeip.net> On 04Nov2020 07:45, Mats Wichmann wrote: >On 11/4/20 7:42 AM, Manprit Singh wrote: >>In the below written mail , we are only raising an exception . I need >>to >>make a program that can end normally while displaying a message "Wrong >>value of order entered" without error if a user provides inappropriate >>input in a function call like ser_gen(9, -1). > >You wrap the call to the function in a try block, and handle the >exception the way you want it. In this case you should remove the >prints in the function and instead print after calling the function. Just to elaborate a bit on Mats' advice, it is uncommon for functions themselves to use print() calls (unless their purpose is actually "output"). Instead, functions usually return values or raise exceptions. This lets the calling code decide what should happen. So the outermost, interactive, part of your programme might look like this: while True: value_s = input("Enter a value: ") try: value = int(value_s) except ValueError: print("Not an int! Received", repr(value_s)) continue try: result = func(value) except ValueError as e: print("Invalid value %r: %s" % (value, e)) else: print("Result =", result) and func would look like: def func(x): if x < 1: raise ValueError("invalid value for x, should be >=1") return x * 2 You can see: - func is cleaner: it returns the value or raises a ValueError exception _with an explaination_ - it does not print anything - it has no opinion about what should happen to its value - the main programme is where "policy" decisions about output and behaviour on errors takes place Also notice that because the ValueError includes an explaination, it is useful to include the exception in the complaint you print in the main programme. All the exceptions you raise should include some explaination of why they were raised, usually as short as possible which still making the failed condition clear. Cheers, Cameron Simpson From alan.gauld at yahoo.co.uk Wed Nov 4 18:21:41 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 4 Nov 2020 23:21:41 +0000 Subject: [Tutor] A problem involving exception handling, need suggestions to improve further In-Reply-To: References: Message-ID: On 04/11/2020 14:42, Manprit Singh wrote: > In the below written mail , we are only raising an exception . I need to > make a program that can end normally while displaying a message Thats fine and there is no problem doing that as pointed out by Mats and Cameron. The difference is in a function. You do not want a function that performs calculations printing things. Why? Because it would make the function unusable in a GUI program, a web application, or a server process running in the background and writing top a log file. One of the main reasons we put things into functions is so that they can be reused 9multiple times within a single program or, even better, multiple times across multiple programs. To do that we want functions to return values or raise exceptions which can be used by the UI parts of the program. That way if an exception occurs the GUI program can pop up a dialog box, the web app can display an error page(or an error dialog) and the server process can write it to the log file. And of course a CLI program can just print the message. A print inside the function would be much harder to handle in each case except the last. Incidentally, you can pass a string into the exception when you raise it and access that string in the except handler where you catch it: def f(x): if x < 0: raise ValueError("%d is less than zero" % x) return int(x**0.5) try: print(" The int root of -5 is: %d" % f(-5)) except ValueError as err: print(err) # prints "-5 is less than zero" -- 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 kanizsumiya at gmail.com Wed Nov 4 21:01:15 2020 From: kanizsumiya at gmail.com (Kaniz Sumiya) Date: Wed, 4 Nov 2020 18:01:15 -0800 Subject: [Tutor] (no subject) Message-ID: I need to make a scraps game with these guidelines: import random money = 100 Ask user if they want to play or "QUIT" (.upper()) while game != "QUIT": 2 dice generate random numbers 1-6 on each (generate random numbers inside while loop) Every roll cost $3 Win $5 if total is 7 Win $10 for snake eyes Else display " Craps" Ask user if they want to play or "QUIT" if money<3 game ="QUIT" Print money From alan.gauld at yahoo.co.uk Thu Nov 5 04:46:59 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 5 Nov 2020 09:46:59 +0000 Subject: [Tutor] Craps game was: Re: (no subject) In-Reply-To: References: Message-ID: On 05/11/2020 02:01, Kaniz Sumiya wrote: > I need to make a scraps game with these guidelines: > > > import random > money = 100 > Ask user if they want to play or "QUIT" (.upper()) > while game != "QUIT": > 2 dice generate random numbers 1-6 on each (generate random > numbers inside while loop) > Every roll cost $3 > Win $5 if total is 7 > Win $10 for snake eyes > Else display " Craps" > Ask user if they want to play or "QUIT" > if money<3 > game ="QUIT" > Print money That all looks clear enough. I assume you want to write it in Python? If so why not start translating the above pseudo code into real python code. If you get stuck ask us a question. If you do that include the code you have written, any error messages you get(in full) and tell us the Python version and OS you are using. -- 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 manpritsinghece at gmail.com Fri Nov 6 12:03:00 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Fri, 6 Nov 2020 22:33:00 +0530 Subject: [Tutor] use of raw strings with regular expression patterns Message-ID: Dear sir , As you know there are some special characters in regular expressions , like : \A, \B, \b, \d, \D, \s, \S, \w, \W, \Z is it necessary to use raw string notation like r'\A' while using re patterns made up of these characters ? Regards From mats at wichmann.us Fri Nov 6 12:06:36 2020 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 6 Nov 2020 10:06:36 -0700 Subject: [Tutor] use of raw strings with regular expression patterns In-Reply-To: References: Message-ID: <2b93ce0c-6f28-22c6-ed98-0c7f0d26d17c@wichmann.us> On 11/6/20 10:03 AM, Manprit Singh wrote: > Dear sir , > > As you know there are some special characters in regular expressions , like > : > \A, \B, \b, \d, \D, \s, \S, \w, \W, \Z > > is it necessary to use raw string notation like r'\A' while using re > patterns made up of these characters ? it's recommended, yes. Otherwise you have a conflict on who processes the escapes, entering as a raw string tells Python to keep its hands off. checkers will give you warnings if you use escapes that don't look like Python's own escapes, and you didn't enter as a raw string. From alan.gauld at yahoo.co.uk Fri Nov 6 12:33:39 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 6 Nov 2020 17:33:39 +0000 Subject: [Tutor] use of raw strings with regular expression patterns In-Reply-To: References: Message-ID: On 06/11/2020 17:03, Manprit Singh wrote: > Dear sir , > > As you know there are some special characters in regular expressions , like > : > \A, \B, \b, \d, \D, \s, \S, \w, \W, \Z > > is it necessary to use raw string notation like r'\A' while using re > patterns made up of these characters ? It's not necessary in the sense that Python will allow you not to. But it is *very strongly recommended*, otherwise some unexpected results are likely. -- 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 manpritsinghece at gmail.com Fri Nov 6 13:56:51 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sat, 7 Nov 2020 00:26:51 +0530 Subject: [Tutor] use of raw strings with regular expression patterns In-Reply-To: References: Message-ID: Dear Sir , I have tried to find all matches in a string that starts with a (.), then the next character is a lowercase alphabet and then a digit. s = "a.b.c.d1.1ef.g5" re.findall('\.[a-z][0-9]', s) is the way i have used the RE patterns ok ? On Fri, Nov 6, 2020 at 11:04 PM Alan Gauld via Tutor wrote: > On 06/11/2020 17:03, Manprit Singh wrote: > > Dear sir , > > > > As you know there are some special characters in regular expressions , > like > > : > > \A, \B, \b, \d, \D, \s, \S, \w, \W, \Z > > > > is it necessary to use raw string notation like r'\A' while using re > > patterns made up of these characters ? > > It's not necessary in the sense that Python will allow you > not to. But it is *very strongly recommended*, otherwise some > unexpected results are likely. > > > -- > 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 Nov 7 04:08:16 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 7 Nov 2020 09:08:16 +0000 Subject: [Tutor] use of raw strings with regular expression patterns In-Reply-To: References: Message-ID: On 06/11/2020 18:56, Manprit Singh wrote: > Dear Sir , > > I have tried to find all matches in a string that starts with a (.), then > the next character is a lowercase alphabet and then a digit. > > s = "a.b.c.d1.1ef.g5" > re.findall('\.[a-z][0-9]', s) > > is the way i have used the RE patterns ok ? What does the interpreter say? >>> s = "a.b.c.d1.1ef.g5" >>> import re >>> re.findall('\.[a-z][0-9]', s) ['.d1', '.g5'] >>> Apparently it is. Although, from your earlier email, you should probably use a raw string >>> re.findall(r'\.[a-z][0-9]', s) ['.d1', '.g5'] However, in this case it makes no difference. -- 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 Sat Nov 7 16:42:02 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 8 Nov 2020 08:42:02 +1100 Subject: [Tutor] use of raw strings with regular expression patterns In-Reply-To: References: Message-ID: <20201107214202.GA90568@cskk.homeip.net> On 06Nov2020 22:33, Manprit Singh wrote: >As you know there are some special characters in regular expressions , >like >: >\A, \B, \b, \d, \D, \s, \S, \w, \W, \Z > >is it necessary to use raw string notation like r'\A' while using re >patterns made up of these characters ? Another thing not mentioned in the replies is the backslash itself. The advantage of a raw string is that when you write a backslash, it is part of the string as-is. So to put a backslash in a regular string, so that it is part of the result, you would need to write: \\ In a raw string, you just write: \ exactly as you want things. Now, it happens that in a regular string a backslash _not_ followed by a special character (eg "n" for "\n", a newline) is preserved. So they get through to the final string anyway. But the moment you _do_ follow the backslash with such a character, it is consumed and the character translated. Example: \h Ordinary string '\h' -> \h Raw string: r'\h' -> \h A backslash and an "h" in the result. But: \n Ordinary string: '\n' -> newline Raw string: r'\n' -> \n A newline in the result for the former, a backslash and an "n" for the latter. So the advantage of the raw string is _reliably preserving the backslash_. For any situation where backslashes are intended in the resulting string it is recommended to use a "raw" string in Python, for this reliability. The two common situations are regexps where backslash introduces special character classes and Windows file paths, where backslash is the file separator. Cheers, Cameron Simpson From phillor9 at gmail.com Sat Nov 7 18:41:44 2020 From: phillor9 at gmail.com (Phil) Date: Sun, 8 Nov 2020 09:41:44 +1000 Subject: [Tutor] Testing for mouse clicks Message-ID: <68fcade6-25ae-75fb-8fd0-42bb35f31eac@gmail.com> Spurred on by success with my recent project involving a grid of lists, I now have another grid project in mind. If I want to test whether the mouse is over, say one of six window locations, I would do something like the following to test the mouse coordinates: if 136 <= x <= 156 and 370 <= y <= 390: ??? do_something elif 186 <= x <= 206 and 370 <= y <= 390: ??? do_something elif 236 <= x <= 256 and 370 <= y <= 390: ???? do_something elif etc Now, if I have a 15 * 15 grid of window locations that I want to test then repeating the above 225 times becomes a bit untidy, and tedious. How might I best attack this mouse_testing problem? -- Regards, Phil From cs at cskk.id.au Sat Nov 7 19:16:27 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 8 Nov 2020 11:16:27 +1100 Subject: [Tutor] Testing for mouse clicks In-Reply-To: <68fcade6-25ae-75fb-8fd0-42bb35f31eac@gmail.com> References: <68fcade6-25ae-75fb-8fd0-42bb35f31eac@gmail.com> Message-ID: <20201108001627.GA26711@cskk.homeip.net> On 08Nov2020 09:41, Phil wrote: >Spurred on by success with my recent project involving a grid of >lists, I now have another grid project in mind. If I want to test >whether the mouse is over, say one of six window locations, I would do >something like the following to test the mouse coordinates: > >if 136 <= x <= 156 and 370 <= y <= 390: >??? do_something >elif 186 <= x <= 206 and 370 <= y <= 390: >??? do_something >elif 236 <= x <= 256 and 370 <= y <= 390: >???? do_something >elif etc > >Now, if I have a 15 * 15 grid of window locations that I want to test >then repeating the above 225 times becomes a bit untidy, and tedious. >How might I best attack this mouse_testing problem? Can you inspect your grid widget to determine its coordinates? Or inspect the button for its coordinates? If so, measure, construct a mapping of bounds to actions to take. Example: widget_map = {} for my_widget in enumerate-your-widgets-here: x0, dx, y0, dy = my_widget.bounds() widget_map[x0, y0, x0+dx, y0+dy] = my_widget ... # find the widget and call its on_clicked method for (x0, x1, y0, y1), my_widget in widget_map.items(): if x0 <= x < x1 and y0 < y <= y1: my_widget.on_clicked(...) break Obviously you need the widgets to know their coordinates and have such a method, but that too can be arranged. Cheers, Cameron Simpson From phillor9 at gmail.com Sat Nov 7 19:40:29 2020 From: phillor9 at gmail.com (Phil) Date: Sun, 8 Nov 2020 10:40:29 +1000 Subject: [Tutor] Testing for mouse clicks In-Reply-To: <20201108001627.GA26711@cskk.homeip.net> References: <68fcade6-25ae-75fb-8fd0-42bb35f31eac@gmail.com> <20201108001627.GA26711@cskk.homeip.net> Message-ID: <5912da62-ca20-11c5-e26e-00f97994b30c@gmail.com> On 8/11/20 10:16 am, Cameron Simpson wrote: > Can you inspect your grid widget to determine its coordinates? Or > inspect the button for its coordinates? If so, measure, construct a > mapping of bounds to actions to take. Example: > > > widget_map = {} > for my_widget in enumerate-your-widgets-here: > x0, dx, y0, dy = my_widget.bounds() > widget_map[x0, y0, x0+dx, y0+dy] = my_widget > ... > # find the widget and call its on_clicked method > for (x0, x1, y0, y1), my_widget in widget_map.items(): > if x0 <= x < x1 and y0 < y <= y1: > my_widget.on_clicked(...) > break > Thank you Cameron, I would never have thought of using a for_loop with multiple variables. I'll experiment with this idea and see what I can come up with. -- Regards, Phil From alan.gauld at yahoo.co.uk Sat Nov 7 19:47:31 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 8 Nov 2020 00:47:31 +0000 Subject: [Tutor] Testing for mouse clicks In-Reply-To: <68fcade6-25ae-75fb-8fd0-42bb35f31eac@gmail.com> References: <68fcade6-25ae-75fb-8fd0-42bb35f31eac@gmail.com> Message-ID: On 07/11/2020 23:41, Phil wrote: > Spurred on by success with my recent project involving a grid of lists, Sorry i dpn;t remember it. Which GUI toolkit are you using? They are all very different! > I now have another grid project in mind. If I want to test whether the > mouse is over, say one of six window locations, I would do something > like the following to test the mouse coordinates: > > if 136 <= x <= 156 and 370 <= y <= 390: > ??? do_something > elif 186 <= x <= 206 and 370 <= y <= 390: > ??? do_something > elif 236 <= x <= 256 and 370 <= y <= 390: > ???? do_something > elif etc See thats exactly what i would NOT do. Its far too fragile, if any of those widgets changes size you are in a mess. Better to express it in terms of the widgets sizes. Especially if your grid has cells of equal size - at least within a column or row. Then it becomes a matter of (admittedly tedious) arithmetic rather than specifying each location. But that's rarely needed since most widgets have ways of detecting if a mouse click happened. So in general when you create the grid you can assign a mouse click handler to that cell. (You normally only need a single handler for the whole grid, just assign different x,y coordinates in a lambda: def mouseClickHandler(x,y): # handle it here using x,y cell1 = Cell(.... mouseclick = lambda x=0,y=0: mouseClickHandler(x,y) ...) cell2 = Cell(.... mouseclick = lambda x=0,y=1: mouseClickHandler(x,y) ...) etc... Now when the mouse is clicked in cell1 it calls mouseClickHandler(0,0) and when the mouse is clicked in cell2 it calls mouseClickHandler(0,1) So now you need to find out how/if your GUI toolkit binds mouseclicks to cells. That will depend on the toolkit you are using and exactly what kind of widget your cell consists of (Entry, Label,Canvas???). For example in Tkinter you'd use the bind() method immediately after creating the cell. Something like: grid[x][y] = Label(gridFrame, text=....) grid[x][y].bind("", lambda X=x, Y=y: mouseClickHandler(X,Y) grid[x][y].grid(column=x,row=y,...) > Now, if I have a 15 * 15 grid of window locations that I want to test > then repeating the above 225 times becomes a bit untidy, and tedious. > How might I best attack this mouse_testing problem? If they are individual windows then your window widget almost certainly allows binding of mouse events. You just need to find out how. Then it becomes a matter of 225 mouse bindings which is marginally easier. But more likely you will create the grid using nested for loops and the cell coordinates will be the loop variables. So it will only be one line of code(as in the Tkinter example above). But we can't be more specific without you showing us how you create your cells and telling us which GUI toolkit you 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 phillor9 at gmail.com Sat Nov 7 21:02:54 2020 From: phillor9 at gmail.com (Phil) Date: Sun, 8 Nov 2020 12:02:54 +1000 Subject: [Tutor] Testing for mouse clicks In-Reply-To: References: <68fcade6-25ae-75fb-8fd0-42bb35f31eac@gmail.com> Message-ID: On 8/11/20 10:47 am, Alan Gauld via Tutor wrote: > On 07/11/2020 23:41, Phil wrote: >> Spurred on by success with my recent project involving a grid of lists, Thank you Alan for your reply. > Which GUI toolkit are you using? In this instance I'm using WxPython. > > if 136 <= x <= 156 and 370 <= y <= 390: > ??? do_something > elif 186 <= x <= 206 and 370 <= y <= 390: > ??? do_something > > See thats exactly what i would NOT do. I can see why, it's a real pain if I decide to add another widget to click on or resize the window. >> Its far too fragile, if any of those widgets changes size you >> are in a mess. Better to express it in terms of the widgets >> sizes. Especially if your grid has cells of equal size - at >> least within a column or row. Then it becomes a matter of >> (admittedly tedious) arithmetic rather than specifying each >> location. >> >> But that's rarely needed since most widgets have ways of detecting >> if a mouse click happened. I use two for loops (x and Y) to create a grid. If I knew how to create a custom widget then I suppose I could bind a mouse click to it. Perhaps I should investigate that idea first. >> So in general when you create the grid >> you can assign a mouse click handler to that cell. (You normally >> only need a single handler for the whole grid, just assign >> different x,y coordinates in a lambda: >> >> def mouseClickHandler(x,y): >> # handle it here using x,y >> >> cell1 = Cell(.... >> mouseclick = lambda x=0,y=0: mouseClickHandler(x,y) >> ...) >> cell2 = Cell(.... >> mouseclick = lambda x=0,y=1: mouseClickHandler(x,y) >> ...) >> etc... >> >> Now when the mouse is clicked in cell1 it calls mouseClickHandler(0,0) >> and when the mouse is clicked in cell2 it calls mouseClickHandler(0,1) >> >> So now you need to find out how/if your GUI toolkit binds mouseclicks to >> cells. That will depend on the toolkit you are using and exactly what >> kind of widget your cell consists of (Entry, Label,Canvas???). Just empty cells on a panel which is why I've been working on mouse coordinates. Another GUI library, (based on Tkinter)? uses what the author calls a Waffle which, it seems, can be bound to mouse events. I think I should look into creating a similar widget, it would save a lot of calculator time and trouble. What I've done in years past, starting with a Sudoku solver, was to create a board of x and y cells and, once those cell have been manipulated, simply use the GUI to display the result. >> For example in Tkinter you'd use the bind() method immediately after >> creating the cell. Something like: >> >> grid[x][y] = Label(gridFrame, text=....) >> grid[x][y].bind("", lambda X=x, Y=y: mouseClickHandler(X,Y) >> grid[x][y].grid(column=x,row=y,...) >> >> Now, if I have a 15 * 15 grid of window locations that I want to test >> then repeating the above 225 times becomes a bit untidy, and tedious. >> How might I best attack this mouse_testing problem? > If they are individual windows then your window widget almost > certainly allows binding of mouse events. You just need to find > out how. It's just one window, or panel, divided into small squares which are filled with data from the board array. Something like panel coordinate[x][y] = board[x][y]. I did this with Conway's Game of Life. I simple painted a square green if the cell was alive. > > Then it becomes a matter of 225 mouse bindings which is marginally easier. > > But more likely you will create the grid using nested for loops > and the cell coordinates will be the loop variables. So it will > only be one line of code(as in the Tkinter example above). > > But we can't be more specific without you showing us how you > create your cells and telling us which GUI toolkit you use. More food for thought. I can see that I need to give this much more consideration. Maybe a grid of buttons? WxPython buttons are just a clickable patch (they don't look like the more usual button, not under Linux at least) but it might be a good place to start. Thank you for spurring me on. -- Regards, Phil From cs at cskk.id.au Sat Nov 7 21:13:03 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 8 Nov 2020 13:13:03 +1100 Subject: [Tutor] Testing for mouse clicks In-Reply-To: <5912da62-ca20-11c5-e26e-00f97994b30c@gmail.com> References: <5912da62-ca20-11c5-e26e-00f97994b30c@gmail.com> Message-ID: <20201108021303.GA52789@cskk.homeip.net> On 08Nov2020 10:40, Phil wrote: >On 8/11/20 10:16 am, Cameron Simpson wrote: >>Can you inspect your grid widget to determine its coordinates? Or >>inspect the button for its coordinates? If so, measure, construct a >>mapping of bounds to actions to take. Example: >> >> widget_map = {} >> for my_widget in enumerate-your-widgets-here: >> x0, dx, y0, dy = my_widget.bounds() >> widget_map[x0, y0, x0+dx, y0+dy] = my_widget >> ... >> # find the widget and call its on_clicked method >> for (x0, x1, y0, y1), my_widget in widget_map.items(): >> if x0 <= x < x1 and y0 < y <= y1: >> my_widget.on_clicked(...) >> break >> >Thank you Cameron, I would never have thought of using a for_loop with >multiple variables. I'll experiment with this idea and see what I can >come up with. Note the brackets: you get (key,value) from .items() and we unpack the key into its 4 components. Look up "unpacking syntax" in the python docs. Cheers, Cameron Simpson From alan.gauld at yahoo.co.uk Sun Nov 8 04:01:00 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 8 Nov 2020 09:01:00 +0000 Subject: [Tutor] Testing for mouse clicks In-Reply-To: References: <68fcade6-25ae-75fb-8fd0-42bb35f31eac@gmail.com> Message-ID: On 08/11/2020 02:02, Phil wrote: >> Which GUI toolkit are you using? > In this instance I'm using WxPython. Ah, OK in that case you have to bind the mouse click to the widget after you create it. The good news pretty much any widget can be bound. cell1.Bind(wz.EVT_LEFT_UP, clickEventHandler)) > I use two for loops (x and Y) to create a grid. If I knew how to create > a custom widget then I suppose I could bind a mouse click to it. Perhaps > I should investigate that idea first. You don;t need a custom widget, wxPython lets you bind mouse events to pretty much any kind of widget. > Just empty cells on a panel which is why I've been working on mouse > coordinates. Sorry, there isn't a cell widget in wxPython. Exactly what kind of widget are you using? Show us the loop where you create the grid and we can probably show you the bind call you need. However, wxPython does have a wx.grid.Grid widget which sounds like it would do exactly what you need without much extra work on your part. Have you looked into that? > It's just one window, or panel, divided into small squares which are > filled with data from the board array. OK, windows, panels, squares are all separate widgets. You need to be precise. Specifically what kind of widget is the container? Which is the individual cell? This is very important, you cannot be woolly about it. > coordinate[x][y] = board[x][y]. I did this with Conway's Game of Life. I > simple painted a square green if the cell was alive. Again show us code! Code is much more precise than vague descriptions. Programming is all about the detail. > consideration. Maybe a grid of buttons? WxPython buttons are just a > clickable patch (they don't look like the more usual button, not under > Linux at least) but it might be a good place to start. Yes, thats what I used for the oxo game in my book. Buttons are easy. And they work with the mouse without any special binding. But I'd check the Wx grid control too since it looks like it does virtually everything you describe for free! -- 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 phillor9 at gmail.com Sun Nov 8 04:24:21 2020 From: phillor9 at gmail.com (Phil) Date: Sun, 8 Nov 2020 19:24:21 +1000 Subject: [Tutor] Testing for mouse clicks In-Reply-To: References: <68fcade6-25ae-75fb-8fd0-42bb35f31eac@gmail.com> Message-ID: <17c2e5fc-4da0-98fe-82b3-157d4160da35@gmail.com> On 8/11/20 7:01 pm, Alan Gauld via Tutor wrote: > But I'd check the Wx grid control too since it looks like it does > virtually everything you describe for free! Thank you again Alan. I've put some code together that uses wx.Grid and it is what I had in mind. When I first looked at wx.Grid I assumed that it's use was to layout widgets but it can also be used to layout empty clickable cells. I'll have to experiment with it, and that's a task for tomorrow. -- Regards, Phil From manpritsinghece at gmail.com Sun Nov 8 08:28:54 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 8 Nov 2020 18:58:54 +0530 Subject: [Tutor] use of raw strings with regular expression patterns In-Reply-To: <20201107214202.GA90568@cskk.homeip.net> References: <20201107214202.GA90568@cskk.homeip.net> Message-ID: Dear Sir, I have one more very basic question . Suppose I have to remove all "a" inside the string s1. s1 = "saaaaregaaaaamaaaa" >>> re.sub(r"a+", "", s1) 'sregm' >>> re.sub(r"a", "", s1) 'sregm' I have solved this with two patterns , one includes a "+" that means one or more repetition of the previous re . I am confused what pattern must be chosen for this particular case? Regards Manprit Singh On Sun, Nov 8, 2020 at 3:12 AM Cameron Simpson wrote: > On 06Nov2020 22:33, Manprit Singh wrote: > >As you know there are some special characters in regular expressions , > >like > >: > >\A, \B, \b, \d, \D, \s, \S, \w, \W, \Z > > > >is it necessary to use raw string notation like r'\A' while using re > >patterns made up of these characters ? > > Another thing not mentioned in the replies is the backslash itself. > > The advantage of a raw string is that when you write a backslash, it is > part of the string as-is. > > So to put a backslash in a regular string, so that it is part of the > result, you would need to write: > > \\ > > In a raw string, you just write: > > \ > > exactly as you want things. > > Now, it happens that in a regular string a backslash _not_ followed by a > special character (eg "n" for "\n", a newline) is preserved. So they get > through to the final string anyway. But the moment you _do_ follow the > backslash with such a character, it is consumed and the character > translated. > > Example: > > \h > > Ordinary string '\h' -> \h > Raw string: r'\h' -> \h > A backslash and an "h" in the result. > > But: > > \n > > Ordinary string: '\n' -> newline > Raw string: r'\n' -> \n > A newline in the result for the former, a backslash and an "n" for the > latter. > > So the advantage of the raw string is _reliably preserving the > backslash_. > > For any situation where backslashes are intended in the resulting string > it is recommended to use a "raw" string in Python, for this reliability. > > The two common situations are regexps where backslash introduces special > character classes and Windows file paths, where backslash is the file > separator. > > Cheers, > Cameron Simpson > _______________________________________________ > 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 Sun Nov 8 08:45:25 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 8 Nov 2020 13:45:25 +0000 Subject: [Tutor] use of raw strings with regular expression patterns In-Reply-To: References: <20201107214202.GA90568@cskk.homeip.net> Message-ID: On 08/11/2020 13:28, Manprit Singh wrote: > s1 = "saaaaregaaaaamaaaa" > >>>> re.sub(r"a+", "", s1) > 'sregm' >>>> re.sub(r"a", "", s1) > 'sregm' > > I have solved this with two patterns , one includes a "+" that means one > or more repetition of the previous re . I am confused what pattern must be > chosen for this particular case? With regex there is very rarely only one "correct" answer. They both work so both are correct. as to which is more efficient, you'd need to time them to find out. However, the difference is that the first applies a pattern repeatedly - that's what the + does. The first simply subs every letter a with a blank. But thee is a big difference that is hidden in this case because you are deleting characters. For example, if instead of replacing 'a' with '', you tried replacing it with 'b' you might get different results. Try it and you will clearly see the difference. -- 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 beachkidken at gmail.com Sun Nov 8 15:15:22 2020 From: beachkidken at gmail.com (Ken Green) Date: Sun, 8 Nov 2020 15:15:22 -0500 Subject: [Tutor] Finding Matplotlib somewhere Message-ID: <2300868e-b1e7-70e2-c922-0fb7444dd6ae@gmail.com> When running the following portion of a bioyear.py program (dated some 8 years ago from Python 2 and now trying to run it in Python 3. Matplotlib was installed by pip and apt-get and verified by pip3 list. When typing each of the following lines in python 3 shell command line, no error were noted. from datetime import date import matplotlib.dates from pylab import * from numpy import array,sin,pi from sys import argv Traceback (most recent call last): ? File "bioyear.py", line 24, in ??? import matplotlib.dates ImportError: No module named matplotlib.dates It seems not to find matplotlib anywhere but it was verified by sudo apt-get and pip. How can I incorporate it into the program? TIA, Ken From beachkidken at gmail.com Sun Nov 8 17:31:17 2020 From: beachkidken at gmail.com (Ken Green) Date: Sun, 8 Nov 2020 17:31:17 -0500 Subject: [Tutor] Finding Matplotlib somewhere ADDING ADDITIONAL INFORMATION Message-ID: <9bef17ae-63f5-209f-ca6e-8b366b41c35d@gmail.com> ADDITION INFORMATION: I forgot to make mention that I have both Python 2 and 3 in separate folders and I am using Linux Ubuntu 20.04.1. When running the following portion of a bioyear.py program (dated some 8 years ago from Python 2 and now trying to run it in Python 3. Matplotlib was installed by pip and apt-get and verified by pip3 list. When typing each of the following lines in python 3 shell command line, no error were noted. from datetime import date import matplotlib.dates from pylab import * from numpy import array,sin,pi from sys import argv Traceback (most recent call last): ? File "bioyear.py", line 24, in ??? import matplotlib.dates ImportError: No module named matplotlib.dates It seems not to find matplotlib anywhere but it was verified by sudo apt-get and pip. How can I incorporate it into the program? TIA, Ken From mats at wichmann.us Sun Nov 8 18:32:07 2020 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 8 Nov 2020 16:32:07 -0700 Subject: [Tutor] Finding Matplotlib somewhere ADDING ADDITIONAL INFORMATION In-Reply-To: <9bef17ae-63f5-209f-ca6e-8b366b41c35d@gmail.com> References: <9bef17ae-63f5-209f-ca6e-8b366b41c35d@gmail.com> Message-ID: On 11/8/20 3:31 PM, Ken Green wrote: > ADDITION INFORMATION: > > I forgot to make mention that I have both Python 2 and 3 in separate > folders and I am using Linux Ubuntu 20.04.1. > > > When running the following portion of a bioyear.py program (dated some 8 > years ago from Python 2 and now trying to run it in Python 3. > > Matplotlib was installed by pip and apt-get and verified by pip3 list. > When typing each of the following lines in python 3 shell command line, > no error were noted. > > from datetime import date > import matplotlib.dates > from pylab import * > from numpy import array,sin,pi > from sys import argv > > Traceback (most recent call last): > ? File "bioyear.py", line 24, in > ??? import matplotlib.dates > ImportError: No module named matplotlib.dates > > It seems not to find matplotlib anywhere but it was verified by sudo > apt-get and pip. How can I incorporate it into the program? Rule 1: if an import fails, it's always a path problem. There is no Rule 2. Sorry, being cute doesn't actually help solve your problem. In general, for the Python version you expect to use, use the same Python to install packages, that is, if pythonFOO works for you, and you're going to use it to run something, then install with pythonFOO -m pip install PKG or, or that's a _system_ version of Python, you probably want to install extra packages with the -U/--user option. If you're going to use the system Python, and there are packages available, it should be okay to use the matching package. Maybe. Do you know that pip3 refers to the Python you want to use? Your information leaves some questions unanswered: the interactive commands are fine. Did you get the same Python REPL as the Python you're using to run the failing program? > Matplotlib was installed by pip and apt-get and verified by pip3 list If you're running Ubuntu 20.04, and haven't installed the python-is-python3 package, then by default "python" will be 2.7. and pip3 is for python3. See the possibilities for confusion when using an old piece of software? From alan.gauld at yahoo.co.uk Sun Nov 8 18:35:41 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 8 Nov 2020 23:35:41 +0000 Subject: [Tutor] Finding Matplotlib somewhere ADDING ADDITIONAL INFORMATION In-Reply-To: <9bef17ae-63f5-209f-ca6e-8b366b41c35d@gmail.com> References: <9bef17ae-63f5-209f-ca6e-8b366b41c35d@gmail.com> Message-ID: On 08/11/2020 22:31, Ken Green wrote: > Matplotlib was installed by pip and apt-get and verified by pip3 list. > When typing each of the following lines in python 3 shell command line, > no error were noted. > > from datetime import date > import matplotlib.dates > Traceback (most recent call last): > ? File "bioyear.py", line 24, in > ??? import matplotlib.dates > ImportError: No module named matplotlib.dates > > It seems not to find matplotlib anywhere It says it can't find matplotlib.dates, which is not the same as saying it can't find matplotlib. I'd check that first >>> import matplotlib Does that work? Are you sure there is a matplotlib.dates in the Python 3 version of matplotlib? Also there is a dedicated support community for SciPy, of which matplotlib is part. You might get more experienced answers there. -- 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 adameyring at gmail.com Sun Nov 8 19:35:37 2020 From: adameyring at gmail.com (Adam Eyring) Date: Sun, 8 Nov 2020 19:35:37 -0500 Subject: [Tutor] Finding Matplotlib somewhere ADDING ADDITIONAL INFORMATION In-Reply-To: References: <9bef17ae-63f5-209f-ca6e-8b366b41c35d@gmail.com> Message-ID: I tried import matplotlib.dates on my Win10 installation of Python 3.7.6 and it worked, though I don't have a use for .dates. I normally use import matplotlib.pyplot as plt for my projects. I wonder if you should uninstall Python 2 and do a clean re-install of Python 3 to see if that makes a difference. By looking at the errors that come up when running bioyear.py, you can make adjustments to work in Python 3, but I would expect it to be backwards compatible (I'm not an expert on that). AME On Sun, Nov 8, 2020 at 6:36 PM Alan Gauld via Tutor wrote: > On 08/11/2020 22:31, Ken Green wrote: > > > Matplotlib was installed by pip and apt-get and verified by pip3 list. > > When typing each of the following lines in python 3 shell command line, > > no error were noted. > > > > from datetime import date > > import matplotlib.dates > > > Traceback (most recent call last): > > File "bioyear.py", line 24, in > > import matplotlib.dates > > ImportError: No module named matplotlib.dates > > > > It seems not to find matplotlib anywhere > > It says it can't find matplotlib.dates, which is not the same > as saying it can't find matplotlib. I'd check that first > > >>> import matplotlib > > Does that work? > > Are you sure there is a matplotlib.dates in the Python 3 version > of matplotlib? > > Also there is a dedicated support community for SciPy, of which > matplotlib is part. You might get more experienced answers there. > > > -- > 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 breamoreboy at gmail.com Mon Nov 9 05:06:13 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Mon, 9 Nov 2020 10:06:13 +0000 Subject: [Tutor] Finding Matplotlib somewhere ADDING ADDITIONAL INFORMATION In-Reply-To: References: <9bef17ae-63f5-209f-ca6e-8b366b41c35d@gmail.com> Message-ID: On 08/11/2020 23:32, Mats Wichmann wrote: > If you're running Ubuntu 20.04, and haven't installed the > python-is-python3 package, then by default "python" will be 2.7.? and > pip3 is for python3.? See the possibilities for confusion when using an > old piece of software? From https://askubuntu.com/questions/1230615/ubuntu-20-04-still-supporting-python2 ' "Support" is a somewhat strong word here. As you stated, you performed an upgrade, not a fresh install. Python 2 is not installed by default, and has not been for a long time, as it was moved out of the main archive into universe, after 18.04. There however, are still plenty of packages in universe which depend on python2, and therefore it is still in the universe archive. As you already had the package installed, it would have been upgraded rather than removed. ' -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From leobizy at yahoo.com Mon Nov 9 09:46:34 2020 From: leobizy at yahoo.com (Leonard Ujomu) Date: Mon, 9 Nov 2020 14:46:34 +0000 (UTC) Subject: [Tutor] BEGINNER - HELP!!! References: <1063670621.3671518.1604933194501.ref@mail.yahoo.com> Message-ID: <1063670621.3671518.1604933194501@mail.yahoo.com> Help please,? I just started learning python and I need assistance with the below code:? def?rectangle_area(base,height):????area_a?=?base*height????print("The?area?is?"?+?str(area_a)) ????rectangle_area(5,6) I am getting the error below when I run it :Error on line 7: print("The area is " + str(area_a)) ^TabError: inconsistent use of tabs and spaces in indentation I understand where the error is but I cannot seem to rectify it. Thank you. Kind Regards,?Leonard Ujomu From savageapple850 at gmail.com Mon Nov 9 10:21:10 2020 From: savageapple850 at gmail.com (cool kid) Date: Mon, 9 Nov 2020 15:21:10 +0000 Subject: [Tutor] BEGINNER - HELP!!! In-Reply-To: <1063670621.3671518.1604933194501@mail.yahoo.com> References: <1063670621.3671518.1604933194501@mail.yahoo.com> Message-ID: Hi Leonard, I believe this has something to do with your indentation. Try this: >>> def rectangle_area(base,height): area_a = base*height print("The area is " + str(area_a)) >>> rectangle_area(5,6) Cheers, Cravan ?On 9/11/20, 11:05 PM, "Tutor on behalf of Leonard Ujomu via Tutor" wrote: Help please, I just started learning python and I need assistance with the below code: def rectangle_area(base,height): area_a = base*height print("The area is " + str(area_a)) rectangle_area(5,6) I am getting the error below when I run it :Error on line 7: print("The area is " + str(area_a)) ^TabError: inconsistent use of tabs and spaces in indentation I understand where the error is but I cannot seem to rectify it. Thank you. Kind Regards, Leonard Ujomu _______________________________________________ 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 Nov 9 10:57:32 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 9 Nov 2020 15:57:32 +0000 Subject: [Tutor] BEGINNER - HELP!!! In-Reply-To: <1063670621.3671518.1604933194501@mail.yahoo.com> References: <1063670621.3671518.1604933194501.ref@mail.yahoo.com> <1063670621.3671518.1604933194501@mail.yahoo.com> Message-ID: On 09/11/2020 14:46, Leonard Ujomu via Tutor wrote: > Help please,? > I just started learning python and I need assistance with the below code: > def?rectangle_area(base,height):????area_a?=?base*height????print("The?area?is?"?+?str(area_a)) > ????rectangle_area(5,6) I don't know if the formatting above is an error from the email system, I'm guessing so. (You should set your mail to plain text when posting to programming lists like this one, otherwise the indentation tends to get stripped!) In which case your code should look like: def rectangle_area(base,height): area_a = base*height print("The area is " + str(area_a)) rectangle_area(5,6) > I am getting the error below when I run it : Error on line 7: print("The area is " + str(area_a)) ^Tab Error: inconsistent use of tabs and spaces in indentation Please always include the fiull error message starting with the word Traceback... It includes a lot of useful data if you know how to read it. > I understand where the error is but I cannot seem to rectify it. Then you know more than me! :-) I suspect that one of the indented lines has a tab character whereas the others are all spaces. Or it might be the other way around. Python is very picky about indentation, it requires it to be consistent in its use of either all spaces or all tabs, but not a mixture. Most of us get round this by using a programmers editor which inserts the spaces for us. In the email all your code had spaces, but if you check your original you will likely find a tab lurking in there somewhere. Incidentally you don't need the str() call or addition in this line: print("The area is " + str(area_a)) since print does that for you. You could just write: print("The area is", area_a) -- 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 phillor9 at gmail.com Wed Nov 11 01:30:54 2020 From: phillor9 at gmail.com (Phil) Date: Wed, 11 Nov 2020 16:30:54 +1000 Subject: [Tutor] Filling an array - with a twist Message-ID: Another call on the Brains Trust I'm afraid. I'd like to fill an 8 x 8 array (list of lists) with random numbers such that no column or row repeats the same number more than twice in a sequence. e.g.. [12344562] is OK but [12223456] is not wanted. Something like the following will give me a row or column that meets the requirements but more often than not fails the complete array test. >>> import random >>> r = random.sample(range(0,8),8) >>> r [6, 2, 4, 5, 3, 0, 1, 7] Searching through the array trying to repair an errant sequence is not the answer. Can anyone suggest an algorithm to do what I need? To add to the complication I really need numbers between 0 and 6 which random.sample() won't allow because, as the value error states, the sample is larger than the population. -- Regards, Phil From psimon at sonic.net Wed Nov 11 00:26:09 2020 From: psimon at sonic.net (Paul Simon) Date: Tue, 10 Nov 2020 21:26:09 -0800 Subject: [Tutor] python 3.8 matplot lib issue Message-ID: I have written a python script using matplotlib and have gotten this error: Traceback (most recent call last): File "C:\Users\paulsimon\Desktop\sborn2.py", line 29, in import seaborn as sns File "C:\Users\paulsimon\AppData\Local\Programs\Python\Python38\lib\site-packages\seaborn\__init__.py", line 2, in from .rcmod import * # noqa: F401,F403 File "C:\Users\paulsimon\AppData\Local\Programs\Python\Python38\lib\site-packages\seaborn\rcmod.py", line 5, in import matplotlib as mpl File "C:\Users\paulsimon\AppData\Local\Programs\Python\Python38\lib\site-packages\matplotlib\__init__.py", line 107, in from . import cbook, rcsetup File "C:\Users\paulsimon\AppData\Local\Programs\Python\Python38\lib\site-packages\matplotlib\cbook\__init__.py", line 28, in import numpy as np File "C:\Users\paulsimon\AppData\Local\Programs\Python\Python38\lib\site-packages\numpy\__init__.py", line 305, in _win_os_check() File "C:\Users\paulsimon\AppData\Local\Programs\Python\Python38\lib\site-packages\numpy\__init__.py", line 302, in _win_os_check raise RuntimeError(msg.format(__file__)) from None RuntimeError: The current Numpy installation ('C:\\Users\\paulsimon\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\numpy\\__init__.py') fails to pass a sanity check due to a bug in the windows runtime. See this issue for more information: https://tinyurl.com/y3dm3h86 I would like some help if anyone has had this problem and solved it. Paul Simon From alan.gauld at yahoo.co.uk Wed Nov 11 04:45:19 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 11 Nov 2020 09:45:19 +0000 Subject: [Tutor] Filling an array - with a twist In-Reply-To: References: Message-ID: On 11/11/2020 06:30, Phil wrote: > I'd like to fill an 8 x 8 array (list of lists) with random numbers such > that no column or row repeats the same number more than twice in a sequence. > > e.g.. [12344562] is OK but [12223456] is not wanted. You might need to write it out longhand with a function that tracks the previous 2 results. There was a recent thread discussing ways to do this (One of Manprits I think?) > To add to the complication I really need numbers between 0 and 6 which > random.sample() won't allow because, as the value error states, the > sample is larger than the population. Depending on what you need it for you could try generating smaller lists then concatenating them. So for 8 items generate 2 lists of 4 using sample. In the general case create n=(N/6)+1 lists each of length N/n. Or just slice the final list to length N. But that may not meet your definition of random... Much slower is the manual method: Lst = [] while len(Lst) < N: item = randint(1,6) if item == Lst[-1] and item == Lst[-2]: continue else: Lst.append(item) But that only addresses a single row. Checking that columns don't repeat is a whole extra level of complexity! You need a nested loop and check the current index against the previous two rows at the same position. I'd definitely hide that in a function... def validate(item, row, index, theList) -- 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 Nov 11 04:57:09 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 11 Nov 2020 09:57:09 +0000 Subject: [Tutor] python 3.8 matplot lib issue In-Reply-To: References: Message-ID: On 11/11/2020 05:26, Paul Simon wrote: > I have written a python script using matplotlib and have gotten this error: > "C:\Users\paulsimon\AppData\Local\Programs\Python\Python38\lib\site-packages\numpy\__init__.py", > line 305, in > _win_os_check() > RuntimeError: The current Numpy installation > ('C:\\Users\\paulsimon\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\numpy\\__init__.py') > fails to pass a sanity check due to a bug in the windows runtime. See > this issue for more information: https://tinyurl.com/y3dm3h86 > > I would like some help if anyone has had this problem and solved it. Did you read the thread at the given URL? The fix is in Windows and expected around March 2021. In the meantime a new version of numpy provides a workaround but has issues of its own (specifically it won't work on Linux!) Did you try the suggested workarounds? Do you still have issues? -- 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 phillor9 at gmail.com Wed Nov 11 05:10:11 2020 From: phillor9 at gmail.com (Phil) Date: Wed, 11 Nov 2020 20:10:11 +1000 Subject: [Tutor] Filling an array - with a twist In-Reply-To: References: Message-ID: On 11/11/20 7:45 pm, Alan Gauld via Tutor wrote: > Checking that columns don't repeat is a whole extra level > of complexity! You need a nested loop and check the current > index against the previous two rows at the same position. > I'd definitely hide that in a function... > > def validate(item, row, index, theList) Thank you Alan for your suggestions. I'll continue to muddle on, however, I was hoping that this problem might be common and have a clever solution. So far, I search each row for and error and correct it with a random number. Of course this can create another error in the same row or a new error in a column. Testing and correcting? could continue for a long time. -- Regards, Phil From alan.gauld at yahoo.co.uk Wed Nov 11 06:51:27 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 11 Nov 2020 11:51:27 +0000 Subject: [Tutor] Filling an array - with a twist In-Reply-To: References: Message-ID: On 11/11/2020 10:10, Phil wrote: >> def validate(item, row, index, theList) > > Thank you Alan for your suggestions. I'll continue to muddle on, > however, I was hoping that this problem might be common and have a > clever solution. The problem is that it is not a general problem. There are too many possible rules for what constitutes "valid". You could write a general function to construct an MxN array that takes a validator as an argument. But you still need to write the validator function yourself. It is possible that numpy has some such array builder function, I don't ever use numpy so don't know. > So far, I search each row for and error and correct it with a random > number. Of course this can create another error in the same row or a new > error in a column. Testing and correcting? could continue for a long time. Searching and correcting is going to be much slower than checking each item is valid before inserting. You have to iterate over the entire array twice for a start: once to create it and once to check it. Much better to test each item for validity before inserting and then, if not valid, generate a new one. -- 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 Richard at Damon-Family.org Wed Nov 11 08:15:57 2020 From: Richard at Damon-Family.org (Richard Damon) Date: Wed, 11 Nov 2020 08:15:57 -0500 Subject: [Tutor] Filling an array - with a twist In-Reply-To: References: Message-ID: <50c7d89f-72db-2b4f-ade6-4f371afea093@Damon-Family.org> On 11/11/20 1:30 AM, Phil wrote: > Another call on the Brains Trust I'm afraid. > > I'd like to fill an 8 x 8 array (list of lists) with random numbers > such that no column or row repeats the same number more than twice in > a sequence. > > e.g.. [12344562] is OK but [12223456] is not wanted. > > Something like the following will give me a row or column that meets > the requirements but more often than not fails the complete array test. > > >>> import random > >>> r = random.sample(range(0,8),8) > >>> r > [6, 2, 4, 5, 3, 0, 1, 7] > > Searching through the array trying to repair an errant sequence is not > the answer. Can anyone suggest an algorithm to do what I need? > > To add to the complication I really need numbers between 0 and 6 which > random.sample() won't allow because, as the value error states, the > sample is larger than the population. > This doesn't sound like a 'common' problem so likely nothing build in will fully deal with it. My thought on the simple (but maybe not shortest) way to fill in like that is iterate through you locations, fill in with a random value, and then check if it is the third of that value in the row or column, and if so, repeat again. For your modification with 7 values and an 8x8 grid, there is one possible issue with the last point that there may be only one possibility, if the column has 3 repeated values and the row and 3 different repeated values. If you find the fail and need to draw again gets repeated values and loops on trying the same number too much (I don't think it will), you could change to make a random draw from a list, which you start with all the values, and when you find a bad value (by trying it) you remove it from the list of possibilities, so you can't get that one for this location again. That will say that the above degenerate case is guaranteed to find the open value in no more than 7 trials, instead of an expected value of 7 trials, but might go with 'bad luck' much longer. It will slow down the normal case by creating the list each time, so probably hurts the average case to help the worse case. -- Richard Damon From mats at wichmann.us Wed Nov 11 11:21:05 2020 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 11 Nov 2020 09:21:05 -0700 Subject: [Tutor] Filling an array - with a twist In-Reply-To: References: Message-ID: On 11/10/20 11:30 PM, Phil wrote: > Another call on the Brains Trust I'm afraid. > > I'd like to fill an 8 x 8 array (list of lists) with random numbers such > that no column or row repeats the same number more than twice in a > sequence. > > e.g.. [12344562] is OK but [12223456] is not wanted. > > Something like the following will give me a row or column that meets the > requirements but more often than not fails the complete array test. > > >>> import random > >>> r = random.sample(range(0,8),8) > >>> r > [6, 2, 4, 5, 3, 0, 1, 7] > > Searching through the array trying to repair an errant sequence is not > the answer. Can anyone suggest an algorithm to do what I need? > > To add to the complication I really need numbers between 0 and 6 which > random.sample() won't allow because, as the value error states, the > sample is larger than the population. > since it's a small array, it should be find to do nested loops where you count what's been seen, and generate a fresh random integer if one doesn't fit the constraint (namely: already seen twice). a collections.defaultdict makes a decent counter - it's a dictionary which doesn't fail if the key hasn't been seen yet, so you can do something like "if counter[i] < 2". You'll need one per "column", plus one for the current "row" to do the complete job. Might not do it this way if you're after a 100k x 100k array, but it's small, and sounds like it's probably a one-off. From PyTutor at DancesWithMice.info Wed Nov 11 13:47:05 2020 From: PyTutor at DancesWithMice.info (dn) Date: Thu, 12 Nov 2020 07:47:05 +1300 Subject: [Tutor] Filling an array - with a twist In-Reply-To: References: Message-ID: <9c909dcb-d9ff-544b-9c98-8eeb7236ec37@DancesWithMice.info> On 11/11/2020 19:30, Phil wrote: > Another call on the Brains Trust I'm afraid. > > I'd like to fill an 8 x 8 array (list of lists) with random numbers such > that no column or row repeats the same number more than twice in a > sequence. > > e.g.. [12344562] is OK but [12223456] is not wanted. > > Something like the following will give me a row or column that meets the > requirements but more often than not fails the complete array test. > > >>> import random > >>> r = random.sample(range(0,8),8) > >>> r > [6, 2, 4, 5, 3, 0, 1, 7] > > Searching through the array trying to repair an errant sequence is not > the answer. Can anyone suggest an algorithm to do what I need? > > To add to the complication I really need numbers between 0 and 6 which > random.sample() won't allow because, as the value error states, the > sample is larger than the population. "Stepwise Decomposition" involves taking a hard-to-solve 'large' problem and splitting it into smaller easier-to-solve problems - repeatedly - until the smallest problems can be solved. In this case, rather than thinking only of an 8x8 matrix, ie the result; let's consider that each element (each 'cell' if you prefer) participates in two sub-problems: 1 does it obey 'the rules' for its row? 2 does it obey 'the rules' for its column? So, now we have three data-structures: 1 the result - what we want 2 something which handles the row-rule 3 something which handles the column-rule For the purposes of illustration, let me change the rules (simplify the 'larger problem') by saying "*no repetition* in a single row or column" - call it "dn's Sudoku rule":- The issue of repetition is most easily addressed in Python by realising that whilst a list (and thus a list of lists) may contain repeated values, a set may not. Thus, create a list of eight (empty) sets representing (the values appearing in) each of the columns, and similar for the eight 'rows'. Now to the process: each time the next element's value is computed from random(), before placing it in the 8x8 structure, check to see if it is already in one/both of the two applicable sets (by row and by column). If it is, then it would be a repetition (so 'reject'/ignore that computed-value. If not, store the value in the applicable sets, and in the list-of-lists. Once you've understood that, and are coming back to me with the word "but...", let's get back to the real spec[ification]. We can't use a set to solve the 'one repetition allowed' rule, because sets refuse any repetition within their "members". There are a couple of ways to achieve 'counts' in Python, but let's stick with built-in data structures, and thus the pattern described (above). Change the eight column- and row-monitoring sets to dictionaries. Please recall that each dictionary (dict) element consists of a key and a value ("key-value pairs"). In this approach, when the next random-value is generated, check the two applicable dicts in-turn: does this value exist as a key (if value in dictionary!). At first it will not, so add a dictionary entry with the random-value as key and a 'count' of one as its value. If both dicts 'pass' the random-value, load it into the list-of-lists. As the 8x8 fills, if a later random-value is generated which matches an existing row-dict (or column-dict) key (ie is "in" the dict), then the dict's value ("counter") must be checked. If it is one, increment to two*, and load the list-of-lists. * ie this value currently appears in the applicable row (or column) twice - which, by definition, means that it may not appear again! Thus, considering the above checks again, if the dict's value is two, reject the random-value because it breaks 'the rules'. Rinse-and-repeat. For extra credit: if you liked playing with sets, then instead of using a dict to manage 'counters' you could have two 'banks' of eight column-sets and the same for the rows. The first bank, used as above, will reveal if the number has/not been generated previously for this row/column. The second bank could be used to indicate if the value appears in the row a second time. Thus when the same value is generated for the third time, ie appears in the applicable row/column set in both 'banks', it should be rejected. I have a feeling/hunch, that multiple sets might be faster than using a dict-counter. Please note: This spec is talking about 8x8 values, and thus the creation of an addition 16 dicts (or 32 sets). In today's world that does not seem 'expensive' (demanding on storage). However, multiply that up to thousands/millions of values and then trading storage for CPU-time may become an issue! -- Regards =dn From PyTutor at DancesWithMice.info Wed Nov 11 14:06:40 2020 From: PyTutor at DancesWithMice.info (dn) Date: Thu, 12 Nov 2020 08:06:40 +1300 Subject: [Tutor] Filling an array - with a twist In-Reply-To: References: Message-ID: <41aa739e-dc1e-2f95-3e52-735e9235cf38@DancesWithMice.info> Reading @wlfraed's response, I at-first wondered if it would lead to yet another approach to the problem of checking for limited-repetition:- On 12/11/2020 07:06, Dennis Lee Bieber wrote: > On Wed, 11 Nov 2020 16:30:54 +1000, Phil declaimed the > following: ... > If any digit is only allowed twice (meaning 12344564 is rejected), then > provide as input a sequence that gives each digit twice! ... >>>> pool > [0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6] The point being that this is a "population" (an important definition in the study of Statistics), ie all of the values which may be chosen for a particular row/column - we can't add an 8, nor can we add another 0, because they are not within the specification. Combine this with the set.remove(x) method which will "remove the first item from s where s[i] is equal to x". Thus: - generate a "pool" for every row and every column in the 8x8 'result' - generate a new random() value - remove it* from the applicable row and column pools - add the value to the 8x8 * if either remove() fails (exception = ValueError), two examples of that number already exist in the applicable row/column ... This is a "subtractive" approach to checking. Whereas previously we took an "additive" approach to deciding if the repetition rule(s) are about to be broken. -- Regards =dn From mats at wichmann.us Wed Nov 11 15:08:30 2020 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 11 Nov 2020 13:08:30 -0700 Subject: [Tutor] Filling an array - with a twist In-Reply-To: <41aa739e-dc1e-2f95-3e52-735e9235cf38@DancesWithMice.info> References: <41aa739e-dc1e-2f95-3e52-735e9235cf38@DancesWithMice.info> Message-ID: <5fdfd43a-c137-7a3b-d9c7-1f62e491b038@wichmann.us> On 11/11/20 12:06 PM, dn via Tutor wrote: > Thus: > - generate a "pool" for every row and every column in the 8x8 'result' > - generate a new random() value > - remove it* from the applicable row and column pools > - add the value to the 8x8 > * if either remove() fails (exception = ValueError), two examples of > that number already exist in the applicable row/column > ... > > > This is a "subtractive" approach to checking. Whereas previously we took > an "additive" approach to deciding if the repetition rule(s) are about > to be broken. This is nice idea that I was also going to pursue, but a complication emerged that I didn't want to deal with. You can generate a population pool quite simply, even if inelegantly: >>> p = list(range(7)) * 2 >>> print(p) [0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6] Now we want to pick a number from that population, which could be easy: >>> print(random.choice(p)) 3 The complication is we actually want to pick a number that appears in two populations simultaneously - again, this would be trivial if we could use sets, where we could perform the choice on the intersection of the two, but the lack of uniqueness means other approaches are needed. After thinking again, you should be able to do that with a simple-ish function that's passed the two relevant populations. I'm not as fond of doing the removes as the check, because you have to fixitup - if it removed cleanly from row-population, and takes an exception from column-population, then you have to put it back into row-population and start the picking process again... I'd rather pick from one and check if the other population disqualifies that choice, something like this: def select(row_pop, column_pop): """choose a value in both populations and remove it from both""" while True: x = random.choice(row_pop) if x not in column_pop: continue row_pop.remove(x) column_pop.remove(x) return x Note that for some instances of this problem, you can run into deadlocks where there is no value that satisfies both row and column constraints, and you would have to backtrack to fix the whole thing up (perhaps throw away and start again). I believe, without stopping to think deeply that the stated problem space does not fall into that. From PyTutor at DancesWithMice.info Wed Nov 11 16:03:10 2020 From: PyTutor at DancesWithMice.info (dn) Date: Thu, 12 Nov 2020 10:03:10 +1300 Subject: [Tutor] Filling an array - with a twist In-Reply-To: <5fdfd43a-c137-7a3b-d9c7-1f62e491b038@wichmann.us> References: <41aa739e-dc1e-2f95-3e52-735e9235cf38@DancesWithMice.info> <5fdfd43a-c137-7a3b-d9c7-1f62e491b038@wichmann.us> Message-ID: <22d55eb6-de78-a03d-963b-7cd6306ab5ce@DancesWithMice.info> On 12/11/2020 09:08, Mats Wichmann wrote: > On 11/11/20 12:06 PM, dn via Tutor wrote: > >> Thus: >> - generate a "pool" for every row and every column in the 8x8 'result' >> - generate a new random() value >> - remove it* from the applicable row and column pools >> - add the value to the 8x8 >> * if either remove() fails (exception = ValueError), two examples of >> that number already exist in the applicable row/column >> ... >> >> This is a "subtractive" approach to checking. Whereas previously we >> took an "additive" approach to deciding if the repetition rule(s) are >> about to be broken. > This is nice idea that I was also going to pursue, but a complication > emerged that I didn't want to deal with. > > You can generate a population pool quite simply, even if inelegantly: > > >>> p = list(range(7)) * 2 > >>> print(p) > [0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6] > > Now we want to pick a number from that population, which could be easy: Apologies, whilst the original use of the "pool" idea went this way, I didn't/wouldn't. Accordingly, (and in my mind, but not in the response!) I would stick with using random() multiplied-up to cover the integral range 0~6 and using the pools only to ensure the rules/spec is fulfilled. Maybe I'm channelling my inner-Monty Hall (or maybe it's the quantity of pollen and/or smelly dog expanding my sinuses) but I immediately started to worry about the stochastic nature of a reducing-population (before quickly giving-up - thinking about anything). Feel free to set me straight... * not mine, a colleague brought along with him - others have brought kid(s), some a preferred food. Me? All I need is my security-blanket (https://peanuts.fandom.com/wiki/Linus%27_security_blanket) > >>> print(random.choice(p)) > 3 > > The complication is we actually want to pick a number that appears in > two populations simultaneously - again, this would be trivial if we > could use sets, where we could perform the choice on the intersection of > the two, but the lack of uniqueness means other approaches are needed. > > After thinking again, you should be able to do that with a simple-ish > function that's passed the two relevant populations.? I'm not as fond of > doing the removes as the check, because you have to fixitup - if it > removed cleanly from row-population, and takes an exception from > column-population, then you have to put it back into row-population and > start the picking process again... I'd rather pick from one and check if > the other population disqualifies that choice, something like this: > > > def select(row_pop, column_pop): > ??? """choose a value in both populations and remove it from both""" > ??? while True: > ??????? x = random.choice(row_pop) > ??????? if x not in column_pop: > ??????????? continue > ??????? row_pop.remove(x) > ??????? column_pop.remove(x) > ??????? return x Well done! PS "pop" is "population" not collection.pop() I didn't offer code, because I'm not sure if that would be doing the OP's homework for him. Also, didn't worry about this (need for "locking a transaction") because (a) it 'spoils' the smooth description of the algorithm, and (b) leaving some process-of-discovery for the coder. (hey, it's a good line, and I'm going to stick with it!) Certainly, this is the issue with all multi-criteria "subtractive" solutions. Is it made more (or less) complex by using the pools as part of the random() selection step? The "in" check is an elegant solution, but by the time we add that check, have we saved anything over the additive approach? (performance-wise, even code-complexity-wise) > Note that for some instances of this problem, you can run into deadlocks > where there is no value that satisfies both row and column constraints, > and you would have to backtrack to fix the whole thing up (perhaps throw > away and start again).? I believe, without stopping to think deeply that > the stated problem space does not fall into that. Are you sure? (forgive my sinuses-where-brain-used-to-be) The population-range (=14) is so much larger than the sample(s) (=8). -- Regards =dn From psimon at sonic.net Wed Nov 11 14:34:15 2020 From: psimon at sonic.net (Paul Simon) Date: Wed, 11 Nov 2020 11:34:15 -0800 Subject: [Tutor] python 3.8 matplot lib issue In-Reply-To: References: Message-ID: On 11/11/2020 9:45 AM, Dennis Lee Bieber wrote: > On Tue, 10 Nov 2020 21:26:09 -0800, Paul Simon declaimed > the following: > >> >> I would like some help if anyone has had this problem and solved it. >> > > As that discussion mentions, the problem is a change in the Windows 10 > C-runtime library. A fix will have to await M$ releasing an update. > > If it means anything -- I think* numpy was working for me last week, > and fails now... M$ pushed updates to my machine last night... (Had to > reboot since it corrupted my graphics card -- the screen saver went to > top-left quarter of screen, and Firefox came up in full-screen but not > maximized) > > > * or was it just matplotlib that I was testing > > Thank you both for the suggestions. Yes, I did look at that web page but was wary of making the change to an earlier version of numpy. I'm just a novice programmer not quite up to journeyman. I was looking for people who were currently using it and what they were doing. I have another computer (or two) with linux installed and runs well with current numpy. I'll make the change on windows and if there is a problem will wait until January to work on windows. Thanks again Paul Simon From leobizy at yahoo.com Wed Nov 11 17:46:51 2020 From: leobizy at yahoo.com (Leonard Ujomu) Date: Wed, 11 Nov 2020 22:46:51 +0000 (UTC) Subject: [Tutor] ASSIST A BEGINNER PLEASSE References: <1495202663.4668074.1605134811875.ref@mail.yahoo.com> Message-ID: <1495202663.4668074.1605134811875@mail.yahoo.com> If a filesystem has a block size of 4096 bytes, this means that a file comprised of only one byte will still use 4096 bytes of storage. A file made up of 4097 bytes will use 4096*2=8192 bytes of storage. Knowing this, can you fill in the gaps in the calculate_storage function below, which calculates the total number of bytes needed to store a file of a given size def?calculate_storage(filesize):????block_size?=?4096????#?Use?floor?division?to?calculate?how?many?blocks?are?fully?occupied????full_blocks?=?8192????#?Use?the?modulo?operator?to?check?whether?there's?any?remainder????partial_block_remainder?=?4097?%?2????#?Depending?on?whether?there's?a?remainder?or?not,?return????#?the?total?number?of?bytes?required?to?allocate?enough?blocks????#?to?store?your?data.????if?partial_block_remainder?>?0:????????return?block_size????return?full_blocks print(calculate_storage(1))????#?Should?be?4096print(calculate_storage(4096))?#?Should?be?4096print(calculate_storage(4097))?#?Should?be?8192print(calculate_storage(6000))?#?Should?be?8192 After running, i get the following result 4096409640964096 Where is my error please????Thank you From PyTutor at DancesWithMice.info Wed Nov 11 18:07:08 2020 From: PyTutor at DancesWithMice.info (dn) Date: Thu, 12 Nov 2020 12:07:08 +1300 Subject: [Tutor] ASSIST A BEGINNER PLEASSE In-Reply-To: <1495202663.4668074.1605134811875@mail.yahoo.com> References: <1495202663.4668074.1605134811875.ref@mail.yahoo.com> <1495202663.4668074.1605134811875@mail.yahoo.com> Message-ID: On 12/11/2020 11:46, Leonard Ujomu via Tutor wrote: > > If a filesystem has a block size of 4096 bytes, this means that a file comprised of only one byte will still use ... The code-listing has been corrupted. Please copy-paste directly from the text-editor/IDE. -- Regards =dn From alan.gauld at yahoo.co.uk Wed Nov 11 19:11:55 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 12 Nov 2020 00:11:55 +0000 Subject: [Tutor] ASSIST A BEGINNER PLEASSE In-Reply-To: <1495202663.4668074.1605134811875@mail.yahoo.com> References: <1495202663.4668074.1605134811875.ref@mail.yahoo.com> <1495202663.4668074.1605134811875@mail.yahoo.com> Message-ID: On 11/11/2020 22:46, Leonard Ujomu via Tutor wrote: def?calculate_storage(filesize):????block_size?=?4096????#?Use?floor?division?to?calculate?how?many?blocks?are?fully?occupied????full_blocks?=?8192????#?Use?the?modulo?operator?to?check?whether?there's?any?remainder????partial_block_remainder?=?4097?%?2????#?Depending?on?whether?there's?a?remainder?or?not,?return????#?the?total?number?of?bytes?required?to?allocate?enough?blocks????#?to?store?your?data.????if?partial_block_remainder?>?0:????????return?block_size????return?full_blocks > print(calculate_storage(1))????#?Should?be?4096print(calculate_storage(4096))?#?Should?be?4096print(calculate_storage(4097))?#?Should?be?8192print(calculate_storage(6000))?#?Should?be?8192 You need to post in plain text otherwise the mail system messes up the indentation, as you can see... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From phillor9 at gmail.com Wed Nov 11 20:22:29 2020 From: phillor9 at gmail.com (Phil) Date: Thu, 12 Nov 2020 11:22:29 +1000 Subject: [Tutor] Filling an array - with a twist In-Reply-To: <22d55eb6-de78-a03d-963b-7cd6306ab5ce@DancesWithMice.info> References: <41aa739e-dc1e-2f95-3e52-735e9235cf38@DancesWithMice.info> <5fdfd43a-c137-7a3b-d9c7-1f62e491b038@wichmann.us> <22d55eb6-de78-a03d-963b-7cd6306ab5ce@DancesWithMice.info> Message-ID: <2739c0f3-1e60-0de1-b600-8cddd27e1fc3@gmail.com> Thank you everyone for your responses and there's a lot to digest. Sets were mentioned and that's how I managed to write a Sudoku solver. However, in this case duplicates are allowed but not duplicates of more than 2, one after the other. I'd used the word sequence previously and it may have caused some confusion. >> After thinking again, you should be able to do that with a simple-ish >> function that's passed the two relevant populations.? I'm not as fond >> of doing the removes as the check, because you have to fixitup - if >> it removed cleanly from row-population, and takes an exception from >> column-population, then you have to put it back into row-population >> and start the picking process again... I'd rather pick from one and >> check if the other population disqualifies that choice, something >> like this: >> >> >> def select(row_pop, column_pop): >> ???? """choose a value in both populations and remove it from both""" >> ???? while True: >> ???????? x = random.choice(row_pop) >> ???????? if x not in column_pop: >> ???????????? continue >> ???????? row_pop.remove(x) >> ???????? column_pop.remove(x) >> ???????? return x This looks like a good place to start, I'll give it some thought and experiment further. > > Well done! > PS "pop" is "population" not collection.pop() > > I didn't offer code, because I'm not sure if that would be doing the > OP's homework for him. Also, didn't worry about this (need for > "locking a transaction") because (a) it 'spoils' the smooth > description of the algorithm, and (b) leaving some > process-of-discovery for the coder. My homework days are but a distant memory from the previous century. I'm grateful for all offerings. -- Regards, Phil From alexkleider at protonmail.com Wed Nov 11 21:45:20 2020 From: alexkleider at protonmail.com (alexkleider) Date: Thu, 12 Nov 2020 02:45:20 +0000 Subject: [Tutor] ASSIST A BEGINNER PLEASSE In-Reply-To: <1495202663.4668074.1605134811875@mail.yahoo.com> References: <1495202663.4668074.1605134811875.ref@mail.yahoo.com> <1495202663.4668074.1605134811875@mail.yahoo.com> Message-ID: ??????? Original Message ??????? On Wednesday, November 11, 2020 2:46 PM, Leonard Ujomu via Tutor wrote: > If a filesystem has a block size of 4096 bytes, this means that a file comprised of only one byte will still use 4096 bytes of storage. A file made up of 4097 bytes will use 4096*2=8192 bytes of storage. Knowing this, can you fill in the gaps in the calculate_storage function below, which calculates the total number of bytes needed to store a file of a given size > def?calculate_storage(filesize):????block_size?=?4096????#?Use?floor?division?to?calculate?how?many?blocks?are?fully?occupied????full_blocks?=?8192????#?Use?the?modulo?operator?to?check?whether?there's?any?remainder????partial_block_remainder?=?4097?%?2????#?Depending?on?whether?there's?a?remainder?or?not,?return????#?the?total?number?of?bytes?required?to?allocate?enough?blocks????#?to?store?your?data.????if?partial_block_remainder?>?0:????????return?block_size????return?full_blocks > print(calculate_storage(1))????#?Should?be?4096print(calculate_storage(4096))?#?Should?be?4096print(calculate_storage(4097))?#?Should?be?8192print(calculate_storage(6000))?#?Should?be?8192 > > After running, i get the following result > 4096409640964096 > > Where is my error please????Thank you > > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor What follows is a direct copy of a file I used to try first to figure out the logic of your code and then, after failing that, suggest a simpler solution. Hope it helps. Remember: use plain text!!! #!/usr/bin/env python3 # File: 2try.py ''' If a filesystem has a block size of 4096 bytes, this means that a file comprised of only one byte will still use 4096 bytes of storage. A file made up of 4097 bytes will use 4096*2=8192 bytes of storage. Knowing this, can you fill in the gaps in the calculate_storage function below, which calculates the total number of bytes needed to store a file of a given size def calculate_storage(filesize): """ I've tried to adjust the indentation but can't follow the logic of your code. """ block_size = 4096 # Use floor division to calculate how many blocks are fully occupied full_blocks = 8192 # Use the modulo operator to check whether there's any remainder partial_block_remainder = 4097 % 2 # Depending on whether there's a remainder or not, return # the total number of bytes required to allocate enough blocks # to store your data. if partial_block_remainder > 0: return block_size return full_blocks print(calculate_storage(1)) # Should be 4096 print(calculate_storage(4096)) # Should be 4096 print(calculate_storage(4097)) ''' def calculate_storage(filesize, block_size=4096): """ The following code is much simpler and seems to provide what you want. Notice has been made a named parameter which will give you flexibility in case you ever need to apply this function to a file system that has a differing block size. As an editorial aside, it would seem to me that a calculate_blocks_required would be a more useful function. (Simply delete the " * block_size" at the end. """ blocks_required, extra = divmod(filesize, block_size) if extra: blocks_required += 1 return blocks_required * block_size print(calculate_storage(1)) # Should be 4096 print(calculate_storage(4096)) # Should be 4096 print(calculate_storage(4097)) # Should be 8192 print(calculate_storage(6000)) # Should be 8192 What_you_got = """ After running, i get the following result 4096 4096 4096 4096 Where is my error please??? Thank you """ what_I_got = """ alex at X1v2:~$ python3 2try.py 4096 4096 8192 1,1 Top From robertvstepp at gmail.com Wed Nov 11 22:53:54 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Wed, 11 Nov 2020 21:53:54 -0600 Subject: [Tutor] Filling an array - with a twist In-Reply-To: References: Message-ID: <20201112035354.GU9135@Dream-Machine1> On Wed, Nov 11, 2020 at 04:30:54PM +1000, Phil wrote: >Another call on the Brains Trust I'm afraid. > >I'd like to fill an 8 x 8 array (list of lists) with random numbers >such that no column or row repeats the same number more than twice in >a sequence. > >e.g.. [12344562] is OK but [12223456] is not wanted. > >Something like the following will give me a row or column that meets >the requirements but more often than not fails the complete array >test. > >>>> import random >>>> r = random.sample(range(0,8),8) >>>> r >[6, 2, 4, 5, 3, 0, 1, 7] > >Searching through the array trying to repair an errant sequence is not >the answer. Can anyone suggest an algorithm to do what I need? > >To add to the complication I really need numbers between 0 and 6 which >random.sample() won't allow because, as the value error states, the >sample is larger than the population. I found this problem interesting this evening, so I thought I would throw out my effort at a solution: ======================================================================================= from pprint import pprint from random import randint NUM_ROWS = 8 NUM_COLS = 8 MIN_INTEGER = 0 MAX_INTEGER = 6 MAX_REPETITIONS = 2 row_ck = [None, None] col_ck = [None, None] L = [] for i in range(NUM_ROWS): L.append([]) for j in range(NUM_COLS): if i > 1: col_ck[0] = L[i - 2][j] if i > 0: col_ck[1] = L[i - 1][j] while True: test_value = randint(MIN_INTEGER, MAX_INTEGER) if ( row_ck.count(test_value) != MAX_REPETITIONS and col_ck.count(test_value) != MAX_REPETITIONS ): row_ck[0] = row_ck[1] row_ck[1] = test_value L[i].append(test_value) break pprint(L) ======================================================================================= A few rounds of output: bob at Dream-Machine1:~/Projects/Tutor_Help$ python3 mk_2d_array.py [[6, 4, 2, 1, 5, 5, 6, 5], [3, 3, 1, 3, 5, 5, 6, 5], [3, 3, 5, 3, 0, 1, 5, 1], [4, 5, 4, 1, 3, 4, 6, 6], [1, 3, 1, 4, 1, 6, 4, 5], [3, 0, 5, 0, 3, 5, 1, 0], [5, 0, 5, 5, 1, 0, 5, 4], [2, 5, 1, 3, 1, 2, 2, 1]] bob at Dream-Machine1:~/Projects/Tutor_Help$ python3 mk_2d_array.py [[3, 1, 6, 4, 4, 5, 1, 3], [5, 2, 3, 4, 0, 3, 3, 1], [4, 0, 4, 0, 5, 3, 5, 1], [0, 3, 6, 5, 5, 1, 1, 5], [0, 2, 3, 2, 2, 6, 6, 4], [1, 2, 0, 5, 6, 0, 5, 1], [3, 5, 2, 5, 3, 3, 4, 5], [5, 1, 2, 4, 0, 1, 2, 2]] bob at Dream-Machine1:~/Projects/Tutor_Help$ python3 mk_2d_array.py [[2, 1, 2, 5, 3, 0, 5, 6], [1, 6, 3, 0, 0, 4, 4, 6], [0, 6, 4, 4, 5, 2, 3, 1], [3, 1, 1, 3, 0, 4, 3, 0], [5, 4, 3, 0, 3, 3, 1, 5], [4, 1, 0, 6, 1, 1, 4, 5], [2, 3, 6, 1, 3, 0, 3, 0], [4, 1, 6, 0, 1, 6, 6, 1]] I tried this with up to 30 rows by 30 columns and I did not notice any perceptible lag on my PC. The third nested loop -- while loop -- most of the time should not run through more than one iteration. I am curious as to your thoughts. -- Wishing you only the best, boB Stepp From phillor9 at gmail.com Thu Nov 12 20:57:14 2020 From: phillor9 at gmail.com (Phil) Date: Fri, 13 Nov 2020 11:57:14 +1000 Subject: [Tutor] Filling an array - with a twist In-Reply-To: <20201112035354.GU9135@Dream-Machine1> References: <20201112035354.GU9135@Dream-Machine1> Message-ID: On 12/11/20 1:53 pm, boB Stepp wrote: > I found this problem interesting this evening, so I thought I would throw > out my effort at a solution: > Thank you Bob, your solution works perfectly. We're full-time travellers and have been out of Internet range for a few days and so I couldn't answer soon. -- Regards, Phil From assaf197254 at yahoo.co.il Sun Nov 15 12:52:00 2020 From: assaf197254 at yahoo.co.il (=?UTF-8?B?15DXodejINeR16DXmdee15nXoNeZ?=) Date: Sun, 15 Nov 2020 17:52:00 +0000 (UTC) Subject: [Tutor] technical problem. References: <73840182.3335733.1605462720775.ref@mail.yahoo.com> Message-ID: <73840182.3335733.1605462720775@mail.yahoo.com> I try to download the python.org system-but website system don't let me do it. Is there any solution for it? assaf benyamini.*1)my email addresses: 029547403 at walla.co.il or: asb783a at gmail.com or: assaf197254 at yahoo.co.il or: ass.benyamini at yandex.com or: a32assaf at outlook.com or: assaf002 at mail2world.com2)my phone numbers: at home-972-2-6427757. cellular-972-52-4575172.3)Here is the error announcement I get when trying to download python.org : Service Pack 0), path: C:\Users\user\AppData\Local\Temp\{76912DBC-23F9-4F9D-94BD-0B08EE164A5B}\.cr\python-3.9.0-amd64.exe[0744:17F0][2020-11-15T19:17:46]i000: Initializing string variable 'ActionLikeInstalling' to value 'Installing'[0744:17F0][2020-11-15T19:17:46]i000: Initializing string variable 'ActionLikeInstallation' to value 'Setup'[0744:17F0][2020-11-15T19:17:46]i000: Initializing string variable 'ShortVersion' to value '3.9'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'ShortVersionNoDot' to value '39'[0744:17F0][2020-11-15T19:17:46]i000: Initializing string variable 'WinVer' to value '3.9'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'WinVerNoDot' to value '39'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'InstallAllUsers' to value '0'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'InstallLauncherAllUsers' to value '1'[0744:17F0][2020-11-15T19:17:46]i000: Initializing string variable 'TargetDir' to value ''[0744:17F0][2020-11-15T19:17:46]i000: Initializing string variable 'DefaultAllUsersTargetDir' to value '[ProgramFiles64Folder]Python[WinVerNoDot]'[0744:17F0][2020-11-15T19:17:46]i000: Initializing string variable 'TargetPlatform' to value 'x64'[0744:17F0][2020-11-15T19:17:46]i000: Initializing string variable 'DefaultJustForMeTargetDir' to value '[LocalAppDataFolder]Programs\Python\Python[WinVerNoDot]'[0744:17F0][2020-11-15T19:17:46]i000: Initializing string variable 'OptionalFeaturesRegistryKey' to value 'Software\Python\PythonCore\[WinVer]\InstalledFeatures'[0744:17F0][2020-11-15T19:17:46]i000: Initializing string variable 'TargetDirRegistryKey' to value 'Software\Python\PythonCore\[WinVer]\InstallPath'[0744:17F0][2020-11-15T19:17:46]i000: Initializing string variable 'DefaultCustomTargetDir' to value ''[0744:17F0][2020-11-15T19:17:46]i000: Initializing string variable 'InstallAllUsersState' to value 'enabled'[0744:17F0][2020-11-15T19:17:46]i000: Initializing string variable 'InstallLauncherAllUsersState' to value 'enabled'[0744:17F0][2020-11-15T19:17:46]i000: Initializing string variable 'CustomInstallLauncherAllUsersState' to value '[InstallLauncherAllUsersState]'[0744:17F0][2020-11-15T19:17:46]i000: Initializing string variable 'TargetDirState' to value 'enabled'[0744:17F0][2020-11-15T19:17:46]i000: Initializing string variable 'CustomBrowseButtonState' to value 'enabled'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'Include_core' to value '1'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'Include_exe' to value '1'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'Include_dev' to value '1'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'Include_lib' to value '1'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'Include_test' to value '1'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'Include_doc' to value '1'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'Include_tools' to value '1'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'Include_tcltk' to value '1'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'Include_pip' to value '1'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'Include_launcher' to value '-1'[0744:17F0][2020-11-15T19:17:46]i000: Initializing string variable 'Include_launcherState' to value 'enabled'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'Include_symbols' to value '0'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'Include_debug' to value '0'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'LauncherOnly' to value '0'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'DetectedLauncher' to value '0'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'DetectedOldLauncher' to value '0'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'AssociateFiles' to value '1'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'Shortcuts' to value '1'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'PrependPath' to value '0'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'CompileAll' to value '0'[0744:17F0][2020-11-15T19:17:46]i000: Initializing numeric variable 'SimpleInstall' to value '0'[0744:17F0][2020-11-15T19:17:46]i000: Initializing string variable 'SimpleInstallDescription' to value ''[0744:17F0][2020-11-15T19:17:46]i009: Command Line: '-burn.clean.room=C:\Users\user\Downloads\python-3.9.0-amd64.exe -burn.filehandle.attached=620 -burn.filehandle.self=616'[0744:17F0][2020-11-15T19:17:46]i000: Setting string variable 'WixBundleOriginalSource' to value 'C:\Users\user\Downloads\python-3.9.0-amd64.exe'[0744:17F0][2020-11-15T19:17:46]i000: Setting string variable 'WixBundleOriginalSourceFolder' to value 'C:\Users\user\Downloads\'[0744:17F0][2020-11-15T19:17:47]i000: Setting string variable 'WixBundleLog' to value 'C:\Users\user\AppData\Local\Temp\Python 3.9.0 (64-bit)_20201115191747.log'[0744:17F0][2020-11-15T19:17:47]i000: Setting string variable 'WixBundleName' to value 'Python 3.9.0 (64-bit)'[0744:17F0][2020-11-15T19:17:47]i000: Setting string variable 'WixBundleManufacturer' to value 'Python Software Foundation'[0744:17F0][2020-11-15T19:17:47]i000: Setting numeric variable 'CRTInstalled' to value 1[0744:1D6C][2020-11-15T19:17:47]i000: Did not find C:\Users\user\Downloads\unattend.xml[0744:1D6C][2020-11-15T19:17:47]i000: Setting string variable 'ActionLikeInstalling' to value 'Installing'[0744:1D6C][2020-11-15T19:17:47]i000: Setting string variable 'ActionLikeInstallation' to value 'Setup'[0744:1D6C][2020-11-15T19:17:47]i000: Setting version variable 'WixBundleFileVersion' to value '3.9.150.0'[0744:1D6C][2020-11-15T19:17:47]i000: Target OS is Windows 10 or later[0744:17F0][2020-11-15T19:17:47]i100: Detect begin, 52 packages[0744:17F0][2020-11-15T19:17:47]i107: Detected forward compatible bundle: {d774c4cf-f89d-47c0-a945-b6345332871f}, type: Upgrade, scope: PerUser, version: 3.9.150.0, enabled: No[0744:17F0][2020-11-15T19:17:47]i102: Detected related bundle: {d774c4cf-f89d-47c0-a945-b6345332871f}, type: Upgrade, scope: PerUser, version: 3.9.150.0, operation: None[0744:17F0][2020-11-15T19:17:47]e000: Related bundle {d774c4cf-f89d-47c0-a945-b6345332871f} is preventing install[0744:17F0][2020-11-15T19:17:47]i000: Setting numeric variable 'InstallLauncherAllUsers' to value 1[0744:17F0][2020-11-15T19:17:47]i000: Setting numeric variable 'Include_launcher' to value 1[0744:17F0][2020-11-15T19:17:47]i000: Setting numeric variable 'DetectedLauncher' to value 1[0744:17F0][2020-11-15T19:17:47]i000: Setting string variable 'Include_launcherState' to value 'disable'[0744:17F0][2020-11-15T19:17:47]i000: Setting string variable 'InstallLauncherAllUsersState' to value 'disable'[0744:17F0][2020-11-15T19:17:47]i000: Setting numeric variable 'AssociateFiles' to value 1[0744:17F0][2020-11-15T19:17:47]i101: Detected package: ucrt_AllUsers, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: ucrt_JustForMe, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: core_AllUsers, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: core_AllUsers_pdb, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: core_AllUsers_d, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: core_JustForMe, state: Present, cached: Complete[0744:17F0][2020-11-15T19:17:47]i101: Detected package: core_JustForMe_pdb, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: core_JustForMe_d, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: dev_AllUsers, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: dev_AllUsers_d, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: dev_JustForMe, state: Present, cached: Complete[0744:17F0][2020-11-15T19:17:47]i101: Detected package: dev_JustForMe_d, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: exe_AllUsers, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i104: Detected package: exe_AllUsers, feature: DefaultFeature, state: Absent[0744:17F0][2020-11-15T19:17:47]i104: Detected package: exe_AllUsers, feature: Shortcuts, state: Absent[0744:17F0][2020-11-15T19:17:47]i101: Detected package: exe_AllUsers_pdb, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: exe_AllUsers_d, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: exe_JustForMe, state: Present, cached: Complete[0744:17F0][2020-11-15T19:17:47]i104: Detected package: exe_JustForMe, feature: DefaultFeature, state: Local[0744:17F0][2020-11-15T19:17:47]i104: Detected package: exe_JustForMe, feature: Shortcuts, state: Local[0744:17F0][2020-11-15T19:17:47]i101: Detected package: exe_JustForMe_pdb, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: exe_JustForMe_d, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: lib_AllUsers, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: lib_AllUsers_pdb, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: lib_AllUsers_d, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: lib_JustForMe, state: Present, cached: Complete[0744:17F0][2020-11-15T19:17:47]i101: Detected package: lib_JustForMe_pdb, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: lib_JustForMe_d, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: test_AllUsers, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: test_AllUsers_pdb, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: test_AllUsers_d, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: test_JustForMe, state: Present, cached: Complete[0744:17F0][2020-11-15T19:17:47]i101: Detected package: test_JustForMe_pdb, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: test_JustForMe_d, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: doc_AllUsers, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i104: Detected package: doc_AllUsers, feature: DefaultFeature, state: Absent[0744:17F0][2020-11-15T19:17:47]i104: Detected package: doc_AllUsers, feature: Shortcuts, state: Absent[0744:17F0][2020-11-15T19:17:47]i101: Detected package: doc_JustForMe, state: Present, cached: Complete[0744:17F0][2020-11-15T19:17:47]i104: Detected package: doc_JustForMe, feature: DefaultFeature, state: Local[0744:17F0][2020-11-15T19:17:47]i104: Detected package: doc_JustForMe, feature: Shortcuts, state: Local[0744:17F0][2020-11-15T19:17:47]i101: Detected package: tools_AllUsers, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: tools_JustForMe, state: Present, cached: Complete[0744:17F0][2020-11-15T19:17:47]i101: Detected package: tcltk_AllUsers, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i104: Detected package: tcltk_AllUsers, feature: DefaultFeature, state: Absent[0744:17F0][2020-11-15T19:17:47]i104: Detected package: tcltk_AllUsers, feature: AssociateFiles, state: Absent[0744:17F0][2020-11-15T19:17:47]i104: Detected package: tcltk_AllUsers, feature: Shortcuts, state: Absent[0744:17F0][2020-11-15T19:17:47]i101: Detected package: tcltk_AllUsers_pdb, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i104: Detected package: tcltk_AllUsers_pdb, feature: Symbols, state: Absent[0744:17F0][2020-11-15T19:17:47]i101: Detected package: tcltk_AllUsers_d, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i104: Detected package: tcltk_AllUsers_d, feature: DebugBinaries, state: Absent[0744:17F0][2020-11-15T19:17:47]i101: Detected package: tcltk_JustForMe, state: Present, cached: Complete[0744:17F0][2020-11-15T19:17:47]i104: Detected package: tcltk_JustForMe, feature: DefaultFeature, state: Local[0744:17F0][2020-11-15T19:17:47]i104: Detected package: tcltk_JustForMe, feature: AssociateFiles, state: Local[0744:17F0][2020-11-15T19:17:47]i104: Detected package: tcltk_JustForMe, feature: Shortcuts, state: Local[0744:17F0][2020-11-15T19:17:47]i101: Detected package: tcltk_JustForMe_pdb, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i104: Detected package: tcltk_JustForMe_pdb, feature: Symbols, state: Absent[0744:17F0][2020-11-15T19:17:47]i101: Detected package: tcltk_JustForMe_d, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i104: Detected package: tcltk_JustForMe_d, feature: DebugBinaries, state: Absent[0744:17F0][2020-11-15T19:17:47]i101: Detected package: launcher_AllUsers, state: Present, cached: Complete[0744:17F0][2020-11-15T19:17:47]i104: Detected package: launcher_AllUsers, feature: DefaultFeature, state: Local[0744:17F0][2020-11-15T19:17:47]i104: Detected package: launcher_AllUsers, feature: AssociateFiles, state: Local[0744:17F0][2020-11-15T19:17:47]i101: Detected package: launcher_JustForMe, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i104: Detected package: launcher_JustForMe, feature: DefaultFeature, state: Absent[0744:17F0][2020-11-15T19:17:47]i104: Detected package: launcher_JustForMe, feature: AssociateFiles, state: Absent[0744:17F0][2020-11-15T19:17:47]i101: Detected package: pip_AllUsers, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: pip_JustForMe, state: Present, cached: Complete[0744:17F0][2020-11-15T19:17:47]i101: Detected package: path_AllUsers, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: path_JustForMe, state: Present, cached: Complete[0744:17F0][2020-11-15T19:17:47]i101: Detected package: compileall_AllUsers, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: compileallO_AllUsers, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: compileallOO_AllUsers, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: compileall_JustForMe, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: compileallO_JustForMe, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i101: Detected package: compileallOO_JustForMe, state: Absent, cached: None[0744:17F0][2020-11-15T19:17:47]i000: Setting string variable 'TargetDir' to value 'C:\Users\user\AppData\Local\Programs\Python\Python39'[0744:17F0][2020-11-15T19:17:47]i199: Detect complete, result: 0x0 4)my first language is Hebrew(?????).? From desaumarez at yahoo.fr Sun Nov 15 07:15:46 2020 From: desaumarez at yahoo.fr (Robin Williamson) Date: Sun, 15 Nov 2020 12:15:46 +0000 (UTC) Subject: [Tutor] Problem solving References: <1601296876.9947436.1605442546816.ref@mail.yahoo.com> Message-ID: <1601296876.9947436.1605442546816@mail.yahoo.com> if b "or" v References: <73840182.3335733.1605462720775.ref@mail.yahoo.com> <73840182.3335733.1605462720775@mail.yahoo.com> Message-ID: On 15/11/2020 17:52, ??? ??????? via Tutor wrote: > I try to download the python.org system-but website system don't let me do it. Is it the download that fails or the installation? >From the error messages it looks like the install? How are you running the installer? Once you download it, what exactly do you do? We need a description of the screens, button presses any commands or settings you pick etc. BTW it looks like you are using Windows. In that case I usually recommend using the ActiveState.com version of Python rather than the vanilla python.org version. There are lots of extra Windows goodies in the Activestate version, although I don't think they've got a 3.9 out yet... -- 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 Nov 15 18:28:59 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 15 Nov 2020 23:28:59 +0000 Subject: [Tutor] Problem solving In-Reply-To: <1601296876.9947436.1605442546816@mail.yahoo.com> References: <1601296876.9947436.1605442546816.ref@mail.yahoo.com> <1601296876.9947436.1605442546816@mail.yahoo.com> Message-ID: On 15/11/2020 12:15, Robin Williamson via Tutor wrote: > if b "or" v print("rouge"): The or should not be in quotes, it is not a string. This should have triggered a n error message. When you get an error always post it in full in the message, they contain a lot of useful information. Also the colon should be on the same line as the if not after the print. The structure is: if else Where the elif section can be repeated and both elif and else are optional. But notice where the colons are positioned. -- 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 steve10brink1 at comcast.net Mon Nov 16 10:46:50 2020 From: steve10brink1 at comcast.net (steve10brink1 at comcast.net) Date: Mon, 16 Nov 2020 08:46:50 -0700 (MST) Subject: [Tutor] passing variables to functions Message-ID: <617378361.101353.1605541610615@connect.xfinity.com> Hi, I always assumed that variables could only be passed to functions via function calls unless they are designated as global. So I was suprised that this code works without any errors. How does the variable 'b' get indirectly assigned in the function testVar(a)? I expected an error. I am using python3 version 3.5.3. Code: ----------------------------------------------------------- def testVar(a): print(b,a) #b is from main and not passed thru function call, expect error return a print("Test variables in function.....") b = 23.4 c = testVar(b) print("Final: ",c) ----------------------------------------------------------- Output: Test variables in function..... 23.4 23.4 Final: 23.4 From mats at wichmann.us Mon Nov 16 11:08:00 2020 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 16 Nov 2020 09:08:00 -0700 Subject: [Tutor] passing variables to functions In-Reply-To: <617378361.101353.1605541610615@connect.xfinity.com> References: <617378361.101353.1605541610615@connect.xfinity.com> Message-ID: <4c0965e2-02b6-545e-ae19-160bce6dc09c@wichmann.us> On 11/16/20 8:46 AM, steve10brink1 at comcast.net wrote: > Hi, > > I always assumed that variables could only be passed to functions via function calls unless they are designated as global. So I was suprised that this code works without any errors. How does the variable 'b' get indirectly assigned in the function testVar(a)? I expected an error. I am using python3 version 3.5.3. > > Code: > ----------------------------------------------------------- > def testVar(a): > print(b,a) #b is from main and not passed thru function call, expect error > return a > > print("Test variables in function.....") > b = 23.4 > c = testVar(b) > print("Final: ",c) > > ----------------------------------------------------------- > Output: > > Test variables in function..... > 23.4 23.4 > Final: 23.4 "That's how it works" :) If there's not a value in the local scope (inside the function definition), Python picks it from the global scope. On the other hand, if you were assigning to b in the function, Python would create b in the local scope if you did not use the "global" statement. It might be useful to think of it as a set of dictionaries, since in most cases that's what it is: >>> b = 23.4 >>> print(globals()) {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': , '__spec__': None, '__annotations__': {}, '__builtins__': , 'b': 23.4} >>> def testVar(a): ... c = 10 ... print(locals()) ... >>> >>> testVar(b) {'a': 23.4, 'c': 10} >>> The local scope in testVar got the var 'c' from the direct assignment and the var 'a' from the function argument; if there where a reference to 'b', it wouldn't find it in the locals dict so it would fall back to the globals, and find it from there. From alan.gauld at yahoo.co.uk Mon Nov 16 11:09:23 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 16 Nov 2020 16:09:23 +0000 Subject: [Tutor] passing variables to functions In-Reply-To: <617378361.101353.1605541610615@connect.xfinity.com> References: <617378361.101353.1605541610615@connect.xfinity.com> Message-ID: On 16/11/2020 15:46, steve10brink1 at comcast.net wrote: > I always assumed that variables could only be passed to functions > via function calls unless they are designated as global. Not quite. Functions can see any variables in their surrounding scope. But if you don't specify them as global inside the function then the function can only read the variable not modify it (modifying the variable would create a new local variable). > How does the variable 'b' get indirectly assigned in the > function testVar(a)? I expected an error. > ----------------------------------------------------------- > def testVar(a): > print(b,a) #b is from main and not passed thru function call, expect error > return a a is a local variable inside the function. b is global and only being read so the function uses the global b. > print("Test variables in function.....") > b = 23.4 > c = testVar(b) Here the local variable a takes on the same value as b So the function prints two copies of the same value and returns the same value that was passed in. > print("Final: ",c) So this prints the returned version of a. > Output: > > Test variables in function..... > 23.4 23.4 > Final: 23.4 You might find the topic entitled "What's in a name?" in my tutorial to be useful. -- 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 marcogp46 at hotmail.com Mon Nov 16 20:59:26 2020 From: marcogp46 at hotmail.com (Marco Pareja) Date: Mon, 16 Nov 2020 20:59:26 -0500 Subject: [Tutor] how Convert this Bash command into Python: Have a nice day Message-ID: Why is wrong with this command Print (?Have a nice day?) ? From alan.gauld at yahoo.co.uk Tue Nov 17 03:58:00 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 17 Nov 2020 08:58:00 +0000 Subject: [Tutor] how Convert this Bash command into Python: Have a nice day In-Reply-To: References: Message-ID: On 17/11/2020 01:59, Marco Pareja wrote: > Why is wrong with this command > Print (?Have a nice day?) ? On the surface I'd say it has a capital P in print() it has to be lower case. Also it has question marks instead of quotes. But I suspect that may be errors introduced by the email system and what you actually have is so-called "smart quotes" around the text instead of vanilla plain text quotes. This often happens if you use a word processor to write the text. Unfortunately smart quotes are different characters from plain quotes and so Python doesn't recognize 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 nathan-tech at hotmail.com Tue Nov 17 07:10:30 2020 From: nathan-tech at hotmail.com (nathan tech) Date: Tue, 17 Nov 2020 12:10:30 +0000 Subject: [Tutor] Two issues I feel very strongly on Message-ID: Dear Sir, I'm reaching out to you as a concerned constituent regarding two issues that I personally feel very much affect us as British citizens at the current time considering both the Political Climate and the Climate that has resulted from The Virus. First, regarding my concern of The Virus. while doing rather unrelated research today I came across this petition (linked below) asking the government for protection for retail workers. My own mother is a Supervisor in our local The Range Southend store, so this is an issue I'm sure you understand I am very aware of! Due to hours, my mother is has shifts twice a week that mean she is not getting home until 9:30 P.M., or even 10:00 P.M. at night. These facts are anxiety inducing enough without the stress on top of that of the potential for violence in the stores, or the abuse being hurled at her and other workers for policies they quite literally have no control over. I understand, as well, that not working in an environment can sometimes lead to disbelief, I mean how hard can it be to do customer service, right? But you yourself Sir likely understand the strain and tribulations that come with meeting customer demands on a daily basis while also keeping in like with company policy. It would mean a lot to me if you would show your support for this petition, or at least show your awareness of it. Petition link: https://petition.parliament.uk/petitions/328621 The second issue I wanted to reach out to you about is actually relating to the research I mentioned that I was doing above to do with our royal Navy. In school you are taught that our Royal Navy once ruled the sea. Is that not what the song Rule Britannia is all about, after all? As an island nation, one might say island superpower, our first and most prominent line of defense is our Navy. Our navy is the fleet that will protect us if, god forbid, a situation ever arises where relationship with a foreign power sour so badly as to be dangerous. Further, the Royal Navy protects our interests overseas, both in trade but also in peace. With Brexit just over the hill, is our royal Navy up to the job? I've read a lot about the Queen Elizabeth II new aircraft carrier, but at the same time I've also read of our fleet size getting smaller, and smaller, and smaller. These days you read all the time about foreign powers sending battleships into British waters, and it's a scary concept for the uninformed! With Brexit, can we really rely on our friends in the European Union or our friends in The United States to cough up military powers if the UK becomes under threat? So I'm reaching out to you sir, what personal assurances can you offer on this matter. Is the UK as well defended as it should be, and if not what does you and or the Conservatives intends to do about this? I don't like living with the idea that we can no longer be reassured of our freedom, and I'm sure you agree. I eagerly await your response (or even to see your next appearance on Parliament.tv). All the best, Nathan smith From nathan-tech at hotmail.com Tue Nov 17 08:11:53 2020 From: nathan-tech at hotmail.com (nathan tech) Date: Tue, 17 Nov 2020 13:11:53 +0000 Subject: [Tutor] OOPS MY BAD Message-ID: Hello tutor List, As you may have realised my previous email to this list was not intended to go hear and was the result of a typo when exiting the address bar of my email application. Thankfully nothing sensitive in the email, though hardly relevant to the mailing list! I've reached out to the MP it was intended for to inform him of the mistake and not to reply to the list itself, just my email address. Sorry for the confusion and thanks to Alan for pointing out my mistake. Still, nothing like a bit of early morning entertainment I suppose. All the best Nathan From gawad at unal.edu.co Tue Nov 17 07:28:07 2020 From: gawad at unal.edu.co (Gabriel A Awad Aubad) Date: Tue, 17 Nov 2020 07:28:07 -0500 Subject: [Tutor] how Convert this Bash command into Python: Have a nice day In-Reply-To: References: Message-ID: Hi everybody!!! Why is wrong with this command Print (?Have a nice day?) ? Print should be print. The capital letter at the beginning caused the problem. Best regards, *Gabriel AWAD* *Profesor Asociado* *Departamento de Ciencias de la Computaci?n y de la Decisi?n* Universidad Nacional de Colombia - Sede Medell?n Carrera 80 # 65 - 223 Bloque M8A Of. 208 Medell?n, Colombia C?digo postal: 050041 e-mail: gawad at unal.edu.co LinkedIn Twitter Facebook Skype: gabriel.awad *"M?s puede en m? el azar que yo". * * Miguel de Montaigne* On Tue, 17 Nov 2020 at 03:53, Marco Pareja wrote: > Why is wrong with this command > Print (?Have a nice day?) ? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- *Aviso legal:*?El contenido de este mensaje y los archivos adjuntos son confidenciales y de uso exclusivo de la Universidad Nacional de Colombia. Se encuentran dirigidos s?lo para el uso del destinatario al cual van enviados. La reproducci?n, lectura y/o copia se encuentran prohibidas a cualquier persona diferente a este y puede ser ilegal. Si usted lo ha recibido por error, inf?rmenos y elim?nelo de su correo. Los Datos Personales ser?n tratados conforme a la Ley 1581 de 2012 y a nuestra Pol?tica de Datos Personales que podr? consultar en la p?gina web? www.unal.edu.co .*?*Las opiniones, informaciones, conclusiones y cualquier otro tipo de dato contenido en este correo electr?nico, no relacionados con la actividad de la Universidad Nacional de Colombia, se entender? como personales y de ninguna manera son avaladas por la Universidad. From marcogp46 at hotmail.com Tue Nov 17 07:39:21 2020 From: marcogp46 at hotmail.com (marco garcia pareja) Date: Tue, 17 Nov 2020 12:39:21 +0000 Subject: [Tutor] how Convert this Bash command into Python: Have a nice day In-Reply-To: References: , Message-ID: Thank you guys I just started to learn python, thank for your patience Get Outlook for iOS ________________________________ From: Gabriel A Awad Aubad Sent: Tuesday, November 17, 2020 7:28:07 AM To: Marco Pareja Cc: Tutor at python.org Subject: Re: [Tutor] how Convert this Bash command into Python: Have a nice day Hi everybody!!! Why is wrong with this command Print (?Have a nice day?) ? Print should be print. The capital letter at the beginning caused the problem. Best regards, Gabriel AWAD Profesor Asociado Departamento de Ciencias de la Computaci?n y de la Decisi?n Universidad Nacional de Colombia - Sede Medell?n Carrera 80 # 65 - 223 Bloque M8A Of. 208 Medell?n, Colombia C?digo postal: 050041 e-mail: gawad at unal.edu.co LinkedIn Twitter Facebook Skype: gabriel.awad "M?s puede en m? el azar que yo". Miguel de Montaigne On Tue, 17 Nov 2020 at 03:53, Marco Pareja > wrote: Why is wrong with this command Print (?Have a nice day?) ? _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor Aviso legal: El contenido de este mensaje y los archivos adjuntos son confidenciales y de uso exclusivo de la Universidad Nacional de Colombia. Se encuentran dirigidos s?lo para el uso del destinatario al cual van enviados. La reproducci?n, lectura y/o copia se encuentran prohibidas a cualquier persona diferente a este y puede ser ilegal. Si usted lo ha recibido por error, inf?rmenos y elim?nelo de su correo. Los Datos Personales ser?n tratados conforme a la Ley 1581 de 2012 y a nuestra Pol?tica de Datos Personales que podr? consultar en la p?gina web www.unal.edu.co. Las opiniones, informaciones, conclusiones y cualquier otro tipo de dato contenido en este correo electr?nico, no relacionados con la actividad de la Universidad Nacional de Colombia, se entender? como personales y de ninguna manera son avaladas por la Universidad. From nulla.epistola at web.de Wed Nov 18 06:33:43 2020 From: nulla.epistola at web.de (Sibylle Koczian) Date: Wed, 18 Nov 2020 12:33:43 +0100 Subject: [Tutor] Problem solving In-Reply-To: <1601296876.9947436.1605442546816@mail.yahoo.com> References: <1601296876.9947436.1605442546816.ref@mail.yahoo.com> <1601296876.9947436.1605442546816@mail.yahoo.com> Message-ID: <219f7ecc-2be3-53dd-52c0-f65d1feb7f25@web.de> Am 15.11.2020 um 13:15 schrieb Robin Williamson via Tutor: > if b "or" v print("rouge"): > elif v"or"r print("bleu") > else: > print("vert")I am trying to write a program that will tell me what the dominant colour is in a photo, either green, red or blue.I have tried to write the above program but it seems I have'nt understood something.Any help and explanations would be greatly appreciated.ThanksRobinYou may have noticed that I'm using rouge for red, vert for green, and bleu for blue, I'm in France! > In addition to Alan Gauld's answer: I think Python may interpret your conditions not like you meant them - but perhaps I've misunderstood the meaning of your variables b, r, v. Those names aren't good. I read your variables like this: b: quantity of blue in the photo r: quantity of red v: quantity of green (v for vert) And I guess that your first condition should tell Python: If there is less blue or green than red in the photo, then print "rouge". Or, nearer to logic and programming: if there is less blue than red *and* less green than red, then print "rouge". But if you change your string "or" to the keyword or, then Python reads it like this: if b or (v < r) which means: if there is any blue at all in the photo, then print "rouge"; if there is less green than red, then print "rouge". So I suppose your first condition should be if b < r and v < r: print("rouge") HTH Sibylle From nulla.epistola at web.de Wed Nov 18 06:33:43 2020 From: nulla.epistola at web.de (Sibylle Koczian) Date: Wed, 18 Nov 2020 12:33:43 +0100 Subject: [Tutor] Problem solving In-Reply-To: <1601296876.9947436.1605442546816@mail.yahoo.com> References: <1601296876.9947436.1605442546816.ref@mail.yahoo.com> <1601296876.9947436.1605442546816@mail.yahoo.com> Message-ID: <219f7ecc-2be3-53dd-52c0-f65d1feb7f25@web.de> Am 15.11.2020 um 13:15 schrieb Robin Williamson via Tutor: > if b "or" v print("rouge"): > elif v"or"r print("bleu") > else: > print("vert")I am trying to write a program that will tell me what the dominant colour is in a photo, either green, red or blue.I have tried to write the above program but it seems I have'nt understood something.Any help and explanations would be greatly appreciated.ThanksRobinYou may have noticed that I'm using rouge for red, vert for green, and bleu for blue, I'm in France! > In addition to Alan Gauld's answer: I think Python may interpret your conditions not like you meant them - but perhaps I've misunderstood the meaning of your variables b, r, v. Those names aren't good. I read your variables like this: b: quantity of blue in the photo r: quantity of red v: quantity of green (v for vert) And I guess that your first condition should tell Python: If there is less blue or green than red in the photo, then print "rouge". Or, nearer to logic and programming: if there is less blue than red *and* less green than red, then print "rouge". But if you change your string "or" to the keyword or, then Python reads it like this: if b or (v < r) which means: if there is any blue at all in the photo, then print "rouge"; if there is less green than red, then print "rouge". So I suppose your first condition should be if b < r and v < r: print("rouge") HTH Sibylle From natesmokes420yall at gmail.com Wed Nov 18 17:19:48 2020 From: natesmokes420yall at gmail.com (Nathaniel Dodson) Date: Wed, 18 Nov 2020 17:19:48 -0500 Subject: [Tutor] Indentation Frustrations Message-ID: Please, for the love of God, why am I constantly getting indentation errors when I'm trying to write some simple Pygame code? I have Googled the error messages and it says my indentation has to be uniform. But it is for Pete's sake! I'm ripping my hair out bc I'm not copying and pasting the code; I'm typing it line for line from a tutorial. I get to a certain point and it just gives me indentation error after indentation error. This is the code, and when I get to the part to assign keyboard key functions for movement, it gives me "expected an indented block" error (and always highlights the "i" in the if statement in red): import pygame pygame.init() win = pygame.display.set_mode((500, 500)) pygame.display.set_caption("First Game") x = 50 y = 50 width = 40 height = 60 vel = 5 run = True while run: pygame.time.delay(100) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: if keys[pygame.K_RIGHT]: I'm not getting what's going on. I know about mixing tabs with spaces, and I'm not doing that. That's what I learned through Googling the issue. From mats at wichmann.us Wed Nov 18 19:17:53 2020 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 18 Nov 2020 17:17:53 -0700 Subject: [Tutor] Indentation Frustrations In-Reply-To: References: Message-ID: <8a99565f-93e0-04e5-4b34-8b68bb219df8@wichmann.us> On 11/18/20 3:19 PM, Nathaniel Dodson wrote: > if keys[pygame.K_LEFT]: > > if keys[pygame.K_RIGHT]: > > I'm not getting what's going on. I know about mixing tabs with spaces, and > I'm not doing that. That's what I learned through Googling the issue. a statement that introduces a block (ones that end with a colon) have to actually have an indented block. Those two don't. Python doesn't know for sure it's an error before it sees a line that can't be correct, which would be the second "if" statement from the included snip. If you're developing iteratively and want a placeholder to avoid those kinds of errors you can use "pass" (traditional) or the ellipsis operator ... as in: if keys[pygame.K_LEFT]: pass if keys[pygame.K_RIGHT]: ... From nathan-tech at hotmail.com Wed Nov 18 19:19:53 2020 From: nathan-tech at hotmail.com (nathan tech) Date: Thu, 19 Nov 2020 00:19:53 +0000 Subject: [Tutor] Indentation Frustrations In-Reply-To: References: Message-ID: Hey there, Are you running this directly in the python command line? If so, remove the blank lines. You could also try copying your code into a file and then doing python file.py. HTH Nathan On 18/11/2020 22:19, Nathaniel Dodson wrote: > Please, for the love of God, why am I constantly getting indentation errors > when I'm trying to write some simple Pygame code? I have Googled the error > messages and it says my indentation has to be uniform. But it is for Pete's > sake! I'm ripping my hair out bc I'm not copying and pasting the code; I'm > typing it line for line from a tutorial. I get to a certain point and it > just gives me indentation error after indentation error. This is the code, > and when I get to the part to assign keyboard key functions for movement, > it gives me "expected an indented block" error (and always highlights the > "i" in the if statement in red): > > import pygame > pygame.init() > > win = pygame.display.set_mode((500, 500)) > pygame.display.set_caption("First Game") > > x = 50 > y = 50 > width = 40 > height = 60 > vel = 5 > > run = True > > while run: > pygame.time.delay(100) > > for event in pygame.event.get(): > if event.type == pygame.QUIT: > run = False > > keys = pygame.key.get_pressed() > > if keys[pygame.K_LEFT]: > > if keys[pygame.K_RIGHT]: > > I'm not getting what's going on. I know about mixing tabs with spaces, and > I'm not doing that. That's what I learned through Googling the issue. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://nam12.safelinks.protection.outlook.com/?url=https%3A%2F%2Fmail.python.org%2Fmailman%2Flistinfo%2Ftutor&data=04%7C01%7C%7Ced0360d5c1eb47895fa908d88c1ead99%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637413410667952176%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C1000&sdata=lkDa088Zq%2Ff1eLuK4v4A%2B6E0r8bHyqn2pm1lYR%2Fk6Fo%3D&reserved=0 From breamoreboy at gmail.com Wed Nov 18 19:25:52 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Thu, 19 Nov 2020 00:25:52 +0000 Subject: [Tutor] Indentation Frustrations In-Reply-To: References: Message-ID: On 18/11/2020 22:19, Nathaniel Dodson wrote: > Please, for the love of God, why am I constantly getting indentation errors > when I'm trying to write some simple Pygame code? I have Googled the error > messages and it says my indentation has to be uniform. But it is for Pete's > sake! I'm ripping my hair out bc I'm not copying and pasting the code; I'm > typing it line for line from a tutorial. I get to a certain point and it > just gives me indentation error after indentation error. This is the code, > and when I get to the part to assign keyboard key functions for movement, > it gives me "expected an indented block" error (and always highlights the > "i" in the if statement in red): > > import pygame > pygame.init() > > win = pygame.display.set_mode((500, 500)) > pygame.display.set_caption("First Game") > > x = 50 > y = 50 > width = 40 > height = 60 > vel = 5 > > run = True > > while run: > pygame.time.delay(100) > > for event in pygame.event.get(): > if event.type == pygame.QUIT: > run = False > > keys = pygame.key.get_pressed() > > if keys[pygame.K_LEFT]: Looks as if there's some code missing here. > if keys[pygame.K_RIGHT]: Hence the above line will give an indentation error. Just carry on down https://www.techwithtim.net/tutorials/game-development-with-python/pygame-tutorial/pygame-tutorial-movement/ and you'll find what's missing :) > > I'm not getting what's going on. I know about mixing tabs with spaces, and > I'm not doing that. That's what I learned through Googling the issue. > My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From alan.gauld at yahoo.co.uk Wed Nov 18 19:43:16 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 19 Nov 2020 00:43:16 +0000 Subject: [Tutor] Indentation Frustrations In-Reply-To: References: Message-ID: On 18/11/2020 22:19, Nathaniel Dodson wrote: > typing it line for line from a tutorial. I get to a certain point and it > just gives me indentation error after indentation error. I'm always leery of making comments about formatting errors because it's often the email system messing things up. However, since the bulk of your code looks OK I'll take a guess on this one. But, in principle for any future posts, please tell us where you are copying the code from (se we can compare) and what editing tool you are using (since many of them do their own formatting!) > and when I get to the part to assign keyboard key functions for movement, > it gives me "expected an indented block" error (and always highlights the > "i" in the if statement in red): That's because you don't have an indented block after your if statements. An if statement (or any other statement ending with a colon) expects an indented line or block of code. If you don't have one you get an indentation error. > while run: > pygame.time.delay(100) > > for event in pygame.event.get(): > if event.type == pygame.QUIT: > run = False See, here you have the run assignment indented after the if line. Presumably no errors in this case. > keys = pygame.key.get_pressed() > if keys[pygame.K_LEFT]: But here there are no lines. You can add a placeholder like pass, or even a random number, anything at all that python can evaluate. > if keys[pygame.K_RIGHT]: > > I'm not getting what's going on. I know about mixing tabs with spaces, and > I'm not doing that. That's what I learned through Googling the issue. Read the error carefully, they are very specific. Mixing tabs/spaces or using inconsistent indent levels would give specific messages about that particular sin. You are getting an "expected an indented block" message which is exactly what is wrong. You need ab indented block. Any block will do but it needs to be there. Incidentally, this may be an issue with your tutorial where the author has only provided an outline instead of runnable code. In that case you will likely find the content of the missing blocks a little later in the tutorial. Naughty author....! But I've been guilty of the same in the past. :-( -- 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 s.molnar at sbcglobal.net Fri Nov 20 12:08:32 2020 From: s.molnar at sbcglobal.net (Stephen P. Molnar) Date: Fri, 20 Nov 2020 12:08:32 -0500 Subject: [Tutor] stats.linregress Problem References: <5FB7F810.4070904.ref@sbcglobal.net> Message-ID: <5FB7F810.4070904@sbcglobal.net> I have been following the steps in https://365datascience.com/linear-regression/ . The libraries are up to date. The code in the reference is (attached): import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm import seaborn as sns from scipy import stats sns.set() df = pd.read_csv('Data.csv') print(df) y = df['GPA'] x1 = df['SAT'] sns.set_style('whitegrid') plt.figure(1) plt.scatter(x1,y, s = 10) plt.xlabel('SAT', fontsize=10) plt.ylabel('GPA', fontsize=10) x = sm.add_constant(x1) results = sm.OLS(y,x).fit() results.summary() print(results.summary()) slope, intercept, r_value, p_value, std_err = stats.linregress(x1, y) print("slope: %f intercept: %f" % (slope, intercept)) print("R-squared: %f" % r_value**2) with the exception of the last lines, which I have added. It runs to the end and gives me the values I want. The modified script and the data file are also attached. However, when I modify the script to use the data that I want I get errors for the last three lines" import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm import seaborn as sns from scipy import stats sns.set() df = pd.read_csv('AllData31e.csv') df = df.dropna(axis=1) x1 = df.iloc[:,2].values.reshape(-1,1) y = df.iloc[:,1].values.reshape(-1,1) print(df.describe()) sns.set_style('whitegrid') plt.figure(1) plt.scatter(x1,y, s = 10) plt.xlabel('log(IC50)', fontsize=10) plt.ylabel('Activity (kcal.mole)', fontsize=10) x = sm.add_constant(x1) results = sm.OLS(y,x).fit() results.summary() print(results.summary()) slope, intercept, r_value, p_value, std_err = stats.linregress(x1, y) print("slope: %f intercept: %f" % (slope, intercept)) print("R-squared: %f" % r_value**2) Traceback (most recent call last): File "/home/comp/Apps/PythonDevelopment/LinReg_2.py", line 39, in slope, intercept, r_value, p_value, std_err = stats.linregress(x1, y) File "/home/comp/Apps/Spyder-4.2.0/Spyder-4.2.0/lib/python3.7/site-packages/scipy/stats/_stats_mstats_common.py", line 116, in linregress ssxm, ssxym, ssyxm, ssym = np.cov(x, y, bias=1).flat ValueError: too many values to unpack (expected 4) Google in this instance has not been my friend. Pointers in the direction of a solution will be appreciated. Thanks in advance. -- Stephen P. Molnar, Ph.D. www.molecular-modeling.net 614.312.7528 (c) Skype: smolnar1 From mats at wichmann.us Fri Nov 20 13:05:55 2020 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 20 Nov 2020 11:05:55 -0700 Subject: [Tutor] stats.linregress Problem In-Reply-To: <5FB7F810.4070904@sbcglobal.net> References: <5FB7F810.4070904.ref@sbcglobal.net> <5FB7F810.4070904@sbcglobal.net> Message-ID: On 11/20/20 10:08 AM, Stephen P. Molnar wrote: there's really too much information missing, Python's complaint is fairly clear: > Traceback (most recent call last): > > ? File "/home/comp/Apps/PythonDevelopment/LinReg_2.py", line 39, in > > ??? slope, intercept, r_value, p_value, std_err = stats.linregress(x1, y) > > ? File > "/home/comp/Apps/Spyder-4.2.0/Spyder-4.2.0/lib/python3.7/site-packages/scipy/stats/_stats_mstats_common.py", > line 116, in linregress > ??? ssxm, ssxym, ssyxm, ssym = np.cov(x, y, bias=1).flat > > ValueError: too many values to unpack (expected 4) The .flat method of NumPy arrays returns a flat iterator over an array, which is being unpacked. iN this case np.cov().flat is returning an interator that produces more than the four values the code line expects, thus the unpacking error. Why that would be the case, though... obviously "that's what the data leads the covariance function to generate".... From breamoreboy at gmail.com Fri Nov 20 13:02:47 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Fri, 20 Nov 2020 18:02:47 +0000 Subject: [Tutor] stats.linregress Problem In-Reply-To: <5FB7F810.4070904@sbcglobal.net> References: <5FB7F810.4070904.ref@sbcglobal.net> <5FB7F810.4070904@sbcglobal.net> Message-ID: On 20/11/2020 17:08, Stephen P. Molnar wrote: > I have been following the steps in > https://365datascience.com/linear-regression/ . The libraries are up to > date. > > The code in the reference is (attached): > > import pandas as pd > import matplotlib.pyplot as plt > import statsmodels.api as sm > import seaborn as sns > from scipy import stats > sns.set() > > df = pd.read_csv('Data.csv') > print(df) > > y = df['GPA'] > x1 = df['SAT'] > sns.set_style('whitegrid') > plt.figure(1) > plt.scatter(x1,y, s = 10) > plt.xlabel('SAT', fontsize=10) > plt.ylabel('GPA', fontsize=10) > > x = sm.add_constant(x1) > results = sm.OLS(y,x).fit() > results.summary() > print(results.summary()) > > slope, intercept, r_value, p_value, std_err = stats.linregress(x1, y) > print("slope: %f??? intercept: %f" % (slope, intercept)) > print("R-squared: %f" % r_value**2) > > with the exception of the last lines, which I have added. It runs to the > end and gives me the values I want. The modified script and the data > file are also attached. > > However, when I modify the script to use the data that I want I get > errors for the last three lines" > > import pandas as pd > import matplotlib.pyplot as plt > import statsmodels.api as sm > import seaborn as sns > from scipy import stats > sns.set() > > > df = pd.read_csv('AllData31e.csv') > df = df.dropna(axis=1) > > > x1 = df.iloc[:,2].values.reshape(-1,1) > y = df.iloc[:,1].values.reshape(-1,1) > > print(df.describe()) > > > sns.set_style('whitegrid') > plt.figure(1) > plt.scatter(x1,y, s = 10) > plt.xlabel('log(IC50)', fontsize=10) > plt.ylabel('Activity (kcal.mole)', fontsize=10) > > x = sm.add_constant(x1) > results = sm.OLS(y,x).fit() > results.summary() > print(results.summary()) > > slope, intercept, r_value, p_value, std_err = stats.linregress(x1, y) > print("slope: %f??? intercept: %f" % (slope, intercept)) > print("R-squared: %f" % r_value**2) > > Traceback (most recent call last): > > ? File "/home/comp/Apps/PythonDevelopment/LinReg_2.py", line 39, in > > ??? slope, intercept, r_value, p_value, std_err = stats.linregress(x1, y) > > ? File > "/home/comp/Apps/Spyder-4.2.0/Spyder-4.2.0/lib/python3.7/site-packages/scipy/stats/_stats_mstats_common.py", > line 116, in linregress > ??? ssxm, ssxym, ssyxm, ssym = np.cov(x, y, bias=1).flat > > ValueError: too many values to unpack (expected 4) > > Google in this instance has not been my friend. Pointers in the > direction of a solution will be appreciated. > > Thanks in advance. > I'd put print calls into the original and modified code to ensure that x1 and y have the same dimensions for the call into stats.linregress. If yes I haven't a clue, sorry. If no then modify the code that gets the data from your file, simples :-) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From jf_byrnes at comcast.net Fri Nov 20 14:46:09 2020 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Fri, 20 Nov 2020 13:46:09 -0600 Subject: [Tutor] yFinance/pandas? Message-ID: Using linux Mint20 and python 3.8 Wondering if anyone is familiar with yfinance/pandas? I am writing a script to pull historical stock data from Yahoo Finance and insert it in a sqlite3 db. yfinance returns data as a pandas dataframe. I'm not that familiar with pandas but in the past I have been able to go on line and figure out how to extract the data I needed, but I am stuck now. some test code: import yfinance as yf import sqlite3 stock = 'AAPL' ticker = yf.Ticker(stock) hist = ticker.history(start='2018-01-01', end='2018-01-04') print(hist) #print(hist.iloc[0]['Name']) #['Name:'] print(hist.loc['2018-01-02']) #['Close']) #print(hist.iloc[0]) print(hist) outputs: Open High Low Close Volume Dividends Stock Splits Date 2018-01-02 40.60 41.12 40.39 41.11 102223600 0 0 2018-01-03 41.17 41.65 41.03 41.10 118071600 0 0 print(hist.loc['2018-01-02']) outputs: Open 4.060000e+01 High 4.112000e+01 Low 4.039000e+01 Close 4.111000e+01 Volume 1.022236e+08 Dividends 0.000000e+00 Stock Splits 0.000000e+00 Name: 2018-01-02 00:00:00, dtype: float64 If I retrieve a large number of rows the terminal will display the first few and last few rows and say x number of rows and 7 columns. Apparently pandas does not consider Date a column. I need to insert the date into the db along with the rest of the row. I've tried using ['Name'] and ['Name:'] and [7] but get either key errors or index errors. How can I retrieve the date? Thanks, Jim From jf_byrnes at comcast.net Fri Nov 20 21:04:11 2020 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Fri, 20 Nov 2020 20:04:11 -0600 Subject: [Tutor] yFinance/pandas? In-Reply-To: References: Message-ID: On 11/20/20 3:09 PM, Dennis Lee Bieber wrote: > On Fri, 20 Nov 2020 13:46:09 -0600, Jim Byrnes > declaimed the following: > >> print(hist.loc['2018-01-02']) outputs: >> >> Open 4.060000e+01 >> High 4.112000e+01 >> Low 4.039000e+01 >> Close 4.111000e+01 >> Volume 1.022236e+08 >> Dividends 0.000000e+00 >> Stock Splits 0.000000e+00 >> Name: 2018-01-02 00:00:00, dtype: float64 >> >> If I retrieve a large number of rows the terminal will display the first >> few and last few rows and say x number of rows and 7 columns. Apparently >> pandas does not consider Date a column. I need to insert the date into >> the db along with the rest of the row. >> >> I've tried using ['Name'] and ['Name:'] and [7] but get either key >> errors or index errors. >> > > I don't do pandas, but... From the yfinance source > https://github.com/ranaroussi/yfinance/blob/master/yfinance/utils.py > """ > quotes = _pd.DataFrame({"Open": opens, > "High": highs, > "Low": lows, > "Close": closes, > "Adj Close": adjclose, > "Volume": volumes}) > > quotes.index = _pd.to_datetime(timestamps, unit="s") > """ > > would imply that the date is NOT really part of the data frame itself; it > is part of the INDEX to the data. Then going into > https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html > may provide hints. Off hand, I'd iterate over the .index values, retrieving > the row for each such index, and then perform the SQL INSERT statement > using the index and the row data. > Turns out google was my friend. I didn't know what to google earlier but I tried "yfinance return Date Column" and it gave me my answer. I needed to change the "hist=" line to: hist = ticker.history(start='2018-01-01', end='2018-01-04').reset_index() That gave me a column I could get a date from and will be able to insert it along with the rest of the row in a db. Thanks for you input. Regards, Jim From shubhangi.patil at icloud.com Fri Nov 20 23:00:45 2020 From: shubhangi.patil at icloud.com (Shubhangi Patil) Date: Sat, 21 Nov 2020 04:00:45 -0000 Subject: [Tutor] Required help in understanding following code Message-ID: Hi, I need guidance to understand following code? image_data = [{"data": typ, "class": name.split('/')[0], "filename": name.split('/')[1]} for dataset, typ in zip([train_dataset, validation_dataset, test_dataset], ["train", "validation", "test"]) for name in dataset.filenames] image_df = pd.DataFrame(image_data) In above code instead of zip files, I would like to upload files from my computer folder. Please explain in details above code. Thank you, Shubhangi Patil From alan.gauld at yahoo.co.uk Sat Nov 21 06:26:27 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 21 Nov 2020 11:26:27 +0000 Subject: [Tutor] Required help in understanding following code In-Reply-To: References: Message-ID: On 21/11/2020 04:00, Shubhangi Patil via Tutor wrote: > I need guidance to understand following code? > Me too. That's one of the most convoluted list comprehensions I've seen I've tried to reformat it. > image_data = [{"data": typ, > "class": name.split('/')[0], > "filename": name.split('/')[1]} > for dataset, typ in zip([train_dataset, validation_dataset, test_dataset], ["train", "validation", "test"]) > for name in dataset.filenames] > > image_df = pd.DataFrame(image_data) But its still pretty complex so it might be better to unwind the comprehension and I'll add comments to explain it. # create an empty list to receive the dictionaries # we are about to create. image_data = [] # create a list of tuples of the form (dataset,"name") for dataset, type in zip(...as above...): # now extract file names from each dataset for name in dataset.filenames: # create a dictionary with the extracted data data = { "data":type, # one of: train, validation, test "class": name.split('/')[0], # first part of filename path(*) "filename":name.split(/)[1] # second part of filename path(*) } image_data.append(data) # add it to the list # create a Pandas data frame using out list of dicts image_df = pd.DataFrame(image_data) (8) - Note that this is incredibly fragile and should probably use the os.path module to extract the filename and path. The solution above relies on a very specific file structure. > In above code instead of zip files, The code above does not use zip files. The zip() function "zips" two sequences of data together. Experiment in the >>> prompt to see how it works: >>> list(zip([1,2,3],['a','b','c'])) [(1, 'a'), (2, 'b'), (3, 'c')] > I would like to upload files from my computer folder. That's what this seems to be doing although the exact nature of the data format is not clear. But somehow you would need to set the 'filenames' attribute of dataset.filenames. But where the three datasets are coming from is not clear in the code snippet you sent. > Please explain in details above code. Hopefully my deconstruction and explanation makes sense. But since it is not complete code we can't be sure what you need to do to meet your aims. -- 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 manpritsinghece at gmail.com Sat Nov 21 10:02:04 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sat, 21 Nov 2020 20:32:04 +0530 Subject: [Tutor] tuple unpacking Message-ID: Dear sir , I just need to know the definition of tuple unpacking. need to know if the examples that i am writing below belongs to tuple unpacking or not : Example 1 : >>> a, b, c = (2, 3, 6) >>> a 2 >>> b 3 >>> c 6 >>> Example 2: >>> x, y, z = [3, 6, 5] >>> x 3 >>> y 6 >>> z 5 >>> Example 3: >>> a, b, c, d = (i for i in range(1, 8) if i%2 != 0) >>> a 1 >>> b 3 >>> c 5 >>> d 7 >>> Similarly values in set and dicts keys can be assigned to variables written on the left side of the assignment statement , provided the number of variables on the left of the assignment statement must be equal to the iterable on right side . According to me these are all examples of tuple unpacking because variables written on the left side of the assignment statement in above given examples - a, b, c are nothing but a tuple, and we are unpacking the values of iterable on the right side to it is my understanding correct ? Regards Manprit Singh From martin at linux-ip.net Sat Nov 21 11:28:48 2020 From: martin at linux-ip.net (Martin A. Brown) Date: Sat, 21 Nov 2020 08:28:48 -0800 Subject: [Tutor] tuple unpacking In-Reply-To: References: Message-ID: Hi Manprit, > According to me these are all examples of tuple unpacking because variables > written on the left side of the assignment statement in above given > examples - a, b, c are nothing but a tuple, and we are unpacking the > values of iterable on the right side to it > > is my understanding correct ? I would say yes. > > I just need to know the definition of tuple unpacking. need to know if the > examples that i am writing below belongs to tuple unpacking or not : > > Example 1 : > >>> a, b, c = (2, 3, 6) > >>> a > 2 > >>> b > 3 > >>> c > 6 > >>> Let's try breaking your example in the interpreter. >>> a, b, c = (2, 3, 6) >>> a, b, c = (2, 3, 6, 7) Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack (expected 3) I see the word unpack. > Example 2: > >>> x, y, z = [3, 6, 5] > >>> x > 3 > >>> y > 6 > >>> z > 5 > >>> >>> x, y, z = [3, 6, 5, 7] Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack (expected 3) Example 2 is identical except that the right-hand side is a list, but yes, it's still an iterable. > Example 3: > >>> a, b, c, d = (i for i in range(1, 8) if i%2 != 0) > >>> a > 1 > >>> b > 3 > >>> c > 5 > >>> d > 7 > >>> >>> a, b, c, d = (i for i in range(1, 7) if i%2 != 0) Traceback (most recent call last): File "", line 1, in ValueError: not enough values to unpack (expected 4, got 3) Same deal, just a generator on the right hand side. > Similarly values in set and dicts keys can be assigned to > variables written on the left side of the assignment statement , > provided the number of variables on the left of the assignment > statement must be equal to the iterable on right side . And, one thing I do not do often enough is to take advantage of this: >>> f0, f1, *rest = fibonacci >>> f0 0 >>> f1 1 >>> rest [1, 2, 3, 5, 8] This allows you to grab a predictable number of elements in your unpacking and store the remainder for further processing later in the program. Nice usage of the interprter to demonstrate your question. -Martin -- Martin A. Brown http://linux-ip.net/ From alan.gauld at yahoo.co.uk Sat Nov 21 12:43:37 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 21 Nov 2020 17:43:37 +0000 Subject: [Tutor] tuple unpacking In-Reply-To: References: Message-ID: On 21/11/2020 15:02, Manprit Singh wrote: > Example 1 : >>>> a, b, c = (2, 3, 6) > Example 2: >>>> x, y, z = [3, 6, 5] > Example 3: >>>> a, b, c, d = (i for i in range(1, 8) if i%2 != 0) > Similarly values in set and dicts keys can be assigned to variables written > on the left side of the assignment statement , provided the number of > variables on the left of the assignment statement must be equal to the > iterable on right side . > > According to me these are all examples of tuple unpacking because variables > written on the left side of the assignment statement in above given > examples - a, b, c are nothing but a tuple, and we are unpacking the > values of iterable on the right side to it > > is my understanding correct ? Yes. -- 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 khoeilar at gmail.com Sun Nov 22 00:40:01 2020 From: khoeilar at gmail.com (Amir Khoeilar) Date: Sun, 22 Nov 2020 09:10:01 +0330 Subject: [Tutor] Tutor List - Amir Khoeilar Message-ID: Hi, This is Amir Khoeilar and I Just started learning Python. Most Definitely will need help. Best A.K From alan.gauld at yahoo.co.uk Sun Nov 22 07:39:44 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 22 Nov 2020 12:39:44 +0000 Subject: [Tutor] Tutor List - Amir Khoeilar In-Reply-To: References: Message-ID: On 22/11/2020 05:40, Amir Khoeilar wrote: > This is Amir Khoeilar and I Just started learning Python. Most Definitely > will need help. Welcome to the tutor list. Feel free to ask anything that puzzles you about Python, its library, or programming in general. If posting please note these points: 1) This is a text only list so binary attachments like screenshots will be stripped out by the server. 2) Always post code in your mail body using plain text not HTML. HTML results in the text formatting (the spacing) being lost which is very bad when dealing with python code! 3) Always include the full text of any error messages, they may seem like gibberish but actually hold a lot of detailed information. -- 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 Yuanyuan.A.Olsen at HealthPartners.Com Mon Nov 23 18:38:46 2020 From: Yuanyuan.A.Olsen at HealthPartners.Com (Olsen, Avalow Y) Date: Mon, 23 Nov 2020 23:38:46 +0000 Subject: [Tutor] sum() function Message-ID: Hi everyone, I am trying to sum up the integer numbers in a list like this: numbers = [1,2,3, 4,5,1,4,5] total = sum(numbers) print(total) _______________________________________________ --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in 4 numbers = [1,2,3,4,5,1,4,5] 5 ----> 6 total = sum(numbers) 7 print(total) 8 TypeError: 'int' object is not callable Don't understand why it doesn't work. I am using Anaconda Jupyter Notebook Python 3 Please help. Thank you for your help in advance! Ava ________________________________ This e-mail and any files transmitted with it are confidential and are intended solely for the use of the individual or entity to whom they are addressed. If you are not the intended recipient or the individual responsible for delivering the e-mail to the intended recipient, please be advised that you have received this e-mail in error and that any use, dissemination, forwarding, printing, or copying of this e-mail is strictly prohibited. If you have received this communication in error, please return it to the sender immediately and delete the original message and any copy of it from your computer system. If you have any questions concerning this message, please contact the sender. Disclaimer R001.0 From joel.goldstick at gmail.com Mon Nov 23 18:48:53 2020 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 23 Nov 2020 18:48:53 -0500 Subject: [Tutor] sum() function In-Reply-To: References: Message-ID: On Mon, Nov 23, 2020 at 6:40 PM Olsen, Avalow Y wrote: > > Hi everyone, > > > I am trying to sum up the integer numbers in a list like this: > > numbers = [1,2,3, 4,5,1,4,5] > > total = sum(numbers) > > print(total) > > _______________________________________________ > --------------------------------------------------------------------------- > TypeError Traceback (most recent call last) > in > 4 numbers = [1,2,3,4,5,1,4,5] > 5 > ----> 6 total = sum(numbers) > 7 print(total) > 8 > > TypeError: 'int' object is not callable > > I did this and it worked fine: >>> numbers = [1,2,3,4,5,1,4,5] >>> total = sum(numbers) >>> print(total) 25 Are you sure what you are providing in your email is exactly what you typed? Did you cut and paste or copy? > > Don't understand why it doesn't work. I am using Anaconda Jupyter Notebook Python 3 > > Please help. > > > > Thank you for your help in advance! > > Ava > > ________________________________ > > This e-mail and any files transmitted with it are confidential and are intended solely for the use of the individual or entity to whom they are addressed. If you are not the intended recipient or the individual responsible for delivering the e-mail to the intended recipient, please be advised that you have received this e-mail in error and that any use, dissemination, forwarding, printing, or copying of this e-mail is strictly prohibited. > > If you have received this communication in error, please return it to the sender immediately and delete the original message and any copy of it from your computer system. If you have any questions concerning this message, please contact the sender. Disclaimer R001.0 > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays From alan.gauld at yahoo.co.uk Mon Nov 23 18:55:15 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 23 Nov 2020 23:55:15 +0000 Subject: [Tutor] sum() function In-Reply-To: References: Message-ID: On 23/11/2020 23:38, Olsen, Avalow Y wrote: > --------------------------------------------------------------------------- > TypeError Traceback (most recent call last) > in > 4 numbers = [1,2,3,4,5,1,4,5] > 5 > ----> 6 total = sum(numbers) > 7 print(total) > 8 > > TypeError: 'int' object is not callable This suggests you have previously assigned sum to a number which is now hiding the function sum(). What is in the missing lines 1-3? -- 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 venku.analyst at gmail.com Mon Nov 23 19:31:28 2020 From: venku.analyst at gmail.com (Venku Prasad) Date: Mon, 23 Nov 2020 19:31:28 -0500 Subject: [Tutor] How to generate Dashboard kind of report using python. Message-ID: Hi Team, I am new to python and need to generate dashboard kind of reports using python. I need to keep report side by side bar chart,pie chart along with detail report. Please find attached sample data. Regards, Venkat, 5017654887. From alan.gauld at yahoo.co.uk Mon Nov 23 20:34:12 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 24 Nov 2020 01:34:12 +0000 Subject: [Tutor] How to generate Dashboard kind of report using python. In-Reply-To: References: Message-ID: On 24/11/2020 00:31, Venku Prasad wrote: > I am new to python and need to generate dashboard kind of reports using > python. Normally dashboards are web pages these days and that means you code the UI in Javascript using AJAX calls to a backend server. The server application could be written in Python and would serve up a dataset of some kind(a tuple of dicts for example) formatted in JSON. > I need to keep report side by side bar chart,pie chart along with detail > report. > Please find attached sample data. This is a text only list so any kind of binary attachment (Word doc, screenshot etc) gets stripped by the server for security reasons. If you are building a desktop app then the UI will depend to some extent on the GUI framework you choose - Tkinter, wxPython, GTk, Qt etc. There are tools for generating the graphs (eg gnuplot, matplotlib etc), usually these can be presented on a canvas in your GUI. But so much depends on the nature of your app and the GUI framework and even how the data is stored and managed - SQL or noSQL, R Dataframes, Flat files... -- 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 Nov 23 20:41:21 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 24 Nov 2020 01:41:21 +0000 Subject: [Tutor] [EXTERNAL]Re: sum() function In-Reply-To: References: Message-ID: <4bea6f56-4c1e-96ac-57ed-8efd524826e2@yahoo.co.uk> Always use Reply-All when responding to tutor list posts. On 24/11/2020 01:06, Olsen, Avalow Y wrote: > This is my complete code. > > numbers = [1,2,3,4,5,1,4,5] > total = sum(numbers) > print(total) > --------------------------------------------------------------------------- > TypeError Traceback (most recent call last) > in > 1 numbers = [1,2,3,4,5,1,4,5] > ----> 2 total = sum(numbers) > 3 print(total) > > TypeError: 'int' object is not callable OK, That should not error in any version of Python. How are you running the code? Is it in a file? Or are you typing it straight into the interpreter in Jupyter? If the latter I'd restart Jupyter and try again. I suspect it may be holding onto an old assignment of sum. Other things to try: print(sum([1,2,3,4,5,1,4,5])) help(sum) If its a file try running it in the vanilla python interpreter outside Jupyter. -- 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 Yuanyuan.A.Olsen at HealthPartners.Com Mon Nov 23 21:37:14 2020 From: Yuanyuan.A.Olsen at HealthPartners.Com (Olsen, Avalow Y) Date: Tue, 24 Nov 2020 02:37:14 +0000 Subject: [Tutor] [EXTERNAL]Re: sum() function In-Reply-To: <4bea6f56-4c1e-96ac-57ed-8efd524826e2@yahoo.co.uk> References: <4bea6f56-4c1e-96ac-57ed-8efd524826e2@yahoo.co.uk> Message-ID: Thanks, Alan! I was typing it straight into the interpreter in Jupyter. I restarted Jupyter and tried again. The problem went away. By the way, there was no a sum variable in the previous assignments. The sum function didn?t work in my program. I created this snippet of test code to test the sum function. And you know the rest of the story. Thanks everyone for the help! This is such a supportive and enthusiastic community. I am proud to be part of it! Ava -----Original Message----- From: Alan Gauld [mailto:alan.gauld at yahoo.co.uk] Sent: Monday, November 23, 2020 7:41 PM To: Olsen, Avalow Y Cc: tutor Subject: Re: [EXTERNAL]Re: [Tutor] sum() function Always use Reply-All when responding to tutor list posts. On 24/11/2020 01:06, Olsen, Avalow Y wrote: > This is my complete code. > > numbers = [1,2,3,4,5,1,4,5] > total = sum(numbers) > print(total) > --------------------------------------------------------------------------- > TypeError Traceback (most recent call last) > in > 1 numbers = [1,2,3,4,5,1,4,5] > ----> 2 total = sum(numbers) > 3 print(total) > > TypeError: 'int' object is not callable OK, That should not error in any version of Python. How are you running the code? Is it in a file? Or are you typing it straight into the interpreter in Jupyter? If the latter I'd restart Jupyter and try again. I suspect it may be holding onto an old assignment of sum. Other things to try: print(sum([1,2,3,4,5,1,4,5])) help(sum) If its a file try running it in the vanilla python interpreter outside Jupyter. -- 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 ________________________________ This e-mail and any files transmitted with it are confidential and are intended solely for the use of the individual or entity to whom they are addressed. If you are not the intended recipient or the individual responsible for delivering the e-mail to the intended recipient, please be advised that you have received this e-mail in error and that any use, dissemination, forwarding, printing, or copying of this e-mail is strictly prohibited. If you have received this communication in error, please return it to the sender immediately and delete the original message and any copy of it from your computer system. If you have any questions concerning this message, please contact the sender. Disclaimer R001.0 From nathan-tech at hotmail.com Tue Nov 24 20:16:15 2020 From: nathan-tech at hotmail.com (nathan tech) Date: Wed, 25 Nov 2020 01:16:15 +0000 Subject: [Tutor] accessing the CD rom Message-ID: Hello folks, I was wondering if anyone has any recommendations for modules or methods for accessing the disk drive? I am using windows and have had very little luck installing the pycdio library and it appears the cd module was taken out in python 2.6? To be clear I'm looking to: 1. Check if there is a CD is the drive. 2. Eject the drive. 3. Play the tracks from the drive. The third I'm able to handle already, the thing I'm not sure is how to check for the drive and, then, to eject it. Thanks in advance. Nathan From PyTutor at DancesWithMice.info Tue Nov 24 20:51:29 2020 From: PyTutor at DancesWithMice.info (dn) Date: Wed, 25 Nov 2020 14:51:29 +1300 Subject: [Tutor] accessing the CD rom In-Reply-To: References: Message-ID: <8dfc19e3-0a6c-cfcd-07d2-39437e99f301@DancesWithMice.info> > I was wondering if anyone has any recommendations for modules or methods > for accessing the disk drive? > > I am using windows and have had very little luck installing the pycdio > library and it appears the cd module was taken out in python 2.6? > > > To be clear I'm looking to: > > 1. Check if there is a CD is the drive. > > 2. Eject the drive. > > 3. Play the tracks from the drive. > > > The third I'm able to handle already, the thing I'm not sure is how to > check for the drive and, then, to eject it. From the choice of language above, MS-Win is assumed. I don't use it, so won't make a specific recommendation. However, a quick web-search offered several alternatives: https://duckduckgo.com/?q=python+eject+(cd+OR+dvd) -- Regards =dn From nathan-tech at hotmail.com Tue Nov 24 21:02:49 2020 From: nathan-tech at hotmail.com (nathan tech) Date: Wed, 25 Nov 2020 02:02:49 +0000 Subject: [Tutor] accessing the CD rom In-Reply-To: <8dfc19e3-0a6c-cfcd-07d2-39437e99f301@DancesWithMice.info> References: <8dfc19e3-0a6c-cfcd-07d2-39437e99f301@DancesWithMice.info> Message-ID: Heya, Ironically, just after I sent the message to this list I also stumbled across the stackoverflow answer you referenced in that link. I also however found out that CDA files are just windows way of, for lack of a better word, they are shortcuts to the actual audio tracks on the disk. This has left me stumped and slightly frustrated as I'm not sure where to go from here in my research in so far as accessing the actual track files from python for examination in terms of their tags, or for backup purposes. Thanks for any tips, Nathan On 25/11/2020 01:51, dn via Tutor wrote: >> I was wondering if anyone has any recommendations for modules or >> methods for accessing the disk drive? >> >> I am using windows and have had very little luck installing the >> pycdio library and it appears the cd module was taken out in python 2.6? >> >> >> To be clear I'm looking to: >> >> 1. Check if there is a CD is the drive. >> >> 2. Eject the drive. >> >> 3. Play the tracks from the drive. >> >> >> The third I'm able to handle already, the thing I'm not sure is how >> to check for the drive and, then, to eject it. > > From the choice of language above, MS-Win is assumed. I don't use it, > so won't make a specific recommendation. However, a quick web-search > offered several alternatives: > https://eur02.safelinks.protection.outlook.com/?url=https%3A%2F%2Fduckduckgo.com%2F%3Fq%3Dpython%2Beject&data=04%7C01%7C%7C2a83eb9dd0b943b6275808d890e4d699%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637418659819134023%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C1000&sdata=gSEfEGUj3Ip1mMi%2BWvkbmqo0PFtRKmiJun9%2FXM1ueGM%3D&reserved=0+(cd+OR+dvd) From anithak1 at systechusa.com Wed Nov 25 01:37:00 2020 From: anithak1 at systechusa.com (Anitha Kothandan) Date: Wed, 25 Nov 2020 06:37:00 +0000 Subject: [Tutor] DataFrame to Nested JSON Conversion issue Message-ID: Hi Guys, I am trying to convert a DataFrame into Nested json. The Policy column value should be an json object instead of an array(square brackets should not be there). Mentioned the code, expected output and screenshots below. Kindly help me out here. Thanks in Advance!! Code: import pandas as pd import json Data=pd.DataFrame() x='{"Specversion":"1.0","PolicyID":"0123456789","EventID":"20201124030503-1000","Division":"LID"}' Data=pd.io.json.json_normalize(json.loads(x)) Data=Data.groupby(['Specversion','PolicyID'])[['EventID','Division']].apply(lambda g: g.to_dict(orient="records")).reset_index(name="Policy") Data['Final_json']=Data.apply(lambda x: x.to_json(date_format='iso'), axis=1) print(json.dumps(json.loads(Data['Final_json'][0]),indent=2,sort_keys=False)) Expected Output: { "Specversion": "1.0", "PolicyID": "0123456789", "Policy": { "EventID": "20201124030503-1000", "Division": "LID" } } Screenshot [cid:image001.png at 01D6C323.74E7D370] Thanks, Anitha From mats at wichmann.us Wed Nov 25 19:53:06 2020 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 25 Nov 2020 17:53:06 -0700 Subject: [Tutor] DataFrame to Nested JSON Conversion issue In-Reply-To: References: Message-ID: <4914da83-40cf-053d-05f7-0373171562b4@wichmann.us> On 11/24/20 11:37 PM, Anitha Kothandan wrote: > Hi Guys, > > I am trying to convert a DataFrame into Nested json. The Policy column value should be an json object instead of an array(square brackets should not be there). Mentioned the code, expected output and screenshots below. Kindly help me out here. Thanks in Advance!! > > Code: > import pandas as pd > import json > Data=pd.DataFrame() > x='{"Specversion":"1.0","PolicyID":"0123456789","EventID":"20201124030503-1000","Division":"LID"}' > Data=pd.io.json.json_normalize(json.loads(x)) > Data=Data.groupby(['Specversion','PolicyID'])[['EventID','Division']].apply(lambda g: g.to_dict(orient="records")).reset_index(name="Policy") > Data['Final_json']=Data.apply(lambda x: x.to_json(date_format='iso'), axis=1) > print(json.dumps(json.loads(Data['Final_json'][0]),indent=2,sort_keys=False)) you're doing so many things in one go that there's no way to see what's going wrong: Data=Data.groupby(['Specversion','PolicyID'])[['EventID','Division']].apply(lambda g: g.to_dict(orient="records")).reset_index(name="Policy") something there is making a list with the dict as an element (which then has to be constructed in json in the way you don't want), rather than just the dict. Simplify into discrete steps with examination at each step if possible, so you can watch the data get transformed. From beachkidken at gmail.com Thu Nov 26 19:37:08 2020 From: beachkidken at gmail.com (Ken Green) Date: Thu, 26 Nov 2020 19:37:08 -0500 Subject: [Tutor] Using 'with open' statementfor reading a file two lines at a time Message-ID: Gentlemen and ladies: I am using 'with open' statement to read a file two lines at a time and then combining them together to print the results into another file. I can read the first two lines, combine them and print the result into another file and then that is it. Just the first and second lines were printed and save. How can I continue reading the third and fourth lines and so forth on until the end of the file? I am using Python 3.8.5 under Ubuntu 20.04.1 with using Thonny 3.3.0 (2020-11-5) as an interface. I used to use Geany but discovered the latest version doesn't work in Ubuntu 20.04 and it only applicable for Windows and Apple and there is no Linux version according to its website. Thanking you all in advance, Ken From alan.gauld at yahoo.co.uk Thu Nov 26 20:00:05 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 27 Nov 2020 01:00:05 +0000 Subject: [Tutor] Using 'with open' statementfor reading a file two lines at a time In-Reply-To: References: Message-ID: On 27/11/2020 00:37, Ken Green wrote: > I am using 'with open' statement to read a file two lines at a time and > then combining them together to print the results into another file. Please don't just describe your code and think we can guess what you've done. Post the actual code and any actual error messages in full. There must be at least half a dozen ways to do what you describe. We can't fix what we can't see. > How can I continue reading the third and fourth lines and so forth on > until the end of the file? You need to use a loop, either a 'while' or 'for' But without seeing what you've done so far I can't say more than that. > (2020-11-5) as an interface. I used to use Geany but discovered the > latest version doesn't work in Ubuntu 20.04 and it only applicable for > Windows and Apple and there is no Linux version according to its website. I'm pretty sure there is a Linux version, in fact I just checked and v1.37 has just been released on Linux as well as Windoze and MacOS. v1.36 is available in the software tool for my Linux Mint 20 which is based on Ubuntu 20 so you should definitely be able to get it working. But if not there are a zillion other code editors out there that will do just fine! -- 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 Thu Nov 26 20:23:35 2020 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 26 Nov 2020 18:23:35 -0700 Subject: [Tutor] Using 'with open' statementfor reading a file two lines at a time In-Reply-To: References: Message-ID: <3b6fbddd-666a-1777-1377-9a1b28f94ee5@wichmann.us> On 11/26/20 6:00 PM, Alan Gauld via Tutor wrote: > On 27/11/2020 00:37, Ken Green wrote: > >> I am using 'with open' statement to read a file two lines at a time and >> then combining them together to print the results into another file. > > Please don't just describe your code and think we can guess > what you've done. > > Post the actual code and any actual error messages in full. > > There must be at least half a dozen ways to do what you describe. > We can't fix what we can't see. > >> How can I continue reading the third and fourth lines and so forth on >> until the end of the file? > > You need to use a loop, either a 'while' or 'for' > But without seeing what you've done so far I can't say more than that. > >> (2020-11-5) as an interface. I used to use Geany but discovered the >> latest version doesn't work in Ubuntu 20.04 and it only applicable for >> Windows and Apple and there is no Linux version according to its website. > > I'm pretty sure there is a Linux version, in fact I just checked > and v1.37 has just been released on Linux as well as Windoze and > MacOS. > v1.36 is available in the software tool for my Linux Mint 20 which > is based on Ubuntu 20 so you should definitely be able to get > it working. I checked in Fedora, and it remains a supported package there. Perhaps - we can only guess - what they meant is that they don't make Linux packages, because the distributions still make Linux packages. And, looking in an Ubuntu VM - geany is available there as a package too. > But if not there are a zillion other code editors out there that > will do just fine! Take a look here for some (it's certainly not a complete list!) https://wiki.python.org/moin/IntegratedDevelopmentEnvironments I've used several of these and most of the ones I've used are quite good (Visual Studio Code is quite popular at the moment, technically it's not an IDE but extensions basically make it so, PyCharm is excellent and the community version is not very limited, WingIDE is the old standby that still has a good no-cost version, and Thonny is a nice free lightweight one. Amongst ones not on the page the Atom editor also does a fine job on Python). From beachkidken at gmail.com Thu Nov 26 20:32:30 2020 From: beachkidken at gmail.com (Ken Green) Date: Thu, 26 Nov 2020 20:32:30 -0500 Subject: [Tutor] Using 'with open' statementfor reading a file two lines at a time In-Reply-To: References: Message-ID: On 11/26/20 8:00 PM, Alan Gauld via Tutor wrote: > On 27/11/2020 00:37, Ken Green wrote: > >> I am using 'with open' statement to read a file two lines at a time and >> then combining them together to print the results into another file. > Please don't just describe your code and think we can guess > what you've done. > > Post the actual code and any actual error messages in full. > > There must be at least half a dozen ways to do what you describe. > We can't fix what we can't see. > >> How can I continue reading the third and fourth lines and so forth on >> until the end of the file? > You need to use a loop, either a 'while' or 'for' > But without seeing what you've done so far I can't say more than that. > >> (2020-11-5) as an interface. I used to use Geany but discovered the >> latest version doesn't work in Ubuntu 20.04 and it only applicable for >> Windows and Apple and there is no Linux version according to its website. > I'm pretty sure there is a Linux version, in fact I just checked > and v1.37 has just been released on Linux as well as Windoze and > MacOS. > v1.36 is available in the software tool for my Linux Mint 20 which > is based on Ubuntu 20 so you should definitely be able to get > it working. > > But if not there are a zillion other code editors out there that > will do just fine! I humbly apologized Alan. Below is the code: # Daily Three Pick Three 99 Combine Test py # 11/26/2020 import sys filename1 = "Pick_Three_Drawings_File.txt" filename2 = "Pick_Three_Drawings_File_Combine.txt" file1 = open(filename1, "r") file2 = open(filename2, "w") with open(filename1) as file1: ??? line1 = file1.readline().strip() ??? line2 = file1.readline().strip() ??? line3 = (line1 + line2) ??? line4 = (line3[ 0: 4] + line3[ 4: 6] + line3[ 6: 8] + line3[ 8: 9] + line3[ 9:12] + line3[20:21] + line3[21:24]) ??? file2.write(line4) file1.close() file2.close() From beachkidken at gmail.com Thu Nov 26 20:34:05 2020 From: beachkidken at gmail.com (Ken Green) Date: Thu, 26 Nov 2020 20:34:05 -0500 Subject: [Tutor] Using 'with open' statementfor reading a file two lines at a time In-Reply-To: References: Message-ID: On 11/26/20 8:00 PM, Alan Gauld via Tutor wrote: > On 27/11/2020 00:37, Ken Green wrote: > >> I am using 'with open' statement to read a file two lines at a time and >> then combining them together to print the results into another file. > Please don't just describe your code and think we can guess > what you've done. > > Post the actual code and any actual error messages in full. > > There must be at least half a dozen ways to do what you describe. > We can't fix what we can't see. > >> How can I continue reading the third and fourth lines and so forth on >> until the end of the file? > You need to use a loop, either a 'while' or 'for' > But without seeing what you've done so far I can't say more than that. > >> (2020-11-5) as an interface. I used to use Geany but discovered the >> latest version doesn't work in Ubuntu 20.04 and it only applicable for >> Windows and Apple and there is no Linux version according to its website. > I'm pretty sure there is a Linux version, in fact I just checked > and v1.37 has just been released on Linux as well as Windoze and > MacOS. > v1.36 is available in the software tool for my Linux Mint 20 which > is based on Ubuntu 20 so you should definitely be able to get > it working. > > But if not there are a zillion other code editors out there that > will do just fine! Sorry, I forgot to mention there is no error code. From Yuanyuan.A.Olsen at HealthPartners.Com Thu Nov 26 21:35:45 2020 From: Yuanyuan.A.Olsen at HealthPartners.Com (Olsen, Avalow Y) Date: Fri, 27 Nov 2020 02:35:45 +0000 Subject: [Tutor] [EXTERNAL]Re: Using 'with open' statementfor reading a file two lines at a time In-Reply-To: References: Message-ID: Could Something like this work? I didn?t test it out. More like pseudo code... Handle1= open('file1', 'r') Handle2 = open('file2', 'w') Count= 0 Lst = [] For line in handle1: Count = count+1 Lst.append(line) if count%2 = 0: handle2.write(lst) lst = [] file1 = open(filename1, "r") file2 = open(filename2, "w") with open(filename1) as file1: line1 = file1.readline().strip() line2 = file1.readline().strip() line3 = (line1 + line2) line4 = (line3[ 0: 4] + line3[ 4: 6] + line3[ 6: 8] + line3[ 8: 9] + line3[ 9:12] + line3[20:21] + line3[21:24]) file2.write(line4) file1.close() file2.close() -----Original Message----- From: Tutor [mailto:tutor-bounces+yuanyuan.a.olsen=healthpartners.com at python.org] On Behalf Of Ken Green Sent: Thursday, November 26, 2020 7:33 PM To: tutor at python.org Subject: [EXTERNAL]Re: [Tutor] Using 'with open' statementfor reading a file two lines at a time External Email: Don't click links or attachments unless you trust the email. On 11/26/20 8:00 PM, Alan Gauld via Tutor wrote: > On 27/11/2020 00:37, Ken Green wrote: > >> I am using 'with open' statement to read a file two lines at a time >> and then combining them together to print the results into another file. > Please don't just describe your code and think we can guess what > you've done. > > Post the actual code and any actual error messages in full. > > There must be at least half a dozen ways to do what you describe. > We can't fix what we can't see. > >> How can I continue reading the third and fourth lines and so forth on >> until the end of the file? > You need to use a loop, either a 'while' or 'for' > But without seeing what you've done so far I can't say more than that. > >> (2020-11-5) as an interface. I used to use Geany but discovered the >> latest version doesn't work in Ubuntu 20.04 and it only applicable >> for Windows and Apple and there is no Linux version according to its website. > I'm pretty sure there is a Linux version, in fact I just checked and > v1.37 has just been released on Linux as well as Windoze and MacOS. > v1.36 is available in the software tool for my Linux Mint 20 which is > based on Ubuntu 20 so you should definitely be able to get it working. > > But if not there are a zillion other code editors out there that will > do just fine! I humbly apologized Alan. Below is the code: # Daily Three Pick Three 99 Combine Test py # 11/26/2020 import sys filename1 = "Pick_Three_Drawings_File.txt" filename2 = "Pick_Three_Drawings_File_Combine.txt" file1 = open(filename1, "r") file2 = open(filename2, "w") with open(filename1) as file1: line1 = file1.readline().strip() line2 = file1.readline().strip() line3 = (line1 + line2) line4 = (line3[ 0: 4] + line3[ 4: 6] + line3[ 6: 8] + line3[ 8: 9] + line3[ 9:12] + line3[20:21] + line3[21:24]) file2.write(line4) file1.close() file2.close() _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ________________________________ This e-mail and any files transmitted with it are confidential and are intended solely for the use of the individual or entity to whom they are addressed. If you are not the intended recipient or the individual responsible for delivering the e-mail to the intended recipient, please be advised that you have received this e-mail in error and that any use, dissemination, forwarding, printing, or copying of this e-mail is strictly prohibited. If you have received this communication in error, please return it to the sender immediately and delete the original message and any copy of it from your computer system. If you have any questions concerning this message, please contact the sender. Disclaimer R001.0 From cs at cskk.id.au Thu Nov 26 22:34:19 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Fri, 27 Nov 2020 14:34:19 +1100 Subject: [Tutor] Using 'with open' statementfor reading a file two lines at a time In-Reply-To: References: Message-ID: <20201127033419.GA38385@cskk.homeip.net> On 26Nov2020 20:32, Ken Green wrote: >On 11/26/20 8:00 PM, Alan Gauld via Tutor wrote: >>Post the actual code and any actual error messages in full. [...] Ok, a few remarks inline in the code... ># Daily Three Pick Three 99 Combine Test py ># 11/26/2020 >import sys >filename1 = "Pick_Three_Drawings_File.txt" >filename2 = "Pick_Three_Drawings_File_Combine.txt" >file1 = open(filename1, "r") The "with open" idiom in Python goes like your main with statement: with open(filename1) as file1: which is preferred because it will close the file automatically for you (even if there's some exception). The open above (a) isn't using that idiom and (b) is ignored because you open filename1 again below in your "with" statement. >file2 = open(filename2, "w") >with open(filename1) as file1: Same with file2. I'd write: with open(filename1) as file1: with open(filename2, 'w') as file2: This has 2 advantages: The big one is that the with statements arrange to close the files when you exit the with statement, reliably and without extra work. The second one is that we open file2 second. That way if the open of file1 (for read) fails, we don't open file2 at all. And opening file2 is a destructive action - it overwrites filename2. So we defer that until we know opening filename1 went well. With the "with" statements you can discard the "file1.close()" and "file2.close()" below. >??? line1 = file1.readline().strip() >??? line2 = file1.readline().strip() >??? line3 = (line1 + line2) >??? line4 = (line3[ 0: 4] + line3[ 4: 6] + line3[ 6: 8] + line3[ 8: 9] >+ line3[ 9:12] + line3[20:21] + line3[21:24]) >??? file2.write(line4) This is the main body of your with statement, which reads the first 2 lines of the file, combines them and writes to file2. There's no loop of any kind here, so naturally it happens only once. The usual idiom for reading lines of text from a file looks like this: for line1 in file1: ... do something with ine1 ... Now, you want pairs of lines. So inside the loop you would want to grab the next line: for line1 in file1: ... get line2 ... combine and write to file2 which will process the whole file. Now, you _could_ just go: for line1 in file1: line2 = file1.readline() combine and write to file2 and it would probably work. Alternatively you could look at _how_ the for-loop reads the file. A Python for-loop iterates over what you give it. A text file is an "iterable" thing, and when you do that you get lines of text. So you could pull out the iterator, and use that: lines = iter(file1) for line1 in lines: line2 = next(lines) ... combine and write to file2 ... This works because "lines" is an iterator, which returns lines from the file1. If you've got an iterator (of anything) you can get the next value with the next() function, which we use to obtain line2. Cheers, Cameron Simpson From PyTutor at DancesWithMice.info Thu Nov 26 23:05:18 2020 From: PyTutor at DancesWithMice.info (dn) Date: Fri, 27 Nov 2020 17:05:18 +1300 Subject: [Tutor] Using 'with open' statementfor reading a file two lines at a time In-Reply-To: References: Message-ID: > I am using 'with open' statement to read a file two lines at a time and then combining them together to print the results into another file. I can read the first two lines, combine them and print the result into another file and then that is it. Just the first and second lines were printed and save. > > How can I continue reading the third and fourth lines and so forth on until the end of the file? > # Daily Three Pick Three 99 Combine Test py > # 11/26/2020 > import sys Why import the sys library? Where is it used in the code? > filename1 = "Pick_Three_Drawings_File.txt" > filename2 = "Pick_Three_Drawings_File_Combine.txt" > file1 = open(filename1, "r") > file2 = open(filename2, "w") The two files are now open (assuming no run-time exception). So, on the next line, it is not necessary to open file1 again! * > with open(filename1) as file1: Am wondering if you are thinking that the with (Context Manager) has some looping function? It doesn't. > ??? line1 = file1.readline().strip() > ??? line2 = file1.readline().strip() > ??? line3 = (line1 + line2) Given that there is only a concatenation operation there is no need for the parentheses (which indicate which operation(s) should have priority execution). The same applies on the next line, given that the usual left-to-right 'priority' is applicable. > ??? line4 = (line3[ 0: 4] + line3[ 4: 6] + line3[ 6: 8] + line3[ 8: 9] > + line3[ 9:12] + line3[20:21] + line3[21:24]) The specification didn't mention this, beyond "combining". Why not: line4 = line3[ :12 ] + line3[ 20:24 ] > ??? file2.write(line4) > file1.close() > file2.close() So, to answer the question: - create a loop using a while statement to replace the with - set the while-condition to True, ie an infinite loop - wrap the two readline()-s into a try-except block - catch the end-of-file exception (EOFError) and break (break will 'stop' the while-loop) - which will execute the two close()-s Web.Refs: https://docs.python.org/3/tutorial/introduction.html?highlight=concatenation https://docs.python.org/3/reference/compound_stmts.html https://docs.python.org/3/library/exceptions.html * If you prefer the context manager (which I probably would) and understand their use-and-abuse, then it is possible to open multiple files using a 'nested with' construct. An example: https://deeplearning.lipingyang.org/2017/01/15/open-multiple-files-using-open-and-with-open-in-python/ but please note that the try-except as-illustrated, is designed to catch errors at the file-level, eg file does not exist, or file cannot be opened; ie the "run-time exception" mentioned above; and is quite a separate consideration from the try-except block proposed in "answer" (above)! -- Regards =dn From breamoreboy at gmail.com Thu Nov 26 21:03:49 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Fri, 27 Nov 2020 02:03:49 +0000 Subject: [Tutor] Using 'with open' statementfor reading a file two lines at a time In-Reply-To: References: Message-ID: <1d8c3fe9-5bb2-866b-1f36-a5f493592ca1@gmail.com> On 27/11/2020 01:32, Ken Green wrote: > On 11/26/20 8:00 PM, Alan Gauld via Tutor wrote: >> On 27/11/2020 00:37, Ken Green wrote: >> >>> I am using 'with open' statement to read a file two lines at a time and >>> then combining them together to print the results into another file. >> Please don't just describe your code and think we can guess >> what you've done. >> >> Post the actual code and any actual error messages in full. >> >> There must be at least half a dozen ways to do what you describe. >> We can't fix what we can't see. >> >>> How can I continue reading the third and fourth lines and so forth on >>> until the end of the file? >> You need to use a loop, either a 'while' or 'for' >> But without seeing what you've done so far I can't say more than that. >> >>> (2020-11-5) as an interface. I used to use Geany but discovered the >>> latest version doesn't work in Ubuntu 20.04 and it only applicable for >>> Windows and Apple and there is no Linux version according to its >>> website. >> I'm pretty sure there is a Linux version, in fact I just checked >> and v1.37 has just been released on Linux as well as Windoze and >> MacOS. >> v1.36 is available in the software tool for my Linux Mint 20 which >> is based on Ubuntu 20 so you should definitely be able to get >> it working. >> >> But if not there are a zillion other code editors out there that >> will do just fine! > I humbly apologized Alan. Below is the code: > > # Daily Three Pick Three 99 Combine Test py > # 11/26/2020 > import sys > filename1 = "Pick_Three_Drawings_File.txt" > filename2 = "Pick_Three_Drawings_File_Combine.txt" > file1 = open(filename1, "r") > file2 = open(filename2, "w") > with open(filename1) as file1: > ??? line1 = file1.readline().strip() > ??? line2 = file1.readline().strip() You're not looping so you'll only ever read two lines from the file. See this https://stackoverflow.com/questions/1657299/how-do-i-read-two-lines-from-a-file-at-a-time-using-python for how to do it. > ??? line3 = (line1 + line2) > ??? line4 = (line3[ 0: 4] + line3[ 4: 6] + line3[ 6: 8] + line3[ 8: 9] > + line3[ 9:12] + line3[20:21] + line3[21:24]) > ??? file2.write(line4) > file1.close() > file2.close() > You don't need to close the files, 'with open' does that for you automatically. Mark Lawrence. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at gmail.com Thu Nov 26 21:31:32 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Fri, 27 Nov 2020 02:31:32 +0000 Subject: [Tutor] Using 'with open' statementfor reading a file two lines at a time In-Reply-To: References: Message-ID: On 27/11/2020 01:32, Ken Green wrote: > On 11/26/20 8:00 PM, Alan Gauld via Tutor wrote: >> On 27/11/2020 00:37, Ken Green wrote: >> >>> I am using 'with open' statement to read a file two lines at a time and >>> then combining them together to print the results into another file. >> Please don't just describe your code and think we can guess >> what you've done. >> >> Post the actual code and any actual error messages in full. >> >> There must be at least half a dozen ways to do what you describe. >> We can't fix what we can't see. >> >>> How can I continue reading the third and fourth lines and so forth on >>> until the end of the file? >> You need to use a loop, either a 'while' or 'for' >> But without seeing what you've done so far I can't say more than that. >> >>> (2020-11-5) as an interface. I used to use Geany but discovered the >>> latest version doesn't work in Ubuntu 20.04 and it only applicable for >>> Windows and Apple and there is no Linux version according to its >>> website. >> I'm pretty sure there is a Linux version, in fact I just checked >> and v1.37 has just been released on Linux as well as Windoze and >> MacOS. >> v1.36 is available in the software tool for my Linux Mint 20 which >> is based on Ubuntu 20 so you should definitely be able to get >> it working. >> >> But if not there are a zillion other code editors out there that >> will do just fine! > I humbly apologized Alan. Below is the code: > > # Daily Three Pick Three 99 Combine Test py > # 11/26/2020 > import sys > filename1 = "Pick_Three_Drawings_File.txt" > filename2 = "Pick_Three_Drawings_File_Combine.txt" > file1 = open(filename1, "r") > file2 = open(filename2, "w") > with open(filename1) as file1: > ??? line1 = file1.readline().strip() > ??? line2 = file1.readline().strip() There's no loop so you'll only ever read two lines from the file. See this https://stackoverflow.com/questions/1657299/how-do-i-read-two-lines-from-a-file-at-a-time-using-python for how to read two lines at a time. > ??? line3 = (line1 + line2) > ??? line4 = (line3[ 0: 4] + line3[ 4: 6] + line3[ 6: 8] + line3[ 8: 9] > + line3[ 9:12] + line3[20:21] + line3[21:24]) > ??? file2.write(line4) > file1.close() > file2.close() > You don't need the calls to 'close', the 'with open' does that automatically. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From bernardoaugustorebelo11 at gmail.com Fri Nov 27 14:54:25 2020 From: bernardoaugustorebelo11 at gmail.com (Bernardo Rebelo) Date: Fri, 27 Nov 2020 19:54:25 +0000 Subject: [Tutor] lists Message-ID: Hi I would like to know how to check if an element in a list is greater than the next element on the same list like this [5,4,3,2,1] if 5 > 4 > 3 > 2 > 1 return True in an example like this one [5,4,5,2], it would give False. best regards, From nathan-tech at hotmail.com Fri Nov 27 16:09:34 2020 From: nathan-tech at hotmail.com (nathan tech) Date: Fri, 27 Nov 2020 21:09:34 +0000 Subject: [Tutor] lists In-Reply-To: References: Message-ID: Hello, Would not this work? if(l[0]>l[1]): ?print("all is well.") Or if you wanted to look at the whole list something like: def is_great(l): ?pos=0 ?for x in range(l): ? if(x==len(l)): ?? return True ?if(l[x]>l[x+1]): ?? return False May need some slight bug checks on that function as I threw it together off the top of my head but. HTH Nathan On 27/11/2020 19:54, Bernardo Rebelo wrote: > Hi I would like to know how to check if an element in a list is greater > than the next element on the same list like this > > [5,4,3,2,1] > > if 5 > 4 > 3 > 2 > 1 > return True > > in an example like this one [5,4,5,2], it would give False. > > best regards, > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://nam11.safelinks.protection.outlook.com/?url=https%3A%2F%2Fmail.python.org%2Fmailman%2Flistinfo%2Ftutor&data=04%7C01%7C%7Cf39ed758a60349382e9408d893182d0b%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637421079326204248%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C1000&sdata=f4mJyKL0z6kLn8NKbBJmZG3%2FTuDs%2FbnLYDfHnkEd3l4%3D&reserved=0 From alan.gauld at yahoo.co.uk Fri Nov 27 18:45:08 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 27 Nov 2020 23:45:08 +0000 Subject: [Tutor] lists In-Reply-To: References: Message-ID: On 27/11/2020 19:54, Bernardo Rebelo wrote: > Hi I would like to know how to check if an element in a list is greater > than the next element on the same list like this > > [5,4,3,2,1] > > if 5 > 4 > 3 > 2 > 1 > return True > > in an example like this one [5,4,5,2], it would give False. You need to write some code. You probably want a loop that starts at the first element and goes up the the second last comparing each with the next in line. Or, slightly easier to do in python, one that starts at the second element through to the end and compares wit the previous to see if its less. We can do that using a slice. We don't do homework for people and I'm not sure if this is homework or not, so just in case here is some psuedo code: >>> l1 = [5,4,3,2,1] >>> l2 = [5,4,5,3,1] >>> def check(L): for index,item in enumerate(L[1:]): check if item is less than L[index} if not return False if it is continue to the next item if all are ok return True >>> check(l1) True >>> check(l2) False >>> 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 alexkleider at protonmail.com Sat Nov 28 01:17:13 2020 From: alexkleider at protonmail.com (alexkleider) Date: Sat, 28 Nov 2020 06:17:13 +0000 Subject: [Tutor] Curses Python: F1 => Xfce Terminal documentation Message-ID: In going through some of the examples in Alan's 'translation' of the curses documentation, specifically Example 7: The F1 key seems to be intercepted by the Xfce Terminal in spite of using wrapper. I added "keypad(True)" but to no avail. A work around is to us 'H' (for help) rather than a function key but the documentation indicates that function keys should work. My system is Debian 10 with Xfce. TIA Alex From cs at cskk.id.au Sat Nov 28 03:06:47 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Sat, 28 Nov 2020 19:06:47 +1100 Subject: [Tutor] Curses Python: F1 => Xfce Terminal documentation In-Reply-To: References: Message-ID: <20201128080647.GA39264@cskk.homeip.net> On 28Nov2020 06:17, alexkleider wrote: >In going through some of the examples in Alan's 'translation' of the curses documentation, specifically Example 7: >The F1 key seems to be intercepted by the Xfce Terminal in spite of using wrapper. I added "keypad(True)" but to no avail. >A work around is to us 'H' (for help) rather than a function key but the documentation indicates that function keys should work. >My system is Debian 10 with Xfce. 1: Anything here? https://docs.xfce.org/apps/xfce4-terminal/preferences There's a "Disable help window shortcut key (F1 by default)" That also suggests you can bind a different key other than F1 for this. Also: https://docs.xfce.org/faq#keyboard_related 2: What happens if you try an xterm or urxvt or aterm etc? Cheers, Cameron Simpson From abhiedu.rkt at gmail.com Fri Nov 27 16:11:18 2020 From: abhiedu.rkt at gmail.com (Abhi Singh) Date: Sat, 28 Nov 2020 02:41:18 +0530 Subject: [Tutor] lists In-Reply-To: References: Message-ID: Just loop over the list and compare every element with the previous one. On Sat, 28 Nov 2020, 2:34 am Bernardo Rebelo, < bernardoaugustorebelo11 at gmail.com> wrote: > Hi I would like to know how to check if an element in a list is greater > than the next element on the same list like this > > [5,4,3,2,1] > > if 5 > 4 > 3 > 2 > 1 > return True > > in an example like this one [5,4,5,2], it would give False. > > best regards, > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From breamoreboy at gmail.com Fri Nov 27 16:46:11 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Fri, 27 Nov 2020 21:46:11 +0000 Subject: [Tutor] lists In-Reply-To: References: Message-ID: <18fd63ce-7057-5c42-25ae-6f17f369eafd@gmail.com> On 27/11/2020 19:54, Bernardo Rebelo wrote: > Hi I would like to know how to check if an element in a list is greater > than the next element on the same list like this > > [5,4,3,2,1] > > if 5 > 4 > 3 > 2 > 1 > return True > > in an example like this one [5,4,5,2], it would give False. > > best regards, Sorry but we don't write code for you, but to get you going you'll need a 'for' loop and for best practice the 'enumerate' function https://docs.python.org/3/library/functions.html#enumerate -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at gmail.com Fri Nov 27 16:50:48 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Fri, 27 Nov 2020 21:50:48 +0000 Subject: [Tutor] lists In-Reply-To: References: Message-ID: <1af2240f-5c3f-7819-771d-764f5949fc95@gmail.com> On 27/11/2020 21:09, nathan tech wrote: Would you please not top post here as it's highly irritating. > Hello, > > > Would not this work? > > > if(l[0]>l[1]): > > ?print("all is well.") > > > Or if you wanted to look at the whole list something like: > > > def is_great(l): > > ?pos=0 > > ?for x in range(l): That'll fail as a list can't be passed to range, plus using range is almost inevitably a code smell in python. > > ? if(x==len(l)): > > ?? return True > > ?if(l[x]>l[x+1]): > > ?? return False > > > > May need some slight bug checks on that function as I threw it together > off the top of my head but. > > HTH > > Nathan > > > On 27/11/2020 19:54, Bernardo Rebelo wrote: >> Hi I would like to know how to check if an element in a list is greater >> than the next element on the same list like this >> >> [5,4,3,2,1] >> >> if 5 > 4 > 3 > 2 > 1 -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From alan.gauld at yahoo.co.uk Sat Nov 28 04:20:09 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 28 Nov 2020 09:20:09 +0000 Subject: [Tutor] Curses Python: F1 => Xfce Terminal documentation In-Reply-To: <20201128080647.GA39264@cskk.homeip.net> References: <20201128080647.GA39264@cskk.homeip.net> Message-ID: On 28/11/2020 08:06, Cameron Simpson wrote: > On 28Nov2020 06:17, alexkleider wrote: > 2: What happens if you try an xterm or urxvt or aterm etc? That would be my first port of call. Check if its the terminal or the OS that's the culprit. Assuming you're sure its not your code (or mine!! :-) If it is the terminal you may need to do something with terminfo to modify the terminal settings to catch F1 before the OS. More detail than my HowTo goes into however - ie. I don't know how... -- 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 Sat Nov 28 04:29:48 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 28 Nov 2020 09:29:48 +0000 Subject: [Tutor] lists In-Reply-To: References: Message-ID: On 27/11/2020 21:09, nathan tech wrote: > def is_great(l): > > ?pos=0 > ?for x in range(l): I assume you meant range(len(l))? > ? if(x==len(l)): > ?? return True But that needs to be x == len(l)-2 due to zero indexing. > ?if(l[x]>l[x+1]): > ?? return False This would fail if you let x get above len(l)-2 > May need some slight bug checks on that function Yes indeed. That's why using range and indexing is so frowned on in Python, its nearly always the wrong approach. See my post for one way to do it without using range and indexing. -- 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 alexkleider at protonmail.com Sat Nov 28 11:56:01 2020 From: alexkleider at protonmail.com (alexkleider) Date: Sat, 28 Nov 2020 16:56:01 +0000 Subject: [Tutor] Curses Python: F1 => Xfce Terminal documentation In-Reply-To: References: <20201128080647.GA39264@cskk.homeip.net> Message-ID: Thanks to both Cameron and Alan for your suggestions. The problem is solved simply by using curses.KEY_F2 (rather than F1.) I tried the virtual console but it resulted in bizarre characters. Don't know about "xterm or urxvt or aterm." I was under the impression that the Xfce terminal was in fact an "xterm." Alex From anders_e3 at denison.edu Sat Nov 28 11:31:18 2020 From: anders_e3 at denison.edu (Erin Anderson) Date: Sat, 28 Nov 2020 10:31:18 -0600 Subject: [Tutor] Coding question Message-ID: <3BEB0C0F-5367-406A-BDE1-2328CF1FF495@denison.edu> Hello, I am trying to figure out how to code for reading in text from a URL in python but in two chunks. I am looking at a transcript from a website and I want to read in the text but I want the reading in of the text to stop when the transcript says ?Part 2?, I then want to have this chunk of information as one entity and then create another entity filled with the text that occurs after the words ?Part 2?. Im thinking one way to do this is using a while loop, but I am not quite sure how to implement it Def text_chunk(url) webpage=web.urlopen(url) while text != ?Part 2?: rawbytes=webpage.read() webpage.close() text = rawBytes.decode('utf-8?) return text Thank you!!!! From PyTutor at DancesWithMice.info Sat Nov 28 13:21:37 2020 From: PyTutor at DancesWithMice.info (dn) Date: Sun, 29 Nov 2020 07:21:37 +1300 Subject: [Tutor] Coding question In-Reply-To: <3BEB0C0F-5367-406A-BDE1-2328CF1FF495@denison.edu> References: <3BEB0C0F-5367-406A-BDE1-2328CF1FF495@denison.edu> Message-ID: On 29/11/2020 05:31, Erin Anderson wrote: > Hello, I am trying to figure out how to code for reading in text from a URL in python but in two chunks. > > I am looking at a transcript from a website and I want to read in the text but I want the reading in of the text to stop when the transcript says ?Part 2?, I then want to have this chunk of information as one entity and then create another entity filled with the text that occurs after the words ?Part 2?. Im thinking one way to do this is using a while loop, but I am not quite sure how to implement it > > Def text_chunk(url) > webpage=web.urlopen(url) > while text != ?Part 2?: The applicable Python idiom is to use the find() method: text.find( "Part 2" ) > rawbytes=webpage.read() > webpage.close() This will close the webpage. Accordingly, if "Part 2" is not in text, the while-loop will repeat, but webpage will not be open! > text = rawBytes.decode('utf-8?) > return text If you wish to persist with this idea, then consider that web-pages, indeed whole books, can easily 'fit' into the average computer's storage-space. So, rather than thinking of "two chunks", read the whole web-page first, and only later figure-out which part of the page you want to keep/discard. What you are describing is known as "web scraping". There are a number of Python tools which will accomplish the mechanics for you. Traditionally this has been an adaptation of "BeautifulSoup" (web pages being described as a 'soup' of HTML tags and/or "<" and ">" symbols). Such would make it quicker/easier to meet the stated objective! -- Regards =dn From alan.gauld at yahoo.co.uk Sat Nov 28 13:40:23 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 28 Nov 2020 18:40:23 +0000 Subject: [Tutor] Curses Python: F1 => Xfce Terminal documentation In-Reply-To: References: <20201128080647.GA39264@cskk.homeip.net> Message-ID: On 28/11/2020 16:56, alexkleider via Tutor wrote: > I was under the impression that the Xfce terminal was in fact an "xterm." It's possible but unlikely. Most folks find an xterms scroll bar operation non intuitive! (Personally I love it!) But xterm has several issues, it basically started life as one of the demo programs for X and became the standard terminal. But modern ones are much better with better colours, tabs, scrollbars etc etc. xterm has none of those things, but is a good vanilla terminal emulator, so a good starting point for debugging terminal issues in curses!. -- 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 Sat Nov 28 13:44:23 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 29 Nov 2020 05:44:23 +1100 Subject: [Tutor] Curses Python: F1 => Xfce Terminal documentation In-Reply-To: References: Message-ID: <20201128184423.GA16808@cskk.homeip.net> On 28Nov2020 16:56, alexkleider wrote: >Thanks to both Cameron and Alan for your suggestions. >The problem is solved simply by using curses.KEY_F2 (rather than F1.) The Xfce terminal docs I cited suggested that F1 is intercepted, and you'll never see F1 _inside_ the terminal unless you change the key binding for "help", which seems possible. >I tried the virtual console but it resulted in bizarre characters. If you mean the non-X11 system console (unsure) that might be a font issue. >Don't know about "xterm or urxvt or aterm." >I was under the impression that the Xfce terminal was in fact an >"xterm." I think not from the docs, again. You may well find that $TERM is set to "xterm" or one of its colour variants so that your curses programmes use a working terminfo entry, which maps capabilities like "clear screen" and "move cursors" etc to the necessary escape sequences. But it looks to be a distinct terminal emulator. xterm and urxvt and aterm are all distinct other terminal emulators you can also install. Cheers, Cameron Simpson From alan.gauld at yahoo.co.uk Sat Nov 28 17:08:15 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 28 Nov 2020 22:08:15 +0000 Subject: [Tutor] Coding question In-Reply-To: <3BEB0C0F-5367-406A-BDE1-2328CF1FF495@denison.edu> References: <3BEB0C0F-5367-406A-BDE1-2328CF1FF495@denison.edu> Message-ID: On 28/11/2020 16:31, Erin Anderson wrote: > Hello, I am trying to figure out how to code for reading in text from a URL in python but in two chunks. There are ways to do that but it's not normal. A URL delivers a stream (or streams) of data and you usually have to read the entire stream. If you start chunking it up you will break the HTML formatting (start/end tags etc) and make parsing much more difficult. HTML is not line oriented. > I am looking at a transcript from a website and I want > to read in the text but I want the reading in of the text > to stop when the transcript says ?Part 2?, The usual way is to read the entire stream then find the bits you want within that using an HTML parser. It does mean all the text is in memory but on any modern computer that's not usually an issue! > I then want to have this chunk of information as one entity > and then create another entity filled with the text that > occurs after the words ?Part 2?. In that case it's all in memory anyway so you might as well use the standard tools and save yourself a world of pain and anguish! > Im thinking one way to do this is using a while loop, That's almost certainly wrong. Use an HTML parser - either BeautifulSoup or the standard library html.parser module(*). Use that to find the tag/class that you are looking for and select the elements you need. On the other hand if you are only interested in the text content rather than the document structure then export the html as plain text and use regular text processing tools to search/slice it. But usually the parser approach will be faster and easier. > Def text_chunk(url) > webpage=web.urlopen(url) > while text != ?Part 2?: You haven't dfined text anywhere so this will fail with an error. And if it passed you'd just read the entire page into text each time round the loop. Just do it once. > rawbytes=webpage.read() At this point you have already read the entire page into memory so there is no point in trying to stop the read. > webpage.close() > text = rawBytes.decode('utf-8?) > return text Now you have text as a string you can try to find your string within it. But better would be to read the bytes into a parser then use that to pull out the bits you need. Since you don't describe what you want to do (other than split the page) we can't really advise how to proceed beyond that. The more specific you are about what you are trying to do (rather than how you are trying to do it!) the more likely we are to be able to help. (*)There is a basic intro on how to use the html.parser module in my "Writing Web Clients" topic of my tutorial(see below) -- 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 alexkleider at protonmail.com Sat Nov 28 20:59:00 2020 From: alexkleider at protonmail.com (alexkleider) Date: Sun, 29 Nov 2020 01:59:00 +0000 Subject: [Tutor] Curses Python: F1 => Xfce Terminal documentation In-Reply-To: <20201128184423.GA16808@cskk.homeip.net> References: <20201128184423.GA16808@cskk.homeip.net> Message-ID: ??????? Original Message ??????? On Saturday, November 28, 2020 10:44 AM, Cameron Simpson wrote: > On 28Nov2020 16:56, alexkleider alexkleider at protonmail.com wrote: > > I tried the virtual console but it resulted in bizarre characters. > > If you mean the non-X11 system console (unsure) that might be a font > issue. I was referring to the screen which shows up if one presses CTL/ALT F1...6 (and then ALT F7 to get back to the GUI.) > > I think not from the docs, again. You may well find that $TERM is set to > "xterm" or one of its colour variants so that your curses programmes use > a working terminfo entry, which maps capabilities like "clear screen" > and "move cursors" etc to the necessary escape sequences. But it looks > to be a distinct terminal emulator. alex at X1v2:~$ echo $TERM xterm-256color So it would appear that you are correct but the terminal I've been using (the one that appears when I hit the icon that looks like a terminal) is the 'xfce4-terminal'. Again, thanks for your support. Alex From martin at linux-ip.net Sat Nov 28 21:07:24 2020 From: martin at linux-ip.net (Martin A. Brown) Date: Sat, 28 Nov 2020 18:07:24 -0800 Subject: [Tutor] lists In-Reply-To: References: Message-ID: Hello there, > Hi I would like to know how to check if an element in a list is greater > than the next element on the same list like this > > [5,4,3,2,1] > > if 5 > 4 > 3 > 2 > 1 > return True > > in an example like this one [5,4,5,2], it would give False. Is this another way of asking: Is the list (reverse) sorted? If so, For many general computation problems, not only will the entire list fits easily in the memory of modern machines, but the sorting is reasonably quick, so you can perform the sort operation on the input and then compare the original list with the sorted list and you know that it's not sorted if you don't have equality. This should work fine for integers (and numbers in general), as in your example. It will not work reliably for more complex elements of a list. Here's a function that returns True or False: def is_reverse_sorted(l): return l == sorted(l, reverse=True) def test_is_reverse_sorted(): examples = [ ([5,4,3,2,1], True), ([5,4,5,2], False), ([5,4,5,3,1], False), ([5,5,5,5,1], True), ] for l, expected in examples: assert is_reverse_sorted(l) == expected In the thread I saw two of the above sample lists and I made up one myself that includes repeated integers, just to demonstrate. If no, or if a future problem needs different rules, you can take this sort of technique (a function and a testing function to run through some test cases) and apply it to increasingly more complicated rules for the input data. Say, for example, you wanted to test that all list elements are integers (or float()-able). You could add logic to ensure that there were no duplicates. You could add testing to see that there were no duplicates. -Martin -- Martin A. Brown http://linux-ip.net/ From sccdzt at foxmail.com Sat Nov 28 23:53:08 2020 From: sccdzt at foxmail.com (=?gb18030?B?U2FpbG9ybW9vbg==?=) Date: Sun, 29 Nov 2020 07:53:08 +0300 Subject: [Tutor] Recommendation to supersede openpyxl Message-ID: Dear  sir : Recently I used The openpyxl library to modify some excel documents and save that ,I found all The inserted picture omission  ,i checked and found that openpyxl can not save The picture information ,so  do You have any other  recommendation for such instance . YOURS SINCERELY?ZHANGTAO From alan.gauld at yahoo.co.uk Mon Nov 30 07:44:04 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 30 Nov 2020 12:44:04 +0000 Subject: [Tutor] Recommendation to supersede openpyxl In-Reply-To: References: Message-ID: On 29/11/2020 04:53, Sailormoon wrote: > Dear  sir : > Recently I used The openpyxl library to modify some excel documents > and save that ,I found all The inserted picture omission I don't know how they compare but the packages I most often see used with Excel are: Xlrd and XLwt There is a post here that compares them along with others: https://owlcation.com/stem/8-Ways-to-Use-Python-with-Excel I haven't read it thoroughly so can't comment on the content, but at least it gives you more options to try. Personally I've only ever used the csv module to create excel readable csv files, but it sounds like you need more than that would provide. -- 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 manpritsinghece at gmail.com Mon Nov 30 09:39:00 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Mon, 30 Nov 2020 20:09:00 +0530 Subject: [Tutor] Function decorators Message-ID: Dear sir, I tried to understand the concept of function decorators from various sources but couldn't . Can i request you a small text that describes the decorators along with an example . I am sorry if I said something wrong. Regards Manprit singh From mats at wichmann.us Mon Nov 30 10:43:06 2020 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 30 Nov 2020 08:43:06 -0700 Subject: [Tutor] Function decorators In-Reply-To: References: Message-ID: On 11/30/20 7:39 AM, Manprit Singh wrote: > Dear sir, > > I tried to understand the concept of function decorators from various > sources but couldn't . > > Can i request you a small text that describes the decorators along with an > example . > > I am sorry if I said something wrong. Don't worry, decorators are a source of some confusion for many (not using them, which is easy, but what they actually are). Both of these sources are usually very good, try looking them over and seeing if they help: https://realpython.com/primer-on-python-decorators/ https://jeffknupp.com/blog/2013/11/29/improve-your-python-decorators-explained/ If not, come back with some slightly more direct questions and folks here should be able to help. From alan.gauld at yahoo.co.uk Mon Nov 30 12:16:54 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 30 Nov 2020 17:16:54 +0000 Subject: [Tutor] Function decorators In-Reply-To: References: Message-ID: On 30/11/2020 14:39, Manprit Singh wrote: > I tried to understand the concept of function decorators from various > sources but couldn't . They are a fairly advanced concept that is rarely used (as in creating decorators) in every day programming. Decorators are easy enough to use once created even if you don't understand what they do under the covers. But creating a decorator is slightly more complex. In essence a decorator is a function that returns a function and then gets called through a bit of Python syntactical magic - the @prefix. Before understanding decorators do you understand the concept of functions as objects? Are you comfortable with lambdas? Lambdas aren't needed for decorators but if you understand what lambdas do you will find it a shorter step to decorators. For example can you, without considering decorators, define a function that returns a new function that will calculate a given power? def exponent_builder(n) def f(.... return f square = exponent_builder(2) print(square(7) ) -> prints 49 triple = exponent_builder(3) print( triple(3)) -> prints 27 If you can write exponent_builder() you are well on the way to writing a decorator. > I am sorry if I said something wrong. No, it's a reasonable question. You will need to be more specific now in any follow-up. -- 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 Mon Nov 30 15:45:02 2020 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Mon, 30 Nov 2020 14:45:02 -0600 Subject: [Tutor] Recommendation to supersede openpyxl In-Reply-To: <6jfasfh0pldror3e7cehf8h9t7297jq0dn@4ax.com> References: <6jfasfh0pldror3e7cehf8h9t7297jq0dn@4ax.com> Message-ID: On 11/30/20 1:00 PM, Dennis Lee Bieber wrote: > On Mon, 30 Nov 2020 12:44:04 +0000, Alan Gauld via Tutor > declaimed the following: > >> On 29/11/2020 04:53, Sailormoon wrote: >>> Dear  sir : >>> Recently I used The openpyxl library to modify some excel documents >>> and save that ,I found all The inserted picture omission >> > >> >> Personally I've only ever used the csv module to create >> excel readable csv files, but it sounds like you need >> more than that would provide. > > I'd have to concur. Most of the Excel interface packages appear to > focus on just the numeric data contents, and /maybe/ formulas. Not on > things that are Excel GUI oriented (forms, embedded images, macros, and VBA > scripts). > > For that level of manipulation, I suspect one will need to script Excel > itself -- not using libraries that just read/write plain Excel files. From > Python that means pywin32 COM control, OR MAYBE using ctypes instead, to > invoke the Excel engine (.DLLs) directly (IOWs, running Excel in the > background and asking /it/ to make the changes to the document).. > > I don't use windows so I have never used Excel so maybe I am way off base here. I have used a combination of pyautogui, oosheet and even openypxl to modify Libreoffice calc sheets. Using pyautogui's ability to send keystrokes I can manipulate calc's menu system and take advantage of what it offers. Maybe you can do the same with Excel. Regards, Jim