From cs at cskk.id.au Sat Apr 1 00:29:24 2023 From: cs at cskk.id.au (Cameron Simpson) Date: Sat, 1 Apr 2023 15:29:24 +1100 Subject: [Tutor] Pen plotter data format In-Reply-To: <441532a4-aa6f-8081-e6db-f520ebdbbf9e@gmail.com> References: <441532a4-aa6f-8081-e6db-f520ebdbbf9e@gmail.com> Message-ID: On 01Apr2023 13:59, Phil wrote: >On 1/4/23 13:19, Cameron Simpson wrote: >>Yeah, the termination is pretty weird. But is Phil generating HP-GL or >>trying to parse it? Generating is much easier because you can be nice >>and regular. Parsing has to handle some flexible termination. > >I'm generating the gcode from SVG files. I've settled on inkscape to >generate the images. Ha! The HPGL job was a code demo for a contract with Inkscape. Didn't pan out, alas. They seemed happy with the code I made for the interview/challenge. So, you've got a g-code file you want to plot on one system, and the RPi connected to that system (serial cable?) controlling your lego based plotter? And you're designing the protocol to go over the serial cable? It's perfectly possible to have a text dialogue over the serial cable. Cheers, Cameron Simpson From phillor9 at gmail.com Sat Apr 1 01:20:51 2023 From: phillor9 at gmail.com (Phil) Date: Sat, 1 Apr 2023 15:20:51 +1000 Subject: [Tutor] Pen plotter data format In-Reply-To: References: <441532a4-aa6f-8081-e6db-f520ebdbbf9e@gmail.com> Message-ID: On 1/4/23 14:29, Cameron Simpson wrote: > So, you've got a g-code file you want to plot on one system, and the > RPi connected to that system (serial cable?) controlling your lego > based plotter? And you're designing the protocol to go over the serial > cable? > > It's perfectly possible to have a text dialogue over the serial cable. That pretty well sums up the project. I always find it helpful to jot down a few ideas whenever I become a little lost and I now have plan. A University lecturer once told a group that I was a member of to talk your problem over with your dog if you have no one else to talk to. -- Regards, Phil From wlfraed at ix.netcom.com Sat Apr 1 02:20:09 2023 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sat, 01 Apr 2023 02:20:09 -0400 Subject: [Tutor] Pen plotter data format References: <2c80cfbb-4c87-9b77-96b6-41f120549316@gmail.com> Message-ID: On Sat, 1 Apr 2023 13:54:23 +1000, Phil declaimed the following: >The original plan was to build a plotter with at least a 100mm x 100mm >drawing surface. However, due to the parts that I have on hand plus some >parts that are in the mail somewhere that area has been reduced so I >will now only need to pass a two digit coordinate byte. What is the resolution of the stepper motors themselves -- I'd hope an attempt at a pen plotter has finer resolution than 1mm steps. Also, are you trying to pass binary data or (ASCII) text strings? I suspect things will be easier if you follow something like the HP-GL style of text. Among other things, it may make it much easier in the future to add commands for "plotting" text (wherein the font and actual coordinate generation of letter forms is performed totally in the controller [R-Pi]). >After the micro-controller has received a byte and moved the motor it >send an acknowledgement back to the laptop signalling that it's ready >for the next byte. > HP-GL assumes a simple serial port -- if one has RTS/CTS (or X-on/X-off) protocols on the serial port that alone should stop the sender while the controller processes each command in sequence (and technically, the R-Pi is not a "microcontroller" -- a microcontroller would be an Arduino, Adafruit Metro M4*, and things of that ilk; they don't run an operating system [though I think FreeRTOS has been ported to the ARM-based Arduinos, probably not to the 8-bit AVR versions]; the R-Pi is, at worst, an embedded microcomputer though some are using them as replacement desktop computers). Granted, with the rarity of serial ports these days, that could mean having a USB<>serial adapter on both the host and R-Pi, with a null-modem adapter between them > >I'm building a plotter from scratch using Lego parts and I'm not using >the Lego software. It's just a project to keep me out of mischief and I >doubt the plotter will ever serve a useful function. I'll be pleased if >it produces a reasonable plot. Either find the source code for a g-code 3-D printer controller (should be lots, since a lot of such printers use R-Pi boards as the controller) and hack it to isolate just the 2-D operations (hijacking the commands used to start/stop the plastic thread feeder for pen-up/-down) and then conform your host side to send in whatever protocol that software requires... Or, as you are no doubt getting tired of reading, send an ASCII text stream and write a parser for that on the R-Pi side. A parser for HP-GL (based on the little I've seen in those links) would look something like (and I'm assuming some sequences may be all in one "line" using ";" delimiters... Also this is pseudo-code, not executable Python -- the real code should have a lot of try/except blocks, especially when handling the parameters of each command) def penUp(parameters): try: x, y = parameters.split(",") except : return "Incorrect number of parameters provided; expected 2" try: int_x = int(x) int_y = int(y) except : return "Invalid integer data" if (MIN_X > int_x > MAX_X) or (MIN_Y > int_y > MAX_Y): return "Coordinate out-of-range" #issue servo command to raise pen #issue stepper motor controls to move pen to (int_x, int_y) command_table = { "SP" : selectPen, "PU" : penUp, "PD" : penDown } while True: command_string = serial.readline() #block for EOL commands = command_string.split(";") #split into each command for command in commands: #process each command cmd, parameters = command[:2], command[2:] #call the handler function matching "cmd" #all handlers have the same signature! result = command_table[cmd.upper()](parameters) if not result: serial.write("%s : %s\n" % (command, result)) Adding a command just requires adding a new "def cmd_handler()" and an entry in the command_table. If you change the signature from (parameters) to (cmd, parameters) you could maybe save some duplication in code. Instead of penUp() and penDown() you would have both commands invoke penMove(cmd, parameters) and have a test for if cmd == "PU": #issue servo command to raise pen else: #issue servo command to lower pen the stepper motor logic being the same for both, as is the parameter parsing. * The (Arduino Uno/Due style) Adafruit Metro M4 Express https://learn.adafruit.com/adafruit-metro-m4-express-featuring-atsamd51/overview (along with a lot of Adafruit microcontroller boards) natively runs CircuitPython -- a variant of Python optimized for small boards (lots of control over the GPIO, etc.) and running without an OS. Instead, one writes a CircuitPython program on the host, connects the board via USB -- it will create a (on Windows at least) "drive". You drag the program file to the drive; the boot firmware on the board detects the new file, and will start running it (and it gets run anytime the board is reset or power-cycled). If you overwrite the firmware with an Arduino boot-loader, you can write Arduino [C/C++] style (setup()/loop() functions) instead. You'd have to restore the CircuitPython firmware to return to "native" mode. If you can't fit your controller program into its 2MB QSPI flash, the larger (Arduino Mega style) Grand Central https://learn.adafruit.com/adafruit-grand-central/overview has 8MB One potential glitch -- I've found that while the "drive" is active, the firmware looking for changed files interrupts (actually -- restarts) the program. "Ejecting" the drive but leaving the board connected via USB seems to allow the program to run without interruptions. I did not check if the USB /serial/ monitor could still read the program output. Just reset the board to get it to remount as a drive. From threesomequarks at proton.me Sat Apr 1 10:53:58 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Sat, 01 Apr 2023 14:53:58 +0000 Subject: [Tutor] Pen plotter data format In-Reply-To: References: <441532a4-aa6f-8081-e6db-f520ebdbbf9e@gmail.com> Message-ID: >>> Phil: >>> A University lecturer once told a group that I was a member of >>> to talk your problem over with your dog if you have no one >>> else to talk to. The dogged approach to solving problems often works best for people new to a subject who doggedly keep plugging away at a pet project until suddenly some pieces finally start to fall together. I have found that use of companion animals can also be distracting as their interests often differ but they can be good listeners unless distracted by the presence of another animal like a cat! Enough joking! What Phil is talking about is similar to advice to talk to yourself as if you were an audience who knew very little and try to explain to them what the problem is and how you might solve it. No dog is needed, albeit some people have a thing about what it might look like if seen muttering to themselves, or nobody, so having a pet around may make them more comfortable as talking to them is somewhat socially acceptable. Half of solving a problem can be a bit like solving many math problems, which they in some sense often are. Write down what is given. Write down some things you can deduce or calculate from those givens. Write down what tools you might have such as related things taught in the classroom. Write down the objective. Then try to look at a way to make progress in the right direction, even if only partial. For example, you may need to read in the data from a file. Then convert it in some way, and so on. If stuck, perhaps go back a few steps and see if something else may work better or perhaps fill in a gap you skipped. Don't optimize too early, just get it working first. A step at a time, perhap with a few stumbles, often gets the problem done and it starts with being able to explain what the problem is and the potential method to deal with it. Often 90% of programming is dogged persistence and maybe an occasional catnap. - Q Sent with Proton Mail secure email. ------- Original Message ------- On Saturday, April 1st, 2023 at 1:20 AM, Phil wrote: > On 1/4/23 14:29, Cameron Simpson wrote: > > > So, you've got a g-code file you want to plot on one system, and the > > RPi connected to that system (serial cable?) controlling your lego > > based plotter? And you're designing the protocol to go over the serial > > cable? > > > > It's perfectly possible to have a text dialogue over the serial cable. > > > That pretty well sums up the project. > > I always find it helpful to jot down a few ideas whenever I become a > little lost and I now have plan. > > A University lecturer once told a group that I was a member of to talk > your problem over with your dog if you have no one else to talk to. > > -- > > Regards, > Phil > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From wlfraed at ix.netcom.com Sat Apr 1 15:21:19 2023 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sat, 01 Apr 2023 15:21:19 -0400 Subject: [Tutor] Pen plotter data format References: <2c80cfbb-4c87-9b77-96b6-41f120549316@gmail.com> Message-ID: <8uvg2ipt3b08q9k8hiai22ruluubql7t3a@4ax.com> On Sat, 01 Apr 2023 02:20:09 -0400, Dennis Lee Bieber declaimed the following: >while True: > command_string = serial.readline() #block for EOL > commands = command_string.split(";") #split into each command > for command in commands: #process each command > cmd, parameters = command[:2], command[2:] > #call the handler function matching "cmd" > #all handlers have the same signature! > result = command_table[cmd.upper()](parameters) > if not result: > serial.write("%s : %s\n" % (command, result)) > >Adding a command just requires adding a new "def cmd_handler()" and an >entry in the command_table. > I need to state that, the above "parser" will fail if you've added plot commands for text printing -- as an embedded ";" will cause a split in the wrong location. For that situation you'll need a stream parsing approach. Hypothetical command format (Text Output): TO, Something similar to: while True: command_string = serial.readline() while command_string: cmd, command_string = (command_string[:2].upper(), command_string[2:]) if cmd in [ "TO", ]: len, command_string = command_string.split(",", 1) ilen = int(len) parameters, command_string = (command_string[:ilen], command_string[ilen+1:]) #^^^ skips ";" separator #vvv recreate "signature" for calling handlers parameters = ",".join([len, parameters]) else: parameters, command_string = command_string.split(";", 1) result = command_table[cmd](parameters) And... before I forget... Adafruit's "blinka" package enables using most of the CircuitPython interfaces from a Python running on R-Pi (or BeagleBone Black -- the BB AI is overkill for this). But given the rarity and rising $$$ for R-Pis I'd recommend using a controller board over a computer board -- again the Metro Express seems suited if one wants to stay in Python. From phillor9 at gmail.com Sat Apr 1 19:45:30 2023 From: phillor9 at gmail.com (Phil) Date: Sun, 2 Apr 2023 09:45:30 +1000 Subject: [Tutor] Pen plotter data format In-Reply-To: References: <2c80cfbb-4c87-9b77-96b6-41f120549316@gmail.com> Message-ID: <3f0a553d-a995-3bc0-f75e-5e21c55ba4ae@gmail.com> On 1/4/23 16:20, Dennis Lee Bieber wrote: Thank you Dennis for your additional thoughts. The weather cooled a little last night and so I concocted some code that I'm keen to test. > What is the resolution of the stepper motors themselves -- I'd hope an > attempt at a pen plotter has finer resolution than 1mm steps. I'm building the plotter from Lego parts so the motors are analogue and not digital stepping motors. I don't expect much, it's just a project. > (and technically, > the R-Pi is not a "microcontroller" -- a microcontroller would be an > Arduino, Adafruit Metro M4*, and things of that ilk; I do know the difference between an SBC and a microcontroller, I just didn't correct what Cameron assumed. > Granted, with the rarity of serial ports these days, that could mean > having a USB<>serial adapter on both the host and R-Pi, with a null-modem > adapter between them Communication from the laptop to the microcontroller is via Bluetooth. > Either find the source code for a g-code 3-D printer controller (should > be lots, since a lot of such printers use R-Pi boards as the controller) > and hack it to isolate just the 2-D operations I started down that route when I first thought of building a plotter but ended up deciding to go my own way. I believe what I now have will work. > def penUp(parameters): > try: > x, y = parameters.split(",") > except : > return "Incorrect number of parameters provided; expected 2" Your suggestion is along the lines that I now have except for the try and except blocks. I haven't built the pen lifting mechanism yet because I'm waiting for parts and I only have a vague idea how I might build it at the moment. > if cmd == "PU": > #issue servo command to raise pen > else: > #issue servo command to lower pen The Z command is a single coordinate so if it's 0 the pen is down otherwise it's up. I could change the '0' to 'pen_up' to make the code more understandable when I look at it again next week. > * The (Arduino Uno/Due style) Adafruit Metro M4 Express > https://learn.adafruit.com/adafruit-metro-m4-express-featuring-atsamd51/overview I have several older Arduino boards (including the first ever Arduino board), a Raspberry Pi Pico, an Adafruit board and one older ESP32 board. I've been thinking about putting micropython on the ESP32 board but since it's easily programmable from the Arduino IDE I haven't bothered. I'd better get back to VScode before the day warms too much. -- Regards, Phil From phillor9 at gmail.com Sat Apr 1 19:51:56 2023 From: phillor9 at gmail.com (Phil) Date: Sun, 2 Apr 2023 09:51:56 +1000 Subject: [Tutor] Pen plotter data format In-Reply-To: References: <441532a4-aa6f-8081-e6db-f520ebdbbf9e@gmail.com> Message-ID: <115a6479-8666-df02-2972-05f8fa78188a@gmail.com> On 2/4/23 00:53, ThreeBlindQuarks wrote: > Often 90% of programming is dogged persistence and maybe an occasional catnap. My wife describes me as being persistent. I don't know anyone who codes, because we are intrants, and so I jot down notes to myself and sometime look for inspiration from this mailing list. -- Regards, Phil From phillor9 at gmail.com Sat Apr 1 20:03:08 2023 From: phillor9 at gmail.com (Phil) Date: Sun, 2 Apr 2023 10:03:08 +1000 Subject: [Tutor] Pen plotter data format In-Reply-To: <8uvg2ipt3b08q9k8hiai22ruluubql7t3a@4ax.com> References: <2c80cfbb-4c87-9b77-96b6-41f120549316@gmail.com> <8uvg2ipt3b08q9k8hiai22ruluubql7t3a@4ax.com> Message-ID: <51a6de6d-6bc6-65e5-f576-51997fff3764@gmail.com> On 2/4/23 05:21, Dennis Lee Bieber wrote: > Hypothetical command format (Text Output): TO, My experiments with plotting text haven't gone well so far. I need to experiment with different typefaces and it's a mechanically intensive task. > And... before I forget... Adafruit's "blinka" package enables using most of I played with blinka sometime ago but didn't do much with it. > -- again the Metro Express seems suited if one wants to stay in Python. The Adafruit board that I have is an Itsybitsy. -- Regards, Phil From wlfraed at ix.netcom.com Sat Apr 1 20:09:06 2023 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sat, 01 Apr 2023 20:09:06 -0400 Subject: [Tutor] Pen plotter data format References: <2c80cfbb-4c87-9b77-96b6-41f120549316@gmail.com> <3f0a553d-a995-3bc0-f75e-5e21c55ba4ae@gmail.com> Message-ID: On Sun, 2 Apr 2023 09:45:30 +1000, Phil declaimed the following: > >I'm building the plotter from Lego parts so the motors are analogue and >not digital stepping motors. I don't expect much, it's just a project. > Those are going to make things tricky -- different rotation speeds will skew any plots, and you have no means of determining the location of the pen. I'd refrained from bringing up a set of micro-switches for determining "home" (0, 0) position. > >I started down that route when I first thought of building a plotter but >ended up deciding to go my own way. I believe what I now have will work. > > >> def penUp(parameters): >> try: >> x, y = parameters.split(",") >> except : >> return "Incorrect number of parameters provided; expected 2" > >Your suggestion is along the lines that I now have except for the try >and except blocks. I haven't built the pen lifting mechanism yet because >I'm waiting for parts and I only have a vague idea how I might build it >at the moment. Small servo motor and some sort of parallelogram arm (keeping the pen vertical as the arm moves up and down). Does mean needing a PWM output (another excuse to not use a costly R-Pi -- most microcontroller systems have multiple true PWM outputs vs the simulation the R-Pi does, and you might need some for motor speed control [suggestion: continuous rotation servos; you shouldn't need to rig something to reverse the motor direction as 50% PWM is "stop", <50% is one direction, >50% is the other]) From phillor9 at gmail.com Sun Apr 2 02:58:20 2023 From: phillor9 at gmail.com (Phil) Date: Sun, 2 Apr 2023 16:58:20 +1000 Subject: [Tutor] Pen plotter data format In-Reply-To: References: <2c80cfbb-4c87-9b77-96b6-41f120549316@gmail.com> <3f0a553d-a995-3bc0-f75e-5e21c55ba4ae@gmail.com> Message-ID: On 2/4/23 10:09, Dennis Lee Bieber wrote: > > Those are going to make things tricky -- different rotation speeds will > skew any plots, and you have no means of determining the location of the > pen. The Lego motors have built-in position encoders. The main cause of inaccuracy seems to gear backlash and a bit of slop in the motor. I only have the x axis working at the moment but it seems to work well enough. Following your advice, I had a look at an Arduino GRB library and "Universal Gcode Sender".? A very useful combination if I were using an Arduino board. > Small servo motor and some sort of parallelogram arm (keeping the pen > vertical as the arm moves up and down). I'm thing a cam on a Lego motor might do the job. -- Regards, Phil From mk1853387 at gmail.com Mon Apr 3 14:17:13 2023 From: mk1853387 at gmail.com (marc nicole) Date: Mon, 3 Apr 2023 20:17:13 +0200 Subject: [Tutor] check if two differently shaped dataframes are contained one another Message-ID: Hello, I have this first dataframe 1 2 3 4 and this second dataframe 5 9 3 8 7 1 2 0 6 3 4 10 and i want to check whether the first dataframe is contained in the second (which is the case here) I know that .isin() and .compare() both require that the dataframes are shaped the same. Note: I am looking for a "pandas" oriented solution From PythonList at DancesWithMice.info Mon Apr 3 19:02:29 2023 From: PythonList at DancesWithMice.info (dn) Date: Tue, 4 Apr 2023 11:02:29 +1200 Subject: [Tutor] check if two differently shaped dataframes are contained one another In-Reply-To: References: Message-ID: <05a67d77-c6f1-bf54-9718-c65245a54e88@DancesWithMice.info> On 04/04/2023 06.17, marc nicole wrote: > Hello, > > I have this first dataframe > > 1 2 > 3 4 > > and this second dataframe > > 5 9 3 8 > 7 1 2 0 > 6 3 4 10 > > and i want to check whether the first dataframe is contained in the second > (which is the case here) > > I know that .isin() and .compare() both require that the dataframes are > shaped the same. > Note: I am looking for a "pandas" oriented solution This looks like fun... What is the use-case, the reason for searching for such sub-set data-frames? What have you tried thus-far? Why does it have to be a pandas-implementation? -- Regards, =dn From threesomequarks at proton.me Mon Apr 3 19:42:04 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Mon, 03 Apr 2023 23:42:04 +0000 Subject: [Tutor] check if two differently shaped dataframes are contained one another In-Reply-To: <05a67d77-c6f1-bf54-9718-c65245a54e88@DancesWithMice.info> References: <05a67d77-c6f1-bf54-9718-c65245a54e88@DancesWithMice.info> Message-ID: Dave, This looks a bit like homework, so I think asking for a motivation is possibly not going to result in much! LOL! But going with it, I would prefer to see the problem done more in the context of a matrix. The problem then can be restated as given an NxM matrix, and a larger matrix (meaning the rows and columns are greater than or equal to the smallone) then can you find a subset on the larger matrix starting with upper left corner at X,Y such that every element between X and X+N-1, and every column between Y an Y+M-1 is the same. There are many ways to do this including some I suspect are not acceptable in the course. But the algorithm basically can look like this in English: I will call the smaller matrix the ORIGINAL. The other I call LARGER. So first if the dimensions of LARGER are too small, the answer is FALSE as in cannot be found. Then you want to do a nested loop for all coordinates for the row between the first and stopping N or so back from the number of rows in largest and then a lo0p similarly for columns. At each step of the loop you extract the matrix of the same size as ORIGINAL and compare to ORIGINAL. Using a list comprehension might do most of the work in a single line depending what info you want to return. Do you want a TRUE/FALSE, or the coordinates at which there is ONE match or maybe a list of many matches? Are there many other ways? Sure. But once you have two matrices of the same dimensions, equality can easily be measured without another equivalent loop. Keeping the data in a Dataframe format in numpy/pandas may also be doable as it can be addressed by row/column numbers. But do note the method chosen may have odd results if the two data structures are different in some ways such as including integers or floating point or even complex numbers or other derived objects. - Q Sent with Proton Mail secure email. ------- Original Message ------- On Monday, April 3rd, 2023 at 7:02 PM, dn via Tutor wrote: > On 04/04/2023 06.17, marc nicole wrote: > > > Hello, > > > > I have this first dataframe > > > > 1 2 > > 3 4 > > > > and this second dataframe > > > > 5 9 3 8 > > 7 1 2 0 > > 6 3 4 10 > > > > and i want to check whether the first dataframe is contained in the second > > (which is the case here) > > > > I know that .isin() and .compare() both require that the dataframes are > > shaped the same. > > Note: I am looking for a "pandas" oriented solution > > > This looks like fun... > > What is the use-case, the reason for searching for such sub-set data-frames? > > What have you tried thus-far? > > Why does it have to be a pandas-implementation? > > -- > Regards, > =dn > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From mk1853387 at gmail.com Tue Apr 4 16:45:55 2023 From: mk1853387 at gmail.com (marc nicole) Date: Tue, 4 Apr 2023 22:45:55 +0200 Subject: [Tutor] Is there an straightforward way to tell if a dataframe is a convex set ? Message-ID: Hello, Is there a way to tell if a dataframe is convex (in the convex set theory sense)(e.g.,scipy.spatial)? From alan.gauld at yahoo.co.uk Wed Apr 5 05:22:19 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 5 Apr 2023 10:22:19 +0100 Subject: [Tutor] Is there an straightforward way to tell if a dataframe is a convex set ? In-Reply-To: References: Message-ID: On 04/04/2023 21:45, marc nicole wrote: > Is there a way to tell if a dataframe is convex (in the convex set theory > sense)(e.g.,scipy.spatial)? This mailing list is for questions about the Python language and its standard library. Although we do have some members familiar with the numpy and Pandas extensions, you will find many more folks with that experience on the sciPy forum. It is probably a more productive place to ask such questions. Try asking here: https://scipy.org/community -- 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 threesomequarks at proton.me Tue Apr 4 20:35:40 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Wed, 05 Apr 2023 00:35:40 +0000 Subject: [Tutor] Is there an straightforward way to tell if a dataframe is a convex set ? In-Reply-To: References: Message-ID: What kind of answer do you want Marc Nicole? Do you want to know if a function exists in some module? Someone may know. Do you want to know how to solve any specific part of the problem in python using common methods? The best way is to come up with a recipe in pseudocode that implements what you think needs to be done. Then you may see a solution or want to ask a very specific question about a part as this is for tutoring rather than supplying free programming. As I see it, convexity in this concept may not be about a Dataframe as much as a set. It is a condition that all values of the set will have some other values in the set based on a condition. Is this web page about right? Did you post it or someone else in a class with you? https://stackoverflow.com/questions/75920490/check-if-a-dataframe-is-a-convex-set You would need to explain if this relates to a Dataframe as in does it have to have two columns with a row for each required pairing with the first number in column one and a pairing in column two? As noted there, using all values between 0 and 1 makes no sense for a finite Dataframe. Now if your question is simpler and about whether all columns of the dataframe can be combined and made into one combined set, then that set can be tested fairly easily by iterating over all elements and calculating for each what else must be in the set and testing if they are present. If any one is missing, exit your loop with a status saying it is not a convex set and so on. You may need to explain more or wait for others who know more and can make a better guess what you want. If you really need to work with a Dataframe and entries in columns, there can be other advice on how to use something, like perhaps a dictionary, or do some brute force searches in numpy/pandas. The easiest questions to answer are the most specific. You mentioned a scipy function which makes a convex hull, not checks if you already have one. - Q Sent with Proton Mail secure email. ------- Original Message ------- On Tuesday, April 4th, 2023 at 4:45 PM, marc nicole wrote: > Hello, > > Is there a way to tell if a dataframe is convex (in the convex set theory > sense)(e.g.,scipy.spatial)? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From mmssdd1920 at gmail.com Wed Apr 5 13:30:30 2023 From: mmssdd1920 at gmail.com (Msd De) Date: Wed, 5 Apr 2023 23:00:30 +0530 Subject: [Tutor] precision for complex numbers Message-ID: Hello, Is there a way to increase precision for complex numbers for python? From alan.gauld at yahoo.co.uk Thu Apr 6 05:09:53 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 6 Apr 2023 10:09:53 +0100 Subject: [Tutor] precision for complex numbers In-Reply-To: References: Message-ID: On 05/04/2023 18:30, Msd De wrote: > Is there a way to increase precision for complex numbers for python? The precison is the same as for floats and as such is fixed by the IEEE float standard. How much more precision did you have in mind, and would you also need that extra precision for floats too, since presumably you'd need to interact with non-complex numbers at times too? There may be more precise complex implemetatioms around as third-party modules but they will likely be very much slower in operation. But I've not heard of any such modules. -- 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 gerard.blais at gmail.com Thu Apr 6 09:34:44 2023 From: gerard.blais at gmail.com (Gerard Blais) Date: Thu, 6 Apr 2023 09:34:44 -0400 Subject: [Tutor] precision for complex numbers In-Reply-To: References: Message-ID: look at mpmath. It's GREAT! On Thu, Apr 6, 2023 at 5:11?AM Alan Gauld via Tutor wrote: > On 05/04/2023 18:30, Msd De wrote: > > > Is there a way to increase precision for complex numbers for python? > > The precison is the same as for floats and as such is fixed by > the IEEE float standard. > > How much more precision did you have in mind, and would you also > need that extra precision for floats too, since presumably you'd > need to interact with non-complex numbers at times too? > > There may be more precise complex implemetatioms around as > third-party modules but they will likely be very much slower > in operation. But I've not heard of any such modules. > > -- > 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 threesomequarks at proton.me Thu Apr 6 12:32:04 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Thu, 06 Apr 2023 16:32:04 +0000 Subject: [Tutor] precision for complex numbers In-Reply-To: References: Message-ID: Alan, Complex numbers are, well, complex, but really are implemented mostly as two linked floating point numbers with the second one considered the imaginary component called i in mathematics. There are other such constructs like quaternions with an i,j,k set of orthogonal parts and even octonions with 7 of these. So your point is that the limits of floats will apply to any such composite data type as unlike the way Python has made unlimited integers, they don't expand and float as needed. This has been a very common theme as people keep asking in just about any programming language for more digits or to maintain ALL digits and perhaps especially now that many fairly complex, ahem, calculations are routinely done in which losing some terminal bits can add up. So could this be done? I believe not easily and perhaps not at all. One choice might be to change the current uses of "double" and pretty much break all existing code. As an example, compilers and interpreters that expect things placed on the stack of some fixed size would now need to look for a more elaborate structure that begins with some notation of how big the payload is and perhaps point to it as stored elsewhere. Connections to libraries of code currently written in C or FORTRAN or RUST might now need to be called by first shrinking your number back into the old format and losing data and converting any answers back. And it would be SLOW. An alternative would be to create new data types such as infinifloat and they might only be usable for a small set of operations that can handle them and perhaps eventually lots would. You would, of course, have to have a type like infinicomplex to match. As hardware changes and evolves, we may well migrate to some new standards with something like 512 bits assigned to each and every numeric type but by then, someone will always want ever more precision. I think a very serious problem to consider is that most numbers in the real world simply cannot be represented in binary. Something as simple as 1/3 expands infinitely and if your machine tries to make a form of floating point that contains it all, it will use all available memory and die. The same applies to most square roots or irrational numbers like ? or things like a repeated multiplication like the product of a huge number of probabilities that in some sense just would keep getting longer and longer. The person asking here, of course, was not asking for infinite precision, just more precision. This is a very common need albeit I suspect people needing this may end up using languages designed to be way more efficient than python. But there is no current solution WITHIN python, albeit there likely are modules you can import and use with care as not everything will accept ... Sent with Proton Mail secure email. ------- Original Message ------- On Thursday, April 6th, 2023 at 5:09 AM, Alan Gauld via Tutor wrote: > On 05/04/2023 18:30, Msd De wrote: > > > Is there a way to increase precision for complex numbers for python? > > > The precison is the same as for floats and as such is fixed by > the IEEE float standard. > > How much more precision did you have in mind, and would you also > need that extra precision for floats too, since presumably you'd > need to interact with non-complex numbers at times too? > > There may be more precise complex implemetatioms around as > third-party modules but they will likely be very much slower > in operation. But I've not heard of any such modules. > > -- > 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 Thu Apr 6 19:46:08 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 7 Apr 2023 00:46:08 +0100 Subject: [Tutor] precision for complex numbers In-Reply-To: References: Message-ID: On 06/04/2023 17:32, ThreeBlindQuarks via Tutor wrote: > I think a very serious problem to consider is that > most numbers in the real world simply cannot be > represented in binary. Something as simple as 1/3 > expands infinitely Not just in binary, 1/3 is also a problem in decimal! It's a problem with real numbers in general, whatever base you choose there will be numbers that have either infinite recurring patterns or, like pi, infinite non-recurring sequences. binary, being the simplest probably has most (I can't prove that mathematically, but I suspect someone can! :-) The only way to make it work would be a software library which would be very slow - you couldn't use the hardware floating point processor or the GPU processor, both of which can process regular floats at very high speed. Gerard mentioned mpmath so maybe it already exists? I haven't had a chance to investigate mpmath yet. But the existing float/double implementations have been way more than I've ever needed, but then I'm an engineer, not a molecular scientist or similar! -- 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 maddyeisnor1998 at gmail.com Sun Apr 9 13:49:51 2023 From: maddyeisnor1998 at gmail.com (Maddison Eisnor) Date: Sun, 9 Apr 2023 13:49:51 -0400 Subject: [Tutor] Plotting baseline to my CV Message-ID: <392AD36B-39B3-43DA-BBA9-1C1300D7F96A@gmail.com> Hello, I need to add baselines to my CV. I have the code to plot the CV but I don?t know where to start for adding the baselines. Thank you, Maddy From alan.gauld at yahoo.co.uk Sun Apr 9 14:56:57 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 9 Apr 2023 19:56:57 +0100 Subject: [Tutor] Plotting baseline to my CV In-Reply-To: <392AD36B-39B3-43DA-BBA9-1C1300D7F96A@gmail.com> References: <392AD36B-39B3-43DA-BBA9-1C1300D7F96A@gmail.com> Message-ID: On 09/04/2023 18:49, Maddison Eisnor wrote: > Hello, > > I need to add baselines to my CV. Where I come from a CV is what Americans call a Resume. I'm guessing you mean something different but I have no idea what. Can you explain? What is a CV? How are you producing it? Are you using particular libraries like numpy for example? What kind of baseline do you mean? A line on a chart or a baseline set of data? Or something else? Don't assume we live in your world. You need to explain the context. > I have the code to plot the CV And if you have any code showing what you've tried that always helps too. Don't make us guess. -- 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 learn2program at gmail.com Mon Apr 10 03:48:08 2023 From: learn2program at gmail.com (Alan Gauld) Date: Mon, 10 Apr 2023 08:48:08 +0100 Subject: [Tutor] Fwd: Plotting baseline to my CV In-Reply-To: References: Message-ID: <8a1e2f6b-5fe9-0532-48e0-407f3d15ba93@yahoo.co.uk> Forward to list -------- Forwarded Message -------- Subject: Re: [Tutor] Plotting baseline to my CV To: Alan Gauld Content-Type: multipart/related; boundary="000000000000d76b6105f8f06095" Content-Length: 144320 import matplotlib.pyplot as plt import numpy as np? import os import pandas as pd import scipy from scipy import signal from?scipy.io ?import loadmat? import re os.chdir('C:\Maddy - Research\Medtronic Project\Raw Data') x = nD['Trace_1_26_3_2'][:,1] y = nD['Trace_1_26_3_1'][:,1] smoothy = signal.savgol_filter(y,40,3) #rflat_start = np.array(()) #rflat_end = np.array(()) #lflat_start = np.array() #lflat_end = np.array() ltang_reg = [] ltang_m = [] ltangb = [] ltang_eg = [[], [], [], [], [], [], []] rtang_reg = [] rtang_m = [] rtang_b = [] rtang_eq = [[], [], [], [], [], [], []] lpeak_index = [] ipcs = np.array(()) Epcs = np.array(()) rpeak_index = [] ipas = np.array(()) Epas = np.array(()) #ltang_reg.append(stats.linregress(x/y) #ltang_m.append(ltang_reg[x/y].slope) #ltang_b.append(ltang_reg[y].intercept) ? ? #for V in potential [i]: ? ? ? ? #ltang_eq[i].append(ltang_m[i] * V + ltang_b[i]) ? ? #currentdif = current[i] - ltang_eq[i] ? ?# rpeak_index.append(np.argmax(currentdif)) ? ?# ipas = np.append(ipas, currentdif[rpeak_index[i]]) ? ?# Epas = np.array(Epas, potential[i][rpeak_index[i]]) ? ?# rtang_reg.append(stats.linregress(potential[i][rflat_start[i]:rflat_end[i]],\current[i][rflat_start[i]:rflat_end[i]])) ? ? ? ? ? ? # ?rtang_m.append(rtang_reg[i].slope) ? ?# rtang.append(rtang_reg[i].intercept) ? ?? ? ?# for v in potential[i]: ? ? ? ? #rtang_eq[i].append(rtang_m[i] * V + rtang_b[i]) ? ?? ? ? #currentdif = current[i] - rtang_eq[i] ? ? #lpeak_index.append(np.armin(currentdif)) ? ?# ipcs = np.append(ipcs, -currentdif[lpeak_index[i]]) ? ?# Epcs = np.array(Epcs, potential[i][lpeak_index[i]]) fig = plt.figure() ax = plt.axes() s = ' mV/s' ax.plot(x,y*1E12,c='Black') #ax.plot(x,smoothy*1E6,c='Blue',label='5' + s) ax.set_xlabel('Potential $\mathregular{(V\ vs\ Li/Li^{+}}$)') ax.set_ylabel('Current (\u03bcA)') #ax.legend(loc='upper left', frameon=False) #plt.ylim(-215, 325) #plt.savefig('10 mM MPT 2.8-4.6V.') plt.show() headersArray = [] for key in nD: ? ? headersArray.append(key) print(headersArray) nD = loadmat('20230327- 10 mM MPT') type(nD) #nD On Sun, Apr 9, 2023 at 2:57 PM Alan Gauld via Tutor > wrote: On 09/04/2023 18:49, Maddison Eisnor wrote: > Hello, > > I need to add baselines to my CV. Where I come from a CV is what Americans call a Resume. I'm guessing you mean something different but I have no idea what. Can you explain? What is a CV? How are you producing it? Are you using particular libraries like numpy for example? What kind of baseline do you mean? A line on a chart or a baseline set of data? Or something else? Don't assume we live in your world. You need to explain the context. > I have the code to plot the CV And if you have any code showing what you've tried that always helps too. Don't make us guess. -- 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 bhuyanprayash18 at gmail.com Mon Apr 10 10:27:57 2023 From: bhuyanprayash18 at gmail.com (Prayash Bhuyan) Date: Mon, 10 Apr 2023 19:57:57 +0530 Subject: [Tutor] Question Message-ID: I wanted to created a program that prompts the user for a name if the name is the list it will randomly generate a group to the name and then again should promt for the next name until all the name in the list is given as input..But if a wrong name is given as input it should repromt the user again for name but should not consider to be one of the iteration of the one that runs when the name is in the list.I am not able to do this ...Please help my code is attached here for your reference along with the output.. you can clearly see in the output section that when i entered a name that is not in the list it considered it as an iteration of it own and the loop ended with one name still left on the list i donot want that.. can you please help From alan.gauld at yahoo.co.uk Mon Apr 10 14:36:49 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 10 Apr 2023 19:36:49 +0100 Subject: [Tutor] Question In-Reply-To: References: Message-ID: On 10/04/2023 15:27, Prayash Bhuyan wrote: > my code is attached here for your reference along with the output.. Please always cut n paste your code (and output). The server strips attachments for security reasons. -- 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 Apr 10 14:45:07 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 10 Apr 2023 19:45:07 +0100 Subject: [Tutor] Question In-Reply-To: References: Message-ID: On 10/04/2023 15:27, Prayash Bhuyan wrote: > I wanted to created a program that prompts the user for a name if the name > is the list it will randomly generate a group to the name and then > again should promt for the next name until all the name in the list is > given as input. You refer to a list. Is this the list of names entered? Or is it a list of names that already exists somewhere? You mention a group. What is that? Its ot a python term, so it must mean something to you, but it doesn't mean anything to us until you tell us. > .But if a wrong name is given as input it should repromt the > user again for name but should not consider to be one of the iteration of > the one that runs when the name is in the list. This implies that you are counting the iterations? What do you do with the count? Does it limit how many names you can enter? Or do you display the number at the end? What is it for? I am guessing that what you want looks like this in pseudo code: validNames = sorted([lots of names here]) inputNames = [] count = 0 while sorted(inputNames) != validNames: name = input(some prompt) if (name in validNames) and (name not in inputNames): inputNames.append(name) count += 1 else: continue Is that something like it? -- 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 Apr 10 15:29:57 2023 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 10 Apr 2023 13:29:57 -0600 Subject: [Tutor] Fwd: Plotting baseline to my CV In-Reply-To: <8a1e2f6b-5fe9-0532-48e0-407f3d15ba93@yahoo.co.uk> References: <8a1e2f6b-5fe9-0532-48e0-407f3d15ba93@yahoo.co.uk> Message-ID: <6cbf2554-0f44-c93a-4c9c-6a3c1a084463@wichmann.us> On 4/10/23 01:48, Alan Gauld wrote: > Forward to list Note: you're *really* going to want to get in the habit of entering Windows-style paths as Python raw strings. > os.chdir('C:\Maddy - Research\Medtronic Project\Raw Data') backslashes are escape characters to Python, so if you're not using them for that purpose (in this case DOS-style path separators) you need to tell Python so or there *will* be surprises at some point. os.chdir(r'C:\Maddy - Research\Medtronic Project\Raw Data') From bhuyanprayash18 at gmail.com Tue Apr 11 07:02:38 2023 From: bhuyanprayash18 at gmail.com (Prayash Bhuyan) Date: Tue, 11 Apr 2023 16:32:38 +0530 Subject: [Tutor] Question In-Reply-To: <38bbdedd-2966-a5ac-a4d7-45de876454ad@yahoo.co.uk> References: <38bbdedd-2966-a5ac-a4d7-45de876454ad@yahoo.co.uk> Message-ID: Loop forever if the name is not in the list On Tue, 11 Apr, 2023, 2:28 pm Alan Gauld, wrote: > Forwarding to list, please always use ReplyAll when responding. > > On 11/04/2023 07:42, Prayash Bhuyan wrote: > > group is just a variable where I am storing the randomly generated > number > > > > import random > > names=["ayush","bhargav","nayan","money","niju"] > > counter=0 > > while True: > > This is not needed. You start the loop by going into the for loop then > immediately exit the while loop. The while loop is not doing anything. > > > for name in names: > > name=input("what is your name: ") > > name=name.casefold() > > group=random.randint(1,5) > > counter+=1 > > if name in names and counter<=len(names): > > print(name,"your group is",group) > > The counter is not needed, you will only go round the loop as many times > as there are names in the list, there is no need to count them or to > check against the list size. counter will always be less than or equal > to len(names). > > Also, you are generating the group number every time, not just if the > name is in names. That's wasteful but does no harm. > > > > name is in the list it should randomly generate a group number from 1-5 > > and then again promt the user for next name > > And thats what your code does. > > > but if the name is no there > > in the list it should repromt for the next name but in doing so it > > shouldnot consider it to be a iteration of its own > > And this is not there. When the if test fails there is no else part to > catch the error so your code just goes to the start of the next for loop > iteration. You need to add an else clause. > > Something to consider is how often should it prompt if the name is not > in names? Will it just offer one more chance or will it loop forever? > > > > -- > 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 torbjorn.svensson.diaz at gmail.com Tue Apr 11 12:15:36 2023 From: torbjorn.svensson.diaz at gmail.com (=?UTF-8?Q?Torbj=c3=b6rn_Svensson_Diaz?=) Date: Tue, 11 Apr 2023 18:15:36 +0200 Subject: [Tutor] Can't use packages in newly installed python 3.11.3 Message-ID: Hello, dear tutors! I recently installed Python 3.11.3 from source from an xz-file downloaded from Python.org. I followed the instructions on https://ubuntuhandbook.org/index.php/2021/10/compile-install-python-3-10-ubuntu/ and were successful in installing it. However, when I try to import numpy and scipy the following message prints: ModuleNotFoundError: No module named 'numpy' I also have Python 3.10.6 installed and when I use that instead, I have no problems importing numpy and scipy. Also, according to pip3 I have numpy 1.21.5 and scipy 1.8.0 installed. (I ran "pip3 list".) What can i do to make my installed packages work in Python 3.11.3? Is it a flaw to have two python 3s installed at the same time? What am I to do? Please help me out! I use Ubuntu 22.04.2 LTS. Best regards, -- Torbj?rn Svensson Diaz From mats at wichmann.us Tue Apr 11 12:56:28 2023 From: mats at wichmann.us (Mats Wichmann) Date: Tue, 11 Apr 2023 10:56:28 -0600 Subject: [Tutor] Can't use packages in newly installed python 3.11.3 In-Reply-To: References: Message-ID: <9fd6de8c-22d4-886f-610b-d8d144c47e3f@wichmann.us> On 4/11/23 10:15, Torbj?rn Svensson Diaz wrote: > Hello, dear tutors! > > I recently installed Python 3.11.3 from source from an xz-file > downloaded from Python.org. I followed the instructions on > https://ubuntuhandbook.org/index.php/2021/10/compile-install-python-3-10-ubuntu/ and were successful in installing it. However, when I try to import numpy and scipy the following message prints: > > > ModuleNotFoundError: No module named 'numpy' > > I also have Python 3.10.6 installed and when I use that instead, I have > no problems importing numpy and scipy. Also, according to pip3 I have > numpy 1.21.5 and scipy 1.8.0 installed. (I ran "pip3 list".) > What can i do to make my installed packages work in Python 3.11.3? Is it > a flaw to have two python 3s installed at the same time? What am I to > do? Please help me out! No, it's fine. But you need to have the packages you need for a given Python installation set up in that installation. Let's say your newly built Python is accessible as python3.11. Do: python3.11 -m pip list If they're missing (as they certainly are, since you wouldn't be getting "No module" messages otherwise), install them the same way: python3.11 -m pip install numpy If your Python went to a system location (e.g. /usr/local/bin, which is common for Linux builds), install the numpy in your user account so you don't have to use "sudo" for installs: python3.11 -m pip install --user numpy From alan.gauld at yahoo.co.uk Tue Apr 11 13:21:50 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 11 Apr 2023 18:21:50 +0100 Subject: [Tutor] Question In-Reply-To: References: <38bbdedd-2966-a5ac-a4d7-45de876454ad@yahoo.co.uk> Message-ID: On 11/04/2023 12:02, Prayash Bhuyan wrote: > Loop forever if the name is not in the list OK, So you need to add a loop in the else part of your code: >>> for name in names: >>> name=input("what is your name: ") >>> name=name.casefold() >>> group=random.randint(1,5) >>> counter+=1 >>> if name in names and counter<=len(names): >>> print(name,"your group is",group) else: while name not in names: name = input(...).casefold() if name not in names: print(...) There is a much more efficient structure you could use that removes the need for duplicate code but this should show the principle. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Tue Apr 11 13:28:21 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 11 Apr 2023 18:28:21 +0100 Subject: [Tutor] Can't use packages in newly installed python 3.11.3 In-Reply-To: References: Message-ID: On 11/04/2023 17:15, Torbj?rn Svensson Diaz wrote: > I recently installed Python 3.11.3 from source from an xz-file > downloaded from Python.org. I followed the instructions on > https://ubuntuhandbook.org/index.php/2021/10/compile-install-python-3-10-ubuntu/ > and were successful in installing it. However, when I try to import > numpy and scipy the following message prints: > Mats has addressed the immediate issue but its important to understand that your Python system comprises two distinct parts: 1) The Python interpreter and standard library 2) Third party modules usually obtained from PyPI A new Python release only includes the first item. The second requires each library provider to update their libraries to the new release. That can take from a couple of days to a few weeks or even months. (This is one reason I try to stay one major release behind current, so I've only recently upgraded to python 3.10 - that way I rarely have problems with incompatible libraries) -- 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 wlfraed at ix.netcom.com Tue Apr 11 14:02:48 2023 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 11 Apr 2023 14:02:48 -0400 Subject: [Tutor] Can't use packages in newly installed python 3.11.3 References: Message-ID: On Tue, 11 Apr 2023 18:15:36 +0200, Torbj?rn Svensson Diaz declaimed the following: > >I also have Python 3.10.6 installed and when I use that instead, I have >no problems importing numpy and scipy. Also, according to pip3 I have >numpy 1.21.5 and scipy 1.8.0 installed. (I ran "pip3 list".) >What can i do to make my installed packages work in Python 3.11.3? Is it >a flaw to have two python 3s installed at the same time? What am I to >do? Please help me out! Numpy and Scipy (and pretty much anything one installs with pip) are 3rd-party packages, handled by other developers. As such, they may not be compatible with newer releases of Python -- or won't be compatible until some months later. FYI: my Python 3.10 install uses numpy 1.24.2, and scipy 1.10.1 -- the versions you have installed are quite old. I had tried installing Python 3.11 a few weeks ago, but pip was unable to install numpy for that version. Numpy github page implies that 1.24.2 supports Python 3.8 to 3.11; it appears to have been released Feb 5 -- but (I'm on Windows) pip binaries may not have been available -- don't know about your OS; it may build from source files. I also don't know where Linux would store the packages. Windows stores them in a subdirectory of the installed Python version; as a result, different Python installs have their own packages and you'd have to run pip install using the pip from the new Python version to add the compatible packages. From mats at wichmann.us Tue Apr 11 14:17:47 2023 From: mats at wichmann.us (Mats Wichmann) Date: Tue, 11 Apr 2023 12:17:47 -0600 Subject: [Tutor] Can't use packages in newly installed python 3.11.3 In-Reply-To: References: Message-ID: <9f5bfa21-77e0-efe5-97c3-ffdce1ea627f@wichmann.us> On 4/11/23 12:02, Dennis Lee Bieber wrote: > On Tue, 11 Apr 2023 18:15:36 +0200, Torbj?rn Svensson Diaz > declaimed the following: > >> >> I also have Python 3.10.6 installed and when I use that instead, I have >> no problems importing numpy and scipy. Also, according to pip3 I have >> numpy 1.21.5 and scipy 1.8.0 installed. (I ran "pip3 list".) >> What can i do to make my installed packages work in Python 3.11.3? Is it >> a flaw to have two python 3s installed at the same time? What am I to >> do? Please help me out! > > Numpy and Scipy (and pretty much anything one installs with pip) are > 3rd-party packages, handled by other developers. As such, they may not be > compatible with newer releases of Python -- or won't be compatible until > some months later. > > FYI: my Python 3.10 install uses numpy 1.24.2, and scipy 1.10.1 -- the > versions you have installed are quite old. > > I had tried installing Python 3.11 a few weeks ago, but pip was unable > to install numpy for that version. Numpy github page implies that 1.24.2 > supports Python 3.8 to 3.11; it appears to have been released Feb 5 -- but > (I'm on Windows) pip binaries may not have been available -- don't know > about your OS; it may build from source files. I also don't know where > Linux would store the packages. Windows stores them in a subdirectory of > the installed Python version; as a result, different Python installs have > their own packages and you'd have to run pip install using the pip from the > new Python version to add the compatible packages. You can always ask Python. A given Python's sys.path has where it will search. And pip can tell you where a package lives. For example, on a current Fedora system: $ python3 -m pip show numpy Name: numpy Version: 1.22.0 Summary: NumPy is the fundamental package for array computing with Python. Home-page: https://www.numpy.org Author: Travis E. Oliphant et al. Author-email: License: BSD Location: /usr/lib64/python3.11/site-packages That's quite typical (might be lib instead of lib64) for a system install. A self-built install is probably (although it's a configure-time parameter) in a similar path, but starting with /usr/local instead of /usr As far as what's ready on PyPI to install via pip, there's pypi itself, and there's a less official "Python Readiness" page: https://pyreadiness.org/3.11/ From bhuyanprayash18 at gmail.com Tue Apr 11 13:58:34 2023 From: bhuyanprayash18 at gmail.com (Prayash Bhuyan) Date: Tue, 11 Apr 2023 23:28:34 +0530 Subject: [Tutor] Question In-Reply-To: References: <38bbdedd-2966-a5ac-a4d7-45de876454ad@yahoo.co.uk> Message-ID: Thanks On Tue, 11 Apr, 2023, 10:52 pm Alan Gauld via Tutor, wrote: > On 11/04/2023 12:02, Prayash Bhuyan wrote: > > Loop forever if the name is not in the list > > OK, So you need to add a loop in the else part of your code: > > >>> for name in names: > >>> name=input("what is your name: ") > >>> name=name.casefold() > >>> group=random.randint(1,5) > >>> counter+=1 > >>> if name in names and counter<=len(names): > >>> print(name,"your group is",group) > > else: > while name not in names: > name = input(...).casefold() > if name not in names: > print(...) > > There is a much more efficient structure you could use that > removes the need for duplicate code but this should show > the principle. > > -- > 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 torbjorn.svensson.diaz at gmail.com Tue Apr 11 14:27:28 2023 From: torbjorn.svensson.diaz at gmail.com (=?UTF-8?Q?Torbj=c3=b6rn_Svensson_Diaz?=) Date: Tue, 11 Apr 2023 20:27:28 +0200 Subject: [Tutor] Can't use packages in newly installed python 3.11.3 In-Reply-To: <9f5bfa21-77e0-efe5-97c3-ffdce1ea627f@wichmann.us> References: <9f5bfa21-77e0-efe5-97c3-ffdce1ea627f@wichmann.us> Message-ID: <19b7b0ad-6d53-df4c-2f4b-4a3851bbc986@gmail.com> On 2023-04-11 20:17, Mats Wichmann wrote: > > You can always ask Python.? A given Python's sys.path has where it > will search. And pip can tell you where a package lives. For example, > on a current Fedora system: > > $ python3 -m pip show numpy > Name: numpy > Version: 1.22.0 > Summary: NumPy is the fundamental package for array computing with > Python. > Home-page: https://www.numpy.org > Author: Travis E. Oliphant et al. > Author-email: > License: BSD > Location: /usr/lib64/python3.11/site-packages > python3.11 -m pip show numpy Name: numpy Version: 1.24.2 Summary: Fundamental package for array computing in Python Home-page: https://www.numpy.org Author: Travis E. Oliphant et al. Author-email: License: BSD-3-Clause Location: /home/user/.local/lib/python3.11/site-packages Requires: Required-by: biopython, bokeh, contourpy, matplotlib, pandas, scikit-learn, scipy python3.10 -m pip show numpy Name: numpy Version: 1.21.5 Summary: NumPy is the fundamental package for array computing with Python. Home-page: https://www.numpy.org Author: Travis E. Oliphant et al. Author-email: License: BSD Location: /usr/lib/python3/dist-packages Requires: Required-by: -- Torbj?rn Svensson Diaz From alan.gauld at yahoo.co.uk Tue Apr 11 18:37:48 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 11 Apr 2023 23:37:48 +0100 Subject: [Tutor] Question In-Reply-To: References: <38bbdedd-2966-a5ac-a4d7-45de876454ad@yahoo.co.uk> Message-ID: On 11/04/2023 18:21, Alan Gauld via Tutor wrote: >>>> if name in names and counter<=len(names): >>>> print(name,"your group is",group) > > else: > while name not in names: > name = input(...).casefold() > if name not in names: Oops! That should be if name in names: print(...) -- 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 Apr 12 01:42:36 2023 From: phillor9 at gmail.com (Phil) Date: Wed, 12 Apr 2023 15:42:36 +1000 Subject: [Tutor] ttk menubutton Message-ID: I'm attempting to get the options from a ttk menubutton without a lot of success. The menubutton and it's list of options are displayed but I don't understand the error message. ??????? # create a menu ??????? self.menu = tk.Menu(self.mainwindow) ??????? self.menu.add_command(label="Option 1") ??????? self.menu.add_command(label="Option 2") ??????? self.menu.add_command(label="Option 3") ??????? self.menu_button.bind("", self.on_menu_button_release) ??? def on_menu_button_release(self, event): ??????? # get the selected option ??????? selected_option = self.menu.entrycget( ??????????? self.menu.index(tk.ACTIVE), "label") ??????? print(f"Selected option: {selected_option}") _tkinter.TclError: wrong # args: should be ".!menu entrycget index option" -- Regards, Phil From bhuyanprayash18 at gmail.com Wed Apr 12 02:28:33 2023 From: bhuyanprayash18 at gmail.com (Prayash Bhuyan) Date: Wed, 12 Apr 2023 11:58:33 +0530 Subject: [Tutor] question Message-ID: I know how to generate random numbers using random function but I want to know how do i generate random numbers say between (1,5) where each random number can only be repeated only 4 times........please help From PythonList at DancesWithMice.info Wed Apr 12 03:50:22 2023 From: PythonList at DancesWithMice.info (dn) Date: Wed, 12 Apr 2023 19:50:22 +1200 Subject: [Tutor] question In-Reply-To: References: Message-ID: <02614284-d1c5-022e-c08a-1bc1775cd1d8@DancesWithMice.info> On 12/04/2023 18.28, Prayash Bhuyan wrote: > I know how to generate random numbers using random function but I want to > know how do i generate random numbers say between (1,5) where each random > number can only be repeated only 4 times........please help Do you know how to write a loop in Python? Do you know about dict[ionary]s? Are we talking about integers or real numbers? (or suites in a deck of cards) Is this a course-assignment? Please show some code... then we will be able to discuss what's missing or what might be added. -- Regards, =dn From davholla2002 at yahoo.co.uk Wed Apr 12 05:11:59 2023 From: davholla2002 at yahoo.co.uk (David Holland) Date: Wed, 12 Apr 2023 09:11:59 +0000 (UTC) Subject: [Tutor] question In-Reply-To: References: Message-ID: <1932689149.3434180.1681290719999@mail.yahoo.com> This looks like homework but I am practising python myself so I will suggest what I wrote import random def print_ran(x): listnumused = []#list of numbers we have generated while len(x)> 0: a = random.choice(x) listnumused.append(a) if listnumused.count(a)>3:#once we have used a number 4 times remove it from the list we are going to use x.remove(a) print (listnumused)#print the random numbers if __name__ == '__main__': x=[1,2,3,4,5] print_ran(x) On Wednesday, 12 April 2023 at 08:45:13 BST, Prayash Bhuyan wrote: I know how to generate random numbers using random function but I want to know how do i generate random numbers say between (1,5) where each random number can only be repeated only 4 times........please help _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From bhuyanprayash18 at gmail.com Wed Apr 12 04:41:07 2023 From: bhuyanprayash18 at gmail.com (Prayash Bhuyan) Date: Wed, 12 Apr 2023 14:11:07 +0530 Subject: [Tutor] question In-Reply-To: <02614284-d1c5-022e-c08a-1bc1775cd1d8@DancesWithMice.info> References: <02614284-d1c5-022e-c08a-1bc1775cd1d8@DancesWithMice.info> Message-ID: import random # list of names names_list = ["ayush","bhargav","akankhya","prayash"] # dictionary to keep track of numbers assigned to names #numbers_dict = {} # prompt the user for a name and randomly assign a number to the name for name in names_list: while True: user_input = input("Enter name: ") if user_input.casefold() in names_list: group = random.randint(1, 4) #numbers_dict[user_input] = number print(user_input,'your group is',group) break else: print("Name not in list. Please try again.") this is my code i am writing a code where the computer asks the user for a name and if the name is in the list then it randomly assigns a number which in this case is the group number ..Now suppose I have 20 members in the lsit and I want to form four groups with five members in each group ..now a particular random number between 1 and 4 should only appear 5 times and not more than that because if that occurs members will not be equally divided in the group ..thats what i want...and it is not an assignment it's something that i am doing to satisfy my curiosity On Wed, Apr 12, 2023 at 1:21?PM dn via Tutor wrote: > On 12/04/2023 18.28, Prayash Bhuyan wrote: > > I know how to generate random numbers using random function but I want to > > know how do i generate random numbers say between (1,5) where each random > > number can only be repeated only 4 times........please help > > Do you know how to write a loop in Python? > Do you know about dict[ionary]s? > Are we talking about integers or real numbers? > (or suites in a deck of cards) > Is this a course-assignment? > > Please show some code... > then we will be able to discuss what's missing or what might be added. > > -- > Regards, > =dn > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From alan.gauld at yahoo.co.uk Wed Apr 12 05:27:31 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 12 Apr 2023 10:27:31 +0100 Subject: [Tutor] question In-Reply-To: References: Message-ID: On 12/04/2023 07:28, Prayash Bhuyan wrote: > I know how to generate random numbers using random function but I want to > know how do i generate random numbers say between (1,5) where each random > number can only be repeated only 4 times........please help You have to write code to do it. If you limit the number of times a number can be used it becomes increasingly less random. (In your case after you generate 19 numbers you know what the 20th will be.) The random functions generate an continuous stream of numbers all of which are random. (Even if theoretically that results in them all being the same!) So you will need to create a function that checks whether the number has already appeared and if so how many times. Hint: A dictionary might be useful. Have a go and if you get stuck show us what you've done and we can help. -- 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 Apr 12 05:35:25 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 12 Apr 2023 10:35:25 +0100 Subject: [Tutor] ttk menubutton In-Reply-To: References: Message-ID: On 12/04/2023 06:42, Phil wrote: > I'm attempting to get the options from a ttk menubutton without a lot of > success. The menubutton and it's list of options are displayed but I > don't understand the error message. > > ??????? # create a menu > ??????? self.menu = tk.Menu(self.mainwindow) > ??????? self.menu.add_command(label="Option 1") > ??????? self.menu.add_command(label="Option 2") > ??????? self.menu.add_command(label="Option 3") > > ??????? self.menu_button.bind("", > self.on_menu_button_release) What is menu_button? It's not mentioned in your code sample until the bind call... BTW I tried this exercise out of interest and couldn't get the bind() to work. I'm not sure why, I might do some more experiments later. However I must ask why you are using bind in this case - its more common to just attach the event handler to the menu item when you create it. Like self.menu = tk.Menu(self.mainwindow) self.menu.add_command(label="Option 1", command=self.on_Option) Or if you want to use the same handler for multiple items use a lambda to pass an option: self.menu = tk.Menu(self.mainwindow) self.menu.add_command(label="Option 1", command=lambda : self.on_option(1)) self.menu.add_command(label="Option 2", command=lambda : self.on_option(2)) def on_option(self, option): # do something with option here But binding should work, I'm just not sure how to make it do so in a menu. -- 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 PythonList at DancesWithMice.info Wed Apr 12 05:49:42 2023 From: PythonList at DancesWithMice.info (dn) Date: Wed, 12 Apr 2023 21:49:42 +1200 Subject: [Tutor] question In-Reply-To: References: <02614284-d1c5-022e-c08a-1bc1775cd1d8@DancesWithMice.info> Message-ID: On 12/04/2023 20.41, Prayash Bhuyan wrote: > import random > > # list of names > names_list = ["ayush","bhargav","akankhya","prayash"] > > # dictionary to keep track of numbers assigned to names > #numbers_dict = {} > > # prompt the user for a name and randomly assign a number to the name > for name in names_list: > ? ? while True: > ? ? ? ? user_input = input("Enter name: ") > ? ? ? ? if user_input.casefold() in names_list: > ? ? ? ? ? ? group = random.randint(1, 4) > ? ? ? ? ? ? #numbers_dict[user_input] = number > ? ? ? ? ? ? print(user_input,'your group is',group) > ? ? ? ? ? ? break > ? ? ? ? else: > ? ? ? ? ? ? print("Name not in list. Please try again.") > > this is my code i am writing a code where the computer?asks the user for > a name and if the name is in the list then it randomly assigns a number > which in this case is the group number ..Now suppose I have 20 members > in the lsit?and I want to form four groups with five members in each > group ..now a particular random number between 1 and 4 should only > appear 5 times and not more than that because if that occurs members > will not be equally divided in the group ..thats what i want...and it is > not an assignment?it's something that i am doing to satisfy my curiosity It would seem that what is required is not entirely random. There must be a uniform distribution of people to groups. It is more a question of algorithm, than of Python - but around here we like challenges! Choice 1: process-oriented - outer loop: for each name - inner loop: while 'name is unassigned' - randomly choose a groupNR in range( NRgroups ) - if group is not full - assign name to group - break The first name will only require one cycle of the inner loop because whichever group is randomly chosen will be empty. As names are assigned, the chance that the inner-loop has to be repeated will increase. No matter how many loops are required, eventually the last loop will fill the last spot in the last group to be filled. Choice 2: data-oriented - preparation step - create a list of group-numbers in range( NRgroups ) & using itertools.cycle() or .repeat(), create a uniformly-distributed range of group-numbers, the same length as len( names_list ). - outer loop: for each name - use len( group_numbers ) as the number of unassigned names (or places in groups). - create a random integer in range( unassignedNR ) - use that as an index to pop() a random group_number from the list of group-numbers NB pop() removes that indexed-element from the list, and thus shortens it - hence looking at the len() each time around the loop As each name is assigned, the remaining/unassigned group_number-s will be reduced. Because the group_numbers were pre-defined and pre-distributed, there is no need to count how many members have been previously assigned to a group - the (math involved in the) preparation step takes care of that! Do you follow the two lines-of-logic? NB I'm sure our colleagues will come-up with other ideas! > On Wed, Apr 12, 2023 at 1:21?PM dn via Tutor > wrote: > > On 12/04/2023 18.28, Prayash Bhuyan wrote: > > I know how to generate random numbers using random function but I > want to > > know how do i generate random numbers say between (1,5) where > each random > > number can only be repeated only 4 times........please help > > Do you know how to write a loop in Python? > Do you know about dict[ionary]s? > Are we talking about integers or real numbers? > (or suites in a deck of cards) > Is this a course-assignment? > > Please show some code... > then we will be able to discuss what's missing or what might be added. > > -- > Regards, > =dn > _______________________________________________ > Tutor maillist? - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > -- Regards, =dn From mats at wichmann.us Wed Apr 12 09:24:42 2023 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 12 Apr 2023 07:24:42 -0600 Subject: [Tutor] question In-Reply-To: References: <02614284-d1c5-022e-c08a-1bc1775cd1d8@DancesWithMice.info> Message-ID: On 4/12/23 03:49, dn via Tutor wrote: > On 12/04/2023 20.41, Prayash Bhuyan wrote: >> import random >> >> # list of names >> names_list = ["ayush","bhargav","akankhya","prayash"] >> >> # dictionary to keep track of numbers assigned to names >> #numbers_dict = {} ... > Choice 2: data-oriented > > - preparation step > - create a list of group-numbers in range( NRgroups ) > ? & using itertools.cycle() or .repeat(), create a uniformly-distributed > ? range of group-numbers, the same length as len( names_list ). > > - outer loop: for each name > ? - use len( group_numbers ) as the number of unassigned names > ??? (or places in groups). > ? - create a random integer in range( unassignedNR ) > ? - use that as an index to pop() a random group_number from the > ??? list of group-numbers > > NB pop() removes that indexed-element from the list, and thus shortens > it - hence looking at the len() each time around the loop > > As each name is assigned, the remaining/unassigned group_number-s will > be reduced. > > Because the group_numbers were pre-defined and pre-distributed, there is > no need to count how many members have been previously assigned to a > group - the (math involved in the) preparation step takes care of that! I'd build on from this model: if you really have these tight constraints (the real world is often a lot more messy than knowing up front that you'll have 20 names and exactly four groups, etc.) you can just preallocate everything: build a list of group numbers that matches the list of names, and shuffle it, getting your randomization that way. Here's an example - just doing the assignment, not including any of the interactive part. Of course you can build this out with more details as needed: >>> import random >>> names = [chr(x + ord('A')) for x in range(20)] >>> names ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T'] >>> groups = list(range(1, 5)) * 5 >>> groups [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4] >>> random.shuffle(groups) >>> groups [2, 4, 3, 3, 2, 2, 2, 1, 4, 3, 3, 1, 4, 3, 1, 4, 4, 1, 1, 2] >>> names_with_groups = dict(zip(names, groups)) >>> names_with_groups {'A': 2, 'B': 4, 'C': 3, 'D': 3, 'E': 2, 'F': 2, 'G': 2, 'H': 1, 'I': 4, 'J': 3, 'K': 3, 'L': 1, 'M': 4, 'N': 3, 'O': 1, 'P': 4, 'Q': 4, 'R': 1, 'S': 1, 'T': 2} >>> From mats at wichmann.us Wed Apr 12 09:29:33 2023 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 12 Apr 2023 07:29:33 -0600 Subject: [Tutor] Can't use packages in newly installed python 3.11.3 In-Reply-To: <19b7b0ad-6d53-df4c-2f4b-4a3851bbc986@gmail.com> References: <9f5bfa21-77e0-efe5-97c3-ffdce1ea627f@wichmann.us> <19b7b0ad-6d53-df4c-2f4b-4a3851bbc986@gmail.com> Message-ID: On 4/11/23 12:27, Torbj?rn Svensson Diaz wrote: Well, this looks good, is it working now? You've got a "user install" of numpy tied to your new Python (on linux it builds those in your .local directory, I forget where it puts them in Windows but since that wasn't the question space...). > python3.11 -m pip show numpy > Name: numpy > Version: 1.24.2 > Location: /home/user/.local/lib/python3.11/site-packages > Requires: > python3.10 -m pip show numpy > Name: numpy > Version: 1.21.5 > Location: /usr/lib/python3/dist-packages From wlfraed at ix.netcom.com Wed Apr 12 13:40:49 2023 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Wed, 12 Apr 2023 13:40:49 -0400 Subject: [Tutor] question References: <02614284-d1c5-022e-c08a-1bc1775cd1d8@DancesWithMice.info> Message-ID: <55qd3ipkruv11981co0q2apejtggir0375@4ax.com> On Wed, 12 Apr 2023 14:11:07 +0530, Prayash Bhuyan declaimed the following: >this is my code i am writing a code where the computer asks the user for a >name and if the name is in the list then it randomly assigns a number which >in this case is the group number ..Now suppose I have 20 members in the >lsit and I want to form four groups with five members in each group ..now a >particular random number between 1 and 4 should only appear 5 times and not >more than that because if that occurs members will not be equally divided >in the group ..thats what i want...and it is not an assignment it's >something that i am doing to satisfy my curiosity Don't use random()/randint()/etc... You have a list of names nG * nM in length (number groups * number members). In your example that is 4 * 5 => 20. Take the original list of names, feed it to shuffle(), then take slices of the shuffled list where each slice is sized nM I have not tested the behavior for cases where the list of names is NOT nG*nM in length. >>> import random >>> names = ("one two three four five " ... "six seven eight nine ten " ... "eleven twelve thirteen fourteen fifteen " ... "sixteen seventeen eighteen nineteen twenty").split() >>> nM = 5 >>> names ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty'] >>> random.shuffle(names) >>> names ['twenty', 'nineteen', 'nine', 'three', 'sixteen', 'thirteen', 'fourteen', 'eleven', 'fifteen', 'ten', 'two', 'eighteen', 'eight', 'twelve', 'seven', 'four', 'one', 'seventeen', 'six', 'five'] >>> for ix in range(0, len(names), nM): ... print(names[ix:ix+nM]) ... ['twenty', 'nineteen', 'nine', 'three', 'sixteen'] ['thirteen', 'fourteen', 'eleven', 'fifteen', 'ten'] ['two', 'eighteen', 'eight', 'twelve', 'seven'] ['four', 'one', 'seventeen', 'six', 'five'] >>> From phillor9 at gmail.com Wed Apr 12 18:56:31 2023 From: phillor9 at gmail.com (Phil) Date: Thu, 13 Apr 2023 08:56:31 +1000 Subject: [Tutor] ttk menubutton In-Reply-To: References: Message-ID: <9c27cb2d-8906-b754-0c24-3df8944523ce@gmail.com> On 12/4/23 19:35, Alan Gauld via Tutor wrote: Thank you Alan for your reply. > What is menu_button? Unless I'm mistaken, there are two similar ttk widgets, a menubutton and an optionmenu. I think the optionmenu widget might be what I want. I'm having no end of trouble maintaining an Internet connection, because I'm currently a long way from a telephone tower, so searching for information is frustratingly difficult. > However I must ask why you are using bind in this case - its > more common to just attach the event handler to the menu item > when you create it. Like > > self.menu = tk.Menu(self.mainwindow) > self.menu.add_command(label="Option 1", > command=self.on_Option) My AI friend had made many suggestions that didn't work and that was one. > > Or if you want to use the same handler for multiple items use a lambda > to pass an option: > > self.menu = tk.Menu(self.mainwindow) > self.menu.add_command(label="Option 1", > command=lambda : self.on_option(1)) > self.menu.add_command(label="Option 2", > command=lambda : self.on_option(2)) > > def on_option(self, option): > # do something with option here I'll see if I can work your suggestion into what I have, or maybe start afresh. -- Regards, Phil From breamoreboy at gmail.com Wed Apr 12 10:01:51 2023 From: breamoreboy at gmail.com (Mark Lawrence) Date: Wed, 12 Apr 2023 15:01:51 +0100 Subject: [Tutor] Can't use packages in newly installed python 3.11.3 In-Reply-To: References: <9f5bfa21-77e0-efe5-97c3-ffdce1ea627f@wichmann.us> <19b7b0ad-6d53-df4c-2f4b-4a3851bbc986@gmail.com> Message-ID: <2e65d92f-0e3d-bf66-90b1-6a54bf371cdc@gmail.com> On 12/04/2023 14:29, Mats Wichmann wrote: > On 4/11/23 12:27, Torbj?rn Svensson Diaz wrote: > > Well, this looks good, is it working now?? You've got a "user install" > of numpy tied to your new Python (on linux it builds those in your > .local directory, I forget where it puts them in Windows but since that > wasn't the question space...). > >> python3.11 -m pip show numpy >> Name: numpy >> Version: 1.24.2 >> Location: /home/user/.local/lib/python3.11/site-packages >> Requires: > >> python3.10 -m pip show numpy >> Name: numpy >> Version: 1.21.5 >> Location: /usr/lib/python3/dist-packages > > If folk want to upgrade a package to the latest version say:- pip install -U numpy -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From THURMHILL33 at outlook.com Wed Apr 12 12:48:16 2023 From: THURMHILL33 at outlook.com (Thurman Hill) Date: Wed, 12 Apr 2023 16:48:16 +0000 Subject: [Tutor] Module Review Message-ID: I?m getting a type error when I put this into the blanks? Please help I?ve been stuck for weeks? Fill in the blanks to print the even numbers from 2 to 12. number = range(2,12+1,2) # Initialize the variable while number > 0: # Complete the while loop condition print(number, end=" ") number # Increment the variable # Should print 2 4 6 8 10 12 Error: Error on line 2: while number > 0: # Complete the while loop condition TypeError: '>' not supported between instances of 'range' and 'int' Sent from Mail for Windows From torbjorn.svensson.diaz at gmail.com Wed Apr 12 06:45:39 2023 From: torbjorn.svensson.diaz at gmail.com (=?UTF-8?Q?Torbj=c3=b6rn_Svensson_Diaz?=) Date: Wed, 12 Apr 2023 12:45:39 +0200 Subject: [Tutor] Can't use packages in newly installed python 3.11.3 In-Reply-To: <9fd6de8c-22d4-886f-610b-d8d144c47e3f@wichmann.us> References: <9fd6de8c-22d4-886f-610b-d8d144c47e3f@wichmann.us> Message-ID: On 2023-04-11 18:56, Mats Wichmann wrote: Dear Mats, Alan and Dennis, Thanks for all your guidance. My problem is now resolved and I learned something in the process as well. Best regards, -- Torbj?rn Svensson Diaz From alan.gauld at yahoo.co.uk Wed Apr 12 20:11:28 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 13 Apr 2023 01:11:28 +0100 Subject: [Tutor] Module Review In-Reply-To: References: Message-ID: On 12/04/2023 17:48, Thurman Hill wrote: > Fill in the blanks to print the even numbers from 2 to 12. > > number = range(2,12+1,2) # Initialize the variable Notice that in Python 3 range returns a range object. So number is a range object > while number > 0: # Complete the while loop condition Now you are comparing a range object to a number. Thats not a valid comparison so Python objects. > print(number, end=" ") > number # Increment the variable I have no idea how you think that works or what it does. > # Should print 2 4 6 8 10 12 You don't need a while loop a for loop over the range will do it just fine > while number > 0: # Complete the while loop condition > TypeError: '>' not supported between instances of 'range' and 'int' As I explained above - number is a range object. You can't compare it to a number. Incidentally even if your code had resulted in a series of numbers, which I think is what you expected, none of them would be less than 0 so your loop would never have ended... A tip for the future: when you hit a problem in Python that you don't understand use print statements to see what you variables look like. In this case a print(number) Would have should that it was not in fact a number but a range object. Also try things out in the interactive prompt: >>> range(2,12+1,2) Would also have shown that you got a range object >>> list(range(2,12+1,2)) [2,4,6,8,10,12] Would show the content of the list version. -- 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 Apr 12 20:19:08 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 13 Apr 2023 01:19:08 +0100 Subject: [Tutor] ttk menubutton In-Reply-To: <9c27cb2d-8906-b754-0c24-3df8944523ce@gmail.com> References: <9c27cb2d-8906-b754-0c24-3df8944523ce@gmail.com> Message-ID: On 12/04/2023 23:56, Phil wrote: >> What is menu_button? > > Unless I'm mistaken, there are two similar ttk widgets, a menubutton and Yes but my point was that you were using menu_button in your code as a name (not a widget) in the bind call, but you had not created any such variable. Normally that would result in a NameError but if such a name existed in the module (maybe you had (foolishly) used, say, from ttk import * ) then there would be no helpful error message, just your code would break. > My AI friend had made many suggestions that didn't work and that was one. If you are trying to use an AI tool like chatGPT to get code then good luck! I've tried it several times and it has never, not once, produced actual code that works. Nothing beats actually knowing what you are doing yourself. -- 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 Apr 12 20:37:33 2023 From: phillor9 at gmail.com (Phil) Date: Thu, 13 Apr 2023 10:37:33 +1000 Subject: [Tutor] ttk menubutton In-Reply-To: References: <9c27cb2d-8906-b754-0c24-3df8944523ce@gmail.com> Message-ID: On 13/4/23 10:19, Alan Gauld via Tutor wrote: > > Yes but my point was that you were using menu_button in your > code as a name (not a widget) in the bind call, but you had > not created any such variable. Sorry for the confusion, I'm wary of burdening the list with excessive code. I'm now using the optionmenu widget which is doing what I want. > If you are trying to use an AI tool like chatGPT to get code then good > luck! Generally, I find AI useful. It doesn't always provide the correct answer but the answer is only sometimes way off the mark. I also use the copilot extension within the IDE. Likewise, it's generally useful. -- Regards, Phil From PythonList at DancesWithMice.info Wed Apr 12 20:37:54 2023 From: PythonList at DancesWithMice.info (dn) Date: Thu, 13 Apr 2023 12:37:54 +1200 Subject: [Tutor] Module Review In-Reply-To: References: Message-ID: <290b89a2-f56e-d617-c423-eb5d542c5dd2@DancesWithMice.info> Hi, Am a little confused by the title - where's the (Python) module? but, let's get on with the question... On 13/04/2023 04.48, Thurman Hill wrote: > I?m getting a type error when I put this into the blanks? Please help I?ve been stuck for weeks? > > Fill in the blanks to print the even numbers from 2 to 12. > > number = range(2,12+1,2) # Initialize the variable > while number > 0: # Complete the while loop condition > print(number, end=" ") > number # Increment the variable > > # Should print 2 4 6 8 10 12 > > Error: > Error on line 2: > while number > 0: # Complete the while loop condition > TypeError: '>' not supported between instances of 'range' and 'int' The experimentation that will help with this sort of problem can be most-easily carried-out in the Python REPL - open a terminal*, start Python, and be able to enter one line of code at a time and have Python immediately execute it (or tell you where things went wrong). * please 'translate' if you are an MS-Win user The error message says it all - of course, if you don't know it all, then... Yes, they can be quite opaque! "TypeError...'range' and 'int' So, what is a type-error? It comes when Python is asked to do something with two operands of different types that it just can't do, ie trying to add apples to oranges, as the saying goes. In this case, the two types are: 'range' and 'int'. The range comes from line 1, and "int" is short for "integer". Thus, we're talking about "number" and "0" (resp). In the REPL, if you type the first line, you can then investigate the result. If you try: print( number ) -> range(2, 13, 2) it appears to tell you what you already know - and exactly what you told Python you wanted - and the "range()" part tells you that it is both of type "range" and not an integer. You can confirm this with: print( type( number ) ) -> In fact, the "range-object" (called "number") is a "collection" of integers: the "2 4 6 8 10 12" you expect. However, the code (in the while-condition) is trying to treat it as if it were a single integer. You can read-up about range-objects, but the full-fat description is a bit complicated for beginners. Have you looked at lists and for-loops? If not, now is the time to do-so! Lists are THE basic "collection" and are "built-in" to Python! For-loops are designed to process each element in a collection, one after the other. Accordingly, are a much better tool than the while (etc) loop (which won't work anyway in its current form). At this stage in your Python-learning, you can get-away-with treating the "number" range, as if it were a list. To double-check the above, try: print( list( number ) ) -> [2, 4, 6, 8, 10, 12] What's happening here is that the range (number) is being turned into a list, and then the list of integers printed. Exactly what you want? Once you've had time to read and think about that, it's time to go back to the REPL and try-out these new ideas... Once you have things working in the REPL, it is relatively easy to copy-paste (the good bits!) into a code-file ("script")... NB I (for one) am having trouble imagining that "number" describes a list/range of integers. If it were called "even_numbers" for example (note the plural - because it is a collection of multiple integers), will such also help you get your head around the ideas? Come back to us once you've had a chance to experiment... -- Regards, =dn From jankenin at gmx.de Thu Apr 13 06:47:08 2023 From: jankenin at gmx.de (Jan Kenin) Date: Thu, 13 Apr 2023 12:47:08 +0200 Subject: [Tutor] working intime on pipes In-Reply-To: References: Message-ID: Hello, I have command, that runs pretty long and outputs many lines, that I would like to filter. I call the command with p=subprocess.Popen( command, stdout=out ) p.wait() If out were sys.stdout, all output would be printed to the screen, which I dont want to. If out were an object with a write( *args ) attribute, this is not called by p. p just calls out.fileno() and all is written to out without using the write attribute. How can I work on the lines sent to out, _before_ p has finished? Thanks for usefull advice! From mats at wichmann.us Thu Apr 13 15:28:17 2023 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 13 Apr 2023 13:28:17 -0600 Subject: [Tutor] working intime on pipes In-Reply-To: References: Message-ID: On 4/13/23 04:47, Jan Kenin wrote: > Hello, > > I have command, that runs pretty long and outputs many lines, that I > would like to filter. I call the command with > > p=subprocess.Popen( command, stdout=out ) > > p.wait() > > If out were sys.stdout, all output would be printed to the screen, which > I dont want to. > > If out were an object with a write( *args ) attribute, this is not > called by p. p just calls out.fileno() and all is written to out without > using the write attribute. > > How can I work on the lines sent to out, _before_ p has finished? > > Thanks for usefull advice! If your question is how can you work with the output from the command before the command is complete, you want to create the Popen object with stdout pointing back to you (stdout=subprocess.PIPE), and then use p.poll(). As long as poll returns None, it's still running, but you can read stuff. It's possible you may have to fiddle buffering, etc. in order to get things working as you want. When it is done, poll() returns the returncode, to let you know the completion status. From diana.katz at gmail.com Fri Apr 14 15:12:24 2023 From: diana.katz at gmail.com (Diana Katz) Date: Fri, 14 Apr 2023 15:12:24 -0400 Subject: [Tutor] Tensorflow Message-ID: I tried installing tensor flow on my computer and I received this error message. C:\pythin>pip install tensorflow-2.12.0-cp311-cp311-win_amd64.whl 'pip' is not recognized as an internal or external command, operable program or batch file. What can I do next? Thanks! From alan.gauld at yahoo.co.uk Fri Apr 14 15:32:31 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 14 Apr 2023 20:32:31 +0100 Subject: [Tutor] Tensorflow In-Reply-To: References: Message-ID: On 14/04/2023 20:12, Diana Katz wrote: > I tried installing tensor flow on my computer and I received this error > message. > > C:\pythin>pip install tensorflow-2.12.0-cp311-cp311-win_amd64.whl > 'pip' is not recognized as an internal or external command, > operable program or batch file. > > What can I do next? Try running C:\pythin> py -m pip install tensorflow-2.12.0-cp311-cp311-win_amd64.whl instead, that often produces better results. -- 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 diana.katz at gmail.com Fri Apr 14 15:57:05 2023 From: diana.katz at gmail.com (Diana Katz) Date: Fri, 14 Apr 2023 15:57:05 -0400 Subject: [Tutor] Tensorflow In-Reply-To: References: Message-ID: I tried but got this error message: C:\Users\merma>cd C:\python C:\python>C: C:\python>C:\python> py -m pip install tensorflow-2.12.0-cp311-cp311-win_amd64.whl 'C:\python' is not recognized as an internal or external command, operable program or batch file. C:\python> On Friday, April 14, 2023, Alan Gauld via Tutor wrote: > On 14/04/2023 20:12, Diana Katz wrote: > > I tried installing tensor flow on my computer and I received this error > > message. > > > > C:\pythin>pip install tensorflow-2.12.0-cp311-cp311-win_amd64.whl > > 'pip' is not recognized as an internal or external command, > > operable program or batch file. > > > > What can I do next? > > Try running > > C:\pythin> py -m pip install tensorflow-2.12.0-cp311-cp311-win_amd64.whl > > instead, that often produces better results. > > > -- > 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 mats at wichmann.us Fri Apr 14 16:12:35 2023 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 14 Apr 2023 14:12:35 -0600 Subject: [Tutor] Tensorflow In-Reply-To: References: Message-ID: On 4/14/23 13:57, Diana Katz wrote: > I tried but got this error message: > > > C:\Users\merma>cd C:\python > > > C:\python>C: > > > C:\python>C:\python> py -m pip install > tensorflow-2.12.0-cp311-cp311-win_amd64.whl > > 'C:\python' is not recognized as an internal or external command, > > operable program or batch file. don't type in the cmd.exe prompt (the C:\python part) From diana.katz at gmail.com Fri Apr 14 16:37:41 2023 From: diana.katz at gmail.com (Diana Katz) Date: Fri, 14 Apr 2023 16:37:41 -0400 Subject: [Tutor] Fwd: Tensorflow In-Reply-To: References: Message-ID: ---------- Forwarded message ---------- From: *Diana Katz* Date: Friday, April 14, 2023 Subject: Tensorflow To: Mats Wichmann Thank you; however, now I am getting a new error: C:\Users\merma> py -m pip install tensorflow-2.12.0-cp311-cp311- win_amd64.whl WARNING: Requirement 'tensorflow-2.12.0-cp311-cp311-win_amd64.whl' looks like a filename, but the file does not exist Processing c:\users\merma\tensorflow-2.12.0-cp311-cp311-win_amd64.whl ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: 'C:\\Users\\merma\\tensorflow-2.12.0-cp311-cp311-win_amd64. whl' Thanks so much On Friday, April 14, 2023, Mats Wichmann wrote: > On 4/14/23 13:57, Diana Katz wrote: > >> I tried but got this error message: >> >> >> C:\Users\merma>cd C:\python >> >> >> C:\python>C: >> >> >> C:\python>C:\python> py -m pip install >> tensorflow-2.12.0-cp311-cp311-win_amd64.whl >> >> 'C:\python' is not recognized as an internal or external command, >> >> operable program or batch file. >> > > don't type in the cmd.exe prompt (the C:\python part) > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From diana.katz at gmail.com Fri Apr 14 17:12:18 2023 From: diana.katz at gmail.com (Diana Katz) Date: Fri, 14 Apr 2023 17:12:18 -0400 Subject: [Tutor] Matplotlib.pyplot Message-ID: I have tensorflow now installed but I?m struggling to install matplotlib . This is my error: C:\Users\merma>py -m pip install matplotlib.pyplot ERROR: Could not find a version that satisfies the requirement matplotlib.pyplot (from versions: none) ERROR: No matching distribution found for matplotlib.pyplot From mats at wichmann.us Fri Apr 14 17:16:31 2023 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 14 Apr 2023 15:16:31 -0600 Subject: [Tutor] Matplotlib.pyplot In-Reply-To: References: Message-ID: On 4/14/23 15:12, Diana Katz wrote: > I have tensorflow now installed but I?m struggling to install matplotlib . > This is my error: > > > C:\Users\merma>py -m pip install matplotlib.pyplot > > ERROR: Could not find a version that satisfies the requirement > matplotlib.pyplot (from versions: none) > > ERROR: No matching distribution found for matplotlib.pyplot Hmmm, I think pyplot is an included part of matplotlib, so not sure anything further needs installing? Presumably someone here knows better. Ah... there seem to be answers on stack overflow. Hopefully even correct ones... :) https://stackoverflow.com/questions/74527084/how-can-i-install-pyplot From diana.katz at gmail.com Fri Apr 14 18:58:49 2023 From: diana.katz at gmail.com (Diana Katz) Date: Fri, 14 Apr 2023 18:58:49 -0400 Subject: [Tutor] Matplotlib.pyplot In-Reply-To: References: Message-ID: I am getting an error when i run my code that i don't have numpy but it shows i already installed it. Any advise? C:\Users\merma\PycharmProjects\pythonProject1\venv\Scripts\python.exe C:\Users\merma\PycharmProjects\pythonProject1\main.py Traceback (most recent call last): File "C:\Users\merma\PycharmProjects\pythonProject1\main.py", line 3, in import numpy as np ModuleNotFoundError: No module named 'numpy' Process finished with exit code 1 import numpy as np print("numpy version: " + np.__version__) numpy version: 1.23.5 shows i already installed it On Fri, Apr 14, 2023 at 5:16?PM Mats Wichmann wrote: > On 4/14/23 15:12, Diana Katz wrote: > > I have tensorflow now installed but I?m struggling to install matplotlib > . > > This is my error: > > > > > > C:\Users\merma>py -m pip install matplotlib.pyplot > > > > ERROR: Could not find a version that satisfies the requirement > > matplotlib.pyplot (from versions: none) > > > > ERROR: No matching distribution found for matplotlib.pyplot > > > Hmmm, I think pyplot is an included part of matplotlib, so not sure > anything further needs installing? Presumably someone here knows better. > > Ah... there seem to be answers on stack overflow. Hopefully even > correct ones... :) > > https://stackoverflow.com/questions/74527084/how-can-i-install-pyplot > > > > From diana.katz at gmail.com Fri Apr 14 21:18:03 2023 From: diana.katz at gmail.com (Diana Katz) Date: Fri, 14 Apr 2023 21:18:03 -0400 Subject: [Tutor] error message In-Reply-To: References: Message-ID: I have everything installed to run an AI program and I?m getting a bunch of error messages. What do these mean/what should I do? > C:\Users\merma\PycharmProjects\pythonProject1\venv\Scripts\python.exe > C:\Users\merma\PycharmProjects\pythonProject1\main.py > Found 0 images belonging to 0 classes. > 2023-04-14 21:10:11.839560: W > tensorflow/tsl/framework/cpu_allocator_impl.cc:83] *Allocation of > 29491200 exceeds 10% of free system memory.* > 2023-04-14 21:10:11.871621: W > tensorflow/tsl/framework/cpu_allocator_impl.cc:83] Allocation of 29491200 > exceeds 10% of free system memory. > 2023-04-14 21:10:11.881745: W > tensorflow/tsl/framework/cpu_allocator_impl.cc:83] Allocation of 29491200 > exceeds 10% of free system memory. > Traceback (most recent call last): > File "C:\Users\merma\PycharmProjects\pythonProject1\main.py", line 46, > in > history = model.fit( > ^^^^^^^^^^ > File > "C:\Users\merma\PycharmProjects\pythonProject1\venv\Lib\site-packages\keras\utils\traceback_utils.py", > line 70, in error_handler > raise e.with_traceback(filtered_tb) from None > File > "C:\Users\merma\PycharmProjects\pythonProject1\venv\Lib\site-packages\keras\preprocessing\image.py", > line 103, in __getitem__ > raise ValueError( > ValueError: *Asked to retrieve element 0, but the Sequence has length 0* > > Process finished with exit code 1 > > > - > From wlfraed at ix.netcom.com Fri Apr 14 22:28:18 2023 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 14 Apr 2023 22:28:18 -0400 Subject: [Tutor] Fwd: Tensorflow References: Message-ID: On Fri, 14 Apr 2023 16:37:41 -0400, Diana Katz declaimed the following: > >C:\Users\merma> py -m pip install tensorflow-2.12.0-cp311-cp311- >win_amd64.whl > >WARNING: Requirement 'tensorflow-2.12.0-cp311-cp311-win_amd64.whl' looks >like a filename, but the file does not exist > Typically one specifies just the module to be installed; pip will commonly determine the newest version compatible with the python being used. If one needs a specific version of a module, that is done by specifying an option to the pip arguments. https://pip.pypa.io/en/stable/reference/requirement-specifiers/ From wlfraed at ix.netcom.com Fri Apr 14 22:58:09 2023 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 14 Apr 2023 22:58:09 -0400 Subject: [Tutor] Matplotlib.pyplot References: Message-ID: <3v2k3ilov7ed0vnbems1rvtlrbr1nr9kn3@4ax.com> On Fri, 14 Apr 2023 18:58:49 -0400, Diana Katz declaimed the following: >I am getting an error when i run my code that i don't have numpy but it >shows i already installed it. Any advise? > >C:\Users\merma\PycharmProjects\pythonProject1\venv\Scripts\python.exe This states that you have python installed under the Scripts directory of a virtual environment >C:\Users\merma\PycharmProjects\pythonProject1\main.py Traceback (most >recent call last): File While this indicates your project file itself is /not/ inside the virtual environment, and is likely using a system-wide python installation. >"C:\Users\merma\PycharmProjects\pythonProject1\main.py", line 3, in > import numpy as np ModuleNotFoundError: No module named >'numpy' Process finished with exit code 1 > You have both PyCharm and a virtual environment mentioned. Did you install numpy INTO the virtual environment? One reason for the virtual environment (which I've never used) is that one can install modules into the \venv that are not visible to the outside. And maybe vice-versa -- system-wide modules may not be visible inside the \venv > >import numpy as np >print("numpy version: " + np.__version__) >numpy version: 1.23.5 > Is that from a PyCharm window, Powershell, or plain Windows command shell. After starting PyCharm, and that \venv, open the "Python Packages" window and scroll down to see if numpy shows up. And try this in Powershell -- without starting the \venv Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. Try the new cross-platform PowerShell https://aka.ms/pscore6 PS C:\Users\Owner> python -m pip list | Select-String "numpy" numpy 1.24.2 PS C:\Users\Owner> Now start the \venv PS C:\Users\Owner> python -m venv mytestvenv PS C:\Users\Owner> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser Execution Policy Change The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose you to the security risks described in the about_Execution_Policies help topic at https:/go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy? [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): A PS C:\Users\Owner> .\mytestvenv\Scripts\Activate.ps1 (mytestvenv) PS C:\Users\Owner> python -m pip list | Select-String "numpy" (mytestvenv) PS C:\Users\Owner> ... shows that creating a virtual environment and activating it does NOT give access to the system-wide library of installed modules! From wlfraed at ix.netcom.com Fri Apr 14 23:04:43 2023 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 14 Apr 2023 23:04:43 -0400 Subject: [Tutor] error message References: Message-ID: On Fri, 14 Apr 2023 21:18:03 -0400, Diana Katz declaimed the following: >I have everything installed to run an AI program and I?m getting a bunch of >error messages. What do these mean/what should I do? Since we haven't seen (or I missed it) the code of this program, we are left guessing... > > >> C:\Users\merma\PycharmProjects\pythonProject1\venv\Scripts\python.exe >> C:\Users\merma\PycharmProjects\pythonProject1\main.py >> Found 0 images belonging to 0 classes. That seems to indicate you are doing something with image recognition -- but there is no image data found during initial set-up of the program. >> Traceback (most recent call last): >> File "C:\Users\merma\PycharmProjects\pythonProject1\main.py", line 46, >> in >> history = model.fit( >> ^^^^^^^^^^ >> File >> "C:\Users\merma\PycharmProjects\pythonProject1\venv\Lib\site-packages\keras\utils\traceback_utils.py", >> line 70, in error_handler >> raise e.with_traceback(filtered_tb) from None >> File >> "C:\Users\merma\PycharmProjects\pythonProject1\venv\Lib\site-packages\keras\preprocessing\image.py", >> line 103, in __getitem__ >> raise ValueError( >> ValueError: *Asked to retrieve element 0, but the Sequence has length 0* If my guess on the image data is correct, then you have no data on which to perform a fit. That goes beyond what I'd consider suitable to this list -- you'd be better off finding/reading documentation for the program you are trying out, documentation for "keras", etc. From PythonList at DancesWithMice.info Sat Apr 15 13:46:50 2023 From: PythonList at DancesWithMice.info (dn) Date: Sun, 16 Apr 2023 05:46:50 +1200 Subject: [Tutor] Module Review In-Reply-To: References: <290b89a2-f56e-d617-c423-eb5d542c5dd2@DancesWithMice.info> Message-ID: On 16/04/2023 03.28, Thurman Hill wrote: > number?= 2 #?Initialize?the?variable > while?number?< 13: #?Complete?the?while?loop?condition > print(number,?end="?") > ????number?+2 #?Increment?the?variable > > #?Should?print?2?4?6?8?10?12 > > this is what i have now but i think the assessment may have messed up > its saying it takes more than 5 seconds > to process so i need a simpler solution. 1 Please check how the email-client works, to ensure reply to list (cf one person only) 2 Did you copy-paste the code from the script? As above, it won't work/has a syntax error. 3 Will https://www.codespeedy.com/augmented-assignment-in-python/ help? > On Wed, Apr 12, 2023 at 8:40?PM dn via Tutor > wrote: > > Hi, > > Am a little confused by the title - where's the (Python) module? > but, let's get on with the question... > > > On 13/04/2023 04.48, Thurman Hill wrote: > > I?m getting a type error when I put this into the blanks? Please > help I?ve been stuck for weeks? > > > > Fill in the blanks to print the even numbers from 2 to 12. > > > > number = range(2,12+1,2) # Initialize the variable > > while number > 0: # Complete the while loop condition > >? ? ? print(number, end=" ") > >? ? ? number # Increment the variable > > > > # Should print 2 4 6 8 10 12 > > > > Error: > > Error on line 2: > >? ? ? while number > 0: # Complete the while loop condition > > TypeError: '>' not supported between instances of 'range' and 'int' > > The experimentation that will help with this sort of problem can be > most-easily carried-out in the Python REPL - open a terminal*, start > Python, and be able to enter one line of code at a time and have Python > immediately execute it (or tell you where things went wrong). > > * please 'translate' if you are an MS-Win user > > The error message says it all - of course, if you don't know it all, > then... Yes, they can be quite opaque! > > "TypeError...'range' and 'int' > > So, what is a type-error? It comes when Python is asked to do something > with two operands of different types that it just can't do, ie > trying to > add apples to oranges, as the saying goes. > > In this case, the two types are: 'range' and 'int'. The range comes > from > line 1, and "int" is short for "integer". Thus, we're talking about > "number" and "0" (resp). > > In the REPL, if you type the first line, you can then investigate the > result. If you try: > > print( number ) > -> range(2, 13, 2) > > it appears to tell you what you already know - and exactly what you > told > Python you wanted - and the "range()" part tells you that it is both of > type "range" and not an integer. > > You can confirm this with: > > print( type( number ) ) > -> > > > In fact, the "range-object" (called "number") is a "collection" of > integers: the "2 4 6 8 10 12" you expect. > > However, the code (in the while-condition) is trying to treat it as if > it were a single integer. > > You can read-up about range-objects, but the full-fat description is a > bit complicated for beginners. > > Have you looked at lists and for-loops? If not, now is the time to > do-so! Lists are THE basic "collection" and are "built-in" to Python! > For-loops are designed to process each element in a collection, one > after the other. Accordingly, are a much better tool than the while > (etc) loop (which won't work anyway in its current form). > > At this stage in your Python-learning, you can get-away-with treating > the "number" range, as if it were a list. > > To double-check the above, try: > > print( list( number ) ) > -> [2, 4, 6, 8, 10, 12] > > What's happening here is that the range (number) is being turned into a > list, and then the list of integers printed. Exactly what you want? > > > Once you've had time to read and think about that, it's time to go back > to the REPL and try-out these new ideas... > > > Once you have things working in the REPL, it is relatively easy to > copy-paste (the good bits!) into a code-file ("script")... > > > NB I (for one) am having trouble imagining that "number" describes a > list/range of integers. If it were called "even_numbers" for example > (note the plural - because it is a collection of multiple integers), > will such also help you get your head around the ideas? > > > Come back to us once you've had a chance to experiment... > > -- > Regards, > =dn > _______________________________________________ > Tutor maillist? - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > -- Regards, =dn From wlfraed at ix.netcom.com Sat Apr 15 15:59:31 2023 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sat, 15 Apr 2023 15:59:31 -0400 Subject: [Tutor] Module Review References: <290b89a2-f56e-d617-c423-eb5d542c5dd2@DancesWithMice.info> Message-ID: On Sun, 16 Apr 2023 05:46:50 +1200, dn via Tutor declaimed the following: >On 16/04/2023 03.28, Thurman Hill wrote: >> number?= 2 #?Initialize?the?variable >> while?number?< 13: #?Complete?the?while?loop?condition >> print(number,?end="?") >> ????number?+2 #?Increment?the?variable >> >> #?Should?print?2?4?6?8?10?12 >> >> this is what i have now but i think the assessment may have messed up >> its saying it takes more than 5 seconds >> to process so i need a simpler solution. >2 Did you copy-paste the code from the script? As above, it won't >work/has a syntax error. > Presuming the code is exactly as posted, it has two, if not three errors... Indentation being one of them. The other is logic, so not caught by the interpreter (I actually thought it would produce some message, but it seems the result of that statement is to execute, and throw away the result) C:\Users\Owner>python junk.py File "C:\Users\Owner\junk.py", line 4 print(number, end=" ") ^ IndentationError: expected an indented block after 'while' statement on line 3 C:\Users\Owner> Fixing that lets the program run... C:\Users\Owner>python junk.py 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 Traceback (most recent call last): File "C:\Users\Owner\junk.py", line 4, in print(number, end=" ") KeyboardInterrupt ^C C:\Users\Owner> The mention of "assessment" makes it sound like the OP is not running the code on a local machine where they can see the results, but is making submittals to some web-based course. With that indentation correction, the "while" loop will never end, so I can see a background processor on a web site reporting that the assignment is running over some allocated time slot. A corrected version runs so fast, the clock used by time.time() doesn't even increment on my system... From threesomequarks at proton.me Sat Apr 15 20:44:36 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Sun, 16 Apr 2023 00:44:36 +0000 Subject: [Tutor] Python to non-Python Message-ID: I recently was asked to take some Python Code snippets and rewrite it in R. This was code I had not written, and it made me think about the process including from the perspective of some of the questions asked here. Questions often are asked why Python does not do something that some language they learned earlier or know about. I learned both R and Python fairly late after many other languages. So I am fairly comfortable with having many different approaches to the same kinds of problems both across languages and within one. Many are not flexible and one way to learn to be is to become multilingual in a computer language sense. So what interested me here, as I see both languages as valid but with different and overlapping abilities, is what was an issue for me in the task. Without explicit details, one barrier was the use of a common technique in Python: first, second, third, last = f(args) Would you believe quite a few other languages insist on returning only one thing with no unpacking easily available? In this case, I returned a named list and the returned function value had to be saved as something like "values" and then examined so to get "second" you had to use a notation like values[[2]] or values$second or other such forms. So one lesson if writing something in python that may need to be copied into another language is perhaps not to overuse the ability to return multiple things. The feature is great but not easily portable. One other lesson to mention is that the code used functions from numpy and pandas that I considered silly. The data it was operating on was not vectorized and was just individual values. The Python interpreter was happy to work on a scalar or with the vectorized data structures used by numpy or pandas of any length BUT when I hit an IF statement checking if it was non-null, that is not vectorized and blows up for anything more than length one. I had no comments in the code and initially assumed the data was a vector of many rows or something until that IF indicated otherwise. In R, for what it is worth, everything is a vector, and the operations they borrowed from numpy and pandas are built-in. Still, without info on what the code actually did (which I figured out on my own) translation was harder than it needed to be. The other thing I realized was about myself and this sort of applies to both Python and R. I do not like visible loops much and detest complex deeply nested loops. There is nothing wrong with them, and little programming can be done without looping, but modern languages often help you hide many loops. So when I rewrote the code, I found myself looking for ways to sort of simplify. I took a big chunk of code that was an IF then and ELIF and another few ELIF followed by an ELSE (upper case is for emphasis, not the actual code written) and used a package in R that allowed me to do something more like this: keywords CASE condition ~ return value, CASE condition ~ return value, ... CASE condition ~ return value, default ~ return value Basically the above sets the value of a variable by trying the first case and if the condition works, exits the whole thing with a value. If the first condition fails, it does the same with the second and so on, till it hits the default. That is a sort of hidden loop that is roughly equivalent but in some sense easier for me to read and reason with. Python has some new features along similar lines. There are many such approaches, including some kinds of functional programing and recursion. As for the nested loops, I moved some into functions called from the above so the overall outline is simpler.And, I rearranged the order and logic in places such as doing the more common things first. Enough examples! Then I asked myself what someone might do if asked to change my R code back into similar Python. I think sometimes a good teaching tool for learning a language can be taking one method of solving a problem then ask them to solve the same problem using a different method in the same language or simply to take a working program from another language or pseudocode. A real eye opener for me in python was how some loop methods could be written with some syntactic sugar as list comprehensions. Again, nice feature but it takes a little work doing the same thing in most other languages. Not much but ... Sent with [Proton Mail](https://proton.me/) secure email. From alan.gauld at yahoo.co.uk Sun Apr 16 04:12:24 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 16 Apr 2023 09:12:24 +0100 Subject: [Tutor] Python to non-Python In-Reply-To: References: Message-ID: On 16/04/2023 01:44, ThreeBlindQuarks via Tutor wrote: > I recently was asked to take some Python Code snippets and rewrite it in R. Translating a design between languages is always interesting, especially if the languages have significant paradigm differences. Back in 1990 I was involved in a networking project where we wrote a protocol translator (X25 and TCP/IP to CMIP) in C, but using OOP style and a bespoke extension library. That translator is still running (and extended to several other protocols with the original X25 long gone and CMIP replaced by SNMP!). But in the intervening time the language has been moved from C to C++(around 1994) then to Java (around 2001) then Python(in 2012) and I recently heard they are now moving it to Rust. The basic design has remained unchanged, most of the core classes and the architecture are still there, but the language is radically different. But that's because they translated between OOP languages. What would they have done if asked to translate to, say Haskell? or Prolog? In general, translating paradigms is the hard bit, translating language features is usually straightforward. > Questions often are asked why Python does not do something > that some language they learned earlier or know about. Yes, the desire for universal language features is often present in learners, but once you know a dozen or more languages 9and 3 or 4 paradigms) you learn to just appreciate the new language for its own features and not crave the past. > Without explicit details, one barrier was the use of a common technique in Python: > > first, second, third, last = f(args) > > Would you believe quite a few other languages insist on returning only one thing I would say most languages. unpacking is quite a rare feature and I only discovered it when I used Python. A few others have introduced it now but its still rare (but a very useful shortcut) > keywords > CASE condition ~ return value, > CASE condition ~ return value, Select/Case/switch constructs are one of the areas where languages differ most in the details. They are also one of the most fault prone features in any language and one of the main things that OOP tries to eliminate - use polymorphism instead its much more reliable and performant. > As for the nested loops, I moved some into functions called > from the above so the overall outline is simpler. One reason the protocol translator mentioned above has had such a long run is that the design was explicitly done to a fairly detailed level. The design is what gets ported between languages not the code. Too many projects only have high level designs that stop at class or even module-level structure but fail to define the dynamics within the structure. -- 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 gmail.com Sun Apr 16 14:09:48 2023 From: alexkleider at gmail.com (Alex Kleider) Date: Sun, 16 Apr 2023 11:09:48 -0700 Subject: [Tutor] sqlite3 module Message-ID: I'm running Python3 within a virtualenv on a Debian machine. My question has to do with the sqlite3 module. Must I provide a value for every field in the table? It seems that this shouldn't be necessary if default values are specified but the following code suggests that one must in fact supply a value for _every_ field. When I complied (up to a point, giving the data dict values for all columns _except_ the autoincrimenting primary key) I got the same error; It would seem to me that it shouldn't accept an entry for the primary key rather than insist on it. Is there a way to make what I want to do possible? Thanks in advance for any guidance provided. """ (p9) alex at t460:~/Git/Sql$ sqlite3 ~/Git/Sql/Secret/club.db SQLite version 3.34.1 2021-01-20 14:10:07 Enter ".help" for usage hints. sqlite> .schema Receipts CREATE TABLE Receipts ( ReceiptID INTEGER PRIMARY KEY, personID INTEGER NOT NULL, date_recieved TEXT NOT NULL, dues INTEGER DEFAULT NULL, dock INTEGER DEFAULT NULL, kayak INTEGER DEFAULT NULL, mooring INTEGER DEFAULT NULL, acknowledged TEXT DEFAULT NULL --date value ); sqlite> .quit (p9) alex at t460:~/Git/Sql$ cat enter.py #!/usr/bin/env python3 # File: enter.py import sqlite3 db_file_name = '/home/alex/Git/Sql/Secret/club.db' db = sqlite3.connect(db_file_name) cursor = db.cursor() data = {"dues": 50, "date_received": "20230407", "date_acknowledged": "20230410", } f_keys = ", ".join([":"+key for key in data.keys()]) query = "INSERT INTO Receipts VALUES ({});".format(f_keys) cursor.executemany(query, data) cursor.close() db.commit() db.close() (p9) alex at t460:~/Git/Sql$ ./enter.py Traceback (most recent call last): File "/home/alex/Git/Sql/./enter.py", line 16, in cursor.executemany(query, data) sqlite3.OperationalError: table Receipts has 8 columns but 3 values were supplied (p9) alex at t460:~/Git/Sql$ """ ... again, thank you. a -- alex at kleider.ca (he/him) (sent from my current gizmo) From wlfraed at ix.netcom.com Sun Apr 16 15:09:37 2023 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sun, 16 Apr 2023 15:09:37 -0400 Subject: [Tutor] sqlite3 module References: Message-ID: On Sun, 16 Apr 2023 11:09:48 -0700, Alex Kleider declaimed the following: > >Must I provide a value for every field in the table? >It seems that this shouldn't be necessary if default values are >specified but the following code suggests that one must in fact >supply a value for _every_ field. >When I complied (up to a point, giving the data dict values for >all columns _except_ the autoincrimenting primary key) I got the >same error; It would seem to me that it shouldn't accept an entry >for the primary key rather than insist on it. The INSERT operation will require a value for EACH FIELD NAMED. However... >sqlite> .schema Receipts >CREATE TABLE Receipts ( > ReceiptID INTEGER PRIMARY KEY, > personID INTEGER NOT NULL, > date_recieved TEXT NOT NULL, > dues INTEGER DEFAULT NULL, > dock INTEGER DEFAULT NULL, > kayak INTEGER DEFAULT NULL, > mooring INTEGER DEFAULT NULL, > acknowledged TEXT DEFAULT NULL > --date value > ); >sqlite> .quit >data = {"dues": 50, > "date_received": "20230407", > "date_acknowledged": "20230410", > } ... There is no "date_acknowledged" in your schema. Furthermore, there is a spelling difference between the schema "date_recieved" and Python "date_received".... >f_keys = ", ".join([":"+key for key in data.keys()]) >query = "INSERT INTO Receipts VALUES ({});".format(f_keys) ... you aren't naming fields, so all fields are required. Use the form of INSERT with field names listed INSERT INTO Receipts (field1, field2, ..., fieldn) VALUES (value1, value2, ..., valuen) >cursor.executemany(query, data) ... the use of .executemany() may be a confusing factor, too, as that implies multiple sets of data (to populate multiple records). For your example, a simple .execute() should be sufficient (especially as the use of the dictionary precludes an ability to provide multiple rows of data). I'll have to confess -- I've never figured out how that strange .format() method operates; the old % string interpolation always made sense to me as a variant of C's formatting operations. Presuming the dictionary keys ARE required to match the schema names, I'd end up with something like (for actual production I'd work at cleaning it up some). keys = data.keys() fields = " ,".join(keys) values = [data[k] for k in keys] val_mark = " ,".join(["?" for k in keys]) cursor.execute( "INSERT INTO Receipts (%s) VALUES (%s)" % (fields, val_mark), values) The first %s receives the field names, in the order the values will be provided; the second %s receives the API "?" placeholder for each provided value. From alexkleider at gmail.com Sun Apr 16 20:27:28 2023 From: alexkleider at gmail.com (Alex Kleider) Date: Sun, 16 Apr 2023 17:27:28 -0700 Subject: [Tutor] sqlite3 module In-Reply-To: References: Message-ID: Thanks, Dennis, for your reply. Sorry about the typos! I've gone with your suggestion of using formatting rather than trying to use the dict directly. Here's an example of what works and which I think is what you've advised: ''' #!/usr/bin/env python3 # File: enter.py import sqlite3 schema = """ ReceiptID INTEGER PRIMARY KEY, personID INTEGER NOT NULL, date_received TEXT NOT NULL, dues INTEGER DEFAULT NULL, dock INTEGER DEFAULT NULL, kayak INTEGER DEFAULT NULL, mooring INTEGER DEFAULT NULL, acknowledged TEXT DEFAULT NULL """ def main(): db_file_name = '/home/alex/Git/Sql/Secret/club.db' db = sqlite3.connect(db_file_name) cursor = db.cursor() data = {"personID": 119, "date_received": "20230407", "dues": 50, "dock": 0, "kayak": 0, "mooring": 0, "acknowledged": "20230410", } f_keys = ", ".join([key for key in data.keys()]) f_values = ", ".join([repr(value) for value in data.values()]) query = ("INSERT INTO Receipts ({}) VALUES ({});" .format(f_keys, f_values)) print(query) cursor.execute(query, data) cursor.close() db.commit() db.close() if __name__ == '__main__': main() ''' Cheers, Alex On Sun, Apr 16, 2023 at 12:11?PM Dennis Lee Bieber wrote: > > On Sun, 16 Apr 2023 11:09:48 -0700, Alex Kleider > declaimed the following: > > > > >Must I provide a value for every field in the table? > >It seems that this shouldn't be necessary if default values are > >specified but the following code suggests that one must in fact > >supply a value for _every_ field. > >When I complied (up to a point, giving the data dict values for > >all columns _except_ the autoincrimenting primary key) I got the > >same error; It would seem to me that it shouldn't accept an entry > >for the primary key rather than insist on it. > > The INSERT operation will require a value for EACH FIELD NAMED. > However... > > >sqlite> .schema Receipts > >CREATE TABLE Receipts ( > > ReceiptID INTEGER PRIMARY KEY, > > personID INTEGER NOT NULL, > > date_recieved TEXT NOT NULL, > > dues INTEGER DEFAULT NULL, > > dock INTEGER DEFAULT NULL, > > kayak INTEGER DEFAULT NULL, > > mooring INTEGER DEFAULT NULL, > > acknowledged TEXT DEFAULT NULL > > --date value > > ); > >sqlite> .quit > > >data = {"dues": 50, > > "date_received": "20230407", > > "date_acknowledged": "20230410", > > } > > ... There is no "date_acknowledged" in your schema. Furthermore, there is a > spelling difference between the schema "date_recieved" and Python > "date_received".... > > >f_keys = ", ".join([":"+key for key in data.keys()]) > >query = "INSERT INTO Receipts VALUES ({});".format(f_keys) > > ... you aren't naming fields, so all fields are required. Use the form of > INSERT with field names listed > > INSERT INTO Receipts (field1, field2, ..., fieldn) VALUES (value1, > value2, ..., valuen) > > >cursor.executemany(query, data) > > ... the use of .executemany() may be a confusing factor, too, as that > implies multiple sets of data (to populate multiple records). For your > example, a simple .execute() should be sufficient (especially as the use of > the dictionary precludes an ability to provide multiple rows of data). > > > I'll have to confess -- I've never figured out how that strange > .format() method operates; the old % string interpolation always made sense > to me as a variant of C's formatting operations. > > Presuming the dictionary keys ARE required to match the schema names, > I'd end up with something like (for actual production I'd work at cleaning > it up some). > > keys = data.keys() > fields = " ,".join(keys) > values = [data[k] for k in keys] > val_mark = " ,".join(["?" for k in keys]) > cursor.execute( > "INSERT INTO Receipts (%s) VALUES (%s)" % (fields, val_mark), > values) > > The first %s receives the field names, in the order the values will be > provided; the second %s receives the API "?" placeholder for each provided > value. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- alex at kleider.ca (he/him) (sent from my current gizmo) From alexkleider at gmail.com Sun Apr 16 23:49:56 2023 From: alexkleider at gmail.com (Alex Kleider) Date: Sun, 16 Apr 2023 20:49:56 -0700 Subject: [Tutor] sqlite3 module In-Reply-To: References: Message-ID: Good of you ('Q' aka ThreeBlindQuarks:-) to respond. Yes, I've been doing more researching and am realizing that one can in fact use dicts but with None/Null as values that are not meant to be touched (at least I think that's correct; haven't tested it yet!) Amused by your German closing comment. I think you meant "Isn't that so?" (and I agree that it is) but google thinks otherwise: https://duckduckgo.com/?t=ftsa&q=german+translation+of+%22Einfach%2C+nicht+wahr!%22&ia=translations Correction, it's not Google! I seem to have set my default to ddg some time ago. Thanks to you and all that contribute so much on this list. Alex PS Don't be fooled by the sir name! My first language was actually Russian but that's a very long time ago and almost all is forgotten. PPS Interesting that my postings seem to be getting to the list as evidenced by the responses, and yet they don't come in to my inbox; only the responses do. On Sun, Apr 16, 2023 at 7:27?PM ThreeBlindQuarks wrote: > > Hi Alex, > > I won't comment on the SQL issues of the module you are using but just about Python aspects. > > You have an item you want to add to a SQL table using a dictionary with only some of the key/value pairs needed in which you expect many items to be some form of Null. Yet you are being forced to add all items even if SQL itself would happily initialize them to null because of the function you are using. You are updating from a dictionary you created that looks like: > > data = {"dues": 50, > "date_received": "20230407", > "date_acknowledged": "20230410", > } > > So suppose you have fields I will call a1 ... a3 that for your purposes are null. I suggest you change or replace data in place to update any fields not currently present to have value NULL. Any existing are left alone. Here is a function that accepts a dictionary and a list of keywords and returns the dictionary update with NULL in all the non-existent keys. You can specify any value if you change it, but this may work for your need. > > Here is the function: > > def adding_nulls(data, the_keys): > """ > Given a dictionary and a list of keywords, > add the keys specified with value NULL but only > if the key does not already exist. > """ > for a_key in the_keys: > data.setdefault(a_key) > return(data) > > Here is the result or running it using three new fields and an existing one to show it does no harm.: > > >>> data > {'dues': 50, 'date_received': '20230407', 'date_acknowledged': '20230410', 'a1': None, 'a2': None, 'a3': None} > >>> adding_nulls(data, ["a1", "a2", "a3", "dues"]) > {'dues': 50, 'date_received': '20230407', 'date_acknowledged': '20230410', 'a1': None, 'a2': None, 'a3': None} > >>> data = adding_nulls(data, ["a1", "a2", "a3", "dues"]) > >>> data > {'dues': 50, 'date_received': '20230407', 'date_acknowledged': '20230410', 'a1': None, 'a2': None, 'a3': None} > > So you can either modify the original or make a copy first. The larger dictionary may then do what you want as long as you set things up right. > > Einfach, nicht wahr! > > Q > > > > > Sent with Proton Mail secure email. > > ------- Original Message ------- > On Sunday, April 16th, 2023 at 2:09 PM, Alex Kleider wrote: > > > > I'm running Python3 within a virtualenv on a Debian machine. > > > > My question has to do with the sqlite3 module. > > > > Must I provide a value for every field in the table? > > It seems that this shouldn't be necessary if default values are > > specified but the following code suggests that one must in fact > > supply a value for every field. > > When I complied (up to a point, giving the data dict values for > > all columns except the autoincrimenting primary key) I got the > > same error; It would seem to me that it shouldn't accept an entry > > for the primary key rather than insist on it. > > > > Is there a way to make what I want to do possible? > > > > Thanks in advance for any guidance provided. > > > > """ > > (p9) alex at t460:~/Git/Sql$ sqlite3 ~/Git/Sql/Secret/club.db > > SQLite version 3.34.1 2021-01-20 14:10:07 > > Enter ".help" for usage hints. > > sqlite> .schema Receipts > > > > CREATE TABLE Receipts ( > > ReceiptID INTEGER PRIMARY KEY, > > personID INTEGER NOT NULL, > > date_recieved TEXT NOT NULL, > > dues INTEGER DEFAULT NULL, > > dock INTEGER DEFAULT NULL, > > kayak INTEGER DEFAULT NULL, > > mooring INTEGER DEFAULT NULL, > > acknowledged TEXT DEFAULT NULL > > --date value > > ); > > sqlite> .quit > > > > (p9) alex at t460:~/Git/Sql$ cat enter.py > > #!/usr/bin/env python3 > > > > # File: enter.py > > > > import sqlite3 > > > > db_file_name = '/home/alex/Git/Sql/Secret/club.db' > > db = sqlite3.connect(db_file_name) > > cursor = db.cursor() > > data = {"dues": 50, > > "date_received": "20230407", > > "date_acknowledged": "20230410", > > } > > f_keys = ", ".join([":"+key for key in data.keys()]) > > query = "INSERT INTO Receipts VALUES ({});".format(f_keys) > > cursor.executemany(query, data) > > cursor.close() > > db.commit() > > db.close() > > (p9) alex at t460:~/Git/Sql$ ./enter.py > > Traceback (most recent call last): > > File "/home/alex/Git/Sql/./enter.py", line 16, in > > > > cursor.executemany(query, data) > > sqlite3.OperationalError: table Receipts has 8 columns but 3 values > > were supplied > > (p9) alex at t460:~/Git/Sql$ > > """ > > ... again, thank you. > > a > > -- > > alex at kleider.ca (he/him) > > (sent from my current gizmo) > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor -- alex at kleider.ca (he/him) (sent from my current gizmo) From iveneret at gmail.com Mon Apr 17 06:23:03 2023 From: iveneret at gmail.com (Iven Eret) Date: Mon, 17 Apr 2023 16:23:03 +0600 Subject: [Tutor] help find out error Message-ID: <0F7CC4C4-44F4-45C4-80C0-69A0940F1BBA@hxcore.ol> ? ? Sent from [1]Mail for Windows def decrypt(encrypted_text:str, n:int): ? ? if n<=0: ? ? ? ? return encrypted_text ? ? ? ? if len(encrypted_text)%2: ? ? ? ? encrypted_text += "_" ? ? ? ? even = encrypted_text[:int(len(encrypted_text)/2) + 1] #including last element ? ? ? ? ? odd= encrypted_text[int(len(encrypted_text)/2):]#not including last element ? ? ? ? text= "" ? ? ? ? shorter_length = min(len(even), len(odd)) ? ? j=0 ? ? while j? "135024" encrypt("012345", 2)? =>? "135024"? ->? "304152" encrypt("012345", 3)? =>? "135024"? ->? "304152"? ->? "012345" ? encrypt("01234", 1)? =>? "13024" encrypt("01234", 2)? =>? "13024"? ->? "32104" encrypt("01234", 3)? =>? "13024"? ->? "32104"? ->? "20314" Together with the encryption function, you should also implement a decryption function which reverses the process. If the string?S?is an empty value or the integer?N?is not positive, return the first argument without changes. Help me find out where I?m going wrong References Visible links 1. https://go.microsoft.com/fwlink/?LinkId=550986 From threesomequarks at proton.me Sun Apr 16 22:27:27 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Mon, 17 Apr 2023 02:27:27 +0000 Subject: [Tutor] sqlite3 module In-Reply-To: References: Message-ID: Hi Alex, I won't comment on the SQL issues of the module you are using but just about Python aspects. You have an item you want to add to a SQL table using a dictionary with only some of the key/value pairs needed in which you expect many items to be some form of Null. Yet you are being forced to add all items even if SQL itself would happily initialize them to null because of the function you are using. You are updating from a dictionary you created that looks like: data = {"dues": 50, "date_received": "20230407", "date_acknowledged": "20230410", } So suppose you have fields I will call a1 ... a3 that for your purposes are null. I suggest you change or replace data in place to update any fields not currently present to have value NULL. Any existing are left alone. Here is a function that accepts a dictionary and a list of keywords and returns the dictionary update with NULL in all the non-existent keys. You can specify any value if you change it, but this may work for your need. Here is the function: def adding_nulls(data, the_keys): """ Given a dictionary and a list of keywords, add the keys specified with value NULL but only if the key does not already exist. """ for a_key in the_keys: data.setdefault(a_key) return(data) Here is the result or running it using three new fields and an existing one to show it does no harm.: >>> data {'dues': 50, 'date_received': '20230407', 'date_acknowledged': '20230410', 'a1': None, 'a2': None, 'a3': None} >>> adding_nulls(data, ["a1", "a2", "a3", "dues"]) {'dues': 50, 'date_received': '20230407', 'date_acknowledged': '20230410', 'a1': None, 'a2': None, 'a3': None} >>> data = adding_nulls(data, ["a1", "a2", "a3", "dues"]) >>> data {'dues': 50, 'date_received': '20230407', 'date_acknowledged': '20230410', 'a1': None, 'a2': None, 'a3': None} So you can either modify the original or make a copy first. The larger dictionary may then do what you want as long as you set things up right. Einfach, nicht wahr! Q Sent with Proton Mail secure email. ------- Original Message ------- On Sunday, April 16th, 2023 at 2:09 PM, Alex Kleider wrote: > I'm running Python3 within a virtualenv on a Debian machine. > > My question has to do with the sqlite3 module. > > Must I provide a value for every field in the table? > It seems that this shouldn't be necessary if default values are > specified but the following code suggests that one must in fact > supply a value for every field. > When I complied (up to a point, giving the data dict values for > all columns except the autoincrimenting primary key) I got the > same error; It would seem to me that it shouldn't accept an entry > for the primary key rather than insist on it. > > Is there a way to make what I want to do possible? > > Thanks in advance for any guidance provided. > > """ > (p9) alex at t460:~/Git/Sql$ sqlite3 ~/Git/Sql/Secret/club.db > SQLite version 3.34.1 2021-01-20 14:10:07 > Enter ".help" for usage hints. > sqlite> .schema Receipts > > CREATE TABLE Receipts ( > ReceiptID INTEGER PRIMARY KEY, > personID INTEGER NOT NULL, > date_recieved TEXT NOT NULL, > dues INTEGER DEFAULT NULL, > dock INTEGER DEFAULT NULL, > kayak INTEGER DEFAULT NULL, > mooring INTEGER DEFAULT NULL, > acknowledged TEXT DEFAULT NULL > --date value > ); > sqlite> .quit > > (p9) alex at t460:~/Git/Sql$ cat enter.py > #!/usr/bin/env python3 > > # File: enter.py > > import sqlite3 > > db_file_name = '/home/alex/Git/Sql/Secret/club.db' > db = sqlite3.connect(db_file_name) > cursor = db.cursor() > data = {"dues": 50, > "date_received": "20230407", > "date_acknowledged": "20230410", > } > f_keys = ", ".join([":"+key for key in data.keys()]) > query = "INSERT INTO Receipts VALUES ({});".format(f_keys) > cursor.executemany(query, data) > cursor.close() > db.commit() > db.close() > (p9) alex at t460:~/Git/Sql$ ./enter.py > Traceback (most recent call last): > File "/home/alex/Git/Sql/./enter.py", line 16, in > > cursor.executemany(query, data) > sqlite3.OperationalError: table Receipts has 8 columns but 3 values > were supplied > (p9) alex at t460:~/Git/Sql$ > """ > ... again, thank you. > a > -- > alex at kleider.ca (he/him) > (sent from my current gizmo) > _______________________________________________ > 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 Apr 17 10:37:23 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 17 Apr 2023 15:37:23 +0100 Subject: [Tutor] help find out error In-Reply-To: <0F7CC4C4-44F4-45C4-80C0-69A0940F1BBA@hxcore.ol> References: <0F7CC4C4-44F4-45C4-80C0-69A0940F1BBA@hxcore.ol> Message-ID: On 17/04/2023 11:23, Iven Eret wrote: It would hep if you tell us what the problem is. If you get any error messages include them in your email. Meantime I include a few comments below... > def decrypt(encrypted_text:str, n:int): > ? ? if n<=0: > ? ? ? ? return encrypted_text > ? ? if len(encrypted_text)%2: > ? ? ? ? encrypted_text += "_" > ? ? even = encrypted_text[:int(len(encrypted_text)/2) + 1] #including last > ? ? odd= encrypted_text[int(len(encrypted_text)/2):]#not including last > ? ? text= "" > ? ? shorter_length = min(len(even), len(odd)) > > ? ? j=0 > ? ? while j ? ? ? ? for i in range(shorter_length): > ? ? ? ? ? ? text=text + odd[i] + even[i] > ? ? ? ? print(text) ? > ? ? ? ? j+=1 ? ? Note that this only prints the string. it would be more helpful if you returned it so that it could be stored somewhere. As a general programming rule we try to avoid having functions print results, it's much better to return them. > def encrypt(text:str, n:int): > ? ? if n<=0: > ? ? ? ? return text > ? ? j=0 > ? ? while j ? ? ? ? odd= '' > ? ? ? ? even= '' ? ? > ? ? ? ? for i in range(0, len(text)): > ? ? ? ? ? ? if i%2: > ? ? ? ? ? ? ? ? odd+=text[i] > ? ? ? ? ? ? else : > ? ? ? ? ? ? ? ? even+=text[i] > text= odd + even > j+=1 You can do this in a single line using slicing. text = text[::2] + text[1::2] Also since you are always starting at zero and incrementing by 1 you don't need the while loop. You can use for _ in range(n): for i in range(len(text)): text = text[::2] + text[1::2] For loops tend to be more reliable than using while loops - no index to maintain. > ? ? return text Interestingly you do return the text in this case. > the goal was to encrypt to mplement a pseudo-encryption algorithm which > given a string?S?and an integer?N?concatenates all the odd-indexed > characters of?S?with all the even-indexed characters of?S, this process > should be repeated?N?times. > > Examples: > > encrypt("012345", 1)? =>? "135024" > encrypt("012345", 2)? =>? "135024"? ->? "304152" > encrypt("012345", 3)? =>? "135024"? ->? "304152"? ->? "012345" > Help me find out where I?m going wrong I can't see any obvious bugs but if you are getting an error either send the error message or if its a data error show us the input and output that you get. It saves us guessing and potentially solving the wrong problem. -- 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 wlfraed at ix.netcom.com Mon Apr 17 15:20:13 2023 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Mon, 17 Apr 2023 15:20:13 -0400 Subject: [Tutor] sqlite3 module References: Message-ID: On Sun, 16 Apr 2023 17:27:28 -0700, Alex Kleider declaimed the following: > f_values = ", ".join([repr(value) for value in data.values()]) NO... You want the API placeholder -- which for Python's sqlite3 module is simple a ? for each value. There may also be the matter that data.values() may not be in the same order as data.keys() (current Python does claim that the keys will be returned in the same order if .keys() is called multiple times, but I haven't seen if values() uses that order) > query = ("INSERT INTO Receipts ({}) VALUES ({});" > .format(f_keys, f_values)) You DO NOT want to stuff the actual data values into the query in this manner -- it opens you up to injection attacks https://xkcd.com/327/ It is the responsibility of the API module to sanitize and escape data values in accordance with the requirements of the actual database engine. (for many years, the MySQL API interface used %s as the placeholder, and used % formatting to fill a copy of the query with values -- BUT every value was first passed through a sanitizing function which was responsible for converting numeric data to string, escaping embedded quotes, etc.) > print(query) > cursor.execute(query, data) Without placeholders, passing "data" does nothing. #relying upon .keys() returning the same order on each call #list-comprehension may not be needed for the first f_keys = ", ".join(list(data.keys())) f_values = [data[key] for key in data.keys()] placeholder = ", ".join(["?" for _ in data.keys()]) query = ("INSERT INTO Receipts ({}) VALUES ({});" .format(f_keys, placeholder)) cursor.execute(query, f_values) From mats at wichmann.us Mon Apr 17 16:59:21 2023 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 17 Apr 2023 14:59:21 -0600 Subject: [Tutor] sqlite3 module In-Reply-To: References: Message-ID: <23bfddfa-4748-ff3c-12c5-31a433721d7f@wichmann.us> On 4/16/23 21:49, Alex Kleider wrote: > Good of you ('Q' aka ThreeBlindQuarks:-) to respond. > Yes, I've been doing more researching and am realizing that one can in > fact use dicts but with None/Null as values that are not meant to be > touched (at least I think that's correct; haven't tested it yet!) Just a comment, not as strong as a recommendation... if you're going to be doing a lot of work with sql, you might want to look into the growing list of Python ORM modules, that map between the Python object model and the sql relational model, so you can basically "write Python" instead of strings full of SQL syntax. See SQLAlchemy, SQLObject, Django, peewee, storm, etc. Some people have negative view of these while some swear by them. From dylanarmstrong43 at yahoo.com Mon Apr 17 12:18:07 2023 From: dylanarmstrong43 at yahoo.com (Dylan Armstrong) Date: Mon, 17 Apr 2023 16:18:07 +0000 (UTC) Subject: [Tutor] SQL Server Script References: <1791526886.2423946.1681748287508.ref@mail.yahoo.com> Message-ID: <1791526886.2423946.1681748287508@mail.yahoo.com> Hello, I'm trying to create a python script that exports the results of a query from sql into an excel file. I got the original version of the code to work but I want to add python variables into my sql code because of the weird variable format differences between oracle and sql variables. I heard that you can insert python variables into the code by placing a ":" before the variable, declaring the variable after the sql query is defined, and having a curser execute the query with the variables as parameters but I'm not sure how to do that last step. I'm also not sure how to give a specific file path destination for my newly created excel file. I'm using oracledb and pandas. my python version is 3.10.11. Sensitive information has been replaced by generic variables. From dylanarmstrong43 at yahoo.com Mon Apr 17 18:42:42 2023 From: dylanarmstrong43 at yahoo.com (Dylan Armstrong) Date: Mon, 17 Apr 2023 22:42:42 +0000 (UTC) Subject: [Tutor] sqlite3 module In-Reply-To: <23bfddfa-4748-ff3c-12c5-31a433721d7f@wichmann.us> References: <23bfddfa-4748-ff3c-12c5-31a433721d7f@wichmann.us> Message-ID: <1538308700.2558626.1681771362463@mail.yahoo.com> This makes sense but I'm not sure how to apply this. In my code I'm trying to limit my data to all orders created in 2023, but in my actual query these two dates are mentioned several times as it is a query spanning a few different tables. I've adjusted the sql query below to better represent what I'm doing. I'm familiar with APIs but I've never used them as a placeholder for variables. import oracledbimport pandas as pd # Set up the connectiondsn_tns = oracledb.makedsn(? ? 'server', 'port', service_name='service name')connection_string = oracledb.connect(user='a', password='b', dsn=dsn_tns) # Define the SQL querysql_query = """select * from orders1where delivery_date between :start_date and :end_dateselect * from orders2where delivery_date between :start_date and :end_dateselect * from orders3where delivery_date between :start_date and :end_date""" start_date = '01-01-2023'end_date = '12-31-2023' data_frame = pd.read_sql(sql_query, connection_string) data_frame.to_excel('output_file.xlsx', index=False) connection_string.close() On Monday, April 17, 2023 at 04:00:56 PM CDT, Mats Wichmann wrote: On 4/16/23 21:49, Alex Kleider wrote: > Good of you ('Q' aka ThreeBlindQuarks:-) to respond. > Yes, I've been doing more researching and am realizing that one can in > fact use dicts but with None/Null as values that are not meant to be > touched (at least I think that's correct; haven't tested it yet!) Just a comment, not as strong as a recommendation... if you're going to be doing a lot of work with sql, you might want to look into the growing list of Python ORM modules, that map between the Python object model and the sql relational model, so you can basically "write Python" instead of strings full of SQL syntax. See SQLAlchemy, SQLObject, Django, peewee, storm, etc. Some people have negative view of these while some swear by them. _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From threesomequarks at proton.me Mon Apr 17 08:35:04 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Mon, 17 Apr 2023 12:35:04 +0000 Subject: [Tutor] sqlite3 module In-Reply-To: References: Message-ID: Alex, I see others have provided a decent way to just specify the fields you want to insert by using another form of the SQL command so the suggestion I made of altering the dict are not necessarily a good way to go, especially if a program may not be aware that an existing table has had additional fields added. That is not your case as you are creating the table. What I suggested was a sort of template and after sending it, I realized the default of adding a Python NULL may not be what is wanted. There is an argument you can add to set it to anything you want such as an empty string or zero. Humorously, I did not necessarily assume you were male so a Sir Name was not implied. I did add a line in German that does better with a comma after the first word to mean something like "Easy, isn't it" or perhaps "Simple, isn't that right." You are correct that your Surname was a misleading clue. I should stick to languages nobody speaks as a first language! Mine is a bit more enigmatic, LOL! Good Luck with your project. Facila ?u ne? Q? Sent with Proton Mail secure email. ------- Original Message ------- On Sunday, April 16th, 2023 at 11:49 PM, Alex Kleider wrote: > Good of you ('Q' aka ThreeBlindQuarks:-) to respond. > Yes, I've been doing more researching and am realizing that one can in > fact use dicts but with None/Null as values that are not meant to be > touched (at least I think that's correct; haven't tested it yet!) > Amused by your German closing comment. > I think you meant "Isn't that so?" (and I agree that it is) but google > thinks otherwise: > https://duckduckgo.com/?t=ftsa&q=german+translation+of+"Einfach%2C+nicht+wahr!"&ia=translations > Correction, it's not Google! I seem to have set my default to ddg some time ago. > Thanks to you and all that contribute so much on this list. > Alex > PS Don't be fooled by the sir name! My first language was actually > Russian but that's a very long time ago and almost all is forgotten. > PPS Interesting that my postings seem to be getting to the list as > evidenced by the responses, and yet they don't come in to my inbox; > only the responses do. > > On Sun, Apr 16, 2023 at 7:27?PM ThreeBlindQuarks > threesomequarks at proton.me wrote: > > > Hi Alex, > > > > I won't comment on the SQL issues of the module you are using but just about Python aspects. > > > > You have an item you want to add to a SQL table using a dictionary with only some of the key/value pairs needed in which you expect many items to be some form of Null. Yet you are being forced to add all items even if SQL itself would happily initialize them to null because of the function you are using. You are updating from a dictionary you created that looks like: > > > > data = {"dues": 50, > > "date_received": "20230407", > > "date_acknowledged": "20230410", > > } > > > > So suppose you have fields I will call a1 ... a3 that for your purposes are null. I suggest you change or replace data in place to update any fields not currently present to have value NULL. Any existing are left alone. Here is a function that accepts a dictionary and a list of keywords and returns the dictionary update with NULL in all the non-existent keys. You can specify any value if you change it, but this may work for your need. > > > > Here is the function: > > > > def adding_nulls(data, the_keys): > > """ > > Given a dictionary and a list of keywords, > > add the keys specified with value NULL but only > > if the key does not already exist. > > """ > > for a_key in the_keys: > > data.setdefault(a_key) > > return(data) > > > > Here is the result or running it using three new fields and an existing one to show it does no harm.: > > > > > > > data > > > > > {'dues': 50, 'date_received': '20230407', 'date_acknowledged': '20230410', 'a1': None, 'a2': None, 'a3': None} > > > > > adding_nulls(data, ["a1", "a2", "a3", "dues"]) > > > > > {'dues': 50, 'date_received': '20230407', 'date_acknowledged': '20230410', 'a1': None, 'a2': None, 'a3': None} > > > > > data = adding_nulls(data, ["a1", "a2", "a3", "dues"]) > > > > > data > > > > > {'dues': 50, 'date_received': '20230407', 'date_acknowledged': '20230410', 'a1': None, 'a2': None, 'a3': None} > > > > So you can either modify the original or make a copy first. The larger dictionary may then do what you want as long as you set things up right. > > > > Einfach, nicht wahr! > > > > Q > > > > Sent with Proton Mail secure email. > > > > ------- Original Message ------- > > On Sunday, April 16th, 2023 at 2:09 PM, Alex Kleider alexkleider at gmail.com wrote: > > > > > I'm running Python3 within a virtualenv on a Debian machine. > > > > > > My question has to do with the sqlite3 module. > > > > > > Must I provide a value for every field in the table? > > > It seems that this shouldn't be necessary if default values are > > > specified but the following code suggests that one must in fact > > > supply a value for every field. > > > When I complied (up to a point, giving the data dict values for > > > all columns except the autoincrimenting primary key) I got the > > > same error; It would seem to me that it shouldn't accept an entry > > > for the primary key rather than insist on it. > > > > > > Is there a way to make what I want to do possible? > > > > > > Thanks in advance for any guidance provided. > > > > > > """ > > > (p9) alex at t460:~/Git/Sql$ sqlite3 ~/Git/Sql/Secret/club.db > > > SQLite version 3.34.1 2021-01-20 14:10:07 > > > Enter ".help" for usage hints. > > > sqlite> .schema Receipts > > > > > > CREATE TABLE Receipts ( > > > ReceiptID INTEGER PRIMARY KEY, > > > personID INTEGER NOT NULL, > > > date_recieved TEXT NOT NULL, > > > dues INTEGER DEFAULT NULL, > > > dock INTEGER DEFAULT NULL, > > > kayak INTEGER DEFAULT NULL, > > > mooring INTEGER DEFAULT NULL, > > > acknowledged TEXT DEFAULT NULL > > > --date value > > > ); > > > sqlite> .quit > > > > > > (p9) alex at t460:~/Git/Sql$ cat enter.py > > > #!/usr/bin/env python3 > > > > > > # File: enter.py > > > > > > import sqlite3 > > > > > > db_file_name = '/home/alex/Git/Sql/Secret/club.db' > > > db = sqlite3.connect(db_file_name) > > > cursor = db.cursor() > > > data = {"dues": 50, > > > "date_received": "20230407", > > > "date_acknowledged": "20230410", > > > } > > > f_keys = ", ".join([":"+key for key in data.keys()]) > > > query = "INSERT INTO Receipts VALUES ({});".format(f_keys) > > > cursor.executemany(query, data) > > > cursor.close() > > > db.commit() > > > db.close() > > > (p9) alex at t460:~/Git/Sql$ ./enter.py > > > Traceback (most recent call last): > > > File "/home/alex/Git/Sql/./enter.py", line 16, in > > > > > > cursor.executemany(query, data) > > > sqlite3.OperationalError: table Receipts has 8 columns but 3 values > > > were supplied > > > (p9) alex at t460:~/Git/Sql$ > > > """ > > > ... again, thank you. > > > a > > > -- > > > alex at kleider.ca (he/him) > > > (sent from my current gizmo) > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > To unsubscribe or change subscription options: > > > https://mail.python.org/mailman/listinfo/tutor > > > > > -- > alex at kleider.ca (he/him) > (sent from my current gizmo) From threesomequarks at proton.me Mon Apr 17 13:56:51 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Mon, 17 Apr 2023 17:56:51 +0000 Subject: [Tutor] sqlite3 module In-Reply-To: References: Message-ID: Alex and others, To answer a simple question, the owner/moderator of this mailing list has set up the system to be moderated so your posts may appear from rapidly to never. It seems set up to not send you a copy but once approved, it should be visible after a bit in the archives. https://mail.python.org/pipermail/tutor/ If you ignore the futuristic message from January 27, the latest messages can be found under April in various ways. If you click on Date your messages may be towards the bottom. Archive View by: Downloadable version January 2027: [ Thread ] [ Subject ] [ Author ] [ Date ] [ Text 790 bytes ] April 2023: [ Thread ] [ Subject ] [ Author ] [ Date ] [ Text 165 KB ] March 2023: [ Thread ] [ Subject ] [ Author ] [ Date ] [ Text 139 KB ] [Tutor] sqlite3 module Alex Kleider [Tutor] sqlite3 module Dennis Lee Bieber [Tutor] sqlite3 module Alex Kleider [Tutor] sqlite3 module ThreeBlindQuarks [Tutor] sqlite3 module Alex Kleider [Tutor] help find out error Iven Eret [Tutor] help find out error Alan Gauld Sent with Proton Mail secure email. ------- Original Message ------- On Sunday, April 16th, 2023 at 11:49 PM, Alex Kleider wrote: ... > PPS Interesting that my postings seem to be getting to the list as > evidenced by the responses, and yet they don't come in to my inbox; > only the responses do. From alan.gauld at yahoo.co.uk Mon Apr 17 20:25:00 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 18 Apr 2023 01:25:00 +0100 Subject: [Tutor] SQL Server Script In-Reply-To: <1791526886.2423946.1681748287508@mail.yahoo.com> References: <1791526886.2423946.1681748287508.ref@mail.yahoo.com> <1791526886.2423946.1681748287508@mail.yahoo.com> Message-ID: On 17/04/2023 17:18, Dylan Armstrong via Tutor wrote: > Sensitive information has been replaced by generic variables. This sounds like you tried to send an attachment. Unfortunately the server strips attachments as security risks so we can't see it. Please send the content as text in your mail message. As for your task the simplest way of getting data from a database into Excel(or most any spreadsheet) is to generate a CSV file. Most databases can be configured to deliver their results directly in CSV format, but if not, generating CSV using the Python csv module is fairly easy. -- 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 Apr 17 20:28:49 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 18 Apr 2023 01:28:49 +0100 Subject: [Tutor] sqlite3 module In-Reply-To: References: Message-ID: On 17/04/2023 18:56, ThreeBlindQuarks via Tutor wrote: > To answer a simple question, the owner/moderator of this mailing > list has set up the system to be moderated so your posts may appear > from rapidly to never. Only for the first few posts. If a name crops up regularly enough that I recognise it then I turn off moderation. Alex is an old hand so should be coming straight through. > It seems set up to not send you a copy That's a user configurable option. You can change it on the setting page of the web server (see url 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 PythonList at DancesWithMice.info Mon Apr 17 20:36:51 2023 From: PythonList at DancesWithMice.info (dn) Date: Tue, 18 Apr 2023 12:36:51 +1200 Subject: [Tutor] SQL Server Script In-Reply-To: <1791526886.2423946.1681748287508@mail.yahoo.com> References: <1791526886.2423946.1681748287508.ref@mail.yahoo.com> <1791526886.2423946.1681748287508@mail.yahoo.com> Message-ID: <642ace31-d6d8-3533-5c7b-2cfefac58ebd@DancesWithMice.info> On 18/04/2023 04.18, Dylan Armstrong via Tutor wrote: > Hello, > I'm trying to create a python script that exports the results of a query from sql into an excel file. I got the original version of the code to work but I want to add python variables into my sql code because of the weird variable format differences between oracle and sql variables. I heard that you can insert python variables into the code by placing a ":" before the variable, declaring the variable after the sql query is defined, and having a curser execute the query with the variables as parameters but I'm not sure how to do that last step. I'm also not sure how to give a specific file path destination for my newly created excel file. I'm using oracledb and pandas. my python version is 3.10.11. Sensitive information has been replaced by generic variables. NB suspect some info missing from OP. Please copy-paste because attachments don't come-through. Will be happy to help, later... (with apologies for a necessarily brief response) A tutorial: https://www.oracle.com/database/technologies/appdev/python/quickstartpythononprem.html (and other references available on same web-site) Docs for the Python-Oracle "Connector": https://python-oracledb.readthedocs.io/en/latest/ Third party alternative (maybe): https://www.oracletutorial.com/python-oracle/connecting-to-oracle-database-in-python/ -- Regards, =dn From threesomequarks at proton.me Mon Apr 17 22:17:42 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Tue, 18 Apr 2023 02:17:42 +0000 Subject: [Tutor] sqlite3 module In-Reply-To: References: Message-ID: Dumb question. Is there a reason to assume the keys are not presented in the same order as the values? Sure, there may be no guarantee. Just as an example, the older version of dictionaries presented the items in no specified order and people who cared, used an ordered dictionary variant. It is now stated the order is maintained as the newest item at the end and deleting items leaves things in order unless a copy is added later and goes to the end. But if what you say is true and you want a more bulletproof version, would this do? keys = [ key for key in dict.keys()] values = [ dict[key] for key in keys ] Something along those lines would guarantee that a static copy of a dictionary could have a 1:1 correspondence between a list of keys and a list of values for purposes like the SQL statement that specifies additions or updates using one list of each that have to be completely aligned. Yes, I hear there are generations of tools that allow you to not really know SQL and that can be great or can grate those not very grateful. BTW, I took Alan's hint and after searching for my darn password, updated my account to send myself a copy of messages. Oddly, it already seemed to be set to do that but I also set the setting to send myself a copy even when I am already a known co-recipient and will see if the software handles anything different. I think many would like to know when their message has been received. The mailing list maintainers, of course, prefer minimizing how many messages they send out. They are not on this forum but I wonder if they have considered letting a sender know when a message has had parts removed or changed. I know not to attach but quite a few people posting here have blithely sent attachments and waited to see if anyone can advise them on things they cannot see! Sent with Proton Mail secure email. ------- Original Message ------- On Monday, April 17th, 2023 at 3:20 PM, Dennis Lee Bieber wrote: > On Sun, 16 Apr 2023 17:27:28 -0700, Alex Kleider alexkleider at gmail.com > > declaimed the following: > > > f_values = ", ".join([repr(value) for value in data.values()]) > > > NO... You want the API placeholder -- which for Python's sqlite3 module > is simple a ? for each value. There may also be the matter that > data.values() may not be in the same order as data.keys() (current Python > does claim that the keys will be returned in the same order if .keys() is > called multiple times, but I haven't seen if values() uses that order) > > > query = ("INSERT INTO Receipts ({}) VALUES ({});" > > .format(f_keys, f_values)) > > > You DO NOT want to stuff the actual data values into the query in this > manner -- it opens you up to injection attacks > > https://xkcd.com/327/ > > It is the responsibility of the API module to sanitize and escape data > values in accordance with the requirements of the actual database engine. > (for many years, the MySQL API interface used %s as the placeholder, and > used % formatting to fill a copy of the query with values -- BUT every > value was first passed through a sanitizing function which was responsible > for converting numeric data to string, escaping embedded quotes, etc.) > > > print(query) > > cursor.execute(query, data) > > > Without placeholders, passing "data" does nothing. > > > #relying upon .keys() returning the same order on each call > #list-comprehension may not be needed for the first > f_keys = ", ".join(list(data.keys())) > f_values = [data[key] for key in data.keys()] > placeholder = ", ".join(["?" for _ in data.keys()]) > > query = ("INSERT INTO Receipts ({}) VALUES ({});" > .format(f_keys, placeholder)) > > cursor.execute(query, f_values) > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From roel at roelschroeven.net Tue Apr 18 04:02:03 2023 From: roel at roelschroeven.net (Roel Schroeven) Date: Tue, 18 Apr 2023 10:02:03 +0200 Subject: [Tutor] sqlite3 module In-Reply-To: References: Message-ID: ThreeBlindQuarks via Tutor schreef op 18/04/2023 om 4:17: > Dumb question. Is there a reason to assume the keys are not presented in the same order as the values? Even in the older version of dictionaries, the order was arbitrary but not random. Adding or deleting items had a good chance of changing the order, but I'm pretty sure order was preserved in the absence of changes to the dictionary. That can get tricky when using multithreading of course, since then another thread can possibly cause changes. -- "Cheer up," they said, "things could be worse." So I cheered up, and sure enough, things got worse. -- Paraphrased from James C. Hagerty From wlfraed at ix.netcom.com Tue Apr 18 09:35:44 2023 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 18 Apr 2023 09:35:44 -0400 Subject: [Tutor] SQL Server Script References: <1791526886.2423946.1681748287508.ref@mail.yahoo.com> <1791526886.2423946.1681748287508@mail.yahoo.com> Message-ID: On Mon, 17 Apr 2023 16:18:07 +0000 (UTC), Dylan Armstrong via Tutor declaimed the following: >Hello, >I'm trying to create a python script that exports the results of a query from sql into an excel file. I got the original version of the code to work but I want to add python variables into my sql code because of the weird variable format differences between oracle and sql variables. I heard that you can insert python variables into the code by placing a ":" before the variable, declaring the variable after the sql query is defined, and having a curser execute the query with the variables as parameters but I'm not sure how to do that last step. I'm also not sure how to give a specific file path destination for my newly created excel file. I'm using oracledb and pandas. my python version is 3.10.11. Sensitive information has been replaced by generic variables. {Somehow your posting client doesn't send "wrapped" text, but single long lines per paragraph -- makes it hard to do decent quoting} First a generic comment. Your message subject reads "SQL Server Script", SQL Server is the formal name for Microsoft's RDBM -- yet the body of your message references Oracle, a completely different RDBM provider. (The original M$ SQL Server was based upon Sybase) The rest of the matter depends upon the exact nature of the Python DB-API adapter being used. You need to read (and understand) the base DB-API documentation, and then the specifics for the adapter. https://peps.python.org/pep-0249/ (in particular, .execute() under Cursor methods, and the paramstyle stuff) https://python-oracledb.readthedocs.io/en/latest/user_guide/bind.html From threesomequarks at proton.me Tue Apr 18 13:07:58 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Tue, 18 Apr 2023 17:07:58 +0000 Subject: [Tutor] sqlite3 module In-Reply-To: References: Message-ID: Roel, It sounds like there are two scenarios. One is about a static dictionary that is guaranteed not to change during an interval either because only one thread of execution is running or can change it, or because you are working on a copy. In that scenario, I would think it is safe to get keys and then values and they should be returned in the same order. If that is not guaranteed, I assume you can get the items back as a data structure of pairs and break them apart yourself. That seems straightforward enough and I shudder at any implementation that would not return keys and values synchronized, albeit older versions in no guaranteed order. In the second scenario, hardly anything works. If a dictionary is having additions, modifications and deletions as you work on it, you either need a sort of atomic snapshot to work with, and ignore changes made after your copy is set aside, or put some kind of lock on the dictionary and block anyone else while you work after making sure you have access. For the purposes of the OP, I doubt this matters. The discussion as I recall was that you had a fairly small dictionary containing a subset of the names of table columns as keys and their corresponding values, with some perhaps being set to some form of NULL. To get around one SQL insertion method that seemed to require even optional fields to be described even as they should default to NULL, it was suggested he use an alternate insertion method where he presents matched lists of sorts with one containing just the names of the fields and the other containing the values IN THE SAME ORDER. The actual order becomes not relevant and only that it be the same. So my question was whether any implementation can be expected to not return keys and values in a static dictionary in the same order. Or, if this was a deal breaker, should the OP (if using this idea) use some variant with guarantees, such as a sorted dictionary. Sent with Proton Mail secure email. ------- Original Message ------- On Tuesday, April 18th, 2023 at 4:02 AM, Roel Schroeven wrote: > ThreeBlindQuarks via Tutor schreef op 18/04/2023 om 4:17: > > > Dumb question. Is there a reason to assume the keys are not presented in the same order as the values? > > Even in the older version of dictionaries, the order was arbitrary but > not random. Adding or deleting items had a good chance of changing the > order, but I'm pretty sure order was preserved in the absence of changes > to the dictionary. That can get tricky when using multithreading of > course, since then another thread can possibly cause changes. > > -- > "Cheer up," they said, "things could be worse." So I cheered up, and > sure enough, things got worse. > -- Paraphrased from James C. Hagerty > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From luk4bernard at gmail.com Wed Apr 19 03:30:42 2023 From: luk4bernard at gmail.com (Bernard Kofi Agboado) Date: Wed, 19 Apr 2023 07:30:42 +0000 Subject: [Tutor] Hello Message-ID: Good morning, please how best can I understand the loops.? From PythonList at DancesWithMice.info Wed Apr 19 04:29:12 2023 From: PythonList at DancesWithMice.info (dn) Date: Wed, 19 Apr 2023 20:29:12 +1200 Subject: [Tutor] Hello In-Reply-To: References: Message-ID: On 19/04/2023 19.30, Bernard Kofi Agboado wrote: > Good morning, please how best can I understand the loops.? Welcome to the group! Are you following a particular course or using a text book? -- Regards, =dn From mhysnm1964 at gmail.com Wed Apr 19 04:30:41 2023 From: mhysnm1964 at gmail.com (mhysnm1964 at gmail.com) Date: Wed, 19 Apr 2023 18:30:41 +1000 Subject: [Tutor] OOPs and general Python questions. Message-ID: <003a01d97299$3b8d2990$b2a77cb0$@GMAIL.COM> All, I have some really broad and general questions to ask. What is a super class? Does python care the order of classes and methods? If you are using "python -m pdb script_name", can you reload the file using this debugging tool? I couldn't find anything which mention this? Chat.gpt references the ability of modifying code while the program is being executed. How difficult is this to achieve? A high level answer is all I need. Sean From cs at cskk.id.au Wed Apr 19 05:36:58 2023 From: cs at cskk.id.au (Cameron Simpson) Date: Wed, 19 Apr 2023 19:36:58 +1000 Subject: [Tutor] OOPs and general Python questions. In-Reply-To: <003a01d97299$3b8d2990$b2a77cb0$@GMAIL.COM> References: <003a01d97299$3b8d2990$b2a77cb0$@GMAIL.COM> Message-ID: On 19Apr2023 18:30, mhysnm1964 at gmail.com wrote: >What is a super class? It is a parent class of some class. Suppose I've got a class like this: class int16(int): ''' A subclass of int which prints in base 16. ''' def __str__(self): return f'0x{self:x}' This behaves just like an int except that converting it to a string results in a base 16 representation: >>> class int16(int): ... def __str__(self): ... return f'0x{self:x}' ... >>> i=int16(15) >>> i 15 >>> str(i) '0xf' >>> print(i) 0xf Here the superclass of int16 is int. >Does python care the order of classes and methods? Order of definition? As a dynamic language, things are defined by executing them. So they happen in the order they're in the file. That means that if defining B requires use of A, then A needs to have been defined by the time you go to define B. class A: def method(self, x): print("A:", x) class B(A): def method(self, x): print("B:", x) Here, the class A needs to be defined in order to define the class B, because B subclasses A. Swapping them around won't work. try it! It is no different to this: x = 1 y = x * 2 You can't swap these around either, for exactly the same reason. Cheers, Cameron Simpson From alan.gauld at yahoo.co.uk Wed Apr 19 07:04:14 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 19 Apr 2023 12:04:14 +0100 Subject: [Tutor] OOPs and general Python questions. In-Reply-To: <003a01d97299$3b8d2990$b2a77cb0$@GMAIL.COM> References: <003a01d97299$3b8d2990$b2a77cb0$@GMAIL.COM> Message-ID: On 19/04/2023 09:30, mhysnm1964 at gmail.com wrote: > What is a super class? It is sometimes called a base class or parent class. It is the class that your class inherits from. The super class of all classes is Object. So class Parent: pass class Child(Parent): pass class Grandchild(Parent, Child): pass Parent's superclass is Object Child's super class is Parent Grandchild has 2 super classes, Parent and Child, so called multiple inheritance (of which this is a really bad example!) > Does python care the order of classes and methods? Yes. You must declare the classes(or import them) before they can be used as a superclass. And if you are using multiple inheritance the order of the superclassses makes a difference to the order in which parent methods will be called. > If you are using "python -m pdb script_name", can you reload the file using > this debugging tool? I couldn't find anything which mention this? I'm not sure what you mean but it has nothing to do with OOP. > Chat.gpt references the ability of modifying code while the program is being > executed. How difficult is this to achieve? Potentially not that difficult to do but to get it right is extremely difficult and should never really be needed. I've done it once in a 40 year career and even that was more just to see if I could! There are nearly always better options. Also be extremely wary of ChatGPT and similar tools. They are designed to create natural sounding answers not correct ones. They may or may not find an accurate source from which to contruct the answer but their main focus is on chatting not being accurate! -- 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 threesomequarks at proton.me Wed Apr 19 12:13:30 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Wed, 19 Apr 2023 16:13:30 +0000 Subject: [Tutor] Hello In-Reply-To: References: Message-ID: <4BthiDqC6_347k7tg3kVb4XnXRzJH3CxuVJxQwYYN59fFk3VTyr-j7fkn21Jhq6SsOJSJ5t31xUDV4fSv1u1_yHi6oV0Vx-hoA-b4ZbSdW0=@proton.me> Bernard, that is an extremely broad question. My first thought was that in America we eat our loops with fruit but that is not very helpful. Could you post a few lines of code that contain an example of loops and tell us what you do not understand or how to modify it so it does not produce error messages or wrong results? Python has lots of constructs that I would call loops. All of them share a concept of repeating the same code some number of times with some things changing as you move along. Are you looking at explicit loops where you see key words like "for" and "while" with indented code below or some more subtle ones including comprehensions or generators or the kind where the loop is done invisibly? Again, send an example or two and say what about it does not make sense. But the people here are not tutors in the sense of teaching very basic things that a student should be getting by reading a textbook and listening to lectures. We would appreciate a more focused question so we can provide more focused help. Sent with Proton Mail secure email. ------- Original Message ------- On Wednesday, April 19th, 2023 at 3:30 AM, Bernard Kofi Agboado wrote: > Good morning, please how best can I understand the loops.? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From threesomequarks at proton.me Wed Apr 19 12:29:33 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Wed, 19 Apr 2023 16:29:33 +0000 Subject: [Tutor] OOPs and general Python questions. In-Reply-To: <003a01d97299$3b8d2990$b2a77cb0$@GMAIL.COM> References: <003a01d97299$3b8d2990$b2a77cb0$@GMAIL.COM> Message-ID: Sean, What is a super class is beyond the scope of this forum but we could discuss what a superclass is compared to a subclass. Loosely, you start with a class and decide you like what you see and would like a version with a few changes. You make a new class where you specify what class it is based on. The new class is a subclass of the older one and the older one is now a superclass of the new one. It can be that simple. Realistically, all classes exist in a hierarchy leading back to a top-level you may not be aware of. Classes can have multiple inheritance. When you want to invoke some action from a superclass it can be as simple as calling superclass() but can also be &$%*@. Does Python care about order. Yep. Oh, and sometimes nope. More seriously, unlike some other languages that look ahead before evaluating in some context, Python generally expects things to refer to previously identified objects or functions or whatever. It can be more complex and interesting. A case where order can really matter is when a class declares multiple other classes it inherits from as the search for things it uses (like members in superclasses with the same names, can be a bit hard to explain. As to your last question, code can be modified in many ways as it runs. Python is generally interpreted. The question is too general. What specifically do you want to know if it can be modified and in what ways. Some people use fairly direct methods and some use some rather arcane ones. Just as an example, if you had a function declared and used and later decided you want to wrap that function in another that adds some functionality by doing something before and/or after the function is called and then return a possibly modified result, you can trivially do it using something like a decorator that stores the result back into the same name. Other things may be hard to achieve and some may not be possible within a session such as when measures have been taken to stop you from accessing something directly. Of course, none of us here is currently an AI so our answers ... Sent with Proton Mail secure email. ------- Original Message ------- On Wednesday, April 19th, 2023 at 4:30 AM, mhysnm1964 at gmail.com wrote: > All, > > > > I have some really broad and general questions to ask. > > > > What is a super class? > > Does python care the order of classes and methods? > > If you are using "python -m pdb script_name", can you reload the file using > this debugging tool? I couldn't find anything which mention this? > > Chat.gpt references the ability of modifying code while the program is being > executed. How difficult is this to achieve? A high level answer is all I > need. > > > > > > Sean > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at yahoo.co.uk Wed Apr 19 12:29:56 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 19 Apr 2023 17:29:56 +0100 Subject: [Tutor] Hello In-Reply-To: <4BthiDqC6_347k7tg3kVb4XnXRzJH3CxuVJxQwYYN59fFk3VTyr-j7fkn21Jhq6SsOJSJ5t31xUDV4fSv1u1_yHi6oV0Vx-hoA-b4ZbSdW0=@proton.me> References: <4BthiDqC6_347k7tg3kVb4XnXRzJH3CxuVJxQwYYN59fFk3VTyr-j7fkn21Jhq6SsOJSJ5t31xUDV4fSv1u1_yHi6oV0Vx-hoA-b4ZbSdW0=@proton.me> Message-ID: On 19/04/2023 17:13, ThreeBlindQuarks via Tutor wrote: > ...the people here are not tutors in the sense of > teaching very basic things To be fair some of us are. And discussing general computing concepts is definitely part of this group's remit (one of the things that separates us from the general Python list). > more focused question so we can provide more focused help. But the more focused a question is the more focused will be the answer! That much is always true. -- 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 threesomequarks at proton.me Wed Apr 19 14:01:33 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Wed, 19 Apr 2023 18:01:33 +0000 Subject: [Tutor] Hello In-Reply-To: References: <4BthiDqC6_347k7tg3kVb4XnXRzJH3CxuVJxQwYYN59fFk3VTyr-j7fkn21Jhq6SsOJSJ5t31xUDV4fSv1u1_yHi6oV0Vx-hoA-b4ZbSdW0=@proton.me> Message-ID: <0u6EyPH5Vf1t6S7KNjdZ_9L7dvWmkBM68RuOt3gSV6eqYPrdDDXn5daWHWpsIwTz-se38feF73jWlv3GSWvJFbBc50cPJCQbCDvmEG7RbIA=@proton.me> Alan, Basically, "basic" can mean many things to people. It is definitely your forum for setting guidelines and the choice of others whether to participate in some activities. I only mean that for some of us who volunteer here, the goal is to help get people who are already learning elsewhere, with some aspect of python or to find out what went wrong with their code or perhaps ideas. Some more detailed requests can be seen as being asked to do their work for them, not educate. Some may be willing either on the forum or offline. But I am not speaking for others. If in my private life, as has happened, I am asked to help someone learn something from the beginning and very interactively, fine. But if someone here asks if they should learn Python and wants instruction in public gradually over many months, I will opt out. I did not see the question as a general computing concept question. It was a brief message, not one saying they had tried while and for loops and had started looking at comprehensions and generators and perhaps constructs in other languages, and wondered when some were better to use than others. I encourage people to follow up a general question with a bit more detail to help guide those answering to meet their needs and not waste too much time for all involved. Sent with Proton Mail secure email. ------- Original Message ------- On Wednesday, April 19th, 2023 at 12:29 PM, Alan Gauld via Tutor wrote: > On 19/04/2023 17:13, ThreeBlindQuarks via Tutor wrote: > > > ...the people here are not tutors in the sense of > > teaching very basic things > > > To be fair some of us are. > > And discussing general computing concepts is definitely > part of this group's remit (one of the things that > separates us from the general Python list). > > > more focused question so we can provide more focused help. > > > But the more focused a question is the more focused will > be the answer! That much is always true. > > -- > 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 Wed Apr 19 20:16:29 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 20 Apr 2023 01:16:29 +0100 Subject: [Tutor] Hello In-Reply-To: <0u6EyPH5Vf1t6S7KNjdZ_9L7dvWmkBM68RuOt3gSV6eqYPrdDDXn5daWHWpsIwTz-se38feF73jWlv3GSWvJFbBc50cPJCQbCDvmEG7RbIA=@proton.me> References: <4BthiDqC6_347k7tg3kVb4XnXRzJH3CxuVJxQwYYN59fFk3VTyr-j7fkn21Jhq6SsOJSJ5t31xUDV4fSv1u1_yHi6oV0Vx-hoA-b4ZbSdW0=@proton.me> <0u6EyPH5Vf1t6S7KNjdZ_9L7dvWmkBM68RuOt3gSV6eqYPrdDDXn5daWHWpsIwTz-se38feF73jWlv3GSWvJFbBc50cPJCQbCDvmEG7RbIA=@proton.me> Message-ID: On 19/04/2023 19:01, ThreeBlindQuarks via Tutor wrote: > I only mean that for some of us who volunteer here, the > goal is to help get people who are already learning elsewhere, That's fine too, each member can decide which message threads they participate in. But the tutor lists remit is to help those learning programming and the Python language and its standard library. That may include explaining very basic concepts like "what is a loop?" "What is data?" and so on. What we mustn't do is confuse our own participation criteria with that of the list as a whole because that might deter some members from posting a question that could be "too basic" > detailed requests can be seen as being asked to do > their work for them, not educate. Yes and trying to spot that and point out the list policy of assisting with homework but not doing it is one of the ongoing challenges. > if someone here asks if they should learn Python Thats a valid question for someone new to programming. And this list should offer assistance in making the choice of language. We are not here to be Python advocates but to help those who decide to go down that route. > and wants instruction in public gradually over > many months, I will opt out. Provided the questions are valid and show some signs of effort and advancement I am happy to see someone progress, even over years(as has been the case with some members - a few who now regularly participate on the general list). > I did not see the question as a general computing > concept question. It was a brief message, In this case it was too brief to be useful, that's why I asked for more details. But if it turns out to be a request for information about the very concept of loops then that's a [perfectly valid question for this list to answer. > I encourage people to follow up a general question > with a bit more detail to help guide those answering Absolutely, and that's the best response. But no matter how basic the question turns out to be it's valid for this list. You may personally decide that you don't want to reply but others may well pick it up - that's why it's a list and not a 1-1 service. -- 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 Apr 19 20:21:11 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 20 Apr 2023 01:21:11 +0100 Subject: [Tutor] OOPs and general Python questions. In-Reply-To: References: <003a01d97299$3b8d2990$b2a77cb0$@GMAIL.COM> Message-ID: On 19/04/2023 17:29, ThreeBlindQuarks via Tutor wrote: > What is a super class is beyond the scope of this forum Sorry, but it really isn't. The tutor list is about learning to program in Python and covers the concepts as well as the language specifics. You can't use the language if you don't understand the concepts. And indeed your answer reflects that.... But as moderator I must challenge statements that might seem to restrict the kinds of questions asked. -- 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 threesomequarks at proton.me Wed Apr 19 20:41:17 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Thu, 20 Apr 2023 00:41:17 +0000 Subject: [Tutor] OOPs and general Python questions. In-Reply-To: References: <003a01d97299$3b8d2990$b2a77cb0$@GMAIL.COM> Message-ID: Please read what I wrote again Alan. I am happy to discuss what a "superclass" is but not whether a class is SUPER or bad. I was gently pointing out that the more common method in Python is to not have a space between the words and that we tend to call them a superclass as compared to a subclass. The OP used "super class". Of course, we can look at a class definition and discuss whether the design and implementation are very good or perhaps terrible and how it might be improved. Personally, I rarely use the phrase "super" to describe something special but I am sure many do. But if my method of writing here is misunderstood, I hesitate to post more. However, with no actual example of a class being discussed, I found it amusing to call it super. Regardless, Q Sent with Proton Mail secure email. ------- Original Message ------- On Wednesday, April 19th, 2023 at 8:21 PM, Alan Gauld via Tutor wrote: > On 19/04/2023 17:29, ThreeBlindQuarks via Tutor wrote: > > > What is a super class is beyond the scope of this forum > > > Sorry, but it really isn't. > The tutor list is about learning to program in Python and > covers the concepts as well as the language specifics. > You can't use the language if you don't understand > the concepts. > > And indeed your answer reflects that.... > > But as moderator I must challenge statements that > might seem to restrict the kinds of questions asked. > > -- > 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 mhysnm1964 at gmail.com Thu Apr 20 03:36:10 2023 From: mhysnm1964 at gmail.com (mhysnm1964 at gmail.com) Date: Thu, 20 Apr 2023 17:36:10 +1000 Subject: [Tutor] OOPs and general Python questions. In-Reply-To: References: <003a01d97299$3b8d2990$b2a77cb0$@GMAIL.COM> Message-ID: <021f01d9735a$c86148d0$5923da70$@GMAIL.COM> Everyone, Thank you for the responses. The Chat.gpt question was more of interest sake as the way the company was promoting the capability. The explanations of the superclass question is a bit clearer. Sean -----Original Message----- From: ThreeBlindQuarks Sent: Thursday, April 20, 2023 2:30 AM To: mhysnm1964 at gmail.com Cc: tutor at python.org Subject: Re: [Tutor] OOPs and general Python questions. Sean, What is a super class is beyond the scope of this forum but we could discuss what a superclass is compared to a subclass. Loosely, you start with a class and decide you like what you see and would like a version with a few changes. You make a new class where you specify what class it is based on. The new class is a subclass of the older one and the older one is now a superclass of the new one. It can be that simple. Realistically, all classes exist in a hierarchy leading back to a top-level you may not be aware of. Classes can have multiple inheritance. When you want to invoke some action from a superclass it can be as simple as calling superclass() but can also be &$%*@. Does Python care about order. Yep. Oh, and sometimes nope. More seriously, unlike some other languages that look ahead before evaluating in some context, Python generally expects things to refer to previously identified objects or functions or whatever. It can be more complex and interesting. A case where order can really matter is when a class declares multiple other classes it inherits from as the search for things it uses (like members in superclasses with the same names, can be a bit hard to explain. As to your last question, code can be modified in many ways as it runs. Python is generally interpreted. The question is too general. What specifically do you want to know if it can be modified and in what ways. Some people use fairly direct methods and some use some rather arcane ones. Just as an example, if you had a function declared and used and later decided you want to wrap that function in another that adds some functionality by doing something before and/or after the function is called and then return a possibly modified result, you can trivially do it using something like a decorator that stores the result back into the same name. Other things may be hard to achieve and some may not be possible within a session such as when measures have been taken to stop you from accessing something directly. Of course, none of us here is currently an AI so our answers ... Sent with Proton Mail secure email. ------- Original Message ------- On Wednesday, April 19th, 2023 at 4:30 AM, mhysnm1964 at gmail.com wrote: > All, > > > > I have some really broad and general questions to ask. > > > > What is a super class? > > Does python care the order of classes and methods? > > If you are using "python -m pdb script_name", can you reload the file > using this debugging tool? I couldn't find anything which mention this? > > Chat.gpt references the ability of modifying code while the program is > being executed. How difficult is this to achieve? A high level answer > is all I need. > > > > > > Sean > > _______________________________________________ > 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 Thu Apr 20 03:38:42 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 20 Apr 2023 08:38:42 +0100 Subject: [Tutor] OOPs and general Python questions. In-Reply-To: References: <003a01d97299$3b8d2990$b2a77cb0$@GMAIL.COM> Message-ID: On 20/04/2023 01:41, ThreeBlindQuarks via Tutor wrote: > > Please read what I wrote again Alan. > > I am happy to discuss what a "superclass" is but not whether a class is SUPER or bad. OK, my bad(sic)! I failed to spot the space. And the humour... :-) -- 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 mhysnm1964 at gmail.com Thu Apr 20 03:50:25 2023 From: mhysnm1964 at gmail.com (mhysnm1964 at gmail.com) Date: Thu, 20 Apr 2023 17:50:25 +1000 Subject: [Tutor] Hello In-Reply-To: <4BthiDqC6_347k7tg3kVb4XnXRzJH3CxuVJxQwYYN59fFk3VTyr-j7fkn21Jhq6SsOJSJ5t31xUDV4fSv1u1_yHi6oV0Vx-hoA-b4ZbSdW0=@proton.me> References: <4BthiDqC6_347k7tg3kVb4XnXRzJH3CxuVJxQwYYN59fFk3VTyr-j7fkn21Jhq6SsOJSJ5t31xUDV4fSv1u1_yHi6oV0Vx-hoA-b4ZbSdW0=@proton.me> Message-ID: <023501d9735c$c6527b20$52f77160$@GMAIL.COM> Bernard Loops are used to execute a piece of code based upon specific conditions (expressions) in the loop statement or within the code block itself. There is three basic loop structures in any language: The for loop -- this example is pythons way of a pre-defined number of iterations over (executions) of a piece of code: for i in range(1, 11): print(i) The above code will print 1 to 10. Then exit. Instead of doing: I = 0 I += 1 Print (i) I += 1 Print (i) I += 1 Print (i) ... and so on. The for loop in Python allows you to execute codes based upon a list and other data types. For example: A = [1,2,3,4,5] For I in a: Print (i) The above will print each element of A. The while loop is the 2nd basic loop. This loop performs the expression test before any of the code within the loop block. If true, then nothing is executed in the loop block. For example: A = 5 While a >4: A -= 1 Print (a) The expression "a > 4" is true because a is greater than 4. The count and print statements are not executed. Change the a variable and the expression to get different results. The do ... while loop does the reverse to the while loop. The test of the expression is at the end. A better question would be, what are common loops used in python? My limited experience is the while and for loops. Sean -----Original Message----- From: Tutor On Behalf Of ThreeBlindQuarks via Tutor Sent: Thursday, April 20, 2023 2:14 AM To: Bernard Kofi Agboado Cc: tutor at python.org Subject: Re: [Tutor] Hello Bernard, that is an extremely broad question. My first thought was that in America we eat our loops with fruit but that is not very helpful. Could you post a few lines of code that contain an example of loops and tell us what you do not understand or how to modify it so it does not produce error messages or wrong results? Python has lots of constructs that I would call loops. All of them share a concept of repeating the same code some number of times with some things changing as you move along. Are you looking at explicit loops where you see key words like "for" and "while" with indented code below or some more subtle ones including comprehensions or generators or the kind where the loop is done invisibly? Again, send an example or two and say what about it does not make sense. But the people here are not tutors in the sense of teaching very basic things that a student should be getting by reading a textbook and listening to lectures. We would appreciate a more focused question so we can provide more focused help. Sent with Proton Mail secure email. ------- Original Message ------- On Wednesday, April 19th, 2023 at 3:30 AM, Bernard Kofi Agboado wrote: > Good morning, please how best can I understand the loops.? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From mhysnm1964 at gmail.com Thu Apr 20 05:05:19 2023 From: mhysnm1964 at gmail.com (mhysnm1964 at gmail.com) Date: Thu, 20 Apr 2023 19:05:19 +1000 Subject: [Tutor] Oops concepts class vs methods. Message-ID: <036501d97367$3c5c06b0$b5141410$@GMAIL.COM> All, In the past I sent some code through related to WX python that I am working on to see if I can make an accessible home book-shelf library program. Thus the reasons for these OOPS questions. I am trying to work out if I should create the following code as a generic method or class. My simplistic understanding of Oops. * A class is an object such as creating a GUI window. * Method is the action you want to do Such as creating an edit control or performing a database query. * Properties are the variables of the class / method. I have a range of WX methods that creates a control on the panel or window. For example: class RecordPanel(wx.Panel): def __init__(self, parent, app): wx.Panel.__init__(self, parent=parent) # defining the book object. self.book = None # Create the controls for the panel # adding controls to a sizer. #sizer = wx.BoxSizer(wx.VERTICAL) sizer = wx.FlexGridSizer(rows=0, cols=2, vgap=10, hgap=10) self.title_label = wx.StaticText(self, label="Title:") self.title_text = wx.TextCtrl(self, size=(300, -1)) sizer.Add(self.title_label, flag=wx.ALIGN_LEFT) sizer.Add(self.title_text, flag=wx.EXPAND) sizer.Add(wx.StaticText(self, label="About Authors:"), flag=wx.ALIGN_LEFT) self.about_author_text = wx.TextCtrl(self, size=(300, 100), style=wx.TE_MULTILINE) sizer.Add(self.about_author_text, flag=wx.EXPAND) # Set the publisher field self.publisher_label = wx.StaticText(self, label="Publisher:") self.publisher_text = wx.TextCtrl(self, size=(300, -1)) sizer.Add(self.publisher_label, flag=wx.ALIGN_LEFT) sizer.Add(self.publisher_text, flag=wx.EXPAND) # Set the series field self.series_label = wx.StaticText(self, label="Series:") self.series_text = wx.TextCtrl(self, size=(300, -1)) sizer.Add(self.series_label, flag=wx.ALIGN_LEFT) sizer.Add(self.series_text, flag=wx.EXPAND) . more declaring of controls and events to be added to the page. self.SetSizer(sizer) # applies the controls to the page. AS you can tell, the creation of the edit fields and the list boxes use the same syntax with different variables. Is it possible to create a class with a couple of methods to reduce the lines above to simplify the debugging and readability of the code? Below is my attempt and could be completely wrong: Class WindowControls(sizer, Label, label_flags, control_flags, xPosition, yPosition): # sizer is the wx sizer object # label - the label to be used for the control # label_flags - the flags used to style and align the control. # control_flags - flag parameters for the control. # xPosition and yPosition - the size of the control. Def EditControl(self) self.control_label = wx.StaticText(self, label=f"{label}:") self.control_text = wx.TextCtrl(self, size=(xPosition, yPosition)) sizer.Add(self.control_label, flag=flags) sizer.Add(self.title_text, flag=control_flags) return sizer WindowsControls. EditControl(self.sizer, "title", wx.ALIGN_LEFT, wx.EXPAND, 300, -1) I hope the above makes sense. As I really an unsure if I am on the right path here or using Oops in the right way. As I do get confused when to use the "self" instance. Sean From alan.gauld at yahoo.co.uk Thu Apr 20 06:42:50 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 20 Apr 2023 11:42:50 +0100 Subject: [Tutor] Oops concepts class vs methods. In-Reply-To: <036501d97367$3c5c06b0$b5141410$@GMAIL.COM> References: <036501d97367$3c5c06b0$b5141410$@GMAIL.COM> Message-ID: On 20/04/2023 10:05, mhysnm1964 at gmail.com wrote: > In the past I sent some code through related to WX python that I am working > on to see if I can make an accessible home book-shelf library program. Thus > the reasons for these OOPS questions. I am trying to work out if I should > create the following code as a generic method or class. My simplistic > understanding of Oops. > > * A class is an object such as creating a GUI window. A class represents an object. It is a pattern for an object. The object is the instance that you create from the class. (Although to confuse things, in Python(and a few other languages) classes are objects too!) Keeping the distinction between classes and objects clear in your mind is critical to success in OOP. > * Method is the action you want to do Such as creating an edit control > or performing a database query. Strictly speaking a method is a response to a message. Each object responds to the same message using a different method. The method definition looks a lot like a function in a non OOP context. And a message looks a lot like a function call... > * Properties are the variables of the class / method. Again being pedantic the properties of a class are both its attributes(public internal data) and its (public) methods. ie the properties of a class are the features that it exposes to the outside world. But again, slightly confusingly, Python properties tend to be used as a way to hide attributes behind methods so that you cannot access the internal data directly but must go through a method. (This is sometimes useful to ensure data stays valid - eg. within certain ranges) > I have a range of WX methods that creates a control on the panel or window. > For example: > class RecordPanel(wx.Panel): > > def __init__(self, parent, app): > wx.Panel.__init__(self, parent=parent) > > # defining the book object. > self.book = None > > # Create the controls for the panel > # adding controls to a sizer. > #sizer = wx.BoxSizer(wx.VERTICAL) > sizer = wx.FlexGridSizer(rows=0, cols=2, vgap=10, hgap=10) > self.title_label = wx.StaticText(self, label="Title:") > self.title_text = wx.TextCtrl(self, size=(300, -1)) > sizer.Add(self.title_label, flag=wx.ALIGN_LEFT) > sizer.Add(self.title_text, flag=wx.EXPAND) > sizer.Add(wx.StaticText(self, label="About Authors:"), > flag=wx.ALIGN_LEFT) > self.about_author_text = wx.TextCtrl(self, size=(300, 100), > style=wx.TE_MULTILINE) > sizer.Add(self.about_author_text, flag=wx.EXPAND) > > # Set the publisher field > self.publisher_label = wx.StaticText(self, label="Publisher:") > self.publisher_text = wx.TextCtrl(self, size=(300, -1)) > sizer.Add(self.publisher_label, flag=wx.ALIGN_LEFT) > sizer.Add(self.publisher_text, flag=wx.EXPAND) > > # Set the series field > self.series_label = wx.StaticText(self, label="Series:") > self.series_text = wx.TextCtrl(self, size=(300, -1)) > sizer.Add(self.series_label, flag=wx.ALIGN_LEFT) > sizer.Add(self.series_text, flag=wx.EXPAND) > > . more declaring of controls and events to be added to the page. > > self.SetSizer(sizer) # applies the controls to the page. > AS you can tell, the creation of the edit fields and the list boxes use the > same syntax with different variables. Is it possible to create a class with > a couple of methods to reduce the lines above to simplify the debugging and > readability of the code? Sure, creating "helper methods" is standard practice. For example in an application class you might have a buildGUI() method that gets called from inside __init__(). Within buildGUI() you could call addLabels() or addControls() etc... Remember that any time you create an attribute with self.xxxx = .... you are making self.xxx available to all methods of the class, including the other helper methods as well as the top level "operational" methods. (In languages other than Python these helper methods would typically be private - ie only usable by other methods of the class. But Python doesn't support private so we use a convention to prefix them with a double underscore: class SomeWidget(Widget): def __init__(self,...): ... self.__buildGUI() ... def __buildGUI(self...): ... It's purely convention and I mention it just in case you come across it and wonder why... > Class WindowControls(sizer, Label, label_flags, control_flags, xPosition, > yPosition): > > # sizer is the wx sizer object > # label - the label to be used for the control > # label_flags - the flags used to style and align the control. > # control_flags - flag parameters for the control. > # xPosition and yPosition - the size of the control. > > Def EditControl(self) > self.control_label = wx.StaticText(self, label=f"{label}:") > self.control_text = wx.TextCtrl(self, size=(xPosition, yPosition)) > sizer.Add(self.control_label, flag=flags) > sizer.Add(self.title_text, flag=control_flags) > return sizer Where is the sizer defined? Should it be return self.sizer? My other question is about the naming of the class. It feels a bit generic. What "window controls"? It contains a sizer and labels so maybe it should be called a LabeledSizer? What kind of object is this class supposed to create? What is it for? Objects should have a purpose not just be a container that you dump stuff into. In OOP parlance you should be able to write down: - The *Class* name - The class *Responsibilities* (what does it do, what does it know) - and the class's *Collaborators* (what dependencies does it have) on a CRC card (originally a 5x3 piece of cardboard but often an electronic note today!) If you can't do that consider whether you should really be making a class at all, maybe it should just be a function? Another factor to consider is how many instances of this class will there be? Can there be more than one? Good! If it's only ever a singleton maybe it should be a module instead? > I hope the above makes sense. As I really an unsure if I am on the right > path here or using Oops in the right way. As I do get confused when to use > the "self" instance. self refers to the current object. When you are inside a method. If you need to refer to, or modify, anything else inside the object (inside yourself) you use self. Remember that methods react to messages sent to instances. If you are accessing something specific to the same object(a method or attribute) you need to use self. For a slightly longer explanation of self see the OOP topic in my tutorial. -- 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 mhysnm1964 at gmail.com Thu Apr 20 07:28:35 2023 From: mhysnm1964 at gmail.com (mhysnm1964 at gmail.com) Date: Thu, 20 Apr 2023 21:28:35 +1000 Subject: [Tutor] Oops concepts class vs methods. In-Reply-To: References: <036501d97367$3c5c06b0$b5141410$@GMAIL.COM> Message-ID: <003501d9737b$40a950b0$c1fbf210$@GMAIL.COM> Alan, Thanks I will refer to your tutorial again. I will go away and try and answer your last couple of questions and respond tomorrow. Sean -----Original Message----- From: Tutor On Behalf Of Alan Gauld via Tutor Sent: Thursday, April 20, 2023 8:43 PM To: tutor at python.org Subject: Re: [Tutor] Oops concepts class vs methods. On 20/04/2023 10:05, mhysnm1964 at gmail.com wrote: > In the past I sent some code through related to WX python that I am > working on to see if I can make an accessible home book-shelf library > program. Thus the reasons for these OOPS questions. I am trying to > work out if I should create the following code as a generic method or > class. My simplistic understanding of Oops. > > * A class is an object such as creating a GUI window. A class represents an object. It is a pattern for an object. The object is the instance that you create from the class. (Although to confuse things, in Python(and a few other languages) classes are objects too!) Keeping the distinction between classes and objects clear in your mind is critical to success in OOP. > * Method is the action you want to do Such as creating an edit control > or performing a database query. Strictly speaking a method is a response to a message. Each object responds to the same message using a different method. The method definition looks a lot like a function in a non OOP context. And a message looks a lot like a function call... > * Properties are the variables of the class / method. Again being pedantic the properties of a class are both its attributes(public internal data) and its (public) methods. ie the properties of a class are the features that it exposes to the outside world. But again, slightly confusingly, Python properties tend to be used as a way to hide attributes behind methods so that you cannot access the internal data directly but must go through a method. (This is sometimes useful to ensure data stays valid - eg. within certain ranges) > I have a range of WX methods that creates a control on the panel or window. > For example: > class RecordPanel(wx.Panel): > > def __init__(self, parent, app): > wx.Panel.__init__(self, parent=parent) > > # defining the book object. > self.book = None > > # Create the controls for the panel > # adding controls to a sizer. > #sizer = wx.BoxSizer(wx.VERTICAL) > sizer = wx.FlexGridSizer(rows=0, cols=2, vgap=10, hgap=10) > self.title_label = wx.StaticText(self, label="Title:") > self.title_text = wx.TextCtrl(self, size=(300, -1)) > sizer.Add(self.title_label, flag=wx.ALIGN_LEFT) > sizer.Add(self.title_text, flag=wx.EXPAND) > sizer.Add(wx.StaticText(self, label="About Authors:"), > flag=wx.ALIGN_LEFT) > self.about_author_text = wx.TextCtrl(self, size=(300, 100), > style=wx.TE_MULTILINE) > sizer.Add(self.about_author_text, flag=wx.EXPAND) > > # Set the publisher field > self.publisher_label = wx.StaticText(self, label="Publisher:") > self.publisher_text = wx.TextCtrl(self, size=(300, -1)) > sizer.Add(self.publisher_label, flag=wx.ALIGN_LEFT) > sizer.Add(self.publisher_text, flag=wx.EXPAND) > > # Set the series field > self.series_label = wx.StaticText(self, label="Series:") > self.series_text = wx.TextCtrl(self, size=(300, -1)) > sizer.Add(self.series_label, flag=wx.ALIGN_LEFT) > sizer.Add(self.series_text, flag=wx.EXPAND) > > . more declaring of controls and events to be added to the page. > > self.SetSizer(sizer) # applies the controls to the page. > AS you can tell, the creation of the edit fields and the list boxes > use the same syntax with different variables. Is it possible to create > a class with a couple of methods to reduce the lines above to simplify > the debugging and readability of the code? Sure, creating "helper methods" is standard practice. For example in an application class you might have a buildGUI() method that gets called from inside __init__(). Within buildGUI() you could call addLabels() or addControls() etc... Remember that any time you create an attribute with self.xxxx = .... you are making self.xxx available to all methods of the class, including the other helper methods as well as the top level "operational" methods. (In languages other than Python these helper methods would typically be private - ie only usable by other methods of the class. But Python doesn't support private so we use a convention to prefix them with a double underscore: class SomeWidget(Widget): def __init__(self,...): ... self.__buildGUI() ... def __buildGUI(self...): ... It's purely convention and I mention it just in case you come across it and wonder why... > Class WindowControls(sizer, Label, label_flags, control_flags, > xPosition, > yPosition): > > # sizer is the wx sizer object > # label - the label to be used for the control > # label_flags - the flags used to style and align the control. > # control_flags - flag parameters for the control. > # xPosition and yPosition - the size of the control. > > Def EditControl(self) > self.control_label = wx.StaticText(self, label=f"{label}:") > self.control_text = wx.TextCtrl(self, size=(xPosition, yPosition)) > sizer.Add(self.control_label, flag=flags) > sizer.Add(self.title_text, flag=control_flags) > return sizer Where is the sizer defined? Should it be return self.sizer? My other question is about the naming of the class. It feels a bit generic. What "window controls"? It contains a sizer and labels so maybe it should be called a LabeledSizer? What kind of object is this class supposed to create? What is it for? Objects should have a purpose not just be a container that you dump stuff into. In OOP parlance you should be able to write down: - The *Class* name - The class *Responsibilities* (what does it do, what does it know) - and the class's *Collaborators* (what dependencies does it have) on a CRC card (originally a 5x3 piece of cardboard but often an electronic note today!) If you can't do that consider whether you should really be making a class at all, maybe it should just be a function? Another factor to consider is how many instances of this class will there be? Can there be more than one? Good! If it's only ever a singleton maybe it should be a module instead? > I hope the above makes sense. As I really an unsure if I am on the > right path here or using Oops in the right way. As I do get confused > when to use the "self" instance. self refers to the current object. When you are inside a method. If you need to refer to, or modify, anything else inside the object (inside yourself) you use self. Remember that methods react to messages sent to instances. If you are accessing something specific to the same object(a method or attribute) you need to use self. For a slightly longer explanation of self see the OOP topic in my tutorial. -- 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 thurmonium at gmail.com Thu Apr 20 19:27:54 2023 From: thurmonium at gmail.com (Thurman Hill) Date: Thu, 20 Apr 2023 19:27:54 -0400 Subject: [Tutor] Help In-Reply-To: References: Message-ID: I need help with this question. Fill in the blanks to complete the ?all_numbers? function. This function should return a space-separated string of all numbers, from the starting ?minimum? variable up to and including the ?maximum? variable that's passed into the function. Complete the for loop so that a function call like ?all_numbers(3,6)? will return the numbers ?3 4 5 6?. def all_numbers(minimum, maximum): return_string = "" # Initializes variable as a string # Complete the for loop with a range that includes all # numbers up to and including the "maximum" value. for ___ # Complete the body of the loop by appending the number # followed by a space to the "return_string" variable. ___ # This .strip command will remove the final " " space # at the end of the "return_string". return return_string.strip() print(all_numbers(2,6)) # Should be 2 3 4 5 6 print(all_numbers(3,10)) # Should be 3 4 5 6 7 8 9 10 print(all_numbers(-1,1)) # Should be -1 0 1 print(all_numbers(0,5)) # Should be 0 1 2 3 4 5 print(all_numbers(0,0)) # Should be 0 On Wed, Apr 12, 2023 at 12:51?PM Thurman Hill wrote: > I?m getting a type error when I put this into the blanks? Please help. > I've been stuck for weeks? > > > > > > > > > > Fill in the blanks to print the even numbers from 2 to 12. > > > > number = range(2,12+1,2) # Initialize the variable > > while number > 0: # Complete the while loop condition > > print(number, end=" ") > > number # Increment the variable > > > > # Should print 2 4 6 8 10 12 > > > > Error: > > Error on line 2: > > while number > 0: # Complete the while loop condition > > TypeError: '>' not supported between instances of 'range' and 'int' > From PythonList at DancesWithMice.info Thu Apr 20 21:44:03 2023 From: PythonList at DancesWithMice.info (dn) Date: Fri, 21 Apr 2023 13:44:03 +1200 Subject: [Tutor] Help In-Reply-To: References: Message-ID: <0c2583ef-172d-5be2-ba1f-8e555c36c1d4@DancesWithMice.info> I'm sorry that this response may not be to your liking:- We will be delighted to HELP you. One of us completing an assignment will not enable your learning. Please show what you have managed thus far, together with the output produced (and/or error-messages). Thereafter, we will be able to offer constructive criticism and point-out anything necessary to help. Which topics and Python constructs has your course or book taught recently? Will one or more of them lead towards an answer? Reproduced from the list's description: "how to learn computer programming with the Python language" cf paying others to write code for you. On 21/04/2023 11.27, Thurman Hill wrote: > I need help with this question. > > > Fill in the blanks to complete the ?all_numbers? function. This function > should return a space-separated string of all numbers, from the starting > ?minimum? variable up to and including the ?maximum? variable that's > passed into the function. Complete the for loop so that a function call > like ?all_numbers(3,6)? will return the numbers ?3 4 5 6?. > > > > def all_numbers(minimum, maximum): > > return_string = "" # Initializes variable as a string > > # Complete the for loop with a range that includes all > # numbers up to and including the "maximum" value. > for ___ > > # Complete the body of the loop by appending the number > # followed by a space to the "return_string" variable. > ___ > > # This .strip command will remove the final " " space > # at the end of the "return_string". > return return_string.strip() > > > print(all_numbers(2,6)) # Should be 2 3 4 5 6 > print(all_numbers(3,10)) # Should be 3 4 5 6 7 8 9 10 > print(all_numbers(-1,1)) # Should be -1 0 1 > print(all_numbers(0,5)) # Should be 0 1 2 3 4 5 > print(all_numbers(0,0)) # Should be 0 > > > On Wed, Apr 12, 2023 at 12:51?PM Thurman Hill wrote: > >> I?m getting a type error when I put this into the blanks? Please help. >> I've been stuck for weeks? >> >> >> >> >> >> >> >> >> >> Fill in the blanks to print the even numbers from 2 to 12. >> >> >> >> number = range(2,12+1,2) # Initialize the variable >> >> while number > 0: # Complete the while loop condition >> >> print(number, end=" ") >> >> number # Increment the variable >> >> >> >> # Should print 2 4 6 8 10 12 >> >> >> >> Error: >> >> Error on line 2: >> >> while number > 0: # Complete the while loop condition >> >> TypeError: '>' not supported between instances of 'range' and 'int' >> > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Regards, =dn From myrefors.magnus at telia.com Fri Apr 21 10:26:30 2023 From: myrefors.magnus at telia.com (Magnus Myrefors) Date: Fri, 21 Apr 2023 16:26:30 +0200 Subject: [Tutor] Strange results when using not operation. Message-ID: <63C2593503EAC8E9@ts201-smtpout72.ddc.teliasonera.net> (added by MAILER-DAEMON@telia.com) Hello ! I am currently Reading a ?Beginning Python? book, and when I did some tests with the not operation in the IDLE python Shell I saw som strange results. When I typed ? not?A? == False ? the result was ?True? and when I typed ? not?A? == True ? the result was ?True? again. I got similar results when I typed ? not(2) == False ? and ? not(2) == True ? which both gave the result ?True? . When I put the whole left side in paranthesis like this: ? (not?A?) == False? and ? (not?A?) == True ? the results were different. Magnus Skickades fr?n E-post f?r Windows From mats at wichmann.us Fri Apr 21 14:02:37 2023 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 21 Apr 2023 12:02:37 -0600 Subject: [Tutor] Strange results when using not operation. In-Reply-To: <63C2593503EAC8E9@ts201-smtpout72.ddc.teliasonera.net> References: <63C2593503EAC8E9@ts201-smtpout72.ddc.teliasonera.net> Message-ID: <78cc8e2e-7c73-61b6-534f-9521c30c1490@wichmann.us> On 4/21/23 08:26, Magnus Myrefors via Tutor wrote: > Hello ! > > I am currently Reading a ?Beginning Python? book, and when I did some tests with the not operation in the IDLE python Shell I saw som strange results. When I typed ? not?A? == False ? the result was ?True? and when I typed ? not?A? == True ? the result was ?True? again. I got similar results when I typed ? not(2) == False ? and ? not(2) == True ? which both gave the result ?True? . When I put the whole left side in paranthesis like this: ? (not?A?) == False? and ? (not?A?) == True ? the results were different. > > Magnus > > Skickades fr?n E-post f?r Windows You're negating an expression. >>> "A" == False False >>> not "A" == False True From alan.gauld at yahoo.co.uk Fri Apr 21 14:45:15 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 21 Apr 2023 19:45:15 +0100 Subject: [Tutor] Strange results when using not operation. In-Reply-To: <24620.3529693716$1682099610@news.gmane.org> References: <24620.3529693716$1682099610@news.gmane.org> Message-ID: On 21/04/2023 15:26, Magnus Myrefors via Tutor wrote: > Hello ! > > I am currently Reading a ?Beginning Python? book, and when > I did some tests with the not operation in the IDLE python > Shell I saw som strange results. When I typed ? not?A? == False ? > the result was ?True? and when I typed ? not?A? == True ? the result was ?True? again. It would help if you actually copy/pasted the actual code and output. Above I see single quotes around the code, I assume you did not type those at the Python prompt? > I got similar results when I typed ? not(2) == False ? > and ? not(2) == True ? which both gave the result ?True? . > When I put the whole left side in paranthesis like this: ? (not?A?) == False? and ? (not?A?) == True ? > the results were different. The answer to this seemingly weird behaviour lies in how Python performs the equality comparison. The relevant part of the language reference says: """The default behavior for equality comparison (== and !=) is based on the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality. A motivation for this default behavior is the desire that all objects should be reflexive (i.e. x is y implies x == y).""" Here is an interactive session including your examples plus a few more along with my commentary: Python 3.10.4 (v3.10.4:9d38120e33, Mar 23 2022, 17:29:05) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> not "A" == False True >>> not "A" == True True Python reads these as: not("A" == False) and not("A" == True") So lets look at the parens: >>> ("A" == False) False >>> ("A" == True) False So both sets of parens are false because the string "A" is not equal to either of the boolean values. The operator uses an ID comparison. And the string has a different identity to the booleans. >>> not "A" False >>> (not "A") == False True >>> (not "A") == True False By putting the parens around the left side you evaluate not "A" first resulting in a boolean value(False in this case) and then compare that boolean value to the literal booleans. Thus you get a differrent result since False == false is indeed True and False == True is indeed False. >>> not(2) == False True >>> not(2) == True True The same applies here. Python sees this as: not ((2) == False) and not ((2) == True) and 2 has a different ID to both True and False so both parens return False and their negations return True, which is what you saw. Now the language reference goes on to describe cases where the behaviour has been changed from the default for some types so ID comparisons are not always used. Here is the link so you can study it all in detail. https://docs.python.org/3/reference/expressions.html#value-comparisons It may take you a few read throughs! -- 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 PythonList at DancesWithMice.info Fri Apr 21 15:39:29 2023 From: PythonList at DancesWithMice.info (dn) Date: Sat, 22 Apr 2023 07:39:29 +1200 Subject: [Tutor] Strange results when using not operation. In-Reply-To: <63C2593503EAC8E9@ts201-smtpout72.ddc.teliasonera.net> References: <63C2593503EAC8E9@ts201-smtpout72.ddc.teliasonera.net> Message-ID: Hello! On 22/04/2023 02.26, Magnus Myrefors via Tutor wrote: > Hello ! > > I am currently Reading a ?Beginning Python? book, and when I did some tests with the not operation in the IDLE python Shell I saw som strange results. When I typed ? not?A? == False ? the result was ?True? and when I typed ? not?A? == True ? the result was ?True? again. I got similar results when I typed ? not(2) == False ? and ? not(2) == True ? which both gave the result ?True? . When I put the whole left side in paranthesis like this: ? (not?A?) == False? and ? (not?A?) == True ? the results were different. To my old eyes, the code seems to run together, eg it should be: not "A" (with a space between) The keyword "not" is a separate "token" from the string! To avoid confusion, please copy-paste code (and responses) from the IDLE editor into separate lines of the email-message. -- Regards, =dn From phillor9 at gmail.com Sat Apr 22 19:46:41 2023 From: phillor9 at gmail.com (Phil) Date: Sun, 23 Apr 2023 09:46:41 +1000 Subject: [Tutor] Python project organisation Message-ID: I'm looking suggestions for organising my python projects. I had, until recently, all of my python projects stored in the one directory (~/Python), all 298 of them. This has become almost unmanageable so I split my projects into multiple sub-directories named Tkinter, Wxpython, etc. and named each project, for example those under the Tkinter sub-directory, as "tkinter_project_name.py". This is, or was, better but still not good. This problem has now come to a head because because my upgraded Linux distribution now requires the use of virtual environments, otherwise "pip3 install" fails. So I created a virtual environment "~/.venv/bleak/bin" named after the name of the module that I needed to upgrade. It probably should be named after the project instead. The code for the project is now in that virtual environment directory which brings me to my question. Should I create a virtual environment for each project, I don't think so? If I do, won't that make the PYTHONPATH unwieldy with hundreds of directories needing to be added to PYTHONPATH? I can see a case where a project should have it's own environment and that's where a project includes images that are solely used by that project. At the moment images and custom classes are all stored under python's global environment. -- Regards, Phil From PythonList at DancesWithMice.info Sat Apr 22 20:49:15 2023 From: PythonList at DancesWithMice.info (dn) Date: Sun, 23 Apr 2023 12:49:15 +1200 Subject: [Tutor] Python project organisation In-Reply-To: References: Message-ID: <37266c13-2bac-254c-6b92-5bb97d383a41@DancesWithMice.info> On 23/04/2023 11.46, Phil wrote: > I'm looking suggestions for organising my python projects. > > I had, until recently, all of my python projects stored in the one > directory (~/Python), all 298 of them. This has become almost > unmanageable so I split my projects into multiple sub-directories named > Tkinter, Wxpython, etc. and named each project, for example those under > the Tkinter sub-directory, as "tkinter_project_name.py". This is, or > was, better but still not good. > > This problem has now come to a head because because my upgraded Linux > distribution now requires the use of virtual environments, otherwise > "pip3 install" fails. > > So I created a virtual environment "~/.venv/bleak/bin" named after the > name of the module that I needed to upgrade. It probably should be named > after the project instead. The code for the project is now in that > virtual environment directory which brings me to my question. > > Should I create a virtual environment for each project, I don't think > so? If I do, won't that make the PYTHONPATH unwieldy with hundreds of > directories needing to be added to PYTHONPATH? I can see a case where a > project should have it's own environment and that's where a project > includes images that are solely used by that project. At the moment > images and custom classes are all stored under python's global environment. Yes, each project SHOULD be 'insulated' from the next. This will allow one project to use a newer version of a library than the others, for example. Whereas, updating the library system-wide sh/would require you to re-test every project which uses same, to head-off any 'breakages' or other difficulties. The mode of utilising virtual-environments is that only one (or a few related) project/environments will be open or "live" at a time. Part of making an environment active is to add it into the PYTHONPATH. Conversely, part of shutting-down the environment, eg when you move your attention to a different project, is to remove those references again, ie back to system-settings. Thus, the modification to PYTHONPATH is only temporary. I have recently started using Poetry under PyCharm. When I decide to work on a particular project, the IDE takes-care of all the 'plumbing', eg PYTHONPATH. The combination of both tools keeps track of (only) the Python libraries which this particular project needs - and enables libraries to be separately updated, as-and-when. Poetry provides a mechanism to "package" the project and move it (my code and the Python-environment) to another machine, or wherever. All this is documented in the PyCharm 'docs'. Presumably VS-Codium/e (etc) will offer something equivalent. -- Regards, =dn From phillor9 at gmail.com Sat Apr 22 21:30:00 2023 From: phillor9 at gmail.com (Phil) Date: Sun, 23 Apr 2023 11:30:00 +1000 Subject: [Tutor] Python project organisation In-Reply-To: <37266c13-2bac-254c-6b92-5bb97d383a41@DancesWithMice.info> References: <37266c13-2bac-254c-6b92-5bb97d383a41@DancesWithMice.info> Message-ID: <25497e48-4da9-cefe-9435-8adbbe8bab34@gmail.com> On 23/4/23 10:49, dn via Tutor wrote: Thank you DN. > Yes, each project SHOULD be 'insulated' from the next. What I've decided to do is only create a project directory and virtual environment for those projects where it makes sense. The rest can stay in the global environment. > The mode of utilising virtual-environments is that only one (or a few > related) project/environments will be open or "live" at a time. Part > of making an environment active is to add it into the PYTHONPATH. > Conversely, part of shutting-down the environment, eg when you move > your attention to a different project, is to remove those references > again, ie back to system-settings. Thus, the modification to > PYTHONPATH is only temporary. I knew about activate but I didn't know that the addition to the PYTHONPATH is temporary. I suppose it's only a matter of activating a new projects environment to deactivate the previous one? > > Presumably VS-Codium/e (etc) will offer something equivalent. Yes it does and it finds a newly created virtual environment automagically. I think VS Code is able to change the activation of different project environments but I'm a little hazy on the exact procedure. It seems that starting VS Code from within a project's virtual environment is the easiest option. -- Regards, Phil From PythonList at DancesWithMice.info Sat Apr 22 22:23:49 2023 From: PythonList at DancesWithMice.info (dn) Date: Sun, 23 Apr 2023 14:23:49 +1200 Subject: [Tutor] Python project organisation In-Reply-To: <25497e48-4da9-cefe-9435-8adbbe8bab34@gmail.com> References: <37266c13-2bac-254c-6b92-5bb97d383a41@DancesWithMice.info> <25497e48-4da9-cefe-9435-8adbbe8bab34@gmail.com> Message-ID: On 23/04/2023 13.30, Phil wrote: > On 23/4/23 10:49, dn via Tutor wrote: > Thank you DN. > >> Yes, each project SHOULD be 'insulated' from the next. > > What I've decided to do is only create a project directory and virtual > environment for those projects where it makes sense. The rest can stay > in the global environment. That makes good sense - the effort of re-arranging every project (and testing to ensure it still works - correctly) might be quite large! What's the point? You might never work on that project again... If/when you come to work on a project, the first step could be to modernise its project-structure according to your new methods - and some benefit will result from the effort along-side the planned upgrade! >> The mode of utilising virtual-environments is that only one (or a few >> related) project/environments will be open or "live" at a time. Part >> of making an environment active is to add it into the PYTHONPATH. >> Conversely, part of shutting-down the environment, eg when you move >> your attention to a different project, is to remove those references >> again, ie back to system-settings. Thus, the modification to >> PYTHONPATH is only temporary. > > I knew about activate but I didn't know that the addition to the > PYTHONPATH is temporary. I suppose it's only a matter of activating a > new projects environment to deactivate the previous one? Not exactly. It is possible (not speaking for VS-Code) to work on two projects concurrently, eg some analysis script may need your email library to present reports or alerts. Because your email library may be used by other projects, it is in a library/project of its own. Thus, you may need/prefer to have both 'projects' open, to ease integration. The "deactivation" will happen when you *close* a project. (at least that's how PyCharm does it). Thus, even taking the (perhaps) unusual illustration, above, when each project is closed, deactivation happens. After both have been closed, the PYTHONPATH will be back to its original system-wide settings - with no 'local directory' included. >> Presumably VS-Codium/e (etc) will offer something equivalent. > > Yes it does and it finds a newly created virtual environment > automagically. I think VS Code is able to change the activation of > different project environments but I'm a little hazy on the exact > procedure. It seems that starting VS Code from within a project's > virtual environment is the easiest option. VS-Code is not used by any of my project teams currently, so am loathe to offer a categorical reply. However, that sounds a bit 'backwards'/too much manual effort. In PyCharm, one selects a (new) project to work within. At that time, the IDE activates the virtual-environment AND sets-up the 'walls' which keep anything from 'leaking' (between projects, or between this project and the system). Part of the activation is to make the project's (virtual) directory the current working-directory, ie the project-settings define the directory, not your locating the directory first. (from memory, there's a subtlety to such, which may not apply in SublimeText - but as neither of us is using that IDE, consider it ignored!) In other words, nominating the project is sufficient for the IDE to effect all that's necessary; and vice-versa when the project is closed. What do the VS-Code user-docs say? (for comparison: https://www.jetbrains.com/help/pycharm/creating-virtual-environment.html and https://www.jetbrains.com/help/pycharm/poetry.html) -- Regards =dn -- Regards, =dn From cs at cskk.id.au Sat Apr 22 22:49:00 2023 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 23 Apr 2023 12:49:00 +1000 Subject: [Tutor] Python project organisation In-Reply-To: <25497e48-4da9-cefe-9435-8adbbe8bab34@gmail.com> References: <25497e48-4da9-cefe-9435-8adbbe8bab34@gmail.com> Message-ID: On 23Apr2023 11:30, Phil wrote: >I knew about activate but I didn't know that the addition to the >PYTHONPATH is temporary. I suppose it's only a matter of activating a >new projects environment to deactivate the previous one? One thing often glossed over with venvs is that the "python" executable inside the venv/bin directory actually sets its search path correctly when you invoke it - you don't need to set your shell's $PYTHONPATH at all. So: ./venv/bin/python3 -m my.module ... would run the python3 from the venv, using the local my.module in the project. When I work with a venv, which I do routinely, I don't "activate" it. Instead I have a little "dev" script/alias which prepends the venv/bin to the front of $PATH (and whatever other local "dev mode" envar changes i might have), then executes my command. So: which python3 will find the normal, nondev python3. But: dev which python3 will find the venv python3, which takes care of the search path when you invoke it. Part of this is because my own code is intwined in my normal operations. So if I run a command, I normally want the "installed" version, _not_ the (possibly broken) version in the project folder I'm standing in. Cheers, Cameron Simpson From phillor9 at gmail.com Sat Apr 22 23:43:02 2023 From: phillor9 at gmail.com (Phil) Date: Sun, 23 Apr 2023 13:43:02 +1000 Subject: [Tutor] Python project organisation In-Reply-To: References: <37266c13-2bac-254c-6b92-5bb97d383a41@DancesWithMice.info> <25497e48-4da9-cefe-9435-8adbbe8bab34@gmail.com> Message-ID: <40d17f91-6638-5741-23b0-8bbef9550605@gmail.com> On 23/4/23 12:23, dn via Tutor wrote: Thank you DN and Cameron, > > Thus, even taking the (perhaps) unusual illustration, above, when each > project is closed, deactivation happens. After both have been closed, > the PYTHONPATH will be back to its original system-wide settings - > with no 'local directory' included. I now have everything sorted out. Within VS Code there's a setting that will create a script that's installed under my Python directory. The script activates the project's virtual environment when a project is selected. I've selected a few different projects and it seems to working correctly. -- Regards, Phil From PythonList at DancesWithMice.info Sun Apr 23 00:46:15 2023 From: PythonList at DancesWithMice.info (dn) Date: Sun, 23 Apr 2023 16:46:15 +1200 Subject: [Tutor] Python project organisation In-Reply-To: <40d17f91-6638-5741-23b0-8bbef9550605@gmail.com> References: <37266c13-2bac-254c-6b92-5bb97d383a41@DancesWithMice.info> <25497e48-4da9-cefe-9435-8adbbe8bab34@gmail.com> <40d17f91-6638-5741-23b0-8bbef9550605@gmail.com> Message-ID: <6bac437a-f988-4664-d63f-5d20def381c2@DancesWithMice.info> On 23/04/2023 15.43, Phil wrote: > > On 23/4/23 12:23, dn via Tutor wrote: > Thank you DN and Cameron, >> >> Thus, even taking the (perhaps) unusual illustration, above, when each >> project is closed, deactivation happens. After both have been closed, >> the PYTHONPATH will be back to its original system-wide settings - >> with no 'local directory' included. > > I now have everything sorted out. Within VS Code there's a setting that > will create a script that's installed under my Python directory. The > script activates the project's virtual environment when a project is > selected. I've selected a few different projects and it seems to working > correctly. Well done! -- Regards, =dn From DomainAdmin at DancesWithMice.info Sat Apr 22 22:21:54 2023 From: DomainAdmin at DancesWithMice.info (David L Neil) Date: Sun, 23 Apr 2023 14:21:54 +1200 Subject: [Tutor] Python project organisation In-Reply-To: <25497e48-4da9-cefe-9435-8adbbe8bab34@gmail.com> References: <37266c13-2bac-254c-6b92-5bb97d383a41@DancesWithMice.info> <25497e48-4da9-cefe-9435-8adbbe8bab34@gmail.com> Message-ID: <3b908df8-de2a-f479-faab-db43ad6cc8fc@DancesWithMice.info> On 23/04/2023 13.30, Phil wrote: > On 23/4/23 10:49, dn via Tutor wrote: > Thank you DN. > >> Yes, each project SHOULD be 'insulated' from the next. > > What I've decided to do is only create a project directory and virtual > environment for those projects where it makes sense. The rest can stay > in the global environment. That makes good sense - the effort of re-arranging every project (and testing to ensure it still works - correctly) might be quite large! What's the point? You might never work on that project again... If/when you come to work on a project, the first step could be to modernise its project-structure according to your new methods - and some benefit will result from the effort along-side the planned upgrade! >> The mode of utilising virtual-environments is that only one (or a few >> related) project/environments will be open or "live" at a time. Part >> of making an environment active is to add it into the PYTHONPATH. >> Conversely, part of shutting-down the environment, eg when you move >> your attention to a different project, is to remove those references >> again, ie back to system-settings. Thus, the modification to >> PYTHONPATH is only temporary. > > I knew about activate but I didn't know that the addition to the > PYTHONPATH is temporary. I suppose it's only a matter of activating a > new projects environment to deactivate the previous one? Not exactly. It is possible (not speaking for VS-Code) to work on two projects concurrently, eg some analysis script may need your email library to present reports or alerts. Because your email library may be used by other projects, it is in a library/project of its own. Thus, you may need/prefer to have both 'projects' open, to ease integration. The "deactivation" will happen when you *close* a project. (at least that's how PyCharm does it). Thus, even taking the (perhaps) unusual illustration, above, when each project is closed, deactivation happens. After both have been closed, the PYTHONPATH will be back to its original system-wide settings - with no 'local directory' included. >> Presumably VS-Codium/e (etc) will offer something equivalent. > > Yes it does and it finds a newly created virtual environment > automagically. I think VS Code is able to change the activation of > different project environments but I'm a little hazy on the exact > procedure. It seems that starting VS Code from within a project's > virtual environment is the easiest option. VS-Code is not used by any of my project teams currently, so am loathe to offer a categorical reply. However, that sounds a bit 'backwards'/too much manual effort. In PyCharm, one selects a (new) project to work within. At that time, the IDE activates the virtual-environment AND sets-up the 'walls' which keep anything from 'leaking' (between projects, or between this project and the system). Part of the activation is to make the project's (virtual) directory the current working-directory, ie the project-settings define the directory, not your locating the directory first. (from memory, there's a subtlety to such, which may not apply in SublimeText - but as neither of us is using that IDE, consider it ignored!) In other words, nominating the project is sufficient for the IDE to effect all that's necessary; and vice-versa when the project is closed. What do the VS-Code user-docs say? (for comparison: https://www.jetbrains.com/help/pycharm/creating-virtual-environment.html and https://www.jetbrains.com/help/pycharm/poetry.html) -- Regards =dn From nulla.epistola at web.de Sun Apr 23 04:38:29 2023 From: nulla.epistola at web.de (Sibylle Koczian) Date: Sun, 23 Apr 2023 10:38:29 +0200 Subject: [Tutor] Hello In-Reply-To: <023501d9735c$c6527b20$52f77160$@GMAIL.COM> References: <4BthiDqC6_347k7tg3kVb4XnXRzJH3CxuVJxQwYYN59fFk3VTyr-j7fkn21Jhq6SsOJSJ5t31xUDV4fSv1u1_yHi6oV0Vx-hoA-b4ZbSdW0=@proton.me> <023501d9735c$c6527b20$52f77160$@GMAIL.COM> Message-ID: <1c84eafb-f7ae-1213-8abc-b17d4f642a5c@web.de> Am 20.04.2023 um 09:50 schrieb mhysnm1964 at gmail.com: > Bernard > > Loops are used to execute a piece of code based upon specific conditions > (expressions) in the loop statement or within the code block itself. There > is three basic loop structures in any language: > ... > > The while loop is the 2nd basic loop. This loop performs the expression test > before any of the code within the loop block. If true, then nothing is > executed in the loop block. For example: > > A = 5 > While a >4: > A -= 1 > Print (a) > > The expression "a > 4" is true because a is greater than 4. The count and > print statements are not executed. Change the a variable and the expression > to get different results. > Wrong. The code inside the while loop is executed as long as the expression is true! Moreover, your code crashes with a NameError: for my part I overlooked your mix of A and a, both meaning the same variable. But my Python shell was more careful, as it should be: Python 3.11.3 (tags/v3.11.3:f3909b8, Apr 4 2023, 23:49:59) [MSC v.1934 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> A = 5 >>> while a > 4: ... A -= 1 ... print(a) ... Traceback (most recent call last): File "", line 1, in NameError: name 'a' is not defined. Did you mean: 'A'? >>> Bernard: additional lesson here, Python is case sensitive. And I didn't find any mention of this at the beginning of the tutorial where I'd expect it. HTH Sibylle From nulla.epistola at web.de Sun Apr 23 04:38:29 2023 From: nulla.epistola at web.de (Sibylle Koczian) Date: Sun, 23 Apr 2023 10:38:29 +0200 Subject: [Tutor] Hello In-Reply-To: <023501d9735c$c6527b20$52f77160$@GMAIL.COM> References: <4BthiDqC6_347k7tg3kVb4XnXRzJH3CxuVJxQwYYN59fFk3VTyr-j7fkn21Jhq6SsOJSJ5t31xUDV4fSv1u1_yHi6oV0Vx-hoA-b4ZbSdW0=@proton.me> <023501d9735c$c6527b20$52f77160$@GMAIL.COM> Message-ID: <1c84eafb-f7ae-1213-8abc-b17d4f642a5c@web.de> Am 20.04.2023 um 09:50 schrieb mhysnm1964 at gmail.com: > Bernard > > Loops are used to execute a piece of code based upon specific conditions > (expressions) in the loop statement or within the code block itself. There > is three basic loop structures in any language: > ... > > The while loop is the 2nd basic loop. This loop performs the expression test > before any of the code within the loop block. If true, then nothing is > executed in the loop block. For example: > > A = 5 > While a >4: > A -= 1 > Print (a) > > The expression "a > 4" is true because a is greater than 4. The count and > print statements are not executed. Change the a variable and the expression > to get different results. > Wrong. The code inside the while loop is executed as long as the expression is true! Moreover, your code crashes with a NameError: for my part I overlooked your mix of A and a, both meaning the same variable. But my Python shell was more careful, as it should be: Python 3.11.3 (tags/v3.11.3:f3909b8, Apr 4 2023, 23:49:59) [MSC v.1934 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> A = 5 >>> while a > 4: ... A -= 1 ... print(a) ... Traceback (most recent call last): File "", line 1, in NameError: name 'a' is not defined. Did you mean: 'A'? >>> Bernard: additional lesson here, Python is case sensitive. And I didn't find any mention of this at the beginning of the tutorial where I'd expect it. HTH Sibylle From luk4bernard at gmail.com Mon Apr 24 06:19:13 2023 From: luk4bernard at gmail.com (Bernard Kofi Agboado) Date: Mon, 24 Apr 2023 10:19:13 +0000 Subject: [Tutor] Hello In-Reply-To: <023501d9735c$c6527b20$52f77160$@GMAIL.COM> References: <4BthiDqC6_347k7tg3kVb4XnXRzJH3CxuVJxQwYYN59fFk3VTyr-j7fkn21Jhq6SsOJSJ5t31xUDV4fSv1u1_yHi6oV0Vx-hoA-b4ZbSdW0=@proton.me> <023501d9735c$c6527b20$52f77160$@GMAIL.COM> Message-ID: This is great, thank you so much! On Thu, Apr 20, 2023 at 7:50?AM wrote: > Bernard > > Loops are used to execute a piece of code based upon specific conditions > (expressions) in the loop statement or within the code block itself. There > is three basic loop structures in any language: > > The for loop -- this example is pythons way of a pre-defined number of > iterations over (executions) of a piece of code: > > for i in range(1, 11): > print(i) > > The above code will print 1 to 10. Then exit. Instead of doing: > > I = 0 > I += 1 > Print (i) > > I += 1 > Print (i) > I += 1 > Print (i) > ... and so on. > > The for loop in Python allows you to execute codes based upon a list and > other data types. For example: > > A = [1,2,3,4,5] > For I in a: > Print (i) > > The above will print each element of A. > > The while loop is the 2nd basic loop. This loop performs the expression > test > before any of the code within the loop block. If true, then nothing is > executed in the loop block. For example: > > A = 5 > While a >4: > A -= 1 > Print (a) > > The expression "a > 4" is true because a is greater than 4. The count and > print statements are not executed. Change the a variable and the expression > to get different results. > > The do ... while loop does the reverse to the while loop. The test of the > expression is at the end. A better question would be, what are common loops > used in python? > > My limited experience is the while and for loops. > > Sean > > -----Original Message----- > From: Tutor On Behalf Of > ThreeBlindQuarks via Tutor > Sent: Thursday, April 20, 2023 2:14 AM > To: Bernard Kofi Agboado > Cc: tutor at python.org > Subject: Re: [Tutor] Hello > > > Bernard, that is an extremely broad question. > > My first thought was that in America we eat our loops with fruit but that > is > not very helpful. > > Could you post a few lines of code that contain an example of loops and > tell > us what you do not understand or how to modify it so it does not produce > error messages or wrong results? > > Python has lots of constructs that I would call loops. All of them share a > concept of repeating the same code some number of times with some things > changing as you move along. > > Are you looking at explicit loops where you see key words like "for" and > "while" with indented code below or some more subtle ones including > comprehensions or generators or the kind where the loop is done invisibly? > > Again, send an example or two and say what about it does not make sense. > But > the people here are not tutors in the sense of teaching very basic things > that a student should be getting by reading a textbook and listening to > lectures. We would appreciate a more focused question so we can provide > more > focused help. > > > > Sent with Proton Mail secure email. > > ------- Original Message ------- > On Wednesday, April 19th, 2023 at 3:30 AM, Bernard Kofi Agboado > wrote: > > > > Good morning, please how best can I understand the loops.? > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > From david at lowryduda.com Thu Apr 27 16:14:21 2023 From: david at lowryduda.com (David Lowry-Duda) Date: Thu, 27 Apr 2023 16:14:21 -0400 Subject: [Tutor] bash heredoc and python Message-ID: I like to use python as a simple commandline calculator. I only just learned that it's possible to do something like the following in bash ``` $ python < References: Message-ID: <4f01c905-af0b-c8b4-9def-da56d5678266@wichmann.us> On 4/27/23 14:14, David Lowry-Duda wrote: > I like to use python as a simple commandline calculator. I only just > learned that it's possible to do something like the following in bash > > ``` > $ python < import math > print('multiple lines') > print(math.pi) > ``` > > and python will happily run this. I had thought this wouldn't work, and > that python would instead complain that there was no file with some > amalgamated name. > > I discovered this by an accident, but googling shows of course that this > isn't new or anything. I would have expected this to run with "python - > < > So I opened up the python manpage to see about this, and saw nothing > there (not even about what `-` is supposed to mean!). Then I went to > > https://docs.python.org/3/using/cmdline.html#command-line > > to see if I could learn more, and I don't see much there either. There > is a somewhat cryptic remark: "In non-interactive mode, the entire input > is parsed before it is executed." > > I guess python does something like: check to see if args were given, if > not then check for standard input and then run it noninteractively? Do > you think this is an intended behavior, or is this merely an > undocumented implementation detail? Intended - and little to do with Python. The shell syntax << connects standard input to the following text stream (the here-document), instead of to the terminal. So when Python opens, stdin is not a tty, and thus non-interactive. Because that plumbing is set up by the shell as it's launching Python, there's no need for Python to be called with any special options. For grins, if you like doing Python inline in your shell, consider a weird project called xonsh. From threesomequarks at proton.me Thu Apr 27 17:45:13 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Thu, 27 Apr 2023 21:45:13 +0000 Subject: [Tutor] bash heredoc and python In-Reply-To: References: Message-ID: David, I would have suggested that bashing was not appreciated on this forum but then realized the moderator would correct us by saying that of course it sometimes was and would not see it as humor. So, I did not say that! Back to being serious, the program you call bash is one of name "shell" programs with names like sh or ksh and quite a few others. The name bash is a it of a pun on the original creator of the UNIX shell program and is supposedly he Bourne Again SHell. Your question is not even slightly about Python because the python interpreter has NO IDEA it was called this way. It was one of may UNIX shell features that have migrated to many other operating systems. Any program you call on the command line has a standard input and out and error that can be redirected in many ways. Think of what happens if you pipe into the Python interpreter from another program as an example as in: cat file | python ... echo "Some text" | python ... or pipe the output elsewhere. A HERE document is just a gimmick similar to the echo above so something like: program args < wrote: > I like to use python as a simple commandline calculator. I only just > learned that it's possible to do something like the following in bash > > `$ python < > and python will happily run this. I had thought this wouldn't work, and > that python would instead complain that there was no file with some > amalgamated name. > > I discovered this by an accident, but googling shows of course that this > isn't new or anything. I would have expected this to run with "python - > < stdin. > > So I opened up the python manpage to see about this, and saw nothing > there (not even about what `-` is supposed to mean!). Then I went to > > https://docs.python.org/3/using/cmdline.html#command-line > > to see if I could learn more, and I don't see much there either. There > is a somewhat cryptic remark: "In non-interactive mode, the entire input > is parsed before it is executed." > > I guess python does something like: check to see if args were given, if > not then check for standard input and then run it noninteractively? Do > you think this is an intended behavior, or is this merely an > undocumented implementation detail? > > - DLD > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From threesomequarks at proton.me Thu Apr 27 18:00:31 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Thu, 27 Apr 2023 22:00:31 +0000 Subject: [Tutor] bash heredoc and python In-Reply-To: References: Message-ID: [RE-SENT after I noticed I did not proofread while rushing with hopefully fewer spelling errors or odd phrasings.] David, I would have suggested that bashing was not appreciated on this forum but then realized the moderator would correct us by saying that of course it sometimes was and would not see it as humor. So, I did not say that! Back to being serious, the program you call bash is one of many "shell" programs with names like sh or ksh and quite a few others. The name bash is a it of a pun on the original creator of the UNIX shell program and is supposedly the Bourne Again SHell. Your question is not even slightly about Python because the Python interpreter has NO IDEA it was called this way. It was one of many UNIX shell features that have migrated to many other operating systems. Any program you call on the command line has a standard input and standard output and standard error streams that can be redirected in many ways. Think of what happens if you pipe into the Python interpreter from another program as an example as in: cat file | python ... echo "Some text" | python ... or if you pipe the output elsewhere to a file or another program. It is done invisibly to Python. A HERE document is just a gimmick similar to the echo statement above so something like: program args < wrote: > David, > > I would have suggested that bashing was not appreciated on this forum but then realized the moderator would correct us by saying that of course it sometimes was and would not see it as humor. > > So, I did not say that! > > Back to being serious, the program you call bash is one of name "shell" programs with names like sh or ksh and quite a few others. The name bash is a it of a pun on the original creator of the UNIX shell program and is supposedly he Bourne Again SHell. > > Your question is not even slightly about Python because the python interpreter has NO IDEA it was called this way. It was one of may UNIX shell features that have migrated to many other operating systems. Any program you call on the command line has a standard input and out and error that can be redirected in many ways. Think of what happens if you pipe into the Python interpreter from another program as an example as in: > > cat file | python ... > echo "Some text" | python ... > > or pipe the output elsewhere. > > A HERE document is just a gimmick similar to the echo above so something like: > > program args < stuff > more stuff > ! > > Is used by the shell as the standard input till it sees the identifier (I used just an ! ) and then passes on everything before the identifier. > > Inside your python program if you try to evaluate your command line arguments, you will never see the above so placing a dash like you asked will likely result in an error. There are ways using a command-line argument to place a short (typically one-liner) set of python commands the way you expect. Here is a silly example: > > python -c "print(5+5)" > > Which prints 10 > > And another which shows all command line arguments: > > python -c "from sys import argv; print(argv)" non sense > ['-c', 'non', 'sense'] > > Q > > > > > Sent with Proton Mail secure email. > > > ------- Original Message ------- > On Thursday, April 27th, 2023 at 4:14 PM, David Lowry-Duda david at lowryduda.com wrote: > > > > > I like to use python as a simple commandline calculator. I only just > > learned that it's possible to do something like the following in bash > > > > `$ python < > > > and python will happily run this. I had thought this wouldn't work, and > > that python would instead complain that there was no file with some > > amalgamated name. > > > > I discovered this by an accident, but googling shows of course that this > > isn't new or anything. I would have expected this to run with "python - > > < > stdin. > > > > So I opened up the python manpage to see about this, and saw nothing > > there (not even about what `-` is supposed to mean!). Then I went to > > > > https://docs.python.org/3/using/cmdline.html#command-line > > > > to see if I could learn more, and I don't see much there either. There > > is a somewhat cryptic remark: "In non-interactive mode, the entire input > > is parsed before it is executed." > > > > I guess python does something like: check to see if args were given, if > > not then check for standard input and then run it noninteractively? Do > > you think this is an intended behavior, or is this merely an > > undocumented implementation detail? > > > > - DLD > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at yahoo.co.uk Thu Apr 27 19:25:33 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 28 Apr 2023 00:25:33 +0100 Subject: [Tutor] bash heredoc and python In-Reply-To: References: Message-ID: On 27/04/2023 22:45, ThreeBlindQuarks via Tutor wrote: > ...the moderator would correct us by saying that > of course it sometimes was and would not see it as humor. Ouch! But I suppose I deserve it after my premature rant last week! :-) -- 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 PythonList at DancesWithMice.info Thu Apr 27 19:46:49 2023 From: PythonList at DancesWithMice.info (dn) Date: Fri, 28 Apr 2023 11:46:49 +1200 Subject: [Tutor] bash heredoc and python In-Reply-To: References: Message-ID: <7f74f9d6-7a96-841f-b23b-e43908cf14a0@DancesWithMice.info> On 28/04/2023 11.25, Alan Gauld via Tutor wrote: > On 27/04/2023 22:45, ThreeBlindQuarks via Tutor wrote: >> ...the moderator would correct us by saying that >> of course it sometimes was and would not see it as humor. > > Ouch! > But I suppose I deserve it after my premature rant last week! :-) We don't often express appreciation for the efforts you exert on our behalf, @Alan. Thanks! -- Regards, =dn From sun.exp14 at gmail.com Fri Apr 28 07:10:55 2023 From: sun.exp14 at gmail.com (sam muhammed) Date: Fri, 28 Apr 2023 16:10:55 +0500 Subject: [Tutor] Handle and display results Message-ID: Dears, Good day! I am a beginner in Python programming and the field of classification images using CNN I try to study the publicly available code in Google Collab or Kaggle to reuse it. I have a problem with how to display the resulting images after training the model (as one image with its label at a time) beginning from the first image until the last one in the dataset. So that in the end, I get all the images that have been trained in the model, not just one image or 9 images as in code). I would like your help correcting the code in order to get all the results of the predictions images. I will attach the program code for you to fix it. All the best, SAM. From mats at wichmann.us Fri Apr 28 12:20:26 2023 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 28 Apr 2023 10:20:26 -0600 Subject: [Tutor] Handle and display results In-Reply-To: References: Message-ID: On 4/28/23 05:10, sam muhammed wrote: > Dears, > > Good day! > > > > I am a beginner in Python programming and the field of > classification images using CNN > > I try to study the publicly available code in Google Collab or Kaggle to > reuse it. > > > > I have a problem with how to display the resulting images after training > the model (as one image with its label at a time) beginning from the first > image until the last one in the dataset. So that in the end, I get all the > images that have been trained in the model, not just one image or 9 images > as in code). > > I would like your help correcting the code in order to get all the > results of the predictions images. > > > > I will attach the program code for you to fix it. To be honest, this is the kind of question that isn't going generate much if any help. You've essentially asked "I tried to use a complex piece of software and didn't get the results I wanted. Fix my code". The vast majority of us will not know what CNN is, other than that we'll think of the television news network. You haven't asked anything about Python. We're really happy to explain Python concepts, comment on code snippets, etc. Specialized software packages are an entirely different issue, questions about such are best asked in forums dedicated to the package/project. The mailing list doesn't forward attachments for security reasons. We don't "do your work" (e.g. fix your code, do your homework, etc.) If you can find a way to ask a question we CAN help with, we're normally happy to do so. From threesomequarks at proton.me Fri Apr 28 13:58:34 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Fri, 28 Apr 2023 17:58:34 +0000 Subject: [Tutor] Handle and display results In-Reply-To: References: Message-ID: Sam, I read all the attachments left after they were all stripped away and that is a polite way of telling you that this mailing list does not accept attachments. Sending in-line properly-formatted code works but please do not send thousands of lines and just focus in on what you specifically need. If I read you correctly, many of the details are not important or relevant. I think you are stuck at a particular point albeit having cobbled lots of different things together, it may well be that things are broken way earlier. You say you trained a convolutional neural network on some images. I am not clear on what follows, but the goal usually is to withhold some (random) images from the training and then use the prediction methods to analyze these additional images for whatever purpose you intended, such as recognizing if the image is of a dog or a cat or whatever. So what exactly are you trying to do that fails and how does it fail? Note that training a model does not normally alter any of the images fed into creating the network. I am not clear on what you want. Maybe others here can read between your lines but it may be best if you pause and explain carefully and clearly. If you supply a list of new images to try and get back a list of results, typically the result is not an image but an ?answer? or ?selection? of sorts, you could show the code you have that tries to do just that last part, such as taking an item at a time from the list and displaying or printing it perhaps as a combination of the original image alongside the resulting classification. Or are you asking a different question having nothing to do with the training such as how to see the pictures you were training on? Do note few people here are unlikely to want to actually run your code and fix it. My personal goal is to be helpful in getting people to help themselves and that begins with them properly explaining what they want to do and show the small amount of code that tries to do it and also shows what is expected versus what they see. Often just doing that lets them solve a problem. So before asking for more help, look at the variables or data structures where you expect your result to be and see if they look right. Trying to display an image if the variable is null or of the wrong type does not work, nor does using the wrong function. Generally, you cannot type ?print(image)? but may have more luck using whatever graphics library normally displays an image of that type if also given enough info such as how many pixels it contains in each direction and other such info. Best of luck, Kyu Sent with Proton Mail secure email. ------- Original Message ------- On Friday, April 28th, 2023 at 7:10 AM, sam muhammed wrote: > Dears, > > Good day! > > > > I am a beginner in Python programming and the field of > classification images using CNN > > I try to study the publicly available code in Google Collab or Kaggle to > reuse it. > > > > I have a problem with how to display the resulting images after training > the model (as one image with its label at a time) beginning from the first > image until the last one in the dataset. So that in the end, I get all the > images that have been trained in the model, not just one image or 9 images > as in code). > > I would like your help correcting the code in order to get all the > results of the predictions images. > > > > I will attach the program code for you to fix it. > > > > All the best, > > SAM. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From edwinconnell at gmail.com Sun Apr 30 17:31:39 2023 From: edwinconnell at gmail.com (Ed Connell) Date: Sun, 30 Apr 2023 16:31:39 -0500 Subject: [Tutor] What's going on? Message-ID: Greetings, I got interested in one of your earlier problems, but THAT PROBLEM is not what I am asking about. It was to generate a random sequence, each taken from a predefined pool. However, nothing is to be used more than four times. Moderately interesting. What I am asking about is this. The first time it runs perfectly. However subsequent runs, sooner or later, foul up. ############################### import random import time for run in range(10): #usually 1 but trying multiple runs through in one trip. # build result, number choices, and choice count lists res = [] nums = [] ct = [] for i in range(10): ct.append(0) nums.append(i) print('\n\n', run, ' start\n') #time.sleep(0.016) # seems to work for 0.016 or more uncommented for _ in range( 30 ): # tried 10 - 40 random.shuffle(nums) res.append(nums[0]) print(res) ct[nums[0]] += 1 if ct[nums[0]] == 4: print( 'Removing', nums[0],nums ) nums = nums[1:] print('leaving', nums ) print() print('numbers left',sorted(nums)) print('result',res) print('number used of each',ct) #################################### The problem seems to be a difference between printing and calculation speed but maybe not. I tried mostly using Geany, but also just ran the .py file. The bad output has incomplete lines as well as missing sections. I will appreciate your ideas. Oh, I am running on Windows 11, an hp with AMD 7. Ed Connll -- I have a right and a left brain, but there is nothing right in the left one and there is nothing left in the right one! From alan.gauld at yahoo.co.uk Sun Apr 30 19:37:58 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 1 May 2023 00:37:58 +0100 Subject: [Tutor] What's going on? In-Reply-To: References: Message-ID: On 30/04/2023 22:31, Ed Connell wrote: > ############################### > import random > import time > > # build result, number choices, and choice count lists > res = [] > nums = [] > ct = [] > > for i in range(10): > ct.append(0) > nums.append(i) I'd probably write that as ct = [0] * 10 nums = list(range(10)) But your way works too... > > print('\n\n', run, ' start\n') > > #time.sleep(0.016) # seems to work for 0.016 or more uncommented > > for _ in range( 30 ): # tried 10 - 40 > random.shuffle(nums) > res.append(nums[0]) > print(res) > ct[nums[0]] += 1 > if ct[nums[0]] == 4: > print( 'Removing', nums[0],nums ) > nums = nums[1:] > print('leaving', nums ) > > print() > print('numbers left',sorted(nums)) > print('result',res) > print('number used of each',ct) > #################################### > The problem seems to be a difference between printing and calculation speed > but maybe not. I don't think so, you don't have any parallel operations going on so it just waits for each print or calculation to happen before moving on. > The bad output has incomplete lines as well as missing sections. It would help if you actually showed us some bad output. Your description is a little vague! -- 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 threesomequarks at proton.me Sun Apr 30 22:32:46 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Mon, 01 May 2023 02:32:46 +0000 Subject: [Tutor] What's going on? In-Reply-To: References: Message-ID: Ed, Thank you for supplying code that works and is brief enough to try. My only glitch was one of your comments lines that became two lines which resulted in an error easy to fix so it did not try to "trip". I got lots of output but as I understand it, you simply wanted to do something N==10 times. You could have encapsulated all the calculations in a function which would cleanly have avoided some issues of your reusing variables. So you initialize these each time: res = [] nums = [] ct = [] Your next code segment seems to re-populate some of these variables I get this when I examine variables at the end: ct: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] nums: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] which makes me wonder if this method is one that could be done differently in perhaps a more Pythonic way. You do this: for i in range(10): ct.append(0) nums.append(i) No error here but consider you are asking for a group of N zeros in a row for the first and a sequence from 0 to N-1 for the second. I personally might have combined all the beginning code into these three lines: N = 10 res = [] nums = list(range(N)) ct = [0] * N Again, nothing wrong with your code so far. Just an alternate viewpoint and note I set a parameter called N to make the code flexible if changed at a single point. This removes an explicit loop and replaces it with two hidden implicit loops, albeit perhaps implemented faster internally. I am not clear on why you have commented out code about sleeping. It is hinting at something. Is there some concern you did not share? I am not aware any pause is needed unless you want results not to flow off the screen. Again, just to show an alternative perspective, you can insert a line of code like this: _ = input("Press RETURN to see next results:") This stops processing after displaying a prompt and waits for the user to hit any keys and a return (and effectively ignores that) before continuing. Again, not really needed as you can often just scroll up in the output and see quite a bit. Now I recall the earlier request was to pick random numbers and never use any one more than four times. I am not sure if your code plans on anything like variations of that. Your next section hard-codes in precisely thirty times in a loop that you shuffle the numbers (initially from 0 to 9) in place and then you pick just the first and append that to res for an eventual result. random.shuffle(nums) res.append(nums[0]) print(res) That seems like a bit of extra work to shuffle the whole thing over and over just to get one at random. What is the advantage over just picking a random number from 0 to 9 each time rather than picking lots of them to re-arrange the deck chairs on the Titanic? But, FWIW, it does get you a random number to add to the growing collection. The next section explains this odd choice as the list to choose from changes dynamically: if ct[nums[0]] == 4: print( 'Removing', nums[0],nums ) nums = nums[1:] print('leaving', nums ) This may have been your problem so I checked. The logic is that once you have used a number four times, remove it and shrink the pool of available to choose from to 9 then later 8 and so on. Is that carried out carefully? You are removing the zeroth item by making a copy of the rest of the list. I would consider an alternate of: nums.pop(0) Which throws away the first and changes the list in place. Note it can also be used to just remove the nth. So if you just picked a random number from zero to the current length of the list, I am guessing it might be easier to just remove any that reached 4 and never scramble an entire list. The rest of the loop is just print statements. So logically, what should happen in the inner loop? Thirty numbers should be chosen first from 10 possibilities so res should keep growing and stop at 30 entries. The ct variable always remains at length 10 with entries rising from 0 towards 4 and never exceeding it. The nums list should shrink and above 40 should disappear and perhaps cause problems beyond that as there is nothing to scramble and use. At 30, it should be safe. But ideally, your algorithm should break out of a loop if everything has hit 4, or alternately if the number of items to choose from reaches zero. So I ran the code and I am embarrassed to say I did not see anything wrong. It seems to do exactly what it is designed to do. My guess is you are using something that cannot keep up with the I/O and produces glitches on your screen. The fact that it happens after the first run may be a clue that some buffer is being over-run or something. So, yes, your sleep attempts make some sense but you may also consider redirecting the output to a file in one of many ways and then viewing the file with something like a text editor and seeing if that looks like you expect. If so, there is nothing wrong with your program but something not quite great about some aspect of your environment. Anyone else try to run this and get an odd output? Q Sent with Proton Mail secure email. ------- Original Message ------- On Sunday, April 30th, 2023 at 5:31 PM, Ed Connell wrote: > Greetings, > > I got interested in one of your earlier problems, but THAT PROBLEM is not > what I am asking about. It was to generate a random sequence, each taken > from a predefined pool. However, nothing is to be used more than four > times. Moderately interesting. > > What I am asking about is this. The first time it runs perfectly. However > subsequent runs, sooner or later, foul up. > ############################### > import random > import time > > for run in range(10): #usually 1 but trying multiple runs through in one > trip. > > # build result, number choices, and choice count lists > res = [] > nums = [] > ct = [] > > for i in range(10): > ct.append(0) > nums.append(i) > > print('\n\n', run, ' start\n') > > #time.sleep(0.016) # seems to work for 0.016 or more uncommented > > for _ in range( 30 ): # tried 10 - 40 > random.shuffle(nums) > res.append(nums[0]) > print(res) > ct[nums[0]] += 1 > if ct[nums[0]] == 4: > print( 'Removing', nums[0],nums ) > nums = nums[1:] > print('leaving', nums ) > > print() > print('numbers left',sorted(nums)) > print('result',res) > print('number used of each',ct) > #################################### > The problem seems to be a difference between printing and calculation speed > but maybe not. > > I tried mostly using Geany, but also just ran the .py file. > > The bad output has incomplete lines as well as missing sections. > > I will appreciate your ideas. > > Oh, I am running on Windows 11, an hp with AMD 7. > > Ed Connll > -- > I have a right and a left brain, but there is nothing right in the left one > and there is nothing left in the right one! > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From threesomequarks at proton.me Sun Apr 30 22:44:13 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Mon, 01 May 2023 02:44:13 +0000 Subject: [Tutor] What's going on? In-Reply-To: References: Message-ID: I looked at your message again Ed and I see you ran the program several ways including just running the .py file on windows. So my suggestion is to use whatever command line program you have, including those that let you redirect output to a file like the bash we bashed a few days ago. I tested the default shell on Windows of CMD like so: C:\Users\xyz>echo "hi" "hi" C:\Users\xyz>echo "hi" >temp.txt C:\Users\xyz>more temp.txt "hi" So it allows redirection and if you run python as in: python file >temp.txt Or something similar, and view it with a pager like I did that shows only a screen at a time, or you can use a text editor. Ideally, all the output will get captured as file I/O may not be as delicate as whatever comes to your screen. I have never had such a problem when I run python with output in RSTUDIO, idle, Jupyter Notebook and so on. If that works, great. And, of course, with a bit of work, you can change the internals of your code to slow down the output, redirect file descriptors for stdout, or just have it pause and ask what to do next. Your program seems to work and is logically sound. Sent with Proton Mail secure email. ------- Original Message ------- On Sunday, April 30th, 2023 at 10:32 PM, ThreeBlindQuarks wrote: > Ed, > > Thank you for supplying code that works and is brief enough to try. > > My only glitch was one of your comments lines that became two lines which resulted in an error easy to fix so it did not try to "trip". > > I got lots of output but as I understand it, you simply wanted to do something N==10 times. You could have encapsulated all the calculations in a function which would cleanly have avoided some issues of your reusing variables. > > So you initialize these each time: > > res = [] > nums = [] > ct = [] > > Your next code segment seems to re-populate some of these variables > > > I get this when I examine variables at the end: > > ct: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] > nums: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > which makes me wonder if this method is one that could be done differently in perhaps a more Pythonic way. You do this: > > for i in range(10): > ct.append(0) > nums.append(i) > > No error here but consider you are asking for a group of N zeros in a row for the first and a sequence from 0 to N-1 for the second. > > I personally might have combined all the beginning code into these three lines: > > N = 10 > res = [] > nums = list(range(N)) > ct = [0] * N > > Again, nothing wrong with your code so far. Just an alternate viewpoint and note I set a parameter called N to make the code flexible if changed at a single point. > > This removes an explicit loop and replaces it with two hidden implicit loops, albeit perhaps implemented faster internally. > > I am not clear on why you have commented out code about sleeping. It is hinting at something. Is there some concern you did not share? I am not aware any pause is needed unless you want results not to flow off the screen. > > Again, just to show an alternative perspective, you can insert a line of code like this: > > _ = input("Press RETURN to see next results:") > > This stops processing after displaying a prompt and waits for the user to hit any keys and a return (and effectively ignores that) before continuing. Again, not really needed as you can often just scroll up in the output and see quite a bit. > > Now I recall the earlier request was to pick random numbers and never use any one more than four times. I am not sure if your code plans on anything like variations of that. Your next section hard-codes in precisely thirty times in a loop that you shuffle the numbers (initially from 0 to 9) in place and then you pick just the first and append that to res for an eventual result. > > random.shuffle(nums) > res.append(nums[0]) > print(res) > > That seems like a bit of extra work to shuffle the whole thing over and over just to get one at random. What is the advantage over just picking a random number from 0 to 9 each time rather than picking lots of them to re-arrange the deck chairs on the Titanic? But, FWIW, it does get you a random number to add to the growing collection. > > The next section explains this odd choice as the list to choose from changes dynamically: > > if ct[nums[0]] == 4: > print( 'Removing', nums[0],nums ) > nums = nums[1:] > print('leaving', nums ) > > This may have been your problem so I checked. The logic is that once you have used a number four times, remove it and shrink the pool of available to choose from to 9 then later 8 and so on. Is that carried out carefully? You are removing the zeroth item by making a copy of the rest of the list. I would consider an alternate of: > > nums.pop(0) > > Which throws away the first and changes the list in place. Note it can also be used to just remove the nth. So if you just picked a random number from zero to the current length of the list, I am guessing it might be easier to just remove any that reached 4 and never scramble an entire list. > > The rest of the loop is just print statements. > > So logically, what should happen in the inner loop? Thirty numbers should be chosen first from 10 possibilities so res should keep growing and stop at 30 entries. The ct variable always remains at length 10 with entries rising from 0 towards 4 and never exceeding it. The nums list should shrink and above 40 should disappear and perhaps cause problems beyond that as there is nothing to scramble and use. At 30, it should be safe. But ideally, your algorithm should break out of a loop if everything has hit 4, or alternately if the number of items to choose from reaches zero. > > So I ran the code and I am embarrassed to say I did not see anything wrong. It seems to do exactly what it is designed to do. My guess is you are using something that cannot keep up with the I/O and produces glitches on your screen. The fact that it happens after the first run may be a clue that some buffer is being over-run or something. > > So, yes, your sleep attempts make some sense but you may also consider redirecting the output to a file in one of many ways and then viewing the file with something like a text editor and seeing if that looks like you expect. > > If so, there is nothing wrong with your program but something not quite great about some aspect of your environment. > > Anyone else try to run this and get an odd output? > > Q > > > > > > > Sent with Proton Mail secure email. > > > ------- Original Message ------- > On Sunday, April 30th, 2023 at 5:31 PM, Ed Connell edwinconnell at gmail.com wrote: > > > > > Greetings, > > > > I got interested in one of your earlier problems, but THAT PROBLEM is not > > what I am asking about. It was to generate a random sequence, each taken > > from a predefined pool. However, nothing is to be used more than four > > times. Moderately interesting. > > > > What I am asking about is this. The first time it runs perfectly. However > > subsequent runs, sooner or later, foul up. > > ############################### > > import random > > import time > > > > for run in range(10): #usually 1 but trying multiple runs through in one > > trip. > > > > # build result, number choices, and choice count lists > > res = [] > > nums = [] > > ct = [] > > > > for i in range(10): > > ct.append(0) > > nums.append(i) > > > > print('\n\n', run, ' start\n') > > > > #time.sleep(0.016) # seems to work for 0.016 or more uncommented > > > > for _ in range( 30 ): # tried 10 - 40 > > random.shuffle(nums) > > res.append(nums[0]) > > print(res) > > ct[nums[0]] += 1 > > if ct[nums[0]] == 4: > > print( 'Removing', nums[0],nums ) > > nums = nums[1:] > > print('leaving', nums ) > > > > print() > > print('numbers left',sorted(nums)) > > print('result',res) > > print('number used of each',ct) > > #################################### > > The problem seems to be a difference between printing and calculation speed > > but maybe not. > > > > I tried mostly using Geany, but also just ran the .py file. > > > > The bad output has incomplete lines as well as missing sections. > > > > I will appreciate your ideas. > > > > Oh, I am running on Windows 11, an hp with AMD 7. > > > > Ed Connll > > -- > > I have a right and a left brain, but there is nothing right in the left one > > and there is nothing left in the right one! > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor