From jon_davies17 at hotmail.co.uk Mon Mar 2 12:51:23 2020 From: jon_davies17 at hotmail.co.uk (Jon Davies) Date: Mon, 2 Mar 2020 17:51:23 +0000 Subject: [Tutor] Pay-at-Pump Use Case - Tkinter GUI In-Reply-To: References: , , Message-ID: Hi Alan, I've been having a look into internationalization / i18n , and trying to have a play to get a simple example working, however I admit I am struggling. My basic test file (translation.py) is stored in a folder Translation, with the structure as follows: ./Translation /translation.py /translation.pot /locales /de /LC_MESSAGES /translation.mo /translation.po Within 'translation.py' is the following: import gettext de = gettext.translation('translation', localedir='locales', languages=['de']) de.install() _ = de.gettext #_ = gettext.text locale_path = 'locales' def print_some_strings(): print(_('Hello world!')) print(_('This is hopefully going to translate!')) print(_('Hooray!')) if __name__ == '__main__': print_some_strings() However, when I try to run it I get the following error: Traceback (most recent call last): File "C:/Users/Jon_D/__/__/__/__/__/Translation/translation.py", line 3, in de = gettext.translation('translation', localedir='locales', languages=['de']) File "C:\Users\Jon_D\AppData\Local\Programs\Python\Python38\lib\gettext.py", line 588, in translation raise FileNotFoundError(ENOENT, FileNotFoundError: [Errno 2] No translation file found for domain: 'translation' I'm confused as I'm pretty certain I've laid everything out correctly. If I can't get a simple example working god knows how I'll apply this in my app! Thanks, Jon ________________________________ From: Jon Davies Sent: 24 February 2020 11:05 To: Alan Gauld ; tutor at python.org Subject: Re: [Tutor] Pay-at-Pump Use Case - Tkinter GUI Thank you Alan much appreciated. I?ll have a dog and a play, will let you know how I get on! Kind regards, Jon Get Outlook for iOS ________________________________ From: Tutor on behalf of Alan Gauld via Tutor Sent: Sunday, February 23, 2020 6:55:08 PM To: tutor at python.org Subject: Re: [Tutor] Pay-at-Pump Use Case - Tkinter GUI On 23/02/2020 18:52, Alan Gauld via Tutor wrote: > There is a well understood solution for this that is used > in real world programs regardless of language ...regardless of programming language... is what I meant! -- 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 Mon Mar 2 14:26:33 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 2 Mar 2020 19:26:33 +0000 Subject: [Tutor] Pay-at-Pump Use Case - Tkinter GUI In-Reply-To: References: Message-ID: On 02/03/2020 17:51, Jon Davies wrote: > Hi Alan, > > I've been having a look into internationalization / i18n , and trying to have a play to get a simple example working, however I admit I am struggling. > > > My basic test file (translation.py) is stored in a folder Translation, with the structure as follows: > > ./Translation > /translation.py,translation.pot /locales/de/LC_MESSAGES/translation.mo,translation.po > > Within 'translation.py' is the following: > > import gettext > > de = gettext.translation('translation', localedir='locales', languages=['de']) > de.install() I normally use a slightly different preamble: ################# import gettext filename = "locales/de/LC_MESSAGES/translation.mo" trans = gettext.GNUTranslateions(open(filename, 'rb') # NB. binary! trans.install() ################## Actually I'd use a different setup for the files but I'm guessing you are following a tutorial somewhere? This creates the GNUTranslations object directly using the translation file object as an argument. > def print_some_strings(): > print(_('Hello world!')) > print(_('This is hopefully going to translate!')) > print(_('Hooray!')) > > if __name__ == '__main__': > print_some_strings() > I'm confused as I'm pretty certain I've laid everything out correctly. > If I can't get a simple example working god knows how I'll apply this in my app! Offline I'll send you the full text from this section of my book. It contains the full code and translation file content plus step by step instructions. See if it helps. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From torbjorn.svensson.diaz at gmail.com Tue Mar 3 11:10:28 2020 From: torbjorn.svensson.diaz at gmail.com (=?UTF-8?Q?Torbj=c3=b6rn_Svensson_Diaz?=) Date: Tue, 3 Mar 2020 17:10:28 +0100 Subject: [Tutor] Partly Off Topic - Email clients for email discussion lists Message-ID: <66b7cb19-5725-e6c6-bab3-11d56ed42f0e@gmail.com> Dear Tutors, What are the best email clients for email discussion lists? Best regards, Torbj?rn Svensson Diaz From mats at wichmann.us Tue Mar 3 11:58:01 2020 From: mats at wichmann.us (Mats Wichmann) Date: Tue, 3 Mar 2020 09:58:01 -0700 Subject: [Tutor] Partly Off Topic - Email clients for email discussion lists In-Reply-To: <66b7cb19-5725-e6c6-bab3-11d56ed42f0e@gmail.com> References: <66b7cb19-5725-e6c6-bab3-11d56ed42f0e@gmail.com> Message-ID: On 3/3/20 9:10 AM, Torbj?rn Svensson Diaz wrote: > Dear Tutors, > > What are the best email clients for email discussion lists? The best? Not sure. Bad, usually: Outlook and Gmail. Both have, umm, "interesting" ideas about topic threading and about applying "styled" (bastardized-html) formatting to message bodies, the former is trouble for any mailing list if you want topics nicely threaded, and the latter a problem for this list which depend on plain text and in particular Python code where consistent indentation is part of the language syntax. It's an uphill battle when those two together make up a vast amount of the current email world.... From alan.gauld at yahoo.co.uk Tue Mar 3 13:47:44 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 3 Mar 2020 18:47:44 +0000 Subject: [Tutor] Partly Off Topic - Email clients for email discussion lists In-Reply-To: <66b7cb19-5725-e6c6-bab3-11d56ed42f0e@gmail.com> References: <66b7cb19-5725-e6c6-bab3-11d56ed42f0e@gmail.com> Message-ID: On 03/03/2020 16:10, Torbj?rn Svensson Diaz wrote: > What are the best email clients for email discussion lists? Defining "best" to mean suitable for a power-user, then the usual response would be mutt. It is a command-line tool but extremely powerful for filtering and doing mas operations. If your email load is measured in the hundreds (or even thousands) per day its a great option. Not pretty or easy to use but very powerful. If you are talking GUIs then that's a different discussion. My favourite is Thunderbird (and on Windows 95 it was Pegasus, but I don't even know if it is still supported!) When I was working I used to process 2-300 emails a day using Outlook but Outlook isn't really an email client; its more a group-ware messaging/collaboration client and, in particular, it doesn't play well with standards-based discussion groups. As for Web based tools, I have no idea. They all seem fairly standard to me (except gmail which is just bizarre!) and I'd never try to manage high volumes via a web app anyway!" But you may have a different concept of "best"... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From cs at cskk.id.au Tue Mar 3 15:39:40 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Wed, 4 Mar 2020 07:39:40 +1100 Subject: [Tutor] Partly Off Topic - Email clients for email discussion lists In-Reply-To: References: Message-ID: <20200303203940.GA62098@cskk.homeip.net> On 03Mar2020 18:47, Alan Gauld wrote: >On 03/03/2020 16:10, Torbj?rn Svensson Diaz wrote: >> What are the best email clients for email discussion lists? > >Defining "best" to mean suitable for a power-user, then the usual >response would be mutt. I also use mutt. Note that any email reader works better if you have some kind of filtering so that mailing lists go to their own folder (or similar lists to a folder - I put most python lists in a single "python" folder). That way your "main" inbox can be the more important and ad hoc stuff - personal, work, etc, and you can have some other folders for lists which can be high volume. Some mail readers include filtering, often poor. Mutt is different - it mostly expects you to filter with another programme; you just read and send email with mutt. For example I collect my email with getmail and filter it using mailfiler. That said, mutt has great in-folder filtering - you can search flexibly, or "limit" the view of the messages to those match some criteria. And it threads well. Cheers, Cameron Simpson From ddavis at ddavis.io Tue Mar 3 15:08:18 2020 From: ddavis at ddavis.io (Doug Davis) Date: Tue, 03 Mar 2020 15:08:18 -0500 Subject: [Tutor] Partly Off Topic - Email clients for email discussion lists In-Reply-To: <66b7cb19-5725-e6c6-bab3-11d56ed42f0e@gmail.com> (=?utf-8?Q?=22Torbj=C3=B6rn?= Svensson Diaz"'s message of "Tue, 3 Mar 2020 17:10:28 +0100") References: <66b7cb19-5725-e6c6-bab3-11d56ed42f0e@gmail.com> Message-ID: Torbj?rn Svensson Diaz writes: > Dear Tutors, > > What are the best email clients for email discussion lists? Another option which dons a poweruser label: a newsreader like Gnus [1] in Emacs. It's a great way to consume many mailing lists (including this one) from Gmane [2] via NNTP. It can also handle other protocols (like IMAP, for example). [1] https://en.wikipedia.org/wiki/Gnus [2] https://en.wikipedia.org/wiki/Gmane From alan.gauld at yahoo.co.uk Wed Mar 4 07:04:48 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 4 Mar 2020 12:04:48 +0000 Subject: [Tutor] Moderated amusement References: <5bc37c24-e249-a94c-fbf7-c2651ad9ae22.ref@yahoo.co.uk> Message-ID: <5bc37c24-e249-a94c-fbf7-c2651ad9ae22@yahoo.co.uk> Being list moderator involves a lot of time rejecting spam that finds its way to the list. Occasionally one of these raises a smile. For example, I just received one from a company that specialising in creating web sites for pets(really!). They wanted to know if we would like assistance in creating a site that would really demonstrate our love and devotion for our python... :-) Made me smile. But at least it was somewhat targeted, most is just random nonsense. -- 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 dkwolfe at gmail.com Wed Mar 4 08:49:22 2020 From: dkwolfe at gmail.com (David Wolfe) Date: Wed, 4 Mar 2020 08:49:22 -0500 Subject: [Tutor] clipping 2 arrays that are in a single cell in a dataframe Message-ID: So I have the following code and output Input: x = dq.iloc[0,1] print(x) Output: (array([ 2.22103139e-16, 3.90537106e-16, 5.69543182e-16, ..., -2.35780223e-08, -2.26280054e-08, -2.13661206e-08]), array([ 7.68783923e-17, 1.43759013e-16, 2.15375256e-16, ..., -1.06071943e-08, -1.02689930e-08, -9.77763418e-09])) As you can see, the contents of this particular cell are 2 arrays. The problem is that there is a lot of junk data in this data. The array is actually X and Y coordinates, but none of them should be below or less than 1. When I had just 1 array per cell, I used the following to limit the array to just what I needed: x_above_one_hundred = np.where(x>10Output:0) xx = np.clip(x[x_above_one_hundred],125,300) Now, I just need something to do the same thing when I have 2 arrays in a dataframe cell. Thanks, David From s.molnar at sbcglobal.net Wed Mar 4 09:00:37 2020 From: s.molnar at sbcglobal.net (Stephen P. Molnar) Date: Wed, 4 Mar 2020 09:00:37 -0500 Subject: [Tutor] Moderated amusement In-Reply-To: <5bc37c24-e249-a94c-fbf7-c2651ad9ae22@yahoo.co.uk> References: <5bc37c24-e249-a94c-fbf7-c2651ad9ae22.ref@yahoo.co.uk> <5bc37c24-e249-a94c-fbf7-c2651ad9ae22@yahoo.co.uk> Message-ID: <5E5FB485.7070607@sbcglobal.net> Marketing Morons strike again! On 03/04/2020 07:04 AM, Alan Gauld via Tutor wrote: > Being list moderator involves a lot of time rejecting spam that > finds its way to the list. Occasionally one of these raises a smile. > > For example, I just received one from a company that specialising > in creating web sites for pets(really!). They wanted to know if we > would like assistance in creating a site that would really > demonstrate our love and devotion for our python... :-) > > Made me smile. But at least it was somewhat targeted, > most is just random nonsense. > -- Stephen P. Molnar, Ph.D. www.molecular-modeling.net 614.312.7528 (c) Skype: smolnar1 From akleider at sonic.net Wed Mar 4 22:33:02 2020 From: akleider at sonic.net (Alex Kleider) Date: Wed, 04 Mar 2020 19:33:02 -0800 Subject: [Tutor] Partly Off Topic - Email clients for email discussion lists In-Reply-To: <66b7cb19-5725-e6c6-bab3-11d56ed42f0e@gmail.com> References: <66b7cb19-5725-e6c6-bab3-11d56ed42f0e@gmail.com> Message-ID: On 2020-03-03 08:10, Torbj?rn Svensson Diaz wrote: > Dear Tutors, > > What are the best email clients for email discussion lists? > My internet provider gives me 'squirrel mail' as an option and it seems to work well enough. There are times I have to use gmail. It's horrid! No experience with MicroSoft's alternative. From oscar.j.benjamin at gmail.com Thu Mar 5 05:16:25 2020 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 5 Mar 2020 10:16:25 +0000 Subject: [Tutor] Partly Off Topic - Email clients for email discussion lists In-Reply-To: References: <66b7cb19-5725-e6c6-bab3-11d56ed42f0e@gmail.com> Message-ID: On Thu, 5 Mar 2020 at 03:46, Alex Kleider wrote: > > On 2020-03-03 08:10, Torbj?rn Svensson Diaz wrote: > > Dear Tutors, > > > > What are the best email clients for email discussion lists? > > > > My internet provider gives me 'squirrel mail' as an option and it seems > to work well enough. > There are times I have to use gmail. It's horrid! I don't know what people here have got against gmail. I'm using it here and it works fine! I have previously used mutt and it works well for some things and less well for others. It's great for reading an old-school text mailing list like this where you don't need to worry about images, html, attachments etc. However in many other cases where you have to receive arbitrary emails from anyone it fails. It's also not something that you would want to use on your phone, is a pain to configure, is built primarily around the idea of local rather than cloud storage and so on. Tips if you are going to use gmail for an email list like this: 1) Don't sign up to receive digest emails: set up a filter so the mailing list skips the inbox instead. 2) Enable the keyboard shortcuts: the most important ones are j and k which navigate up and down between threads marking them as read. 3) When replying by email you can use Ctrl-A or Cmd-A to expand the quoted parts that are otherwise hidden by the little dots. 4) You can configure gmail to reply in plain-text mode: click the three dots at lower-right when replying. I get plain text by default. The advantage of using gmail is that I can read the threads on my phone or on any computer without any configuration needed. The read/unread status of threads is stored at google's end so I can see where I was whichever device I use. The advantages of mutt over gmail are that mutt gives a better view of the tree structure of a thread and is always monospace which is good for code (there are browser extensions that make gmail use monospace). I notice now that some Python-related mailing lists seem to be migrating over to discourse instead of mailman which changes the situation somewhat. With discourse you can explicitly format code with backticks in the github/stackoverflow style. This means that code displays as monospace in the html version of the message that you will be able to see in gmail but presumably not in mutt. The discourse style list means that you probably want to reply via the web rather than email and that if you are browsing by email you probably want a html-enabled email client. -- Oscar From agbehi_ogiri at yahoo.com Thu Mar 5 15:51:37 2020 From: agbehi_ogiri at yahoo.com (Ogiri) Date: Thu, 5 Mar 2020 20:51:37 +0000 (UTC) Subject: [Tutor] Python Training: Intermediate to Advanced References: <1049410185.5136554.1583441497100.ref@mail.yahoo.com> Message-ID: <1049410185.5136554.1583441497100@mail.yahoo.com> Hello,I am interested in Python training and in need of a trainer.Kindly assist. Regards,Raphael. From torbjorn.svensson.diaz at gmail.com Thu Mar 5 15:10:30 2020 From: torbjorn.svensson.diaz at gmail.com (=?UTF-8?Q?Torbj=c3=b6rn_Svensson_Diaz?=) Date: Thu, 5 Mar 2020 21:10:30 +0100 Subject: [Tutor] Partly Off Topic - Email clients for email discussion lists In-Reply-To: References: <66b7cb19-5725-e6c6-bab3-11d56ed42f0e@gmail.com> Message-ID: <00cc3821-7fe6-09a2-27a9-519ea20adf0e@gmail.com> On 2020-03-03 19:47, Alan Gauld via Tutor wrote: > On 03/03/2020 16:10, Torbj?rn Svensson Diaz wrote: >> What are the best email clients for email discussion lists? > > If you are talking GUIs then that's a different discussion. > My favourite is Thunderbird (and on Windows 95 it was Pegasus, > but I don't even know if it is still supported!) I currently use Thunderbird with a gmail address. Do you know how to configure it, so that all email from a specific list is automatically sorted into a specific folder? I have searched the Internet for instructions but haven't found any. This far I have manually moved all email belonging to this list from the inbox to a folder I call "tutor at python.org". I am a newcomer to email lists. > But you may have a different concept of "best"... I think I have the same concept of "best" as you do. I was formerly very active on text-only Usenet groups but now that they're dead I look for greener pastures in the world of email lists. Email lists and text-only Usenet groups seem pretty similar to me. -- Torbj?rn Svensson Diaz From alan.gauld at yahoo.co.uk Thu Mar 5 16:58:56 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 5 Mar 2020 21:58:56 +0000 Subject: [Tutor] Partly Off Topic - Email clients for email discussion lists In-Reply-To: <00cc3821-7fe6-09a2-27a9-519ea20adf0e@gmail.com> References: <66b7cb19-5725-e6c6-bab3-11d56ed42f0e@gmail.com> <00cc3821-7fe6-09a2-27a9-519ea20adf0e@gmail.com> Message-ID: On 05/03/2020 20:10, Torbj?rn Svensson Diaz wrote: > I currently use Thunderbird with a gmail address. Do you know how to > configure it, so that all email from a specific list is automatically > sorted into a specific folder? Yes I have a filter rul set up for that, although its so long ago I'll need to dig to find out how! but... Have you looked at gmane? It turns mailing lists into news feeds and Thunderbird is a fully fledged usenet reader so you just need to set up a new list with the server pointing at news.gmane.io Saves creating rules and you can read all the other Python, (and other language) lists all in the one place. I monitor Python, Smalltalk, Java, Javascript and C++ lists - all via gmane in Thunderbird. > Email lists and text-only Usenet groups seem pretty similar to me. Yep, gmane thinks so too... -- 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 oscar.j.benjamin at gmail.com Thu Mar 5 18:42:57 2020 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 5 Mar 2020 23:42:57 +0000 Subject: [Tutor] Partly Off Topic - Email clients for email discussion lists In-Reply-To: <00cc3821-7fe6-09a2-27a9-519ea20adf0e@gmail.com> References: <66b7cb19-5725-e6c6-bab3-11d56ed42f0e@gmail.com> <00cc3821-7fe6-09a2-27a9-519ea20adf0e@gmail.com> Message-ID: On Thu, 5 Mar 2020 at 21:47, Torbj?rn Svensson Diaz wrote: > > On 2020-03-03 19:47, Alan Gauld via Tutor wrote: > > On 03/03/2020 16:10, Torbj?rn Svensson Diaz wrote: > >> What are the best email clients for email discussion lists? > > > > If you are talking GUIs then that's a different discussion. > > My favourite is Thunderbird (and on Windows 95 it was Pegasus, > > but I don't even know if it is still supported!) > > I currently use Thunderbird with a gmail address. Do you know how to > configure it, so that all email from a specific list is automatically > sorted into a specific folder? I have searched the Internet for > instructions but haven't found any. This far I have manually moved all > email belonging to this list from the inbox to a folder I call > "tutor at python.org". I am a newcomer to email lists. The easiest way to do this is from within gmail. Select a few of the emails from your inbox and then choose "filter messages like these". -- Oscar From alan.gauld at yahoo.co.uk Thu Mar 5 18:50:39 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 5 Mar 2020 23:50:39 +0000 Subject: [Tutor] Python Training: Intermediate to Advanced In-Reply-To: <1049410185.5136554.1583441497100@mail.yahoo.com> References: <1049410185.5136554.1583441497100.ref@mail.yahoo.com> <1049410185.5136554.1583441497100@mail.yahoo.com> Message-ID: On 05/03/2020 20:51, Ogiri via Tutor wrote: > Hello,I am interested in Python training and in need of a trainer.Kindly assist. > Regards,Raphael. Hi, That's not how the list works. The list is the tutor. You ask us questions and we answer. Ideally you find one of the many online or paper tutorials that suits your style and work through it. If you find anything hard to understand or that doesn't seem to work then you can ask us and we will try to help. When you ask please include: Your OS and Python version Your code and any error messages (in full) Any sample data input and output (if relevant) Which tutorial you are reading The more information you give the higher the likelihood that we can give you an answer. -- 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 Thu Mar 5 18:59:43 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 5 Mar 2020 23:59:43 +0000 Subject: [Tutor] Partly Off Topic - Email clients for email discussion lists In-Reply-To: <00cc3821-7fe6-09a2-27a9-519ea20adf0e@gmail.com> References: <66b7cb19-5725-e6c6-bab3-11d56ed42f0e@gmail.com> <00cc3821-7fe6-09a2-27a9-519ea20adf0e@gmail.com> Message-ID: On 05/03/2020 20:10, Torbj?rn Svensson Diaz wrote: > I currently use Thunderbird with a gmail address. Do you know how to > configure it, so that all email from a specific list is automatically > sorted into a specific folder? The T'bird way is: Go to Tools->Message Filters Hit New to create a new filter Give it a meaningful name = Python Mail say... Ensure "Getting new mail" is checked and set the drop down to "Filter before junk" In the filter section select the "From" field and "contains" operation Set the value to python.org I the Actions area set the operation to "Copy message to" ( it actually moves it!) Choose a folder to store your Pyton mail - create one if necessary OK back out and anything from any python.org address will go to your folder. Obviously you can refine that further to separate the different python mails (general, tkinter, idle...) as needed. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From cs at cskk.id.au Thu Mar 5 23:00:23 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Fri, 6 Mar 2020 15:00:23 +1100 Subject: [Tutor] Partly Off Topic - Email clients for email discussion lists In-Reply-To: <00cc3821-7fe6-09a2-27a9-519ea20adf0e@gmail.com> References: <00cc3821-7fe6-09a2-27a9-519ea20adf0e@gmail.com> Message-ID: <20200306040023.GA60332@cskk.homeip.net> On 05Mar2020 21:10, Torbj?rn Svensson Diaz wrote: >On 2020-03-03 19:47, Alan Gauld via Tutor wrote: >>On 03/03/2020 16:10, Torbj?rn Svensson Diaz wrote: >>>What are the best email clients for email discussion lists? >I currently use Thunderbird with a gmail address. Do you know how to >configure it, so that all email from a specific list is automatically >sorted into a specific folder? I have searched the Internet for >instructions but haven't found any. This far I have manually moved all >email belonging to this list from the inbox to a folder I call >"tutor at python.org". I am a newcomer to email lists. I've a Thunderbird here... Under the Tools menu is a "Message Filters" entry; seems to let you make per-account filters. There is also a "Create filter from message..." entry under the "Message" menu. >>But you may have a different concept of "best"... > >I think I have the same concept of "best" as you do. > >I was formerly very active on text-only Usenet groups but now that >they're dead I look for greener pastures in the world of email lists. >Email lists and text-only Usenet groups seem pretty similar to me. I consider them very similar too. Yea, even unto plugging a crude usenet<->email facility into my mutt at one point (fetch from usenet, save as email with "from: news.group.name at usenet", use a script for "sendmail" and intercept "news.group.name at usenet" and delivery via usenet). Cheers, Cameron Simpson From PyTutor at DancesWithMice.info Fri Mar 6 17:53:12 2020 From: PyTutor at DancesWithMice.info (David L Neil) Date: Sat, 7 Mar 2020 11:53:12 +1300 Subject: [Tutor] Python Training: Intermediate to Advanced In-Reply-To: References: <1049410185.5136554.1583441497100.ref@mail.yahoo.com> <1049410185.5136554.1583441497100@mail.yahoo.com> Message-ID: On 6/03/20 12:50 PM, Alan Gauld via Tutor wrote: > On 05/03/2020 20:51, Ogiri via Tutor wrote: >> Hello,I am interested in Python training and in need of a trainer.Kindly assist. >> Regards,Raphael. > > Hi, > > That's not how the list works. The list is the tutor. > You ask us questions and we answer. That said (and Alan will advise if this is in any way inappropriate), there are competent tutors 'here'. So, after considering Alan's (very valid) suggestions, if you are still looking for paid-teaching, please advise. -- Regards =dn From PyTutor at DancesWithMice.info Fri Mar 6 21:54:19 2020 From: PyTutor at DancesWithMice.info (David L Neil) Date: Sat, 7 Mar 2020 15:54:19 +1300 Subject: [Tutor] overlapping tuples In-Reply-To: References: <0a6ff5ca-46e7-4562-cce3-d49adc66236d@DancesWithMice.info> <235a9339-d408-dd63-83a3-422157635de8@wichmann.us> Message-ID: <38da9272-1718-3082-616d-44b829a4cbe9@DancesWithMice.info> Am disappointed that we haven't heard-back on this (per request - mine of Fri, 28 Feb 2020 20:31:37 +0000 (UTC) ) (I rarely use sets, so this is an example of personal-gain from membership - how the list can help even >beginners improve their Python!) >> Thanks Mats for your inputs. overlap means if two numbers share across two >> tuples For Ex if we take two tuples (1,20) and (15,20) there is a >> over lap because 15,6,17,18,19,20 numbers are sharing between these >> two sets. Was intrigued by the solution using set-intersection. Neat! - as long as the 'ranges' are not too large*. * am not going to try to define "too large". It works! I suspect that the assignment came too early in the course to expect trainees to use set-functionality, but who knows... During the conversation, noted criticisms of the wording of the question, and perhaps of the attempted solution/approach. In my experience, this could just as possibly be laid at the door of the trainer, as the trainee. We've all seen 'academic' questions which tersely expect that 'the latest lesson' be applied. Yes, it might have been easier if there was some practical context, eg a "time-line", thus: were Beethoven and Mozart alive at the same time? This would also have helped with the overlap (define as sub-set or intersection?) queries - although the example data provided did (appear to!) illustrate. Am wondering then: We already have well-worn refrains: requesting the actual code, the full trace-back and err.msg, etc. Should we also be asking for/expecting the full text/relevant part thereof, of assignments? (in my courses (not Python!) we already know the trainee's context because each session/assignment has its own attached discussion list. So, even where the assignment topic develops over successive assignments, we avoid confusion) This would not only facilitate the IT-creator advice (which this thread realised in generous quantity), but also give 'us' the opportunity to provide feedback to course-leaders/instructional designers who might not otherwise become aware of the need to 'improve' the original question... More generally, such would also help 'us' to readily appreciate if the OP needs help with Python code, per-se, or to understand how Python fits-together (the 'I'm not helping if I do your homework for you' category). Accordingly, to be able to tailor more 'intelligent' responses! NB there could be a technical issue with the definition and application of Copyright, in some jurisdictions - although the same could be said about code-snippets which appear on (are volunteered to) such lists every day! -- Regards =dn From narasimha928 at gmail.com Fri Mar 6 22:57:11 2020 From: narasimha928 at gmail.com (Narasimharao Nelluri) Date: Fri, 6 Mar 2020 19:57:11 -0800 Subject: [Tutor] overlapping tuples In-Reply-To: <38da9272-1718-3082-616d-44b829a4cbe9@DancesWithMice.info> References: <0a6ff5ca-46e7-4562-cce3-d49adc66236d@DancesWithMice.info> <235a9339-d408-dd63-83a3-422157635de8@wichmann.us> <38da9272-1718-3082-616d-44b829a4cbe9@DancesWithMice.info> Message-ID: Hi David, i was working professional and was monday to friday with working Hours. i will get time during Saturdays/Sundays. I will try your inputs and get back to you soon. -Narasimha On Fri, Mar 6, 2020 at 6:54 PM David L Neil via Tutor wrote: > Am disappointed that we haven't heard-back on this (per request - mine > of Fri, 28 Feb 2020 20:31:37 +0000 (UTC) ) > > > (I rarely use sets, so this is an example of personal-gain from > membership - how the list can help even >beginners improve their Python!) > > >> Thanks Mats for your inputs. overlap means if two numbers share across > two > >> tuples For Ex if we take two tuples (1,20) and (15,20) there is a > >> over lap because 15,6,17,18,19,20 numbers are sharing between these > >> two sets. > > Was intrigued by the solution using set-intersection. Neat! > - as long as the 'ranges' are not too large*. > * am not going to try to define "too large". It works! > > I suspect that the assignment came too early in the course to expect > trainees to use set-functionality, but who knows... > > > During the conversation, noted criticisms of the wording of the > question, and perhaps of the attempted solution/approach. > > In my experience, this could just as possibly be laid at the door of the > trainer, as the trainee. We've all seen 'academic' questions which > tersely expect that 'the latest lesson' be applied. Yes, it might have > been easier if there was some practical context, eg a "time-line", thus: > were Beethoven and Mozart alive at the same time? This would also have > helped with the overlap (define as sub-set or intersection?) queries - > although the example data provided did (appear to!) illustrate. > > > Am wondering then: > > We already have well-worn refrains: requesting the actual code, the full > trace-back and err.msg, etc. Should we also be asking for/expecting the > full text/relevant part thereof, of assignments? > > (in my courses (not Python!) we already know the trainee's context > because each session/assignment has its own attached discussion list. > So, even where the assignment topic develops over successive > assignments, we avoid confusion) > > This would not only facilitate the IT-creator advice (which this thread > realised in generous quantity), but also give 'us' the opportunity to > provide feedback to course-leaders/instructional designers who might not > otherwise become aware of the need to 'improve' the original question... > > More generally, such would also help 'us' to readily appreciate if the > OP needs help with Python code, per-se, or to understand how Python > fits-together (the 'I'm not helping if I do your homework for you' > category). Accordingly, to be able to tailor more 'intelligent' responses! > > > NB there could be a technical issue with the definition and application > of Copyright, in some jurisdictions - although the same could be said > about code-snippets which appear on (are volunteered to) such lists > every day! > -- > Regards =dn > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From loomer at gmx.com Sun Mar 8 00:20:12 2020 From: loomer at gmx.com (loomer at gmx.com) Date: Sun, 8 Mar 2020 00:20:12 -0500 Subject: [Tutor] math (pkg) in Jupyter Notebook Message-ID: Hi I'm a very new python programmer. I'm trying to mess around with the mathematical equation, pi, in Jupyter Notebook which was installed with Anaconda3/Windows 10. The math package is installed somewhere on my PC because when I try it in an Anaconda terminal, I get... >>> math.pi 3.141592653589793 I checked the environment... >>> import sys; sys.prefix 'C:\\Program Files\\Anaconda3' But when I try to run that in a python3 Jupyter Notebook, I get... NameError Traceback (most recent call last) in ----> 1 math.pi NameError: name 'math' is not defined The error if I start python from a Windows command prompt... >>> math.pi Traceback (most recent call last): File "", line 1, in NameError: name 'math' is not defined Also, I've been starting Anaconda using the terminal because I don't need that interface with all those modules. I share Notebook files (.ipynb) with my Linux Mint laptop through network sharing. So I have a Linux directory mapped as drive P in Windows... >C: cd P: >P: jupyter notebook And I get the shared files in a browser window. I also tried to run that command (math.pi) from a Jupyter Notebook started from the Anaconda application and I got the same error. From alan.gauld at yahoo.co.uk Sun Mar 8 05:21:23 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 8 Mar 2020 09:21:23 +0000 Subject: [Tutor] math (pkg) in Jupyter Notebook In-Reply-To: References: Message-ID: On 08/03/2020 05:20, loomer at gmx.com wrote: > The math package is installed somewhere on my PC because when I try it > in an Anaconda terminal, I get... > > >>> math.pi > 3.141592653589793 So I'm guessing anaconda automatically imports the math package for you. (I don't use it so don't know for sure). > But when I try to run that in a python3 Jupyter Notebook, I get... > > NameError Traceback (most recent call last) > in > ----> 1 math.pi > > NameError: name 'math' is not defined You normally (in vanilla python) have to import any module before using it. So you need: >>> import math >>> math.pi HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From loomer at gmx.com Tue Mar 10 00:39:37 2020 From: loomer at gmx.com (loomer at gmx.com) Date: Tue, 10 Mar 2020 00:39:37 -0400 Subject: [Tutor] syntax error-unexpected EOF while parsing Message-ID: <4db7faea-a4ca-e806-4712-567cd96a82d1@gmx.com> Hello, I'm going through an online python course and in the video called "Basic I/O with Files," I generated an error that I cannot figure out. It starts with creating a .txt file in Jupyter Notebook... %%writefile test.txt line 1 line 2 line 3 I guess "%%Writefile" only works in JNotebook but it did create a file called "test.txt" with those lines. I opened the actual file to check. Then he says test the file with... myfile = open('test.txt') which returns nothing indicating that the file exists. OK, then... myfile.read() 'line 1\nline 2\nline 3\n' Then... myfile.seek(0) to reset the cursor to 0, then... myfile.close() to close it for the next part I guess. The problem arises when I try the next part... with open('test.txt') as new_file: which, from what I understand, creates a virtual file that you can add lines to, right? OK, the error in JNotebook is... File "", line 1 with open('test.txt') as new_file: ^ SyntaxError: unexpected EOF while parsing I tried using the path to the file... PWD 'P:\\' myfile = open('P:\\test.txt') and that works, but same error with... with open('P:\\test.txt') as new_file: So I tried it in Atom and got a similar error... myfile = open('P:\\test.txt') myfile.read() myfile.seek(0) myfile.close() with open('P:\\test.txt') as test_virt: File "P:\test-txt-glitch.py", line 6 ^ SyntaxError: unexpected EOF while parsing [Finished in 0.668s] [love Atom lol] The file only has 3 lines so I have no idea what's wrong. It works for the instructor in the video and I've checked and rechecked my typing against the video. Thanks. From alan.gauld at yahoo.co.uk Tue Mar 10 05:30:34 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 10 Mar 2020 09:30:34 +0000 Subject: [Tutor] syntax error-unexpected EOF while parsing In-Reply-To: <4db7faea-a4ca-e806-4712-567cd96a82d1@gmx.com> References: <4db7faea-a4ca-e806-4712-567cd96a82d1@gmx.com> Message-ID: On 10/03/2020 04:39, loomer at gmx.com wrote: > Then... > > myfile.seek(0) > > to reset the cursor to 0, then... This is an unnecessary step since you are not doing anything with the cursor. After you close the file the cursor is lost and a new one created when you next open the file. > > myfile.close() > > to close it for the next part I guess. > > The problem arises when I try the next part... > > with open('test.txt') as new_file: > > which, from what I understand, creates a virtual file that you can add > lines to, right? OK, the error in JNotebook is... It is exactly equivalent to new_file = open('test.txt') except that the with structure guarantees to close the file for you at the end. But it is not creating virtual anything, it just assigns the open file object to your alias. However, to add lines to it you need to specify the file mode. Either 'w' to write(creaes a new file) or 'a' to append, keeping the previous content. So with open('test.txt', 'w') as new_file: or with open('test.txt', 'a') as myfile: > > File "", line 1 > with open('test.txt') as new_file: > ^ > SyntaxError: unexpected EOF while parsing This is because with is the start of a block - as indicated by the colon at the end. You have not provided a block so you get an error. try adding pass: with open('test.txt', 'a') as myfile: pass That should compile and run, although it will do nothing. You would get the same error if you tried typing a while line without a body: >>> while True: Python expects more code but instead reaches the end of the file, so it complains. -- 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 thehouse.be at me.com Sun Mar 15 11:41:23 2020 From: thehouse.be at me.com (thehouse.be at me.com) Date: Sun, 15 Mar 2020 16:41:23 +0100 Subject: [Tutor] UnicodeDecodeError References: <1d7800a8-4b68-4111-bff8-7cc4e873a706@Spark> Message-ID: I am a beginner, learning Python. So sorry if my question is basic. I am trying to work with .csv files in order to analyse data which comes from a Google Forms survey. Idea is to handle the raw data, do some statistical analysis and make a report. When trying to convert the data into a listy of lists, I get a UnicodeDecodeError. This is what I do: >>> import csv >>> exampleFile = open(?example.csv?) >>> exampleReader = csv.reader(exampleFile) >>> exampleData = list(exampleReader) This last statement generates: ????????????????????????????????????? UnicodeDecodeError Traceback (most recent call last) in ----> 1 exampleData = list(exampleReader) /Applications/mu-editor.app/Contents/Resources/python/lib/python3.6/encodings/ascii.pyc in decode(self, input, final) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1798: ordinal not in range(128) I suppose there is a bizarre character somewhere in the file, but no idea where. As we use accents and umlauts in our language, could that be the problem? If that would be the problem, how to solve? Best regards and tnaks for the help, Chris From PyTutor at DancesWithMice.info Sun Mar 15 14:45:47 2020 From: PyTutor at DancesWithMice.info (David L Neil) Date: Mon, 16 Mar 2020 07:45:47 +1300 Subject: [Tutor] UnicodeDecodeError In-Reply-To: References: <1d7800a8-4b68-4111-bff8-7cc4e873a706@Spark> Message-ID: <95c2c4cb-0ce5-cf5b-a359-9bcfa1354d76@DancesWithMice.info> On 16/03/20 4:41 AM, thehouse.be--- via Tutor wrote: > I am a beginner, learning Python. > So sorry if my question is basic. > > I am trying to work with .csv files in order to analyse data which comes from a Google Forms survey. > Idea is to handle the raw data, do some statistical analysis and make a report. > > When trying to convert the data into a listy of lists, I get a UnicodeDecodeError. > > This is what I do: > >>>> import csv >>>> exampleFile = open(?example.csv?) >>>> exampleReader = csv.reader(exampleFile) >>>> exampleData = list(exampleReader) > > This last statement generates: > ????????????????????????????????????? > UnicodeDecodeError Traceback (most recent call last) > in > ----> 1 exampleData = list(exampleReader) > /Applications/mu-editor.app/Contents/Resources/python/lib/python3.6/encodings/ascii.pyc in decode(self, input, final) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1798: ordinal not in range(128) > > I suppose there is a bizarre character somewhere in the file, but no idea where. > As we use accents and umlauts in our language, could that be the problem? > If that would be the problem, how to solve? NB there are major differences in this area between Python2 and Python3. I'm assuming you are using Python3. The difficulty, as you say, is that the majority of the world's population use languages which cannot be adequately-expressed using ASCII (*American* Standard Code...) - which also makes this type of question difficult to answer because of the many permutations and combinations... If the spreadsheet/original .CSV file was built using MS-Excel and/or on a non-English-speaking MS-Windows machine, then it is highly likely we need to harmonise this Python code with that characteristic. Are you able to ascertain such detail? If not, you can probably make an educated guess (given your analysis to-date). Microsoft Windows tends to put European users into one of the ISO 8859-x character sets. (but which one? Good news: we may not need to be *exactly* correct in this choice!) Python3 works with Unicode by default. It is possible to encode and decode between "text encodings". Some experimentation may be necessary. Please let us know the results of your investigation/experiments, and/or if that leads to further questions... WebRefs: https://en.wikipedia.org/wiki/ISO/IEC_8859-1 https://docs.python.org/3/howto/unicode.html https://docs.python.org/3/library/codecs.html -- Regards =dn From nulla.epistola at web.de Sun Mar 15 14:55:22 2020 From: nulla.epistola at web.de (Sibylle Koczian) Date: Sun, 15 Mar 2020 19:55:22 +0100 Subject: [Tutor] UnicodeDecodeError In-Reply-To: References: <1d7800a8-4b68-4111-bff8-7cc4e873a706@Spark> Message-ID: <4446231d-0f03-c265-7078-1101fa0dd95f@web.de> Am 15.03.2020 um 16:41 schrieb thehouse.be--- via Tutor: > I am a beginner, learning Python. > So sorry if my question is basic. > > I am trying to work with .csv files in order to analyse data which comes from a Google Forms survey. > Idea is to handle the raw data, do some statistical analysis and make a report. > > When trying to convert the data into a listy of lists, I get a UnicodeDecodeError. > > This is what I do: > >>>> import csv >>>> exampleFile = open(?example.csv?) >>>> exampleReader = csv.reader(exampleFile) >>>> exampleData = list(exampleReader) > > This last statement generates: > ????????????????????????????????????? > UnicodeDecodeError Traceback (most recent call last) > in > ----> 1 exampleData = list(exampleReader) > /Applications/mu-editor.app/Contents/Resources/python/lib/python3.6/encodings/ascii.pyc in decode(self, input, final) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1798: ordinal not in range(128) > > I suppose there is a bizarre character somewhere in the file, but no idea where. > As we use accents and umlauts in our language, could that be the problem? > If that would be the problem, how to solve? > There doesn't need to be anything bizarre in the file - accents and umlauts suffice for ascii to choke. Opening the file with the right encoding given explicitly should help, for example for utf-8: exampleFile = open('example.csv', encoding='utf-8') HTH Sibylle From nulla.epistola at web.de Sun Mar 15 14:55:22 2020 From: nulla.epistola at web.de (Sibylle Koczian) Date: Sun, 15 Mar 2020 19:55:22 +0100 Subject: [Tutor] UnicodeDecodeError In-Reply-To: References: <1d7800a8-4b68-4111-bff8-7cc4e873a706@Spark> Message-ID: <4446231d-0f03-c265-7078-1101fa0dd95f@web.de> Am 15.03.2020 um 16:41 schrieb thehouse.be--- via Tutor: > I am a beginner, learning Python. > So sorry if my question is basic. > > I am trying to work with .csv files in order to analyse data which comes from a Google Forms survey. > Idea is to handle the raw data, do some statistical analysis and make a report. > > When trying to convert the data into a listy of lists, I get a UnicodeDecodeError. > > This is what I do: > >>>> import csv >>>> exampleFile = open(?example.csv?) >>>> exampleReader = csv.reader(exampleFile) >>>> exampleData = list(exampleReader) > > This last statement generates: > ????????????????????????????????????? > UnicodeDecodeError Traceback (most recent call last) > in > ----> 1 exampleData = list(exampleReader) > /Applications/mu-editor.app/Contents/Resources/python/lib/python3.6/encodings/ascii.pyc in decode(self, input, final) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1798: ordinal not in range(128) > > I suppose there is a bizarre character somewhere in the file, but no idea where. > As we use accents and umlauts in our language, could that be the problem? > If that would be the problem, how to solve? > There doesn't need to be anything bizarre in the file - accents and umlauts suffice for ascii to choke. Opening the file with the right encoding given explicitly should help, for example for utf-8: exampleFile = open('example.csv', encoding='utf-8') HTH Sibylle From breamoreboy at gmail.com Sun Mar 15 14:50:53 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Sun, 15 Mar 2020 18:50:53 +0000 Subject: [Tutor] UnicodeDecodeError In-Reply-To: <95c2c4cb-0ce5-cf5b-a359-9bcfa1354d76@DancesWithMice.info> References: <1d7800a8-4b68-4111-bff8-7cc4e873a706@Spark> <95c2c4cb-0ce5-cf5b-a359-9bcfa1354d76@DancesWithMice.info> Message-ID: On 15/03/2020 18:45, David L Neil via Tutor wrote: > On 16/03/20 4:41 AM, thehouse.be--- via Tutor wrote: >> I am a beginner, learning Python. >> So sorry if my question is basic. >> >> I am trying to work with .csv files in order to analyse data which >> comes from a Google Forms survey. >> Idea is to handle the raw data, do some statistical analysis and make >> a report. >> >> When trying to convert the data into a listy of lists, I get a >> UnicodeDecodeError. >> >> This is what I do: >> >>>>> import csv >>>>> exampleFile = open(?example.csv?) >>>>> exampleReader = csv.reader(exampleFile) >>>>> exampleData = list(exampleReader) >> >> This last statement generates: >> ????????????????????????????????????? >> UnicodeDecodeError Traceback (most recent call last) >> in >> ----> 1 exampleData = list(exampleReader) >> /Applications/mu-editor.app/Contents/Resources/python/lib/python3.6/encodings/ascii.pyc >> in decode(self, input, final) >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position >> 1798: ordinal not in range(128) >> >> I suppose there is a bizarre character somewhere in the file, but no >> idea where. >> As we use accents and umlauts in our language, could that be the problem? >> If that would be the problem, how to solve? > > > NB there are major differences in this area between Python2 and Python3. > I'm assuming you are using Python3. > > > The difficulty, as you say, is that the majority of the world's > population use languages which cannot be adequately-expressed using > ASCII (*American* Standard Code...) - which also makes this type of > question difficult to answer because of the many permutations and > combinations... > > If the spreadsheet/original .CSV file was built using MS-Excel and/or on > a non-English-speaking MS-Windows machine, then it is highly likely we > need to harmonise this Python code with that characteristic. > > Are you able to ascertain such detail? If not, you can probably make an > educated guess (given your analysis to-date). > > > Microsoft Windows tends to put European users into one of the ISO 8859-x > character sets. (but which one? Good news: we may not need to be > *exactly* correct in this choice!) > > Python3 works with Unicode by default. > > It is possible to encode and decode between "text encodings". Some > experimentation may be necessary. > > Please let us know the results of your investigation/experiments, and/or > if that leads to further questions... > > > WebRefs: > https://en.wikipedia.org/wiki/ISO/IEC_8859-1 > https://docs.python.org/3/howto/unicode.html > https://docs.python.org/3/library/codecs.html This https://pypi.org/project/chardet/ might also come in handy. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From thehouse.be at me.com Sun Mar 15 17:04:25 2020 From: thehouse.be at me.com (thehouse.be at me.com) Date: Sun, 15 Mar 2020 22:04:25 +0100 Subject: [Tutor] UnicodeDecodeError In-Reply-To: <4446231d-0f03-c265-7078-1101fa0dd95f@web.de> References: <1d7800a8-4b68-4111-bff8-7cc4e873a706@Spark> <4446231d-0f03-c265-7078-1101fa0dd95f@web.de> Message-ID: <2d6ef75a-9be1-4cb1-bf6e-ab9aed6251c7@Spark> Dear Sibylle, Thank you so much. Adding encoding=?utf-8? is indeed the solution. Extra info: I was working in the mu-editor when I encountered the problem. I tried the same original commands (without ?utf-8?) in Idle? and there it worked. Again thank you for solving my problem, Chris On 15 Mar 2020, 20:05 +0100, Sibylle Koczian , wrote: > Am 15.03.2020 um 16:41 schrieb thehouse.be--- via Tutor: > > I am a beginner, learning Python. > > So sorry if my question is basic. > > > > I am trying to work with .csv files in order to analyse data which comes from a Google Forms survey. > > Idea is to handle the raw data, do some statistical analysis and make a report. > > > > When trying to convert the data into a listy of lists, I get a UnicodeDecodeError. > > > > This is what I do: > > > > > > > import csv > > > > > exampleFile = open(?example.csv?) > > > > > exampleReader = csv.reader(exampleFile) > > > > > exampleData = list(exampleReader) > > > > This last statement generates: > > ????????????????????????????????????? > > UnicodeDecodeError Traceback (most recent call last) > > in > > ----> 1 exampleData = list(exampleReader) > > /Applications/mu-editor.app/Contents/Resources/python/lib/python3.6/encodings/ascii.pyc in decode(self, input, final) > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1798: ordinal not in range(128) > > > > I suppose there is a bizarre character somewhere in the file, but no idea where. > > As we use accents and umlauts in our language, could that be the problem? > > If that would be the problem, how to solve? > > > > There doesn't need to be anything bizarre in the file - accents and > umlauts suffice for ascii to choke. Opening the file with the right > encoding given explicitly should help, for example for utf-8: > > exampleFile = open('example.csv', encoding='utf-8') > > HTH > Sibylle > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From igwe.kalu at live.com Sun Mar 15 22:07:35 2020 From: igwe.kalu at live.com (Igwe Kalu) Date: Mon, 16 Mar 2020 02:07:35 +0000 Subject: [Tutor] =?windows-1252?q?Python_scripts=3A_to_use_class_or_not_?= =?windows-1252?q?=97_what_is_the_best_practice=3F?= Message-ID: Hi Community, I need your feedback on a possibly simple idea. Python scripts: to use class or not ? what is the best practice? The details of my question are posted on https://softwareengineering.stackexchange.com/questions/406585/python-scripts-to-use-class-or-not-what-is-the-best-practice I would greatly appreciate your inputs there, thank you. Best regards Der Neu PythonMeister From breamoreboy at gmail.com Mon Mar 16 05:23:51 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Mon, 16 Mar 2020 09:23:51 +0000 Subject: [Tutor] =?utf-8?q?Python_scripts=3A_to_use_class_or_not_?= =?utf-8?q?=E2=80=94_what_is_the_best_practice=3F?= In-Reply-To: References: Message-ID: On 16/03/2020 02:07, Igwe Kalu wrote: > Hi Community, > > I need your feedback on a possibly simple idea. > > Python scripts: to use class or not ? what is the best practice? > > The details of my question are posted on https://softwareengineering.stackexchange.com/questions/406585/python-scripts-to-use-class-or-not-what-is-the-best-practice > > I would greatly appreciate your inputs there, thank you. > > > Best regards > Der Neu PythonMeister > Stick with the KISS principle https://en.wikipedia.org/wiki/KISS_principle so functions in a module will be fine, only write classes if you really need them. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From alan.gauld at yahoo.co.uk Mon Mar 16 06:59:24 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 16 Mar 2020 10:59:24 +0000 Subject: [Tutor] =?utf-8?q?Python_scripts=3A_to_use_class_or_not_?= =?utf-8?q?=E2=80=94_what_is_the_best_practice=3F?= In-Reply-To: References: Message-ID: On 16/03/2020 02:07, Igwe Kalu wrote: > Python scripts: to use class or not ? what is the best practice? As with anything in programming, if a tool works use it. Modules package up code for reuse beyond your current program. If that is your aim use a module. Classes bundle functions(methods) along with the data/state needed by those functions. Classes allow for multiple instances(objects) to be created. Classes generally model some real or conceptual thing. If that's what you are trying to do, use classes. If the class can be reused elsewhere put your class in a module. If your program is object oriented then you will almost certainly need to use classes. If your program is primarily procedural (or functional) then you may find classes convenient but equally you may not need them. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From mats at wichmann.us Mon Mar 16 10:13:14 2020 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 16 Mar 2020 08:13:14 -0600 Subject: [Tutor] =?utf-8?q?Python_scripts=3A_to_use_class_or_not_?= =?utf-8?q?=E2=80=94_what_is_the_best_practice=3F?= In-Reply-To: References: Message-ID: <58876afd-c914-d7be-afe5-a1fd9071eb0e@wichmann.us> On 3/15/20 8:07 PM, Igwe Kalu wrote: > Hi Community, > > I need your feedback on a possibly simple idea. > > Python scripts: to use class or not ? what is the best practice? > > The details of my question are posted on https://softwareengineering.stackexchange.com/questions/406585/python-scripts-to-use-class-or-not-what-is-the-best-practice > > I would greatly appreciate your inputs there, thank you. well, you'll have seen that Stackexchange doesn't like questions that require an opinion, so like the others, I won't reply over there. And that's really what you've done - you've veered into the opinion space. Python is indeed very object oriented, in that everything you operate on is an object. It is *not* a language that forces you to wrap everything you do in a class definition, if Guido thought that was best-practice-for-all-uses, he presumably would have written the language that way. So maybe take a hint from that? Software design is complicated. You want to build a program that is practical for as many uses as possible, but don't want to overdesign it to the point where you waste time on things that it won't be used for. You have to balance building a design with lots of features, easily expandable, with a consistent API with the need to get something working which maybe won't actually get used widely enough to need all of that. It's actually quite fine also to build something simply to throw away - fitness for purpose. Only you know what your requirements are for a given project. A class definition in Python is a new datatype. Do you need a new datatype? These normally abstract/encapsulate something... consider a Python list type - it bundles some data storage together with functions to act on it, like append(), extend(), sort(), etc. That makes sense, you can think of a "list" as a particular Thing. The example you psuedo-coded doesn't seem to encapsulate any particularly interesting behavior that would qualify it as being a datatype - but I recognize that it was only an example, and some real cases may be different. From thehouse.be at me.com Mon Mar 16 10:11:59 2020 From: thehouse.be at me.com (thehouse.be at me.com) Date: Mon, 16 Mar 2020 15:11:59 +0100 Subject: [Tutor] UnicodeDecodeError In-Reply-To: <2d6ef75a-9be1-4cb1-bf6e-ab9aed6251c7@Spark> References: <1d7800a8-4b68-4111-bff8-7cc4e873a706@Spark> <4446231d-0f03-c265-7078-1101fa0dd95f@web.de> <2d6ef75a-9be1-4cb1-bf6e-ab9aed6251c7@Spark> Message-ID: > > > I am trying to work with .csv files in order to analyse data which comes from a Google Forms survey. > > > Idea is to handle the raw data, do some statistical analysis and make a report. > > > > > > When writing to a text file I get the same error: Traceback (most recent call last): File "/Users/chrisvanroey/mu_code/collab_comment_decoder.py", line 79, in p.write_text('- ' + (cel)) File "/Users/travis/build/mu-editor/mu_portable_python_macos/python/lib/python3.6/pathlib.py", line 1214, in write_text UnicodeEncodeError: 'ascii' codec can't encode character '\xeb' in position 144: ordinal not in range(128) So probably I have also to put???utf-8? somewhere in the p.write_text code. But I can?t find where?. Can you help? Here is the code: ## maak een txt bestand (ipv print) import os from pathlib import Path os.chdir('/users/chrisvanroey/Desktop?) p = Path(?output.txt?) # write header p.write_text('COLLAB COMMENTS?) p.write_text(?/n?) # write commentaar x personen voor elke vraag for kolom in range(3,62,2): ? ? p.write_text(collabData[0][kolom-1]) ? ? for rij in range(1,aantalResp+1): ? ? ? ? cel = collabData[rij][kolom] ? ? ? ? if cel != ??: ? ? ? ? ? ? p.write_text('- ' + (cel)) ? ?<<<<<<<<< HER I GET THE UNICODE ERROR ? ? p.write_text('?????????????????????????????????) # print additionele feedback x personen p.write_text('Additional feedback:?) for rij in range(1,aantalResp+1): ? ? cel = collabData[rij][62] ? ? if cel != ??: ? ? ? ? p.write_text('- ' + (cel)) On 16 Mar 2020, 02:28 +0100, thehouse.be--- via Tutor , wrote: > Dear Sibylle, > > Thank you so much. > Adding encoding=?utf-8? is indeed the solution. > > Extra info: I was working in the mu-editor when I encountered the problem. > I tried the same original commands (without ?utf-8?) in Idle? and there it worked. > > Again thank you for solving my problem, > Chris > On 15 Mar 2020, 20:05 +0100, Sibylle Koczian , wrote: > > Am 15.03.2020 um 16:41 schrieb thehouse.be--- via Tutor: > > > I am a beginner, learning Python. > > > So sorry if my question is basic. > > > > > > I am trying to work with .csv files in order to analyse data which comes from a Google Forms survey. > > > Idea is to handle the raw data, do some statistical analysis and make a report. > > > > > > When trying to convert the data into a listy of lists, I get a UnicodeDecodeError. > > > > > > This is what I do: > > > > > > > > > import csv > > > > > > exampleFile = open(?example.csv?) > > > > > > exampleReader = csv.reader(exampleFile) > > > > > > exampleData = list(exampleReader) > > > > > > This last statement generates: > > > ????????????????????????????????????? > > > UnicodeDecodeError Traceback (most recent call last) > > > in > > > ----> 1 exampleData = list(exampleReader) > > > /Applications/mu-editor.app/Contents/Resources/python/lib/python3.6/encodings/ascii.pyc in decode(self, input, final) > > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1798: ordinal not in range(128) > > > > > > I suppose there is a bizarre character somewhere in the file, but no idea where. > > > As we use accents and umlauts in our language, could that be the problem? > > > If that would be the problem, how to solve? > > > > > > > There doesn't need to be anything bizarre in the file - accents and > > umlauts suffice for ascii to choke. Opening the file with the right > > encoding given explicitly should help, for example for utf-8: > > > > exampleFile = open('example.csv', encoding='utf-8') > > > > HTH > > Sibylle > > _______________________________________________ > > 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 mats at wichmann.us Mon Mar 16 11:15:25 2020 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 16 Mar 2020 09:15:25 -0600 Subject: [Tutor] UnicodeDecodeError In-Reply-To: References: <1d7800a8-4b68-4111-bff8-7cc4e873a706@Spark> <4446231d-0f03-c265-7078-1101fa0dd95f@web.de> <2d6ef75a-9be1-4cb1-bf6e-ab9aed6251c7@Spark> Message-ID: On 3/16/20 8:11 AM, thehouse.be--- via Tutor wrote: > >>>> I am trying to work with .csv files in order to analyse data which comes from a Google Forms survey. >>>> Idea is to handle the raw data, do some statistical analysis and make a report. >>>> >>>> > When writing to a text file I get the same error: > Traceback (most recent call last): > File "/Users/chrisvanroey/mu_code/collab_comment_decoder.py", line 79, in > p.write_text('- ' + (cel)) > File "/Users/travis/build/mu-editor/mu_portable_python_macos/python/lib/python3.6/pathlib.py", line 1214, in write_text > UnicodeEncodeError: 'ascii' codec can't encode character '\xeb' in position 144: ordinal not in range(128) > > > So probably I have also to put???utf-8? somewhere in the p.write_text code. > But I can?t find where?. You set it in the open, then all the methods on the file (or Path object in your case) respect it. See the docs: Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None) From alan.gauld at yahoo.co.uk Mon Mar 16 11:23:10 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 16 Mar 2020 15:23:10 +0000 Subject: [Tutor] UnicodeDecodeError In-Reply-To: References: <1d7800a8-4b68-4111-bff8-7cc4e873a706@Spark> <4446231d-0f03-c265-7078-1101fa0dd95f@web.de> <2d6ef75a-9be1-4cb1-bf6e-ab9aed6251c7@Spark> Message-ID: On 16/03/2020 14:11, thehouse.be--- via Tutor wrote: > p.write_text('- ' + (cel)) > File "/Users/travis/build/mu-editor/mu_portable_python_macos/python/lib/python3.6/pathlib.py", line 1214, in write_text > UnicodeEncodeError: 'ascii' codec can't encode character '\xeb' in position 144: ordinal not in range(128) > > > So probably I have also to put???utf-8? somewhere in the p.write_text code. The help says: >>> help(p.write_text) Help on method write_text in module pathlib: write_text(data, encoding=None, errors=None) method of pathlib.PosixPath instance Open the file in text mode, write to it, and close the file. Notice the encoding parameter? I think that might be the place... I've never used pathlib to write to a file before, but I notice you have write_text inside a loop. From the description it would seem likely that write_text in a loop will overwrite the previous text each time round. Might be worth checking? You may have to use the Path.open() method to open the file object. (open() also has an encoding parameter) -- 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 PyTutor at DancesWithMice.info Mon Mar 16 18:41:58 2020 From: PyTutor at DancesWithMice.info (DL Neil) Date: Tue, 17 Mar 2020 11:41:58 +1300 Subject: [Tutor] =?utf-8?q?Python_scripts=3A_to_use_class_or_not_?= =?utf-8?q?=E2=80=94_what_is_the_best_practice=3F?= In-Reply-To: References: Message-ID: On 16/03/20 3:07 PM, Igwe Kalu wrote: > Hi Community, > > I need your feedback on a possibly simple idea. > > Python scripts: to use class or not ? what is the best practice? > > The details of my question are posted on https://softwareengineering.stackexchange.com/questions/406585/python-scripts-to-use-class-or-not-what-is-the-best-practice > > I would greatly appreciate your inputs there, thank you. +1 to previous responses. Valuable learning opportunities! I may use class(es) more than others, and may be more data-centric. There are arguments both-ways, as you've read. When designing a program, I look for 'entities' - the who and the what, relating to the objectives. I also appreciate, and (some may say) 'over practice' the concept of 'information hiding'. After basic design (likely on a white-board), I start 'coding' by encoding application-objectives/requirements into comments. Logically then, once entities are realised, such decisions can be 'documented' with a class statement and docstring (and pass)! Similarly, delving into greater detail, data attributes can be added, with type information (if practiced) and explanatory comments, as appropriate. Also functional attributes (methods and functions) can be denoted with a def, docstring, and pass. (not forgetting the import-ation of libraries and other third-party or utilities! etc) Where possible, the bulk of the code's structure is thus transferred from the 'design documents' into source-code. Somewhere around this point (depends upon the application, if multiple coders are involved, etc, etc), I will probably switch from 'top-down design' to 'bottom-up', by following Test-Driven Development practice. It must be acknowledged that one's method and how practical the above may appear, is a function of experience (and comfort with the approach). YMMV big time! Back in the ?good, old days, "subroutine libraries" came into being, and for much the same advantages, we became convinced of "modular programming". (those older "modular" code-units might be translated into modern 'Python' as "namespaces" - and thus include modules, classes, methods (inside classes), and functions (outside classes)). More recently Grady Booch's view of Object-Oriented Programming (OOP) talked of "encapsulation" - I'm a little wary of quoting his ideas (which are nevertheless valid) because their implementation is an anathema to Python and the pythonic way of thinking, eg we don't (really) have "private" attributes nor do we need 'getters' or 'setters' in the normal case... In both cases, the idea is that calling a 'routine' reduces "cognitive load". (and should "document" one's code!) Attempting to build from the example given, "start" would become THE routine, eg def optimise_simulation(): etc Thus, someone reading the 'mainline' code has been given enough knowledge to be able to decide to keep reading and see how the rest of the application fits-together. Alternately, the reader wanting to 'dive' into the optimisation itself, can find the function and commence reading the detail - which would lead to the branch-decision and the two alternative 'actual' implementations... Back to the meat of the question: if the 'simulation' were already a class, likely these routines would be implemented as methods. If however the code might be applicable to another class, or indeed to code which is not part of a class (ie the 'subroutine library' idea or in the modern parlance: "reuse"), then it would be inappropriate to 'bury it' within a class that cannot also be part of such re-use. Just to offer you a (sort of) third option, in such a 'shared'/multiple-use situation, you could consider coding such utility routines as a "mixin [class]" which is either inherited or included into (multiple units of) host code by "composition". Alternately, it may be appropriate to view the optimisation process as a full-fat, separate, class (in such vague terms, I don't interpret a process as an "entity" - but others may disagree...) Is there a right/wrong answer? Doubt it! During code reviews, in such a situation, people often comment "I would [not] have used a class 'here'." However, such usually passes as a comment (perhaps a learning-opportunity), and seldom leads into a criticism (by itself) which requires a re-write/re-factoring. (in my experience) There's a difference between someone who has eleven years of experiences, and someone who repeats one year of experience eleven times! My suggestion, if I may (and bearing in-mind what others have already said about choosing one way over the other according to certain circumstances): try coding (as you have) the function-way 'today', but next time you're faced with something similar, employ classes. Later, reflection on (learning from) those experiences will (intelligently) equip you for 'the future'... -- Regards =dn From alan.gauld at yahoo.co.uk Mon Mar 16 20:44:11 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 17 Mar 2020 00:44:11 +0000 Subject: [Tutor] =?utf-8?q?Python_scripts=3A_to_use_class_or_not_?= =?utf-8?q?=E2=80=94_what_is_the_best_practice=3F?= In-Reply-To: References: Message-ID: On 16/03/2020 22:41, DL Neil via Tutor wrote: > More recently Grady Booch's view of Object-Oriented Programming (OOP) > talked of "encapsulation" - I'm a little wary of quoting his ideas > (which are nevertheless valid) because their implementation is an > anathema to Python and the pythonic way of thinking, I'm not sure I'd agree with that. Grady's ideas were expressed in his OOD book from 1991 - 29 years ago - and were in line with common thinking about OOP at the time. Grady was (and is) a big fan of information hiding (which is separate to, but often confused with, ecapsulation), an important feature of creating robust systems. But he is not a big fan of getters/setters. Rather he follows the idioms of the languages he uses. So, in his second edition he primarily used Java and so included getters/setters but in both his 1st and 3rd editions (both multi-lingual) he uses the conventions of the language, often without getter/setter methods. But that nit-pick aside, I agree with what you wrote... :-) -- 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 PyTutor at DancesWithMice.info Tue Mar 17 00:27:19 2020 From: PyTutor at DancesWithMice.info (David L Neil) Date: Tue, 17 Mar 2020 17:27:19 +1300 Subject: [Tutor] =?utf-8?q?Python_scripts=3A_to_use_class_or_not_?= =?utf-8?q?=E2=80=94_what_is_the_best_practice=3F?= In-Reply-To: References: Message-ID: <9f57a800-5a5b-fde6-f3a1-ad9d985b242d@DancesWithMice.info> On 17/03/20 1:44 PM, Alan Gauld via Tutor wrote: > On 16/03/2020 22:41, DL Neil via Tutor wrote: > >> More recently Grady Booch's view of Object-Oriented Programming (OOP) >> talked of "encapsulation" - I'm a little wary of quoting his ideas >> (which are nevertheless valid) because their implementation is an >> anathema to Python and the pythonic way of thinking, > > I'm not sure I'd agree with that. Grady's ideas were expressed in > his OOD book from 1991 - 29 years ago - and were in line with > common thinking about OOP at the time. > > Grady was (and is) a big fan of information hiding (which is > separate to, but often confused with, ecapsulation), an > important feature of creating robust systems. But he is not a > big fan of getters/setters. Rather he follows the idioms of > the languages he uses. So, in his second edition he primarily > used Java and so included getters/setters but in both his 1st > and 3rd editions (both multi-lingual) he uses the conventions > of the language, often without getter/setter methods. > > But that nit-pick aside, I agree with what you wrote... :-) awww, and there was I thinking this might be an opportunity for you to 'pick me up' on my view of classes... To clarify (just in case): the "More recently" was comparative to the ideas of "modular programming" (which long preceded main-stream programming - early users of 'unusual languages' such as Algol being possible exceptions). I'd suggest 'modular' was a feature of the ?late seventies? Regardless, I did not mean "more recently", as (perhaps) the twenty-teens decade! I can't recall when I last read Grady Booch. Do any of his later works cite Python examples as their second language? The 'culture' within IT has been changing along with the more noticeable 'rise' and 'fall' of programming languages. Many of the old 'compulsory reading' texts seem so out-of-step with Pythonic thinking. (sadly - but IMHO putting-in the time to read such 'classics' is still a worthwhile investment!) -- Regards =dn From savageapple850 at gmail.com Tue Mar 17 03:20:52 2020 From: savageapple850 at gmail.com (Cravan) Date: Tue, 17 Mar 2020 15:20:52 +0800 Subject: [Tutor] Artificial intelligence trouble Message-ID: <08BF8093-647A-4E23-B04B-7F5EB3DB184A@gmail.com> Hi all, ??????????????? As part of my capstone project, I need to implement an AI. My project is a maze game which works like pac-man except that: It is coded in pygame The enemies can go through walls My ideas for my AI were: To allow coins( and well fixed-territory monsters) to be spawned randomly across the map Or to allow the ai to create random new maps (this can be done in python but I am required to do this in ai) However, I have next to no knowledge on the subject of reinforcement learning and cannot find a suitable tutorial compatible with pygame which teaches me to code out the required programs. Could someone kindly advise me as to what to do next? I have browsed a few tutorials but I don?t seem to actually understand how to use them. Yours sincerely, Cravan From alan.gauld at yahoo.co.uk Tue Mar 17 06:19:08 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 17 Mar 2020 10:19:08 +0000 Subject: [Tutor] =?utf-8?q?Python_scripts=3A_to_use_class_or_not_?= =?utf-8?q?=E2=80=94_what_is_the_best_practice=3F?= In-Reply-To: <9f57a800-5a5b-fde6-f3a1-ad9d985b242d@DancesWithMice.info> References: <9f57a800-5a5b-fde6-f3a1-ad9d985b242d@DancesWithMice.info> Message-ID: On 17/03/2020 04:27, David L Neil via Tutor wrote: > I can't recall when I last read Grady Booch. Do any of his later works > cite Python examples as their second language? No. In his 3rd edition he mentions it as one of the modern languages, but he doesn't use it. The 3rd edition uses C++, Java, Smalltalk and Lisp. The 1st edition used ObjectPascal which is probably the closest to Python in that it has no explicit data hiding. -- 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 Mahmudulhasanabir700978 at outlook.com Tue Mar 17 09:48:46 2020 From: Mahmudulhasanabir700978 at outlook.com (Mahmudul Abir) Date: Tue, 17 Mar 2020 13:48:46 +0000 Subject: [Tutor] I need help with creating my own software using python Message-ID: Sent from Mail for Windows 10 Hi I am Mahmudul hasan abir, I need help in creating my own software using python and install in my laptop. Can someone help me with this. Thanks Mahmudul Hasan Abir From tziny704 at gmail.com Tue Mar 17 10:07:17 2020 From: tziny704 at gmail.com (Genius Pete) Date: Tue, 17 Mar 2020 10:07:17 -0400 Subject: [Tutor] Python Beginner Book Advice Message-ID: Hello! I am a high schooler taking AP CSP and I am about 2 weeks off from school due to coronavirus. My teacher has told us that we will start with the Create Task when we come back, but I only know JavaScript and HTML. I need to learn either Python or Java, and decided to learn about Python. I need to study for those two weeks, so can you please recommend a textbook for beginners and or a step by step guide that would be helpful. Thank you very much, I don?t know whom to contact, but please let me know whom to contact if you don?t know the answer to my problem. Also I have been looking around Automate the Boring Stuff, Python Crash Course, and Invent your own Games with Python. Do you recommend to buy all three of these books for my create task, or stick to one or two? Thanks for your time, Pete P.S: I would like a textbook since I can see it and take notes on it, I don?t want a virtual guide, but if it helps include it with the textbook. From david at lowryduda.com Tue Mar 17 14:46:28 2020 From: david at lowryduda.com (David Lowry-Duda) Date: Tue, 17 Mar 2020 14:46:28 -0400 Subject: [Tutor] Python Beginner Book Advice In-Reply-To: References: Message-ID: <20200317184628.GA5092@icerm-dld> Hello Pete! > I don?t know whom to contact, but please let me know whom to contact > if you don?t know the answer to my problem. Welcome to the exciting world of python! You have found a right place for asking for help. > Also I have been looking around Automate the Boring Stuff, Python > Crash Course, and Invent your own Games with Python. Do you recommend > to buy all three of these books for my create task, or stick to one or > two? The books you have chosen are each a good start. But instead of getting all three (or even two of them), I suggest that you choose one and work through it. If you fully work through it, then move onto a second book. I would suggest that you start with Automate the Boring Stuff. Conveniently you can start right now, since the author has made it freely available online. (If you like it, it would be good to perhaps send him a dollar or two). And remember --- one doesn't learn to program by reading about how others program. It is necessary for you to write code, think about what you're writing, and to experiment. A good follow up book is Think Python (which also happens to be made freely available online by the author). This happens to be quite a good book not just about python, but about programming. And just so that it's all in one place, I'll note that perhaps the best intermediate python book is Fluent Python (not free --- but an excellent book). But this is not a book for the beginner, since the idioms it teaches and goes over are there to sharpen skills and intuition as opposing to forging the blade. Good luck! - DLD -- David Lowry-Duda From PyTutor at DancesWithMice.info Tue Mar 17 15:56:43 2020 From: PyTutor at DancesWithMice.info (DL Neil) Date: Wed, 18 Mar 2020 08:56:43 +1300 Subject: [Tutor] I need help with creating my own software using python In-Reply-To: References: Message-ID: <0ecce635-1291-2006-4b8e-f5bf1e5544b7@DancesWithMice.info> > I am Mahmudul hasan abir, I need help in creating my own software using python and install in my laptop. Can someone help me with this. Sure! The *volunteers* here are very helpful. Help us to help you: what have you achieved so-far? -- Regards =dn From akleider at sonic.net Tue Mar 17 18:13:28 2020 From: akleider at sonic.net (Alex Kleider) Date: Tue, 17 Mar 2020 15:13:28 -0700 Subject: [Tutor] Python Beginner Book Advice In-Reply-To: References: Message-ID: <9c5ee0f5835d88fb26329a67fab36893@sonic.net> On 2020-03-17 07:07, Genius Pete wrote: > Hello! > I am a high schooler taking AP CSP and I am about 2 weeks off from > school > due to coronavirus. My teacher has told us that we will start with the > Create Task when we come back, but I only know JavaScript and HTML. I > need > to learn either Python or Java, and decided to learn about Python. I > need > to study for those two weeks, so can you please recommend a textbook > for > beginners and or a step by step guide that would be helpful. Thank you > very > much, I don?t know whom to contact, but please let me know whom to > contact > if you don?t know the answer to my problem. Also I have been looking > around > Automate the Boring Stuff, Python Crash Course, and Invent your own > Games > with Python. Do you recommend to buy all three of these books for my > create > task, or stick to one or two? My suggestion would be: https://greenteapress.com/wp/think-python-2e/ From alan.gauld at yahoo.co.uk Tue Mar 17 18:22:09 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 17 Mar 2020 22:22:09 +0000 Subject: [Tutor] I need help with creating my own software using python In-Reply-To: References: Message-ID: On 17/03/2020 13:48, Mahmudul Abir wrote: > I am Mahmudul hasan abir, I need help in creating my own software using python Sure. What is your background? Can you program already in Python? Can you program in any other language? Is it learning how to program that puzzles you or how to build full applications? Once we know where you are starting from and where exactly you aim to go then we cam help you plan the journey. > and install in my laptop. Can someone help me with this. Again, sure. But we need to know what you know already. If you need to learn to program, that's a big journey ahead. If you only need to learn Python it is much shorter. And if its only how to package an existing python program then we can get there real quick. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From jf_byrnes at comcast.net Tue Mar 17 16:08:22 2020 From: jf_byrnes at comcast.net (Jim) Date: Tue, 17 Mar 2020 15:08:22 -0500 Subject: [Tutor] Python Beginner Book Advice In-Reply-To: References: Message-ID: On 3/17/20 9:07 AM, Genius Pete wrote: > Hello! > I am a high schooler taking AP CSP and I am about 2 weeks off from school > due to coronavirus. My teacher has told us that we will start with the > Create Task when we come back, but I only know JavaScript and HTML. I need > to learn either Python or Java, and decided to learn about Python. I need > to study for those two weeks, so can you please recommend a textbook for > beginners and or a step by step guide that would be helpful. Thank you very > much, I don?t know whom to contact, but please let me know whom to contact > if you don?t know the answer to my problem. Also I have been looking around > Automate the Boring Stuff, Python Crash Course, and Invent your own Games > with Python. Do you recommend to buy all three of these books for my create > task, or stick to one or two? > > Thanks for your time, > Pete > > P.S: I would like a textbook since I can see it and take notes on it, I > don?t want a virtual guide, but if it helps include it with the textbook. Automate the Boring Stuff versions I & II and as David mentioned in another post, Think Python are available free on line. I don't know if the other books mentioned have a free on line version or not. Since you prefer hard copy I would check out the free on line ones and buy a hard copy of the one that suits your style of learning. Just be sure to get one that covers some version of Python 3. Regards, Jim From PyTutor at DancesWithMice.info Tue Mar 17 21:05:40 2020 From: PyTutor at DancesWithMice.info (David L Neil) Date: Wed, 18 Mar 2020 14:05:40 +1300 Subject: [Tutor] Python Beginner Book Advice In-Reply-To: References: Message-ID: On 18/03/20 3:07 AM, Genius Pete wrote: > Hello! > I am a high schooler taking AP CSP and I am about 2 weeks off from school > due to coronavirus. My teacher has told us that we will start with the > Create Task when we come back, but I only know JavaScript and HTML. I need > to learn either Python or Java, and decided to learn about Python. I need > to study for those two weeks, so can you please recommend a textbook for > beginners and or a step by step guide that would be helpful. Thank you very > much, I don?t know whom to contact, but please let me know whom to contact > if you don?t know the answer to my problem. Also I have been looking around > Automate the Boring Stuff, Python Crash Course, and Invent your own Games > with Python. Do you recommend to buy all three of these books for my create > task, or stick to one or two? > Thanks for your time, > Pete > P.S: I would like a textbook since I can see it and take notes on it, I > don?t want a virtual guide, but if it helps include it with the textbook. Wow, I wonder how many other genii (geniuses) we have here? I'd make a joke about genies (also genii?) but you're probably too young to remember Barbara Eden. Your question about 'how many books' reminds me of the old saw: never take two chronometers to sea. (if they differ, which one do you believe?) In this case, one book is good (implicit quality assumption), two books might be helpful, but having a third is likely to find itself used much less. You need to start with a focus, ie following one book. If something is unclear, having a second volume will enable you to see if 'the same material' presented differently helps your mind go 'click'. However, there are so many sources on-line, if that one book is insufficient, you might as well improve your search-engine key-word selection skills to find alternative presentations - and ultimately, we are here! I learned the language using a book called "Core Python" by Chen. Hundreds of pages long, I describe such tomes as 'sold by the pound'. After sounding like an insult, I have to say I found it very comprehensive. Sadly, my copy is Python2, but I recall that he published an update for Python3. Perhaps you will find details on Amazon or similar? Referring back to the three-books idea: Sixty-North publish a series of books: Python Apprentice, ...Journeyman, and ...Master. (you won't want to purchase all three at once!). These follow a circular or spiral path through Python materials, so as a total picture they exceed your current request - but will 'grow' with you! I can recommend them. I am intrigued by your preference for a "textbook". Most 'modern' educational writing suggests that today's generation of school-kids are "digital natives" and prefer their materials on-screen. (rightly or wrongly). Did you have a particular reason for using the term, or is the medium less important than a cohesive and cumulative presentation? Noting that you already have a response which talks about books available on-line, continuing that idea, would you consider on-line courses from edX, Coursera, etc? Were you implying that video-lectures don't suit you? The earlier advice - don't just read, but practice, is pure-gold! You cannot prove your understanding of Python until you can write code! I would like to add, that highlighting or scribbling in textbook margins is NOT an effective learning technique. Interestingly, making notes on a PC or tablet similarly lacks 'stickability' in the brain. The proven way to learn (from (at least) as far back as my time, and according to current research) is to make notes in a lab-book/log-book. The process of pausing (not so easy during a live-lecture), thinking about the material, forming your own "model", and then (hand) writing notes in your own words; which aids memory. It also facilitates reviewing the material that evening/next day (or very soon but not immediately-after initial writing). The first step helps you to form your own view or 'map' of the material. The second, will more than double the chances that the major points will lodge in long-term memory - ie you will remember it even after this year's exams! One word of warning, if I may: (Cognitive Psychology is my research area) there was a Pop-Psy theory which spread widely through the teaching community, parents, et al; that there are different 'intelligences' (which part we won't debate at this time), which led to the conclusion that different intelligences require different forms of teaching. This last part is *not* proven by serious research. In reality, we need to be able to take any and all information we are given, in whatever form/format/media - and learn from that if we are to survive in a fast-changing world. Accordingly, the aforementioned theory does tremendous damage when people fixate on the idea that they can only learn in one manner or mode. Yes we might have preferences, and yours might well differ from mine, but the fact remains that the IT-business changes so much and so fast, we must 'learn'/stay up-to-date from a veritable fire-hose of information-flow. So, learning-flexibility is a paramount skill! Disclaimers: - I use edX as a training platform, but not in Python - I would receive no commission were you to purchase a book from Amazon, etc - I'm writing this without Internet access, so no web.refs (apologies), but I'm sure you're capable of tracking-down stuff for yourself. -- Regards =dn From stephen.m.smith at comcast.net Tue Mar 17 21:03:33 2020 From: stephen.m.smith at comcast.net (stephen.m.smith at comcast.net) Date: Tue, 17 Mar 2020 21:03:33 -0400 Subject: [Tutor] Python Beginner Book Advice In-Reply-To: References: Message-ID: <011401d5fcc1$0d713bb0$2853b310$@comcast.net> Can't recommend Starting Out with Python by Tony Gaddis strong enough. -----Original Message----- From: Tutor On Behalf Of Jim Sent: Tuesday, March 17, 2020 4:08 PM To: tutor at python.org Subject: Re: [Tutor] Python Beginner Book Advice On 3/17/20 9:07 AM, Genius Pete wrote: > Hello! > I am a high schooler taking AP CSP and I am about 2 weeks off from > school due to coronavirus. My teacher has told us that we will start > with the Create Task when we come back, but I only know JavaScript and > HTML. I need to learn either Python or Java, and decided to learn > about Python. I need to study for those two weeks, so can you please > recommend a textbook for beginners and or a step by step guide that > would be helpful. Thank you very much, I don?t know whom to contact, > but please let me know whom to contact if you don?t know the answer to > my problem. Also I have been looking around Automate the Boring Stuff, > Python Crash Course, and Invent your own Games with Python. Do you > recommend to buy all three of these books for my create task, or stick to one or two? > > Thanks for your time, > Pete > > P.S: I would like a textbook since I can see it and take notes on it, > I don?t want a virtual guide, but if it helps include it with the textbook. Automate the Boring Stuff versions I & II and as David mentioned in another post, Think Python are available free on line. I don't know if the other books mentioned have a free on line version or not. Since you prefer hard copy I would check out the free on line ones and buy a hard copy of the one that suits your style of learning. Just be sure to get one that covers some version of Python 3. Regards, Jim _______________________________________________ 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 Mar 18 06:16:52 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 18 Mar 2020 10:16:52 +0000 Subject: [Tutor] Python Beginner Book Advice In-Reply-To: References: Message-ID: On 17/03/2020 14:07, Genius Pete wrote: > Create Task when we come back, but I only know JavaScript and HTML. I need > to learn either Python or Java, and decided to learn about Python. I need > to study for those two weeks, so can you please recommend a textbook First, learn python 3. Make sure your book is based on that. Second don't ignore the tutorial on the Python web site - it is kept up to date with new releases whereas books will always become out of date in the details. My recommendation for a Python 3 beginner is Mark Sommerville's "Programming in Python 3" from Addison Wesley. In addition to the core language it covers a wide range of topics beyond the basics but without going too deep. I found his style very readable. And of course, if you have any questions come back here... PS. You could also try my tutorial(see below)... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From adii0617 at gmail.com Wed Mar 18 08:33:24 2020 From: adii0617 at gmail.com (=?utf-8?Q?Adam_=C5=81uszcz?=) Date: Wed, 18 Mar 2020 13:33:24 +0100 Subject: [Tutor] Python Programming for the Absolute Beginner - Chap 7 Q: 2 Message-ID: <8A51B6CA-6C4C-42B0-849A-DC114AA7BACC@gmail.com> Hey I've jus found your post about help in .py chellenge 2 chapter 7. [below] I got one qustion. Did you resolve that problem ? Please if its possible Could you sent me a solve that problem ? Thanks def high_score(): """Records a player's score""" high_scores = [] #add a score // Do current stuff for adding a new score... name = input("What is your name? ") player_score = int(input("What is your score? ")) entry = (name, player_score) high_scores.append(entry) high_scores.sort(reverse=True) high_scores = high_scores[:5] # keep only top five # dump scores f = open("pickles1.dat", "wb") pickle.dump(high_scores, f) f.close() f = open("pickles1.dat", "rb") high_scores = pickle.load(f) print(high_scores) f.close() When I execute this program in the main() program I get only the existing single name, player_score list combination stored in the pickles1.dat file. From alan.gauld at yahoo.co.uk Wed Mar 18 13:37:14 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 18 Mar 2020 17:37:14 +0000 Subject: [Tutor] Python Programming for the Absolute Beginner - Chap 7 Q: 2 In-Reply-To: <8A51B6CA-6C4C-42B0-849A-DC114AA7BACC@gmail.com> References: <8A51B6CA-6C4C-42B0-849A-DC114AA7BACC@gmail.com> Message-ID: On 18/03/2020 12:33, Adam ?uszcz wrote: > def high_score(): > > """Records a player's score""" > high_scores = [] Note that this creates a new empty list. > > #add a score // Do current stuff for adding a new score... > name = input("What is your name? ") > player_score = int(input("What is your score? ")) > entry = (name, player_score) > high_scores.append(entry) > high_scores.sort(reverse=True) > high_scores = high_scores[:5] # keep only top five > > # dump scores > f = open("pickles1.dat", "wb") > pickle.dump(high_scores, f) > f.close() Despite the comments the above code only stores a single name.... It overwrites anything else that may have been in the file. > f = open("pickles1.dat", "rb") > high_scores = pickle.load(f) > print(high_scores) > f.close() And this reads it back. > When I execute this program in the main() program I get only the existing > single name, player_score list combination stored in the pickles1.dat file. What else did you expect to get? Only one name is stored and therefore only one name is read. -- 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 andre.luis.m.pinto at gmail.com Thu Mar 19 05:42:49 2020 From: andre.luis.m.pinto at gmail.com (=?iso-8859-1?Q?Andr=E9_Pinto?=) Date: Thu, 19 Mar 2020 06:42:49 -0300 Subject: [Tutor] Only one value different columns Message-ID: <004601d5fdd2$c28e1ab0$47aa5010$@gmail.com> I have a dataset with 22500 items (rows) and most rows show columns withX the same values. It is like this: Item col1 col2 col 3 col 4 col5 XYZ 4 4 4 PQR 12 12 ... 22500 rows I need so: Item col1 col2 col 3 col 4 col5 XYZ 4 PQR 12 ... 22500 rows How can I keep only one value per row, determining the column I want with the respective value. Note: for each line the column I want to keep the value changes. It is possible? Com os cumprimentos Best Regards Atentos Saludos Andr? Lu?s M. Pinto * +55 (71) 98802-6841 Skype ID: andre.luis.m.pinto at outlook.com P Antes de imprimir pense em seu comprimisso com o Meio Ambiente. -- Este email foi escaneado pelo Avast antiv?rus. https://www.avast.com/antivirus From alan.gauld at yahoo.co.uk Thu Mar 19 06:53:43 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 19 Mar 2020 10:53:43 +0000 Subject: [Tutor] Only one value different columns In-Reply-To: <004601d5fdd2$c28e1ab0$47aa5010$@gmail.com> References: <004601d5fdd2$c28e1ab0$47aa5010$@gmail.com> Message-ID: On 19/03/2020 09:42, Andr? Pinto wrote: > I have a dataset with 22500 items (rows) and most rows show columns withX > the same values. Most? Or always? > It is like this: > > Item col1 col2 col 3 col 4 col5 > XYZ 4 4 4 > PQR 12 12 > I need so: > > Item col1 col2 col 3 col 4 col5 > XYZ 4 > PQR 12 It is not obvious from that which column the output should use. Is it always the same column that the second instance of the value was originally in? Or is that just coincidence in your example? > How can I keep only one value per row, determining the column I want with > the respective value. Yes, provided you can define the rules. We have insufficient knowledge to do so. But you can write a function that will process the row and return a new row. > Note: for each line the column I want to keep the value changes. > It is possible? Of course provided you have a set of rules (or an equation) that predicts which column. Or a table of column against row. You can encapsulate that within another function which is called by the row processing function. Your top level function will look something like: for row in data: results.append(process(row) and process(row) will extract the value, calculate the required column (using your helper function) and build a new output row using those values and return 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 Richard at Damon-Family.org Thu Mar 19 08:21:08 2020 From: Richard at Damon-Family.org (Richard Damon) Date: Thu, 19 Mar 2020 08:21:08 -0400 Subject: [Tutor] Only one value different columns In-Reply-To: <004601d5fdd2$c28e1ab0$47aa5010$@gmail.com> References: <004601d5fdd2$c28e1ab0$47aa5010$@gmail.com> Message-ID: <786d8db7-42a5-27c1-33c3-79a355599372@Damon-Family.org> On 3/19/20 5:42 AM, Andr? Pinto wrote: > I have a dataset with 22500 items (rows) and most rows show columns withX > the same values. > > > > It is like this: > > Item col1 col2 col 3 col 4 col5 > > XYZ 4 4 4 > > PQR 12 12 > > ... > > 22500 rows > > > > I need so: > > Item col1 col2 col 3 col 4 col5 > > XYZ 4 > > PQR 12 > > ... > > 22500 rows > > > > How can I keep only one value per row, determining the column I want with > the respective value. > > Note: for each line the column I want to keep the value changes. > > It is possible? > > > > > > Com os cumprimentos > > Best Regards > > Atentos Saludos > > > > Andr? Lu?s M. Pinto > > * +55 (71) 98802-6841 > > Skype ID: > andre.luis.m.pinto at outlook.com > > P Antes de imprimir pense em seu comprimisso com o Meio Ambiente. > > If you ALWAYS are going to have only one 'value' per row, it may be better to define your dataset so each row has 3 fields, The Item The 'column' The Value -- Richard Damon From chamblin850 at gmail.com Thu Mar 19 15:52:48 2020 From: chamblin850 at gmail.com (Curt Hamblin) Date: Thu, 19 Mar 2020 14:52:48 -0500 Subject: [Tutor] using dictionaries Message-ID: I'm not the sharpest knife in the drawer, but I cannot understand why one works and the other doesn't -------------- next part -------------- parts_in_inv_dict {37163: 2, 37869: 3, 37871: 2, 39331: 5, 39385: 1, 40172: 1, 40181: 1, 40525: 4, 40764: 1, 40864: 1, 40868: 1, 40869: 1, 40871: 2, 40885: 4, 40887: 2, 41921: 1, 42297: 1, 46070: 1, 46078: 2, 46088: 1, 46089: 2, 47083: 1, 49127: 2, 54851: 1, 54857: 1, 54862: 1, 54863: 1, 55025: 1, 55148: 1, 55614: 1, 56725: 1} need = {} need[40885] = 9 need[37869] = 3 need[46041] = 1 print ('Need dictionary = ',need) print('Belt Counter == ', belt_dict) Need dictionary = {40885: 9, 37869: 3, 46041: 1} Belt Counter == Counter({'40885': 9, '37869': 3, '46041': 1}) print (' ================================================') #print('Need') print('Uses Need dictionary -----------------------------') for x_key,y_value in need.items(): print(x_key,y_value) print(inv_dict.get(x_key,' no idea why this does NOT work')) print(x_key,y_value,inv_dict.get(x_key,'Not in inventory')) print() print ( '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=---') c = belt_dict dict(c) print('Uses belt_dict Counter ') for x_key,y_value in c.items(): print(x_key,y_value) print(inv_dict.get(x_key,' key only')) print(x_key,y_value,inv_dict.get(x_key,'Not in inventory')) print() results of running this code Uses Need dictionary ---- Works as expected ------------------------- 40885 9 4 40885 9 4 37869 3 3 37869 3 3 46041 1 no idea why this does NOT work 46041 1 Not in inventory -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--- Does NOT Work Uses belt_dict Counter 40885 9 key only 40885 9 Not in inventory 37869 3 key only 37869 3 Not in inventory 46041 1 key only 46041 1 Not in inventory From chamblin850 at gmail.com Thu Mar 19 16:17:46 2020 From: chamblin850 at gmail.com (Curt Hamblin) Date: Thu, 19 Mar 2020 15:17:46 -0500 Subject: [Tutor] Can't be that difficult Message-ID: I have two dictionaries: inv (partNbr(key):qtyOnHand(value),? #inventory need (partNbr(key):qtyNeeded(value)? # parts needed for job the question to answer is :? what's in inventory, what has to be ordered For code : for partNbr,qtyNeeded in need.items(): ???? print(partNbr, qtyNeeded, inv.get(partNbr,'Not in inventory')) desired output : ?12345 4? 8 23456? 3?? 2 34567 2? 'Not in Inventory' this code ALWAYS returns 'Not in Inventory' From roch_camo89 at hotmail.com Thu Mar 19 15:43:18 2020 From: roch_camo89 at hotmail.com (Rodrigo Camacho) Date: Thu, 19 Mar 2020 19:43:18 +0000 Subject: [Tutor] Dice game problems Message-ID: To whom it may concern: I?m a newcomer in PHYTON programing so as you may have experienced, one of the first excersises that beginners are recommended to do (Lantangen P. Python Scripting for Computational Science) is to simulate a dice rolling game and calculate the probability of getting the number 6 after a certain amout of rolls. My idea was, instead of doing it by testing diffrent amount of rolls, use an infinite loop to roll the dice n number of times and when a 6 is obtained, use a counter to register it. Parelly, the probability is calculated as p=n/t, where t is a second counter that registers the amount of rolls that had to be made in order to obtain the correspondent 6?s. The script I proposed was the following: import random n=float(input(?Introduce the number 3 to start the program?)) r=random.randint(1,6)---------------------------------Indentation error t=0 s=0 p=0 P=0 while n==3: t+=1 print() print(r) print() if r==6: s+=1 p=s/t P=round(P,3) elif P==0.306:-----------------------------Syntax problem break print(?The number of times the dice had to be rolled to obtain a probability value of 0.306 is ?+str(t)+) Two main erros were obtained: Syntax error and indentation. I?ve been trying to find information about how to correct the mentioned problems. However, the solutions proposed haven?t worked for me. I also have tried to separate the script by using functions but I still get the same errors. Most of the tutorials I found in sources like YOUTUBE, use a FOR loop. However, for learning purposes, I insisted in using a WHILE loop. Thanks a lot for your help. Arthur C. From mats at wichmann.us Thu Mar 19 16:52:01 2020 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 19 Mar 2020 14:52:01 -0600 Subject: [Tutor] Can't be that difficult In-Reply-To: References: Message-ID: On 3/19/20 2:17 PM, Curt Hamblin wrote: > I have two dictionaries: > > inv (partNbr(key):qtyOnHand(value),? #inventory > > need (partNbr(key):qtyNeeded(value)? # parts needed for job > > the question to answer is :? what's in inventory, what has to be ordered > > For code : > > for partNbr,qtyNeeded in need.items(): > > ???? print(partNbr, qtyNeeded, inv.get(partNbr,'Not in inventory')) There's nothing visually wrong with your two-line snip here. We can't see what else could be wrong, because you only excerpted your program. > > > > desired output : > > ?12345 4? 8 > > 23456? 3?? 2 > > 34567 2? 'Not in Inventory' > > this code ALWAYS returns 'Not in Inventory' > > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From mats at wichmann.us Thu Mar 19 16:54:44 2020 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 19 Mar 2020 14:54:44 -0600 Subject: [Tutor] Can't be that difficult In-Reply-To: References: Message-ID: <228e8be1-0d8a-6c44-bbed-76846858e9d5@wichmann.us> On 3/19/20 2:52 PM, Mats Wichmann wrote: > There's nothing visually wrong with your two-line snip here. > > We can't see what else could be wrong, because you only excerpted your > program. ah, that was supposed to be the same as your previous message with the attachment. there, it's easy to see what is wrong: Need dictionary = {40885: 9, 37869: 3, 46041: 1} Belt Counter == Counter({'40885': 9, '37869': 3, '46041': 1}) Need uses integer keys. Belt Counter uses string keys. Those won't compare equal... From PyTutor at DancesWithMice.info Thu Mar 19 18:10:30 2020 From: PyTutor at DancesWithMice.info (David L Neil) Date: Fri, 20 Mar 2020 11:10:30 +1300 Subject: [Tutor] using dictionaries In-Reply-To: References: Message-ID: <6fe775c4-6ca2-ca42-b132-969154c6426a@DancesWithMice.info> On 20/03/20 8:52 AM, Curt Hamblin wrote: > I'm not the sharpest knife in the drawer, but I cannot understand why > one works and the other doesn't Before causing us to sharpen our knives (the Ides of March has passed!), please copy-paste your code and any error messages (Tracebacks), ie straight from the terminal window into the email msg. There are a number of inconsistencies in the code-presented, and it is confused by in-line comments which are not preceded by # eg "Belt Counter == Counter({'40885': 9, '37869': 3, '46041': 1})" is not legal Python and requires the collections library be imported (I assume) add to the above line of 'code': c = belt_dict dict(c) print('Uses belt_dict Counter ') and the multiple terms (for what I assume is the same collection of values) becomes confusing to simple-minds (like mine). The "dict(c)" is unused (and unusable). Right, now that I've grumped (more than) enough: Please take a look at the keys and values in "parts_in_inv_dict"/"inv_dict". What data-type(s) are they - are these (both) integers, strings, floats, booleans, ...or what? Similarly, inspect "Belt Counter"/"c"/"belt_dict". What data-types are used here? Spotted the difference? NB in Python: 40885 != '40885' -- Regards =dn From alan.gauld at yahoo.co.uk Thu Mar 19 20:16:28 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 20 Mar 2020 00:16:28 +0000 Subject: [Tutor] Dice game problems In-Reply-To: References: Message-ID: On 19/03/2020 19:43, Rodrigo Camacho wrote: > The script I proposed was the following: Please post the code in plain text. The email system has stripped the spacing out of the code below making it impossible to debug. Also please include the full error messages - they contain a lot of information, your summary tells us very little. > import random > > n=float(input(?Introduce the number 3 to start the program?)) > > r=random.randint(1,6)---------------------------------Indentation error > > t=0 > > s=0 > > p=0 > > P=0 > > while n==3: > > t+=1 > > print() > > print(r) > > print() > > if r==6: > > s+=1 > > p=s/t > > P=round(P,3) > > elif P==0.306:-----------------------------Syntax problem > > break > > print(?The number of times the dice had to be rolled to obtain a probability value of 0.306 is ?+str(t)+) > > Two main erros were obtained: Syntax error and indentation. We need the whole message, not just a summary. And how did you manage to get two errors so far apart? Usually python stops at the first error. > Most of the tutorials I found in sources like YOUTUBE, use a FOR loop. > However, for learning purposes, I insisted in using a WHILE loop. You can use either loop, for is usually more convenient and considered better Python style for processing collections. But for 'infinite' loops while is preferred. -- 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 PyTutor at DancesWithMice.info Thu Mar 19 22:37:09 2020 From: PyTutor at DancesWithMice.info (DL Neil) Date: Fri, 20 Mar 2020 15:37:09 +1300 Subject: [Tutor] using dictionaries In-Reply-To: References: <6fe775c4-6ca2-ca42-b132-969154c6426a@DancesWithMice.info> Message-ID: On 20/03/20 11:46 AM, Curt Hamblin wrote: > Thanks for responding. the problem was the string / integer comparison. > To soon old, to late smart.? I had to have someone else to point it out > to me. But it's fixed and working now, with only my pride being hurt. You got it! Don't be too bothered: it's a typical 'can't see the wood for the trees' issue. I suspect (am I allowed to say, "hope"?) that we will have many more 'beginners' appearing on the list, taking advantage of virus down-time and using it to learn Python. You'll be able to lend them a hand... -- Regards =dn From robertvstepp at gmail.com Thu Mar 19 22:37:32 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Thu, 19 Mar 2020 21:37:32 -0500 Subject: [Tutor] Python Beginner Book Advice In-Reply-To: References: Message-ID: On Wed, Mar 18, 2020 at 5:22 AM Alan Gauld via Tutor wrote: > > My recommendation for a Python 3 beginner is > Mark Sommerville's "Programming in Python 3" from Addison Wesley. Did you mean Mark Summerfield? -- boB From PyTutor at danceswithmice.info Thu Mar 19 22:52:26 2020 From: PyTutor at danceswithmice.info (DL Neil) Date: Fri, 20 Mar 2020 15:52:26 +1300 Subject: [Tutor] Python Beginner Book Advice In-Reply-To: References: Message-ID: <75d8dc0f-4e06-b6d7-a18f-2bfc36ee3311@DancesWithMice.info> On 20/03/20 3:37 PM, boB Stepp wrote: > On Wed, Mar 18, 2020 at 5:22 AM Alan Gauld via Tutor wrote: > >> >> My recommendation for a Python 3 beginner is >> Mark Sommerville's "Programming in Python 3" from Addison Wesley. > > Did you mean Mark Summerfield? Yes he did, and in an earlier post I misspelled Wesley Chun's name. In both cases though, the book is almost ten years old. Whilst I have used both (Chun's dates back to v1, and Summerfield's as a two-to-three assistance), I would criticise the latter as a new-learner's tool. The first chapter is called "Rapid Introduction to Procedural Programming", which rather neatly summarises the point. I'm not sure that I would have enjoyed it so much, were I completely-new to Python at the time. WebRefs: https://www.pearson.com/us/higher-education/program/Summerfield-Programming-in-Python-3-A-Complete-Introduction-to-the-Python-Language-2nd-Edition/PGM156621.html http://corepython.com/ -- Regards =dn From alan.gauld at yahoo.co.uk Fri Mar 20 05:53:20 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 20 Mar 2020 09:53:20 +0000 Subject: [Tutor] Python Beginner Book Advice In-Reply-To: References: Message-ID: On 20/03/2020 02:37, boB Stepp wrote: > On Wed, Mar 18, 2020 at 5:22 AM Alan Gauld via Tutor wrote: > >> >> My recommendation for a Python 3 beginner is >> Mark Sommerville's "Programming in Python 3" from Addison Wesley. > > Did you mean Mark Summerfield? oops, yes. Mark Summerville was an old colleague! :-) A slip of the keys -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Mar 20 05:58:50 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 20 Mar 2020 09:58:50 +0000 Subject: [Tutor] Python Beginner Book Advice In-Reply-To: <75d8dc0f-4e06-b6d7-a18f-2bfc36ee3311@DancesWithMice.info> References: <75d8dc0f-4e06-b6d7-a18f-2bfc36ee3311@DancesWithMice.info> Message-ID: On 20/03/2020 02:52, DL Neil via Tutor wrote: > On 20/03/20 3:37 PM, boB Stepp wrote: >>> Mark Sommerville's "Programming in Python 3" from Addison Wesley. > assistance), I would criticise the latter as a new-learner's tool. The > first chapter is called "Rapid Introduction to Procedural Programming", Its not for newbies to programming that's for sure. But the OP said they knew Javascript so I figured it would be OK for a transitioning programmer. -- 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 danrieder312 at gmail.com Sun Mar 22 08:18:21 2020 From: danrieder312 at gmail.com (D Rizdek) Date: Sun, 22 Mar 2020 08:18:21 -0400 Subject: [Tutor] I'm new to Python too Message-ID: Arthur C. I'm new to Python too and signed up to be able to post email questions, so I get email questions. I probably deleted one of your earlier questions and all I have is the rsp from Alan. I copied your program and got it to work run...ie no error messages...but it just loops continually. How did you envision r being updated within the while loop? It is initialized at the beginning in the r=random stmt, but not in the while loop. I assume you want to keep checking to see when a 6 is "rolled" and use how long it took...how many loops to calculate some sort of probability, right? I inserted an r=random.randint(1,6) so it keeps generating new "rolls" of a die and checks if it is a 6 each time. Why do you think P would ever actually == .306? That is the only way it will break out of the while loop. Maybe that is why it just keeps looping...it is almost certain it will run for a long time before it happens to produce exactly .306. And so what if it did? How does the program keep track of P from one loop to the next? Wouldn't you need to do something like that then use that to estimate some sort of probability? Dan . From iamsatyabrata428 at gmail.com Sun Mar 22 11:10:47 2020 From: iamsatyabrata428 at gmail.com (SATYABRATA DATTA) Date: Sun, 22 Mar 2020 20:40:47 +0530 Subject: [Tutor] TypeError: unsupported operand type(s) Message-ID: def x1(ap,dp,ph,e1,e2,e3,e4,e5,y): if Delta(ap,dp,ph,e1,e2,e3,e4,e5,y) >= 0: return 2*(b(ap,dp,ph,e1,e2,e3,e4,e5,y)**3) - 9*a*b(ap,dp,ph,e1,e2,e3,e4,e5,y)*c(ap,dp,ph,e1,e2,e3,e4,e5,y) + 27*(a**2)*d(ap,dp,ph,e1,e2,e3,e4,e5,y) else: return None def y1(ap,dp,ph,e1,e2,e3,e4,e5,y): if Delta(ap,dp,ph,e1,e2,e3,e4,e5,y) >= 0: return 3*np.sqrt(3)*a*np.sqrt(Delta(ap,dp,ph,e1,e2,e3,e4,e5,y)) else: return None This is creating a problem return np.sqrt(x1(ap,dp,ph,e1,e2,e3,e4,e5,y)**2+y1(ap,dp,ph,e1,e2,e3,e4,e5,y)**2) TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'int' I think the main problem is due to the condition for Delta>=0 which returns a None value for some input dataset but I only need the Delta>=0 condition values From alan.gauld at yahoo.co.uk Sun Mar 22 12:31:12 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 22 Mar 2020 16:31:12 +0000 Subject: [Tutor] TypeError: unsupported operand type(s) In-Reply-To: References: Message-ID: On 22/03/2020 15:10, SATYABRATA DATTA wrote: > def x1(ap,dp,ph,e1,e2,e3,e4,e5,y): > if Delta(ap,dp,ph,e1,e2,e3,e4,e5,y) >= 0: > return 2*(b(ap,dp,ph,e1,e2,e3,e4,e5,y)**3) - > 9*a*b(ap,dp,ph,e1,e2,e3,e4,e5,y)*c(ap,dp,ph,e1,e2,e3,e4,e5,y) + > 27*(a**2)*d(ap,dp,ph,e1,e2,e3,e4,e5,y) > else: > return None > np.sqrt(x1(ap,dp,ph,e1,e2,e3,e4,e5,y)**2+y1(ap,dp,ph,e1,e2,e3,e4,e5,y)**2) > TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'int' > > > I think the main problem is due to the condition for Delta>=0 which returns > a None value for some input dataset but I only need the Delta>=0 condition > values You are correct. So you need to construct the code to do something if the return value is None (or return some other value) What should your code do if Delta < 0? And if delta should not be less than 0 what is making it so? Alternatively, if you just want to ignore the error you could wrap your code in a try/except block, but then you run the risk of ignoring other valid Typeerrors.... Only you can decide what the correct behaviour is! -- 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 PyTutor at danceswithmice.info Sun Mar 22 12:36:53 2020 From: PyTutor at danceswithmice.info (DL Neil) Date: Mon, 23 Mar 2020 05:36:53 +1300 Subject: [Tutor] TypeError: unsupported operand type(s) In-Reply-To: References: Message-ID: On 23/03/20 4:10 AM, SATYABRATA DATTA wrote: > def x1(ap,dp,ph,e1,e2,e3,e4,e5,y): > if Delta(ap,dp,ph,e1,e2,e3,e4,e5,y) >= 0: > return 2*(b(ap,dp,ph,e1,e2,e3,e4,e5,y)**3) - > 9*a*b(ap,dp,ph,e1,e2,e3,e4,e5,y)*c(ap,dp,ph,e1,e2,e3,e4,e5,y) + > 27*(a**2)*d(ap,dp,ph,e1,e2,e3,e4,e5,y) > else: > return None > def y1(ap,dp,ph,e1,e2,e3,e4,e5,y): > if Delta(ap,dp,ph,e1,e2,e3,e4,e5,y) >= 0: > return 3*np.sqrt(3)*a*np.sqrt(Delta(ap,dp,ph,e1,e2,e3,e4,e5,y)) > else: > return None > > This is creating a problem > > return > np.sqrt(x1(ap,dp,ph,e1,e2,e3,e4,e5,y)**2+y1(ap,dp,ph,e1,e2,e3,e4,e5,y)**2) > TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'int' > > > I think the main problem is due to the condition for Delta>=0 which returns > a None value for some input dataset but I only need the Delta>=0 condition > values At one time our programming languages gave us no choice but to return 'flags' in some cases and valid-output in others. These days to avoid the frequent errors experienced working this way, the principle is to only ever return one type of data - not sometimes a float and sometimes None (etc). Be aware that in Python, "exceptions" are not necessarily "errors". Thus, if the provided-data suits your analysis, there's no problem; but if it does not meet the criteria, 'exception[al] processing' side-steps the analysis, perhaps by dropping that data-set, without halting execution. To solve this problem, if the data does not suit your (current) analysis, raise a custom exception within the function. In the 'mainline' code, "wrap" the function calls within a try...except block, thus handling 'good data' situations differently from 'bad data'. -- Regards =dn From iamsatyabrata428 at gmail.com Sun Mar 22 16:19:04 2020 From: iamsatyabrata428 at gmail.com (SATYABRATA DATTA) Date: Mon, 23 Mar 2020 01:49:04 +0530 Subject: [Tutor] TypeError: unsupported operand type(s) In-Reply-To: References: Message-ID: The main thing I have to do to take only the meaningful values for my problem and which are only those which satisfies Delta>=0 (I want to skip the negative Deltas). How to write that in my code On Sun, 22 Mar, 2020, 8:40 PM SATYABRATA DATTA, wrote: > def x1(ap,dp,ph,e1,e2,e3,e4,e5,y): > if Delta(ap,dp,ph,e1,e2,e3,e4,e5,y) >= 0: > return 2*(b(ap,dp,ph,e1,e2,e3,e4,e5,y)**3) - > 9*a*b(ap,dp,ph,e1,e2,e3,e4,e5,y)*c(ap,dp,ph,e1,e2,e3,e4,e5,y) + > 27*(a**2)*d(ap,dp,ph,e1,e2,e3,e4,e5,y) > else: > return None > def y1(ap,dp,ph,e1,e2,e3,e4,e5,y): > if Delta(ap,dp,ph,e1,e2,e3,e4,e5,y) >= 0: > return 3*np.sqrt(3)*a*np.sqrt(Delta(ap,dp,ph,e1,e2,e3,e4,e5,y)) > else: > return None > > This is creating a problem > > return > np.sqrt(x1(ap,dp,ph,e1,e2,e3,e4,e5,y)**2+y1(ap,dp,ph,e1,e2,e3,e4,e5,y)**2) > TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and > 'int' > > > I think the main problem is due to the condition for Delta>=0 which > returns a None value for some input dataset but I only need the Delta>=0 > condition values > From alan.gauld at yahoo.co.uk Sun Mar 22 21:32:56 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 23 Mar 2020 01:32:56 +0000 Subject: [Tutor] TypeError: unsupported operand type(s) In-Reply-To: References: Message-ID: On 22/03/2020 20:19, SATYABRATA DATTA wrote: > The main thing I have to do to take only the meaningful values for my > problem and which are only those which satisfies Delta>=0 (I want to skip > the negative Deltas). How to write that in my code In that case, we can assume that a negative Delta value is due to faulty input data? So, as david suggested, it would be reasonable to raise a ValueError in your code if such an event occurred. >> def x1(ap,dp,ph,e1,e2,e3,e4,e5,y): >> if Delta(ap,dp,ph,e1,e2,e3,e4,e5,y) >= 0: >> return 2*(b(ap,dp,ph,e1,e2,e3,e4,e5,y)**3) - >> 9*a*b(ap,dp,ph,e1,e2,e3,e4,e5,y)*c(ap,dp,ph,e1,e2,e3,e4,e5,y) + >> 27*(a**2)*d(ap,dp,ph,e1,e2,e3,e4,e5,y) >> else: raise Valueerror("Delta returned negative result") try: np.sqrt(x1(ap,dp,ph,e1,e2,e3,e4,e5,y)**2+y1(ap,dp,ph,e1,e2,e3,e4,e5,y)**2) except ValueError: # do something here? or log the faulty data values or just pass # do nothing. raise # or reraise the error after logging That way your function never returns an invalid value. It either returns a float or throws an exception which you can catch and do with it as you will. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From robertvstepp at gmail.com Sun Mar 22 23:27:53 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 22 Mar 2020 22:27:53 -0500 Subject: [Tutor] I'm new to Python too In-Reply-To: References: Message-ID: On Sun, Mar 22, 2020 at 8:45 AM D Rizdek wrote: > > Arthur C. > > I'm new to Python too and signed up to be able to post email questions, so > I get email questions. I probably deleted one of your earlier questions > and all I have is the rsp from Alan. I don't know about the thread you are referring to, but if you wish to see the whole thread Tutor has an archive location at: https://mail.python.org/pipermail/tutor/ Hope this is of interest to you. It would be better for your questions if you could cite the code fragments being referenced so we have context. The archive would help you do that. Cheers! -- boB From gramirez32 at fordham.edu Mon Mar 23 18:57:52 2020 From: gramirez32 at fordham.edu (Garismar Ramirez) Date: Mon, 23 Mar 2020 18:57:52 -0400 Subject: [Tutor] Problem with my idle Message-ID: Hello, I have a MacBook pro-2017. When I try to save a file on idle, it freezes (the idle program everything else on my computer is fine). Why is this and how can i resolve this issue? Best regards G Ramirez. From lea.koeppel at gmx.net Tue Mar 24 04:42:54 2020 From: lea.koeppel at gmx.net (=?UTF-8?Q?=22Lea_K=C3=B6ppel=22?=) Date: Tue, 24 Mar 2020 09:42:54 +0100 Subject: [Tutor] question Message-ID: Dear Madam/Sir of the Python Handbook I have the task below and would be very grateful if you could answer me. Thank you very much for your efforts. Sincerely, Lea K?ppel ? ? Recall If a Min-Heap is stored in an array C with 1-based indices, then for all i the entry C[i] must be smaller than (or equal to) its two children entries C[2?i]?and?C[2?i+1] . Concatenating Min-Heaps Let's look at two Min-Heaps A and B of size n and m, respectively. We assume that each element of A is smaller than all the elements of B (formally: ?i,j:A[i] References: Message-ID: On 24/03/2020 08:42, "Lea K?ppel" wrote: > Dear Madam/Sir of the Python Handbook > I have the task below and would be very grateful if you could answer me. Thank you very much for your efforts. > Sincerely, Lea K?ppel This doesn't appear to be a Python problem, rather a bit of theoretical Computing Science. As such, a math approach is probably more appropriate than a programming one. You could certainly construct some test cases in Python but they would not prove the general case. -- 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 joel.goldstick at gmail.com Tue Mar 24 07:36:51 2020 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 24 Mar 2020 07:36:51 -0400 Subject: [Tutor] question In-Reply-To: References: Message-ID: On Tue, Mar 24, 2020 at 5:58 AM "Lea K?ppel" wrote: > > Dear Madam/Sir of the Python Handbook > I have the task below and would be very grateful if you could answer me. Thank you very much for your efforts. > Sincerely, Lea K?ppel > > Welcome Lea. This is a group of python interested people of varying levels of expertise. A play to ask questions about code, and how python works. Its a voluntary thing. That said, your question looks like a homework assignment. People here don't provide answers to homework assignments, but often provide guidance or help to get you started. Since your problem is not a coding question, and really isn't specific to python. It is more of what I would call a 'computer science question'. > > > > Recall > > If a Min-Heap is stored in an array C > > with 1-based indices, then for all i the entry C[i] must be smaller than > (or equal to) its two children entries C[2?i] and C[2?i+1] > > . > > Concatenating Min-Heaps > > Let's look at two Min-Heaps A > > and B of size n and m, respectively. We assume that each element of A is > smaller than all the elements of B (formally: ?i,j:A[i] be the array of size n+m which we get as a concatenation of A and B, > meaning that C is given by C[i]=A[i] if i?n and C[i]=B[i?n] > > otherwise. > > Question: > > Is it clear that C > > is a Min-Heap as well? If yes, argue why, otherwise find a counterexample. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays From mats at wichmann.us Tue Mar 24 10:50:19 2020 From: mats at wichmann.us (Mats Wichmann) Date: Tue, 24 Mar 2020 08:50:19 -0600 Subject: [Tutor] Problem with my idle In-Reply-To: References: Message-ID: <42908fc5-6af8-42e6-87c6-f91fe654d0f8@wichmann.us> On 3/23/20 4:57 PM, Garismar Ramirez wrote: > Hello, > > I have a MacBook pro-2017. When I try to save a file on idle, it freezes > (the idle program everything else on my computer is fine). Why is this and > how can i resolve this issue? You'd have to check with the IDLE experts on that. I see some hints that you're not alone... https://bugs.python.org/issue34120 that particular issue is claimed to be resolved, but you might do some more mining. possible workaround: don't use IDLE. There are a *ton* of Python editors/IDEs, a large number of them free. Many are listed here: https://wiki.python.org/moin/IntegratedDevelopmentEnvironments https://wiki.python.org/moin/PythonEditors From iamsatyabrata428 at gmail.com Thu Mar 26 17:16:48 2020 From: iamsatyabrata428 at gmail.com (SATYABRATA DATTA) Date: Fri, 27 Mar 2020 02:46:48 +0530 Subject: [Tutor] How to convert the fortran logic to python definition Message-ID: delta=18.*a*b*c*d-4.*(b**3)*d+b**2*c**2-4.*a*c**3-27.*a**2*d**2 print *, delta, a, b, c, d,d1 if(delta.gt.0.)then x=2.*b**3-9.*a*b*c+27.*a**2*d y=3.*sqrt(3.)*a*sqrt(delta) if((x.lt.0.and.y.lt.0).or.(x.lt.0.and.y.gt.0))then nii=2 else nii=0 endif How to convert this fortran logic to python where delta(a,b,c,d) should return x(a,b,c,d) and y(a,b,c,d) for the next job when satisfied the conditions From PyTutor at danceswithmice.info Thu Mar 26 19:00:00 2020 From: PyTutor at danceswithmice.info (DL Neil) Date: Fri, 27 Mar 2020 12:00:00 +1300 Subject: [Tutor] How to convert the fortran logic to python definition In-Reply-To: References: Message-ID: <5fe5329c-8798-e2d0-20b4-109c9251d473@DancesWithMice.info> On 27/03/20 10:16 AM, SATYABRATA DATTA wrote: > delta=18.*a*b*c*d-4.*(b**3)*d+b**2*c**2-4.*a*c**3-27.*a**2*d**2 > print *, delta, a, b, c, d,d1 > if(delta.gt.0.)then > x=2.*b**3-9.*a*b*c+27.*a**2*d > y=3.*sqrt(3.)*a*sqrt(delta) > if((x.lt.0.and.y.lt.0).or.(x.lt.0.and.y.gt.0))then > nii=2 > else > nii=0 > endif > How to convert this fortran logic to python where delta(a,b,c,d) > should return x(a,b,c,d) and y(a,b,c,d) for the next job when > satisfied the conditions As requested previously, please copy-paste actual code, because the above has become unnecessarily hard to comprehend. I'm not sure that I've correctly understood your question. The logic does NOT need to change. The two languages/code-snippets are/will be remarkably similar. Are you actually asking that someone to write the Python code for you? -- Regards =dn From alan.gauld at yahoo.co.uk Thu Mar 26 19:15:41 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 26 Mar 2020 23:15:41 +0000 Subject: [Tutor] How to convert the fortran logic to python definition In-Reply-To: References: Message-ID: On 26/03/2020 21:16, SATYABRATA DATTA wrote: > delta=18.*a*b*c*d-4.*(b**3)*d+b**2*c**2-4.*a*c**3-27.*a**2*d**2 > print *, delta, a, b, c, d,d1 > if(delta.gt.0.)then > x=2.*b**3-9.*a*b*c+27.*a**2*d > y=3.*sqrt(3.)*a*sqrt(delta) > if((x.lt.0.and.y.lt.0).or.(x.lt.0.and.y.gt.0))then > nii=2 > else > nii=0 > endif > How to convert this fortran logic to python where delta(a,b,c,d) > should return x(a,b,c,d) and y(a,b,c,d) for the next job when > satisfied the conditions My Fortran is extremely rusty and was never great to start with. I've never used it in anger... But here goes a first attempt: First of all I'm going to guess that your code is the body of a Fortran function defined something like: real function delta(a,b,c,d) delta=...your code... ...here end function delta from math import sqrt def delta(a,b,c,d): dval = 18*a*b*c*d-4*(b**3)*d+b**2*c**2-4*a*c**3-27*a**2*d**2 print( dval, a, b, c, d, d1) # where is d1 defined? if dval > 0: x=(2*b**3) - (9*a*b*c) + (27*a**2)*d # fortran precedence??? y=3*sqrt(3)*a*sqrt(dval) if (x < 0 and y < 0) or (x < 0 and y > 0) nii=2 else: nii=0 # no idea what part nii plays. return dval Hopefully those with better Fortran skills can improve on that! -- 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 Thu Mar 26 19:21:57 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 26 Mar 2020 23:21:57 +0000 Subject: [Tutor] How to convert the fortran logic to python definition In-Reply-To: References: Message-ID: On 26/03/2020 21:16, SATYABRATA DATTA wrote: > if((x.lt.0.and.y.lt.0).or.(x.lt.0.and.y.gt.0))then The obvious question here is what happens when x and/or y is equal to zero? That is undefined. Also (A and B) or (A and notB) is equal to: A Draw the truth table to prove 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 alan.gauld at yahoo.co.uk Fri Mar 27 07:30:04 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 27 Mar 2020 11:30:04 +0000 Subject: [Tutor] How to convert the fortran logic to python definition In-Reply-To: References: Message-ID: Please always use replyAll or ReplyList when responding to the Python tutor list. Otherwise t just goes to the original poster. On 27/03/2020 04:08, SATYABRATA DATTA wrote: > Thanks?Alan but if the x and y are both functions of Delta and I want to > get back x(a,b,c,d) and y(a,b,c,d) OK, I don't really understand what you want. Where are x and y defined in the fortran code? Also do you want to get back (x(a,b,c,d) and y(a,b,c,d)) ie the logical and of the two functions results. Or do you want to get back both x(a,b,c,d as well as y(a,b,c,d) That is two values? I wasn't even aware Fortran could do that and it isn't what your code snippet appears to do. Are you sure your fortran code does what you want? > >? ? ? ? ? if((x.lt.0.and.y.lt.0).or.(x.lt.0.and.y.gt.0))then > > The obvious question here is what happens when x and/or y > is equal to zero? That is undefined. > > Also > > (A and B) or (A and notB) > > is equal to: > > A > > Draw the truth table to prove it. You haven't addressed either of my issues above. If we ignore the zero cases your if statement is the same as: if( x.lt.0) then so y is effectively ignored. Now, as I said I was never an expert in Fortran and there may be some subtle fortran magic going on that I'm unaware of. But it looks to me like your fortran is suspect, or at least incomplete. Its very difficult to guess what should be happening. Perhaps you should try asking on a Fortran forum, its probably more likely that modern Fortran programmers will also know Python than that Python programmers will know Fortran! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Mar 27 07:30:04 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 27 Mar 2020 11:30:04 +0000 Subject: [Tutor] How to convert the fortran logic to python definition In-Reply-To: References: Message-ID: Please always use replyAll or ReplyList when responding to the Python tutor list. Otherwise t just goes to the original poster. On 27/03/2020 04:08, SATYABRATA DATTA wrote: > Thanks?Alan but if the x and y are both functions of Delta and I want to > get back x(a,b,c,d) and y(a,b,c,d) OK, I don't really understand what you want. Where are x and y defined in the fortran code? Also do you want to get back (x(a,b,c,d) and y(a,b,c,d)) ie the logical and of the two functions results. Or do you want to get back both x(a,b,c,d as well as y(a,b,c,d) That is two values? I wasn't even aware Fortran could do that and it isn't what your code snippet appears to do. Are you sure your fortran code does what you want? > >? ? ? ? ? if((x.lt.0.and.y.lt.0).or.(x.lt.0.and.y.gt.0))then > > The obvious question here is what happens when x and/or y > is equal to zero? That is undefined. > > Also > > (A and B) or (A and notB) > > is equal to: > > A > > Draw the truth table to prove it. You haven't addressed either of my issues above. If we ignore the zero cases your if statement is the same as: if( x.lt.0) then so y is effectively ignored. Now, as I said I was never an expert in Fortran and there may be some subtle fortran magic going on that I'm unaware of. But it looks to me like your fortran is suspect, or at least incomplete. Its very difficult to guess what should be happening. Perhaps you should try asking on a Fortran forum, its probably more likely that modern Fortran programmers will also know Python than that Python programmers will know Fortran! -- 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 basicbare at gmail.com Fri Mar 27 11:38:38 2020 From: basicbare at gmail.com (Alan Thwaits) Date: Fri, 27 Mar 2020 11:38:38 -0400 Subject: [Tutor] Unexpected Indent Error Message Message-ID: I'm trying to run a script I've copied from Exercise 43 of Zeb Shaw's "Learn Python the Hard Way." But I'm getting an "unexpected indent" error message. Here's the guilty block of script I've copied (and checked umpteen times for accuracy): class EscapePod(Scene): def enter(self): print(dedent(""" You rush through the ship, desperately trying to make it to the escape pod before the ship explodes. It seems like hardly any Nastics are on the ship, so your run is clear of interference. You get to the escape pod chamber, and now need to pick a pod. Some of them could be damaged, but you don't have time to look. There are five pods. Which one do you take? """)) good_pod = randint(1,5) guess = input("[pod #]> ") if int(guess) != good_pod: print(dedent(""" You jump into pod {guess} and hit the eject button. The pod escapes out into the void of space. Then it implodes as the ship's hull ruptures, crushing your body into jam jelly. """)) return 'death' else: print(dedent(""" You jump into pod {guess} and hit the eject button. The pod slides easily out into space, heading to the planet below. As it flies down to the planet, you back, and see the ship implode, then explode like a bright star. It takes out the Nastic ship at the same time. You won! """)) return 'finished' And here's the error message I get back: Type "copyright", "credits" or "license" for more information. IPython 7.8.0 -- An enhanced Interactive Python. runfile('C:/Users/Alan/Documents/Python/ex43.py', wdir='C:/Users/Alan/Documents/Python') Traceback (most recent call last): File "C:\Users\Alan\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "", line 1, in runfile('C:/Users/Alan/Documents/Python/ex43.py', wdir='C:/Users/Alan/Documents/Python') File "C:\Users\Alan\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile execfile(filename, namespace) File "C:\Users\Alan\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Alan/Documents/Python/ex43.py", line 158 return 'death' ^ IndentationError: unexpected indent For the life of me, I can't figure out what I've done wrong. I've gone through the code line-by-line. I've used VSCode's grid markings to check that the indents all line up properly. I've tried various indent/tab/space settings. I've learned a lot about indent/dedent. But no joy. Can anyone see from the above snippets where I've gone wrong? Thanks! Alan From __peter__ at web.de Fri Mar 27 13:07:51 2020 From: __peter__ at web.de (Peter Otten) Date: Fri, 27 Mar 2020 18:07:51 +0100 Subject: [Tutor] Unexpected Indent Error Message References: Message-ID: Alan Thwaits wrote: If instead of the fancy dedent() > print(dedent(""" > You jump into pod {guess} and hit the eject button. The pod > escapes out into the void of space. Then it implodes as the ship's hull > ruptures, crushing your body into jam jelly. > """)) > return 'death' you print something simple print("Hi") return 'death' I'm sure you can't miss the problem :) From alan.gauld at yahoo.co.uk Fri Mar 27 13:24:50 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 27 Mar 2020 17:24:50 +0000 Subject: [Tutor] Unexpected Indent Error Message In-Reply-To: References: Message-ID: On 27/03/2020 15:38, Alan Thwaits wrote: > I'm trying to run a script I've copied from Exercise 43 of Zeb Shaw's > "Learn Python the Hard Way." But I'm getting an "unexpected indent" error > message. Peter has highlighted the immediate problem causing the error. But I wonder if that's all... > class EscapePod(Scene): > > def enter(self): > print(dedent(""" ...> """)) > > good_pod = randint(1,5) > guess = input("[pod #]> ") Notice that these lines are not indented to the same level as the print statement. That means they are not part of the enter() method. But they are part of the class definition. Now that is legal Python, but it's extremely unusual Python. So I suspect these lines and all that follow should be indented under the print() statement? Indentation is key in python. Arguably that's a good thing since it forces your code to be formatted in a readable style, but you do need to keep your eyes peeled because it can trip you up. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From basicbare at gmail.com Fri Mar 27 13:18:18 2020 From: basicbare at gmail.com (Alan Thwaits) Date: Fri, 27 Mar 2020 13:18:18 -0400 Subject: [Tutor] Unexpected Indent Error Message In-Reply-To: References: Message-ID: I've aligned 'death' with the print above it (checking with VSCode to be certain of the alignment), and get the following: runfile('C:/Users/Alan/Documents/Python/ex43.py', wdir='C:/Users/Alan/Documents/Python') Traceback (most recent call last): File "C:\Users\Alan\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "", line 1, in runfile('C:/Users/Alan/Documents/Python/ex43.py', wdir='C:/Users/Alan/Documents/Python') File "C:\Users\Alan\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile execfile(filename, namespace) File "C:\Users\Alan\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Alan/Documents/Python/ex43.py", line 158 return 'death' ^ SyntaxError: 'return' outside function Perhaps this means that I need to look at function somewhere else in the script. Any suggestions re where or what? Thanks! Alan On Fri, Mar 27, 2020 at 12:57 PM Baptista Albert wrote: > Hi Alan, > > Your return 'Death' and the print above it should align, I see 1space in > the alignment of the return statement. > > Hope this helps, > > > On Fri, Mar 27, 2020, 11:53 AM Alan Thwaits wrote: > >> I'm trying to run a script I've copied from Exercise 43 of Zeb Shaw's >> "Learn Python the Hard Way." But I'm getting an "unexpected indent" error >> message. >> >> Here's the guilty block of script I've copied (and checked umpteen times >> for accuracy): >> >> class EscapePod(Scene): >> >> def enter(self): >> print(dedent(""" >> You rush through the ship, desperately trying to make it to >> the >> escape pod before the ship explodes. It seems like hardly any Nastics are >> on the ship, so your run is clear of interference. You get to the escape >> pod chamber, and now need to pick a pod. Some of them could be damaged, >> but >> you don't have time to look. There are five pods. Which one do you take? >> """)) >> >> good_pod = randint(1,5) >> guess = input("[pod #]> ") >> >> >> if int(guess) != good_pod: >> print(dedent(""" >> You jump into pod {guess} and hit the eject button. The pod >> escapes out into the void of space. Then it implodes as the ship's hull >> ruptures, crushing your body into jam jelly. >> """)) >> return 'death' >> else: >> print(dedent(""" >> You jump into pod {guess} and hit the eject button. The pod >> slides easily out into space, heading to the planet below. As it flies >> down >> to the planet, you back, and see the ship implode, then explode like a >> bright star. It takes out the Nastic ship at the same time. You won! >> """)) >> >> return 'finished' >> >> And here's the error message I get back: >> >> Type "copyright", "credits" or "license" for more information. >> >> IPython 7.8.0 -- An enhanced Interactive Python. >> >> runfile('C:/Users/Alan/Documents/Python/ex43.py', >> wdir='C:/Users/Alan/Documents/Python') >> Traceback (most recent call last): >> >> File >> >> "C:\Users\Alan\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", >> line 3326, in run_code >> exec(code_obj, self.user_global_ns, self.user_ns) >> >> File "", line 1, in >> runfile('C:/Users/Alan/Documents/Python/ex43.py', >> wdir='C:/Users/Alan/Documents/Python') >> >> File >> >> "C:\Users\Alan\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", >> line 827, in runfile >> execfile(filename, namespace) >> >> File >> >> "C:\Users\Alan\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", >> line 110, in execfile >> exec(compile(f.read(), filename, 'exec'), namespace) >> >> File "C:/Users/Alan/Documents/Python/ex43.py", line 158 >> return 'death' >> ^ >> IndentationError: unexpected indent >> >> For the life of me, I can't figure out what I've done wrong. I've gone >> through the code line-by-line. I've used VSCode's grid markings to check >> that the indents all line up properly. I've tried various indent/tab/space >> settings. I've learned a lot about indent/dedent. But no joy. >> >> Can anyone see from the above snippets where I've gone wrong? >> >> Thanks! >> >> Alan >> _______________________________________________ >> 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 Fri Mar 27 13:33:19 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 27 Mar 2020 17:33:19 +0000 Subject: [Tutor] Unexpected Indent Error Message In-Reply-To: References: Message-ID: On 27/03/2020 17:18, Alan Thwaits wrote: > I've aligned 'death' with the print above it (checking with VSCode to be > certain of the alignment), and get the following: > File "C:/Users/Alan/Documents/Python/ex43.py", line 158 > return 'death' > ^ > SyntaxError: 'return' outside function Its not the death that needs to be aligned its the return. You should review the rulkes of indentation in Python, they really are critical. Essentially the indentation level determines what is inside the function. In this case the first line (print) sets the required indent. All other lines in the function must align with that. (or deeper if they are sub blocks) >>> class EscapePod(Scene): >>> >>> def enter(self): >>> print(dedent(""" >>> You rush through the ship, desperately trying to make it to >>> return 'death' ... >>> if.... >>> else: >>> print(dedent("""... As above. Notice how all the top level lines are at the same indent under the function def line? That is crucial. -- 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 basicbare at gmail.com Fri Mar 27 13:45:27 2020 From: basicbare at gmail.com (Alan Thwaits) Date: Fri, 27 Mar 2020 13:45:27 -0400 Subject: [Tutor] Unexpected Indent Error Message In-Reply-To: References: Message-ID: I tried that, with this resulting code: class EscapePod(Scene): def enter(self): print("You rush through the ship, desperately trying to make it to the escape pod before the whole ship explodes. It seems like hardly any Nastics are on the ship, so your run is clear of interference. You get to the chamber with the escape pods, and now need to pick one to take. Some of them could be damaged, but you don't have time look closely. There are five pods, Which one do you take?") good_pod = randint(1,5) guess = input("[pod #]> ") if int(guess) != good_pod: print("You jump into pod {guess} and hit the eject button. The pod slides easily into space, heading to the planet below. Then, as the hull ruptures, it implodes, crushing your body like jam jelly.") return 'death' else: print("You jump into pod {guess} and hit the eject button. The pod slides easily out into space, heading to the planet below. As it flies down to the planet, you back, and see the ship implode, then explode like a bright star. It takes out the Nastic ship at the same time. You won!") return 'finished' And got this error message: runfile('C:/Users/Alan/Documents/Python/ex43.py', wdir='C:/Users/Alan/Documents/Python') Traceback (most recent call last): File "C:\Users\Alan\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "", line 1, in runfile('C:/Users/Alan/Documents/Python/ex43.py', wdir='C:/Users/Alan/Documents/Python') File "C:\Users\Alan\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile execfile(filename, namespace) File "C:\Users\Alan\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Alan/Documents/Python/ex43.py", line 153 return 'death' ^ SyntaxError: 'return' outside function Which is the same as what I got originally. Am I being dumb? Clumsy? Thanks! Alan On Fri, Mar 27, 2020 at 1:17 PM Peter Otten <__peter__ at web.de> wrote: > Alan Thwaits wrote: > > If instead of the fancy dedent() > > > print(dedent(""" > > You jump into pod {guess} and hit the eject button. The pod > > escapes out into the void of space. Then it implodes as the ship's hull > > ruptures, crushing your body into jam jelly. > > """)) > > return 'death' > > you print something simple > > print("Hi") > return 'death' > > I'm sure you can't miss the problem :) > > _______________________________________________ > 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 Fri Mar 27 15:32:54 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 27 Mar 2020 19:32:54 +0000 Subject: [Tutor] Unexpected Indent Error Message In-Reply-To: References: Message-ID: On 27/03/2020 17:45, Alan Thwaits wrote: > I tried that, with this resulting code: A large part of the problem is the trple quoted strings are obscuring the stricture of your code. Take them out(assign them to variables at the top of the code then print the varoiables) It looks like: > > class EscapePod(Scene): > > def enter(self): > print(foo) > > good_pod = randint(1,5) > guess = input("[pod #]> ") > > if int(guess) != good_pod: > print(bar") > return 'death' > else: > print(baz) > > return 'finished' Notice how your indentation is too far left. So the return is associated with the code starting good_pod= Which is not inside a function. And return outside a function is illegal, so python complains. -- 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 janethcat21 at gmail.com Fri Mar 27 15:32:47 2020 From: janethcat21 at gmail.com (Janet Hernandez) Date: Fri, 27 Mar 2020 12:32:47 -0700 Subject: [Tutor] Unexpected result Message-ID: <1794DC77-F2CA-4C73-8D01-857EFD0FFA73@gmail.com> Hello my name is Janet Hernandez. I am a beginner in computer science and I have been using python to learn programming logic in my course. As an assignment, I was prompted to display a list of celsius to fahrenheit conversions from 1 to 15 using a while loop. However, when I ran the program, the conversion for 13 celsius to fahrenheit appeared to be 55.400000000000006, which is incorrect. All the other values were correct. I did a few trials apart from the while loop and it appears that python incorrectly calculates the product of 1.8*13, 1.8*26, 1.7*13, 1.7*26. Why is this happening? I have attached the python file below. Thank you. From alan.gauld at yahoo.co.uk Fri Mar 27 15:49:34 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 27 Mar 2020 19:49:34 +0000 Subject: [Tutor] Unexpected result In-Reply-To: <1794DC77-F2CA-4C73-8D01-857EFD0FFA73@gmail.com> References: <1794DC77-F2CA-4C73-8D01-857EFD0FFA73@gmail.com> Message-ID: On 27/03/2020 19:32, Janet Hernandez wrote: > Hello my name is Janet Hernandez. I am a beginner in computer science and I have been using python to learn programming logic in my course. > > ... it appears that python incorrectly calculates the product of 1.8*13, This is not a Python issue, it happens in most languages. The explanation is to do with how computers store floating point numbers. Its quite detailed and there is a good explanation on wikipedia here: https://en.wikipedia.org/wiki/Floating-point_arithmetic#Representable_numbers,_conversion_and_rounding Read sections 4 through 7 for the full explanation. (You should cover this in your course at some stage!) And its not just 13*1.8 Try print(3*0.8) -- 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 basicbare at gmail.com Fri Mar 27 15:42:49 2020 From: basicbare at gmail.com (Alan Thwaits) Date: Fri, 27 Mar 2020 15:42:49 -0400 Subject: [Tutor] Unexpected Indent Error Message In-Reply-To: References: Message-ID: Alan, you're absolutely right. Following the function def line correctly solved the problem. Many thanks! Alan On Fri, Mar 27, 2020 at 1:33 PM Alan Gauld via Tutor wrote: > On 27/03/2020 17:18, Alan Thwaits wrote: > > I've aligned 'death' with the print above it (checking with VSCode to be > > certain of the alignment), and get the following: > > > File "C:/Users/Alan/Documents/Python/ex43.py", line 158 > > return 'death' > > ^ > > SyntaxError: 'return' outside function > > Its not the death that needs to be aligned its the return. > You should review the rulkes of indentation in Python, they really are > critical. > > Essentially the indentation level determines what is inside the > function. In this case the first line (print) sets the required indent. > All other lines in the function must align with that. (or deeper if they > are sub blocks) > > >>> class EscapePod(Scene): > >>> > >>> def enter(self): > >>> print(dedent(""" > >>> You rush through the ship, desperately trying to make it to > >>> return 'death' > ... > >>> if.... > >>> else: > >>> print(dedent("""... > > As above. Notice how all the top level lines are at the same > indent under the function def line? That is crucial. > > -- > 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 basicbare at gmail.com Fri Mar 27 17:49:26 2020 From: basicbare at gmail.com (Alan Thwaits) Date: Fri, 27 Mar 2020 17:49:26 -0400 Subject: [Tutor] Object and Attribute Error Message-ID: Another error message in my game script from Exercise 43 in Zeb Shaw's "Learn Python the Hard Way." The first block of code which the error message references is this: class Engine(object): def __init__(self, scene_map): self.scene_map = scene_map def play(self): current_scene = self.scene_map.opening_scene() last_scene = self.scene_map.next_scene('finished') while current_scene != last_scene: next_scene_name = current_scene.enter() current_scene = self.scene_map.next_scene(next_scene_name) #be sure to print out the last scene current_scene.enter() The second block of code referenced is this: class Map(object): scenes = { 'central_corridor': CentralCorridor(), 'laser_weapon_armory': LaserWeaponArmory(), 'the_bridge': TheBridge(), 'escape_pod': EscapePod(), 'death': Death(), 'finished': Finished(), } def __init__(self, start_scene): self.start_scene = start_scene def next_scene(self, scene_name): val = Map.scenes.get(scene_name) return val def opening_scene(self): return self.next_scene(self.start_scene) a_map = Map('central_corridor') a_game = Engine(a_map) a_game.play() The error message is this: Traceback (most recent call last): File "", line 1, in runfile('C:/Users/Alan/Documents/Python/ex43.py', wdir='C:/Users/Alan/Documents/Python') File "C:\Users\Alan\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile execfile(filename, namespace) File "C:\Users\Alan\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Alan/Documents/Python/ex43.py", line 194, in a_game.play() File "C:/Users/Alan/Documents/Python/ex43.py", line 29, in play next_scene_name = current_scene.enter() AttributeError: 'NoneType' object has no attribute 'enter' Obviously, I need to understand object and attribute better. Any guidance would be appreciated. Thanks! Alan From cs at cskk.id.au Fri Mar 27 20:59:12 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Sat, 28 Mar 2020 11:59:12 +1100 Subject: [Tutor] Object and Attribute Error In-Reply-To: References: Message-ID: <20200328005912.GA48769@cskk.homeip.net> On 27Mar2020 17:49, Alan Thwaits wrote: >Another error message in my game script from Exercise 43 in Zeb Shaw's >"Learn Python the Hard Way." > >The first block of code which the error message references is this: > >class Engine(object): > > def __init__(self, scene_map): > self.scene_map = scene_map > > def play(self): > current_scene = self.scene_map.opening_scene() > last_scene = self.scene_map.next_scene('finished') > > while current_scene != last_scene: > next_scene_name = current_scene.enter() > current_scene = self.scene_map.next_scene(next_scene_name) > > #be sure to print out the last scene > current_scene.enter() [...] > File "C:/Users/Alan/Documents/Python/ex43.py", line 29, in play > next_scene_name = current_scene.enter() >AttributeError: 'NoneType' object has no attribute 'enter' [...] This indicates that current_scene.enter cannot be accessed because current_scene is None. The reason for this is twofold: 1: self.scene_map.next_scene(next_scene_name) can return None because it does a .get(), which returns None if there is no matching key. If you used Map.scenes[scene_name] that would not happen, though you would of course get a KeyError on no matching key; at least that would be closer to the source of your problem. 2: your while loop: while current_scene != last_scene: next_scene_name = current_scene.enter() current_scene = self.scene_map.next_scene(next_scene_name) is written on the presumption that self.scene_map.next_scene always returns a scene, when in fact it can return None. I would take this to indicate that your graph-of-scenes does not in fact flow through to the 'finished' scene. That can be as simple as mistyping the name of the next scene. I'd be inclined to write the loop like this: while current_scene != last_scene: next_scene_name = current_scene.enter() next_scene = self.scene_map.next_scene(next_scene_name) if next_scene is None: raise ValueError( "current_scene %s: no next scene with name %r" % (current_scene, next_scene_name)) current_scene = next_scene This provides a nice exception detailing the name of the scene which was not found. BTW, this function: >class Map(object): [...] > scenes = { [...] > def next_scene(self, scene_name): > val = Map.scenes.get(scene_name) > return val The class is in an instances attribute search space, so you can write: val = self.scenes.get(scene_name) and avoid hardwiring the class name into the method. (This also means you can write a subclass with a different next_scene method easily.) Cheers, Cameron Simpson From alan.gauld at yahoo.co.uk Fri Mar 27 21:25:40 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 28 Mar 2020 01:25:40 +0000 Subject: [Tutor] Object and Attribute Error In-Reply-To: References: Message-ID: On 27/03/2020 21:49, Alan Thwaits wrote: > Another error message in my game script from Exercise 43 in Zeb Shaw's > "Learn Python the Hard Way." I'm assuming you are only sending us a fraction of the code because otherwise you should be getting many more errors before reaching that line. > class Engine(object): > > def __init__(self, scene_map): > self.scene_map = scene_map > > def play(self): > current_scene = self.scene_map.opening_scene() > last_scene = self.scene_map.next_scene('finished') > > while current_scene != last_scene: > next_scene_name = current_scene.enter() This is where the error is reported and it says current_scene is None. So where is current scene defined? In the line above where Map.opening_scene() is called... > def opening_scene(self): > return self.next_scene(self.start_scene) Which is just a wrapper for Map.next_scene() > def next_scene(self, scene_name): > val = Map.scenes.get(scene_name) > return val which returns the result from scenes.get() scenes is a dictionary, and dict.get returns None when it cannot find the requested key. This is where we start guessing because we cannot see the code. The call to enter() presumably returns the name of the next scene, and so on to the end of the dict? Presumably one of the enter methods returns an invalid key? But without seeing the enter methods we cant tell. > class Map(object): > > scenes = { > 'central_corridor': CentralCorridor(), > 'laser_weapon_armory': LaserWeaponArmory(), > 'the_bridge': TheBridge(), > 'escape_pod': EscapePod(), > 'death': Death(), > 'finished': Finished(), > } This is instantiating a bunch of classes which we can't see so I assume they are defined elsewhere? And that they all have enter() methods. > File "C:/Users/Alan/Documents/Python/ex43.py", line 29, in play > next_scene_name = current_scene.enter() > > AttributeError: 'NoneType' object has no attribute 'enter' > > Obviously, I need to understand object and attribute better. Any guidance > would be appreciated. classes are type definitions. objects are instances of classes. attributes are the names inside the classes/objects. A return value of None from the get() method is a NoneType object. NoneType objects do not have an attribute(aka name) called enter so you get an error You can check the attributes of an object with the dir function: >>> dir(None) ['__bool__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] So while None has a bunch of names they are all "hidden"(ie they have __ in front - sometimes called dunder.) Most are oprerationds. But nothing you can call by name, and certainly no enter() -- 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 basicbare at gmail.com Sat Mar 28 11:22:21 2020 From: basicbare at gmail.com (Alan Thwaits) Date: Sat, 28 Mar 2020 11:22:21 -0400 Subject: [Tutor] Object and Attribute Error In-Reply-To: References: Message-ID: Thank you for your reply. Your clarity around classes, attributes, and objects is much appreciated. I'm still working hard to get my head around the concepts. I'll continue working through your message. There's a lot there to be unpacked. Alan On Fri, Mar 27, 2020 at 9:26 PM Alan Gauld via Tutor wrote: > On 27/03/2020 21:49, Alan Thwaits wrote: > > Another error message in my game script from Exercise 43 in Zeb Shaw's > > "Learn Python the Hard Way." > > I'm assuming you are only sending us a fraction of the code because > otherwise you should be getting many more errors before reaching that line. > > > > class Engine(object): > > > > def __init__(self, scene_map): > > self.scene_map = scene_map > > > > def play(self): > > current_scene = self.scene_map.opening_scene() > > last_scene = self.scene_map.next_scene('finished') > > > > while current_scene != last_scene: > > next_scene_name = current_scene.enter() > > This is where the error is reported and it says current_scene > is None. > > So where is current scene defined? In the line above > where Map.opening_scene() is called... > > > def opening_scene(self): > > return self.next_scene(self.start_scene) > > Which is just a wrapper for Map.next_scene() > > > def next_scene(self, scene_name): > > val = Map.scenes.get(scene_name) > > return val > > > which returns the result from scenes.get() > scenes is a dictionary, > and dict.get returns None when it cannot find the > requested key. > > This is where we start guessing because we cannot > see the code. The call to enter() presumably returns > the name of the next scene, and so on to the end of > the dict? > > Presumably one of the enter methods returns an invalid > key? But without seeing the enter methods we cant tell. > > > class Map(object): > > > > scenes = { > > 'central_corridor': CentralCorridor(), > > 'laser_weapon_armory': LaserWeaponArmory(), > > 'the_bridge': TheBridge(), > > 'escape_pod': EscapePod(), > > 'death': Death(), > > 'finished': Finished(), > > } > > This is instantiating a bunch of classes which we can't see > so I assume they are defined elsewhere? And that they all > have enter() methods. > > > File "C:/Users/Alan/Documents/Python/ex43.py", line 29, in play > > next_scene_name = current_scene.enter() > > > > AttributeError: 'NoneType' object has no attribute 'enter' > > > > Obviously, I need to understand object and attribute better. Any guidance > > would be appreciated. > > classes are type definitions. > objects are instances of classes. > attributes are the names inside the classes/objects. > > A return value of None from the get() method is a NoneType object. > NoneType objects do not have an attribute(aka name) called enter > so you get an error > > You can check the attributes of an object with the dir function: > > >>> dir(None) > ['__bool__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', > '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', > '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', > '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', > '__sizeof__', '__str__', '__subclasshook__'] > > So while None has a bunch of names they are all "hidden"(ie they > have __ in front - sometimes called dunder.) Most are oprerationds. > But nothing you can call by name, and certainly no enter() > > -- > 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 basicbare at gmail.com Sat Mar 28 11:25:38 2020 From: basicbare at gmail.com (Alan Thwaits) Date: Sat, 28 Mar 2020 11:25:38 -0400 Subject: [Tutor] Object and Attribute Error In-Reply-To: <20200328005912.GA48769@cskk.homeip.net> References: <20200328005912.GA48769@cskk.homeip.net> Message-ID: Thank you for your reply. I'll try out your suggestions about re-writing the loop and changing the val = statement. The learning journey continues... Alan On Fri, Mar 27, 2020 at 8:59 PM Cameron Simpson wrote: > On 27Mar2020 17:49, Alan Thwaits wrote: > >Another error message in my game script from Exercise 43 in Zeb Shaw's > >"Learn Python the Hard Way." > > > >The first block of code which the error message references is this: > > > >class Engine(object): > > > > def __init__(self, scene_map): > > self.scene_map = scene_map > > > > def play(self): > > current_scene = self.scene_map.opening_scene() > > last_scene = self.scene_map.next_scene('finished') > > > > while current_scene != last_scene: > > next_scene_name = current_scene.enter() > > current_scene = self.scene_map.next_scene(next_scene_name) > > > > #be sure to print out the last scene > > current_scene.enter() > [...] > > File "C:/Users/Alan/Documents/Python/ex43.py", line 29, in play > > next_scene_name = current_scene.enter() > >AttributeError: 'NoneType' object has no attribute 'enter' > [...] > > This indicates that current_scene.enter cannot be accessed because > current_scene is None. > > The reason for this is twofold: > > 1: self.scene_map.next_scene(next_scene_name) can return None because it > does a .get(), which returns None if there is no matching key. If you > used Map.scenes[scene_name] that would not happen, though you would of > course get a KeyError on no matching key; at least that would be closer > to the source of your problem. > > 2: your while loop: > > while current_scene != last_scene: > next_scene_name = current_scene.enter() > current_scene = self.scene_map.next_scene(next_scene_name) > > is written on the presumption that self.scene_map.next_scene always > returns a scene, when in fact it can return None. I would take this to > indicate that your graph-of-scenes does not in fact flow through to the > 'finished' scene. That can be as simple as mistyping the name of the > next scene. > > I'd be inclined to write the loop like this: > > while current_scene != last_scene: > next_scene_name = current_scene.enter() > next_scene = self.scene_map.next_scene(next_scene_name) > if next_scene is None: > raise ValueError( > "current_scene %s: no next scene with name %r" > % (current_scene, next_scene_name)) > current_scene = next_scene > > This provides a nice exception detailing the name of the scene which was > not found. > > BTW, this function: > > >class Map(object): > [...] > > scenes = { > [...] > > def next_scene(self, scene_name): > > val = Map.scenes.get(scene_name) > > return val > > The class is in an instances attribute search space, so you can write: > > val = self.scenes.get(scene_name) > > and avoid hardwiring the class name into the method. (This also means > you can write a subclass with a different next_scene method easily.) > > Cheers, > Cameron Simpson > From JMV59 at pitt.edu Sat Mar 28 20:05:30 2020 From: JMV59 at pitt.edu (Vazquez, Juliana Mary) Date: Sun, 29 Mar 2020 00:05:30 +0000 Subject: [Tutor] Python Help: Converting a text file into a specified format Message-ID: <4E252E91-22F4-42F6-AD5F-81743C1BD123@pitt.edu> Your task is to process each record in a file named ?punned_result.txt (see attached) and convert it into the following format: ?[2] Brandt, Mary D; London, Jack E. ?Health Informatics Standards: A User?s Guide.? Journal of AHIMA 71, no. 4 (2000): 39-43. 1. You are required to list all the author names [last_name, first_name initial] 2. The content in the quotation is the title of the article 3. Here [2] is the order of the record, 71 is the volume, 4 is the issue number, 2000 is the year of publication, and 39-43 is the start and end pages of the article in that issue of the journal. Hints: ?You may want to use if/elif/else structure inside a while statement to test the first two characters in each line so that you can determine whether you need the info in that line or not. Please help me work through this problem! Thank you! Juliana -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: pubmed_result.txt URL: From nulla.epistola at web.de Sun Mar 29 06:55:45 2020 From: nulla.epistola at web.de (Sibylle Koczian) Date: Sun, 29 Mar 2020 12:55:45 +0200 Subject: [Tutor] Python Help: Converting a text file into a specified format In-Reply-To: <4E252E91-22F4-42F6-AD5F-81743C1BD123@pitt.edu> References: <4E252E91-22F4-42F6-AD5F-81743C1BD123@pitt.edu> Message-ID: Am 29.03.2020 um 01:05 schrieb Vazquez, Juliana Mary: > Your task is to process each record in a file named ?punned_result.txt (see attached) and convert it into the following format: > > ?[2] Brandt, Mary D; London, Jack E. ?Health Informatics Standards: A User?s Guide.? Journal of AHIMA 71, no. 4 (2000): 39-43. > > 1. You are required to list all the author names [last_name, first_name initial] > > 2. The content in the quotation is the title of the article > > 3. Here [2] is the order of the record, 71 is the volume, 4 is the issue number, 2000 is the year of publication, and 39-43 is the start and end pages of the article in that issue of the journal. > > Hints: > > ?You may want to use if/elif/else structure inside a while statement to test the first two characters in each line so that you can determine whether you need the info in that line or not. > > > > Please help me work through this problem! > Which parts do you know how to do, which parts are difficult? There is quite a big part that doesn't need any coding: examining your data file and the format you want to get from it. I'd tend to work through that first of all. - How are the records separated? - Which fields (with which short names at the beginning of the line) contain data you need and where does this data belong in the finished citation? - Can you use these fields as is or do you need to pick parts out of them? - What about the lines that start with whitespace? When all this is cleared up: where do you need help with coding? - Do you know how to open the file and read it line by line? - Does the hint about using a if/elif/else structure inside a while loop help you structure the main part of your code or is it just another riddle? - Do you know how to take the first two characters of the line (or the first word - some of the field names have more than two characters) and the rest? - Do you know how to pick the right parts out of field contents if that's necessary? - Do you know how to reassemble the necessary data in the format you need, including the record order? - Do you know how to write the end results into a new text file? If some of these questions are very silly, ignore them. If they are unclear, tell us. We can't know what is easy for you and what isn't. Greetings Sibylle From alan.gauld at yahoo.co.uk Sun Mar 29 06:56:21 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 29 Mar 2020 11:56:21 +0100 Subject: [Tutor] Python Help: Converting a text file into a specified format In-Reply-To: <4E252E91-22F4-42F6-AD5F-81743C1BD123@pitt.edu> References: <4E252E91-22F4-42F6-AD5F-81743C1BD123@pitt.edu> Message-ID: On 29/03/2020 00:05, Vazquez, Juliana Mary wrote: We won't do your assignment for you but will try to help. However, it's not clear what you want help with. Which part of the assignment is proving difficult? > Your task is to process each record in a file named ?punned_result.txt (see attached) Do you know how to read a text file? and convert it into the following format: And do you know how to print formatted text? > ?[2] Brandt, Mary D; London, Jack E. ?Health Informatics Standards: A User?s Guide.? Journal of AHIMA 71, no. 4 (2000): 39-43. > > 1. You are required to list all the author names [last_name, first_name initial] > > 2. The content in the quotation is the title of the article > > 3. Here [2] is the order of the record, 71 is the volume, 4 is the issue number, 2000 is the year of publication, and 39-43 is the start and end pages of the article in that issue of the journal. You can use a format string to gather all the fields together then inset the values from variables. > ?You may want to use if/elif/else structure inside a while statement Are you familiar with if/elif/else structures? Do you know how to use a while loop? > to test the first two characters in each line Do you know how to extract the first two characters from a line of text? > Please help me work through this problem! If you make clear to us what you need made clear then we can help you further. Incidentally the file you attached seems to contain patient records with real email addresses etc. You have just posted these to several hundred people on the internet. I suspect that is a breach of data protection legislation. Please take care of personal data. (Of course the data may have been anonymized before you got it, but it doesn't look like it!) It's also far more than was necessary to illustrate the file format. Just three or four records worth would have been sufficient, and you could have edited the contents to remove personal data. Some people pay for their data by the byte... -- 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 nulla.epistola at web.de Sun Mar 29 06:55:45 2020 From: nulla.epistola at web.de (Sibylle Koczian) Date: Sun, 29 Mar 2020 12:55:45 +0200 Subject: [Tutor] Python Help: Converting a text file into a specified format In-Reply-To: <4E252E91-22F4-42F6-AD5F-81743C1BD123@pitt.edu> References: <4E252E91-22F4-42F6-AD5F-81743C1BD123@pitt.edu> Message-ID: Am 29.03.2020 um 01:05 schrieb Vazquez, Juliana Mary: > Your task is to process each record in a file named ?punned_result.txt (see attached) and convert it into the following format: > > ?[2] Brandt, Mary D; London, Jack E. ?Health Informatics Standards: A User?s Guide.? Journal of AHIMA 71, no. 4 (2000): 39-43. > > 1. You are required to list all the author names [last_name, first_name initial] > > 2. The content in the quotation is the title of the article > > 3. Here [2] is the order of the record, 71 is the volume, 4 is the issue number, 2000 is the year of publication, and 39-43 is the start and end pages of the article in that issue of the journal. > > Hints: > > ?You may want to use if/elif/else structure inside a while statement to test the first two characters in each line so that you can determine whether you need the info in that line or not. > > > > Please help me work through this problem! > Which parts do you know how to do, which parts are difficult? There is quite a big part that doesn't need any coding: examining your data file and the format you want to get from it. I'd tend to work through that first of all. - How are the records separated? - Which fields (with which short names at the beginning of the line) contain data you need and where does this data belong in the finished citation? - Can you use these fields as is or do you need to pick parts out of them? - What about the lines that start with whitespace? When all this is cleared up: where do you need help with coding? - Do you know how to open the file and read it line by line? - Does the hint about using a if/elif/else structure inside a while loop help you structure the main part of your code or is it just another riddle? - Do you know how to take the first two characters of the line (or the first word - some of the field names have more than two characters) and the rest? - Do you know how to pick the right parts out of field contents if that's necessary? - Do you know how to reassemble the necessary data in the format you need, including the record order? - Do you know how to write the end results into a new text file? If some of these questions are very silly, ignore them. If they are unclear, tell us. We can't know what is easy for you and what isn't. Greetings Sibylle From __peter__ at web.de Sun Mar 29 11:16:17 2020 From: __peter__ at web.de (Peter Otten) Date: Sun, 29 Mar 2020 17:16:17 +0200 Subject: [Tutor] Python Help: Converting a text file into a specified format References: <4E252E91-22F4-42F6-AD5F-81743C1BD123@pitt.edu> Message-ID: Vazquez, Juliana Mary wrote: > Your task is to process each record in a file named ?punned_result.txt > (see attached) and convert it into the following format: > > ?[2] Brandt, Mary D; London, Jack E. ?Health Informatics Standards: A > User?s Guide.? Journal of AHIMA 71, no. 4 (2000): 39-43. > > 1. You are required to list all the author names [last_name, first_name > initial] > > 2. The content in the quotation is the title of the article > > 3. Here [2] is the order of the record, 71 is the volume, 4 is the > issue number, 2000 is the year of publication, and 39-43 is the start and > end pages of the article in that issue of the journal. > > Hints: > > ?You may want to use if/elif/else structure inside a while statement to > test the first two characters in each line so that you can determine > whether you need the info in that line or not. Uh -- that seems to be a rather hard problem to solve with just if and while. > Please help me work through this problem! Start small and write a script that breaks your input data into individual records. These seem to be separated by empty lines. For now you can build a list of lists where each publication record is one of the inner lists: [ ["PMID- 32203977", ...], ["PMID- 32203970", ...], ... ] When you have that working (in the process you may need to ask here again) you can split the inner lists into (key, [value1, value2, ...]) pairs. Note how the value part consists of a list because one key (example: FAU (which is "full author" according to https://www.nlm.nih.gov/bsd/mms/medlineelements.html) will occur once for every author of a publication. A Python dict is well-suited for that data (look at the dict.setdefault() method, or collections.defaultdict). Example dict: {'AD': ['Department of Cardiovascular, Endocrine-Metabolic Diseases ' 'and Aging, IstitutoSuperiore di Sanita, Rome, Italy.', 'Department of Infectious Diseases, Istituto Superiore di ' 'Sanita, Rome, Italy.', 'Office of the President, Istituto Superiore di Sanita, Rome, ' 'Italy.'], 'AID': ['2763667 [pii]', '10.1001/jama.2020.4683 [doi]'], 'AU': ['Onder G', 'Rezza G', 'Brusaferro S'], 'CRDT': ['2020/03/24 06:00'], 'DEP': ['20200323'], 'DP': ['2020 Mar 23'], 'EDAT': ['2020/03/24 06:00'], 'FAU': ['Onder, Graziano', 'Rezza, Giovanni', 'Brusaferro, Silvio'], 'IS': ['1538-3598 (Electronic)', '0098-7484 (Linking)'], 'JID': ['7501160'], 'JT': ['JAMA'], 'LA': ['eng'], 'LID': ['10.1001/jama.2020.4683 [doi]'], 'LR': ['20200323'], 'MHDA': ['2020/03/24 06:00'], 'OWN': ['NLM'], 'PHST': ['2020/03/24 06:00 [entrez]', '2020/03/24 06:00 [pubmed]', '2020/03/24 06:00 [medline]'], 'PL': ['United States'], 'PMID': ['32203977'], 'PST': ['aheadofprint'], 'PT': ['Journal Article'], 'SB': ['AIM', 'IM'], 'SO': ['JAMA. 2020 Mar 23. pii: 2763667. doi: ' '10.1001/jama.2020.4683.'], 'STAT': ['Publisher'], 'TA': ['JAMA'], 'TI': ['Case-Fatality Rate and Characteristics of Patients Dying in ' 'Relation to COVID-19 in Italy.']} Once you have your data in the format above the next step is to print it as requested -- and to come up with a way to cope with missing information (example: some of the publications do not provide an author). Some final tweaks (like extracting the year from the publication date), and you are there. From drjnbaruah at gmail.com Sun Mar 29 10:18:08 2020 From: drjnbaruah at gmail.com (JNB) Date: Sun, 29 Mar 2020 19:48:08 +0530 Subject: [Tutor] Installing IDLE Message-ID: Dear Sirs, I have Python 3.8.2 installed, but it seems to be without IDLE. Would you kindly guide me to get IDLE. Thanking you, Jatin From nulla.epistola at web.de Sun Mar 29 13:20:10 2020 From: nulla.epistola at web.de (Sibylle Koczian) Date: Sun, 29 Mar 2020 19:20:10 +0200 Subject: [Tutor] Python Help: Converting a text file into a specified format In-Reply-To: References: <4E252E91-22F4-42F6-AD5F-81743C1BD123@pitt.edu> Message-ID: Am 29.03.2020 um 12:56 schrieb Alan Gauld via Tutor: > Incidentally the file you attached seems to contain patient records > with real email addresses etc. You have just posted these to several > hundred people on the internet. > > I suspect that is a breach of data protection legislation. > Please take care of personal data. (Of course the data may have > been anonymized before you got it, but it doesn't look like it!) > I wonder about this, because I can't find anything that looks like patient records. All the email adresses I looked at in that file seemed to be adresses of the institutions where the research was done. On the other hand I did only look at a handful. Moreover all the records have a field "PST" containing "aheadofprint", "epublish" or "ppublish". So I think they all are either already published or going to be. The whole file reminds me strongly of the contents of bibliographic databases (medline is mentioned in many of them). > It's also far more than was necessary to illustrate the file format. > Just three or four records worth would have been sufficient, and you > could have edited the contents to remove personal data. Some people pay > for their data by the byte... > That's very true. And finding a good mix of typical and less typical records might help towards parsing them as needed. Greetings Sibylle From nulla.epistola at web.de Sun Mar 29 13:20:10 2020 From: nulla.epistola at web.de (Sibylle Koczian) Date: Sun, 29 Mar 2020 19:20:10 +0200 Subject: [Tutor] Python Help: Converting a text file into a specified format In-Reply-To: References: <4E252E91-22F4-42F6-AD5F-81743C1BD123@pitt.edu> Message-ID: Am 29.03.2020 um 12:56 schrieb Alan Gauld via Tutor: > Incidentally the file you attached seems to contain patient records > with real email addresses etc. You have just posted these to several > hundred people on the internet. > > I suspect that is a breach of data protection legislation. > Please take care of personal data. (Of course the data may have > been anonymized before you got it, but it doesn't look like it!) > I wonder about this, because I can't find anything that looks like patient records. All the email adresses I looked at in that file seemed to be adresses of the institutions where the research was done. On the other hand I did only look at a handful. Moreover all the records have a field "PST" containing "aheadofprint", "epublish" or "ppublish". So I think they all are either already published or going to be. The whole file reminds me strongly of the contents of bibliographic databases (medline is mentioned in many of them). > It's also far more than was necessary to illustrate the file format. > Just three or four records worth would have been sufficient, and you > could have edited the contents to remove personal data. Some people pay > for their data by the byte... > That's very true. And finding a good mix of typical and less typical records might help towards parsing them as needed. Greetings Sibylle From mats at wichmann.us Sun Mar 29 13:36:03 2020 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 29 Mar 2020 11:36:03 -0600 Subject: [Tutor] Installing IDLE In-Reply-To: References: Message-ID: On 3/29/20 8:18 AM, JNB wrote: > Dear Sirs, > I have Python 3.8.2 installed, but it seems to be without IDLE. Would you > kindly guide me to get IDLE. You need to tell us the platform you are using first. On Linux systems, IDLE is sometimes a separate package. On Windows, it is in install-time option, by default on I believe, but the path it is installed to is often not in the Windows Path. etc. From PyTutor at DancesWithMice.info Sun Mar 29 18:47:02 2020 From: PyTutor at DancesWithMice.info (David L Neil) Date: Mon, 30 Mar 2020 11:47:02 +1300 Subject: [Tutor] Python Help: Converting a text file into a specified format In-Reply-To: References: <4E252E91-22F4-42F6-AD5F-81743C1BD123@pitt.edu> Message-ID: <894dc2d3-908e-bddd-fa7e-4e3f62f31251@DancesWithMice.info> On 29/03/20 11:56 PM, Alan Gauld via Tutor wrote: > On 29/03/2020 00:05, Vazquez, Juliana Mary wrote: > We won't do your assignment for you but will try to help. +1 ...to help you learn. > Incidentally the file you attached seems to contain patient records > with real email addresses etc. You have just posted these to several > hundred people on the internet. > > I suspect that is a breach of data protection legislation. > Please take care of personal data. (Of course the data may have > been anonymized before you got it, but it doesn't look like it!) +1 (different rules/laws in different jurisdictions but an important lesson to learn if you intend to work in data science!) > It's also far more than was necessary to illustrate the file format. > Just three or four records worth would have been sufficient, and you > could have edited the contents to remove personal data. Some people pay > for their data by the byte... Indeed we do! -- Regards =dn From drjnbaruah at gmail.com Mon Mar 30 00:28:26 2020 From: drjnbaruah at gmail.com (JNB) Date: Mon, 30 Mar 2020 09:58:26 +0530 Subject: [Tutor] Installing IDLE In-Reply-To: References: Message-ID: Thank you. My platform is Windows 10. On Sun 29 Mar, 2020, 11:06 PM Mats Wichmann, wrote: > On 3/29/20 8:18 AM, JNB wrote: > > Dear Sirs, > > I have Python 3.8.2 installed, but it seems to be without IDLE. Would you > > kindly guide me to get IDLE. > > You need to tell us the platform you are using first. > > On Linux systems, IDLE is sometimes a separate package. > > On Windows, it is in install-time option, by default on I believe, but > the path it is installed to is often not in the Windows Path. > > etc. > > > From drjnbaruah at gmail.com Mon Mar 30 02:41:24 2020 From: drjnbaruah at gmail.com (JNB) Date: Mon, 30 Mar 2020 12:11:24 +0530 Subject: [Tutor] Installing IDLE Message-ID: Dear Sirs, Would you kindly help me to get IDLE on my Laptop running Windows 10. Thanking You, Regards, Jatin Baruah From arj.python at gmail.com Mon Mar 30 06:25:46 2020 From: arj.python at gmail.com (Abdur-Rahmaan Janhangeer) Date: Mon, 30 Mar 2020 14:25:46 +0400 Subject: [Tutor] Installing IDLE In-Reply-To: References: Message-ID: On windows 10 it's automatically listed in list of programs i think. Did you check? Kind Regards, Abdur-Rahmaan Janhangeer https://www.compileralchemy.com https://www.github.com/Abdur-RahmaanJ Mauritius sent from gmail client on Android, that's why the signature is so ugly. On Mon, 30 Mar 2020, 14:08 JNB, wrote: > Thank you. My platform is Windows 10. > > On Sun 29 Mar, 2020, 11:06 PM Mats Wichmann, wrote: > > > On 3/29/20 8:18 AM, JNB wrote: > > > Dear Sirs, > > > I have Python 3.8.2 installed, but it seems to be without IDLE. Would > you > > > kindly guide me to get IDLE. > > > > You need to tell us the platform you are using first. > > > > On Linux systems, IDLE is sometimes a separate package. > > > > On Windows, it is in install-time option, by default on I believe, but > > the path it is installed to is often not in the Windows Path. > > > > etc. > > > > > > > _______________________________________________ > 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 Mar 30 06:51:08 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 30 Mar 2020 11:51:08 +0100 Subject: [Tutor] Installing IDLE In-Reply-To: References: Message-ID: On 30/03/2020 05:28, JNB wrote: > Thank you. My platform is Windows 10. > > On Sun 29 Mar, 2020, 11:06 PM Mats Wichmann, wrote: > >> On 3/29/20 8:18 AM, JNB wrote: >>> Dear Sirs, >>> I have Python 3.8.2 installed, but it seems to be without IDLE. Would you >>> kindly guide me to get IDLE If it is thee it should be located in the idlelib folder under your Python install. On my PC that is: C:\Python3\idlelib\idle.bat Create a shortcut to idle.bat and put it on your desktop. (or add it to your start menu or whatever) You may have installed Python in a different location so you will need to find that first. -- 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 jamignott at gmail.com Mon Mar 30 07:20:51 2020 From: jamignott at gmail.com (Julian Mignott) Date: Mon, 30 Mar 2020 07:20:51 -0400 Subject: [Tutor] Installing IDLE In-Reply-To: References: Message-ID: This might be of help.. https://www.youtube.com/watch?v=P7sFdnK590I On Mon, Mar 30, 2020 at 6:51 AM Alan Gauld via Tutor wrote: > On 30/03/2020 05:28, JNB wrote: > > Thank you. My platform is Windows 10. > > > > On Sun 29 Mar, 2020, 11:06 PM Mats Wichmann, wrote: > > > >> On 3/29/20 8:18 AM, JNB wrote: > >>> Dear Sirs, > >>> I have Python 3.8.2 installed, but it seems to be without IDLE. Would > you > >>> kindly guide me to get IDLE > > If it is thee it should be located in the idlelib folder under your > Python install. > > On my PC that is: > > C:\Python3\idlelib\idle.bat > > Create a shortcut to idle.bat and put it on your desktop. > (or add it to your start menu or whatever) > > You may have installed Python in a different location > so you will need to find that first. > > -- > 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 Mon Mar 30 10:56:10 2020 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 30 Mar 2020 08:56:10 -0600 Subject: [Tutor] Installing IDLE In-Reply-To: References: Message-ID: <14754b05-23b7-2479-6a7f-757a826b4e96@wichmann.us> On 3/29/20 8:18 AM, JNB wrote: > Dear Sirs, > I have Python 3.8.2 installed, but it seems to be without IDLE. Would you > kindly guide me to get IDLE. Assuming you're using the python.org installer (you can also get the same Python from the Microsoft Store now, if you prefer that route), check the setup this way: click the Windows icon (start menu) in the bottom left corner, click settings click Apps scroll down to Python in the app list, click it to expand the entry, and click Modify In the Python Setup window that appears, click Modify see if the "tcl/tk and IDLE" box is ticked. If it isn't, tick it and click Next, then Install, to update your installation. If it is already ticked, you already have IDLE, and it's a question of actually finding it - just go ahead and cancel out of the setup. If it is installed, in a Windows / Cortana search box, just start typing idle, it should pop up with a match, and you can launch from there. As a side note: IDLE comes with Python, but IDLE is not Python. Feel free to choose any other editor/IDE you want that knows how to edit Python (if an IDE, it should also give you th option to run in place, debug, etc,. as IDLE does). From alan.gauld at yahoo.co.uk Mon Mar 30 15:08:09 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 30 Mar 2020 20:08:09 +0100 Subject: [Tutor] Installing IDLE In-Reply-To: References: Message-ID: On 30/03/2020 11:51, Alan Gauld via Tutor wrote: > On my PC that is: > > C:\Python3\idlelib\idle.bat Oops, that should be: C:\Python3\Lib\idlelib\idle.bat I missed Lib, sorry. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From michael.langdon01 at gmail.com Mon Mar 30 17:11:22 2020 From: michael.langdon01 at gmail.com (Michael Langdon) Date: Tue, 31 Mar 2020 10:11:22 +1300 Subject: [Tutor] Beginners question Message-ID: Hi there, I have been tasked to use a while loop to repeatedly ask the user to enter a word. If the word is not 'quit', then add it to the list of words collected so far, in lower case. Then ask for the next word and so on. If they enter 'quit', do not add this word to the list, but print the list of words collected so far and exit the program. My input. a = input("Enter a word: ") sentence = sentence , a while a != ("quit"): sentence = sentence , a a = input("Enter a word: ") print(sentence) My output. Enter a word: orange ((), 'orange') Enter a word: apple (((), 'orange'), 'orange') Enter a word: quit ((((), 'orange'), 'orange'), 'apple') Can you help me with this? Regards, Michael From alan.gauld at yahoo.co.uk Mon Mar 30 20:38:58 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 31 Mar 2020 01:38:58 +0100 Subject: [Tutor] Beginners question In-Reply-To: References: Message-ID: On 30/03/2020 22:11, Michael Langdon wrote: > My input. > a = input("Enter a word: ") > sentence = sentence , a > while a != ("quit"): > sentence = sentence , a > a = input("Enter a word: ") > print(sentence) As you can see your code has lost all indentation. To avoid this you *must* post in plain text BTW You don't need the second line, it is not really doing anything (In fact I'd expect it to give an error since you are assigning sentence before creating it!) > My output. > Enter a word: orange > ((), 'orange') > Enter a word: apple > (((), 'orange'), 'orange') > Enter a word: quit > ((((), 'orange'), 'orange'), 'apple') > > > Can you help me with this? I'm not sure what you expect? The program is doubless doing exactly what you told it to do. What did you want it to do differently? I can guess but it is better if you explain it to us (you might even figure out the issue as you explain 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 akleider at sonic.net Mon Mar 30 20:31:26 2020 From: akleider at sonic.net (Alex Kleider) Date: Mon, 30 Mar 2020 17:31:26 -0700 Subject: [Tutor] Beginners question In-Reply-To: References: Message-ID: <9ce8306447a1a36279947ed0e514c3ad@sonic.net> On 2020-03-30 14:11, Michael Langdon wrote: > Hi there, > > > I have been tasked to use a while loop to repeatedly ask the user to > enter > a word. > > If the word is not 'quit', then add it to the list of words collected > so > far, in lower case. Then ask for the next word and so on. > > If they enter 'quit', do not add this word to the list, but print the > list > of words collected so far and exit the program. > > My input. > a = input("Enter a word: ") > sentence = sentence , a > while a != ("quit"): > sentence = sentence , a > a = input("Enter a word: ") > print(sentence) > > My output. > Enter a word: orange > ((), 'orange') > Enter a word: apple > (((), 'orange'), 'orange') > Enter a word: quit > ((((), 'orange'), 'orange'), 'apple') > > > Can you help me with this? Do you know about the key word 'break'? use it as follows: while True: # get input # if input means quit break # break out of the loop # proceed with whatever you want to do Another key word worth knowing about is 'continue' From PyTutor at danceswithmice.info Mon Mar 30 22:56:43 2020 From: PyTutor at danceswithmice.info (DL Neil) Date: Tue, 31 Mar 2020 15:56:43 +1300 Subject: [Tutor] Beginners question In-Reply-To: <9ce8306447a1a36279947ed0e514c3ad@sonic.net> References: <9ce8306447a1a36279947ed0e514c3ad@sonic.net> Message-ID: <54af6ab0-936c-0e63-38e6-1d7b6130645f@DancesWithMice.info> On 31/03/20 1:31 PM, Alex Kleider wrote: > On 2020-03-30 14:11, Michael Langdon wrote: >> Hi there, >> >> >> I have been tasked to use a while loop to repeatedly ask the user to >> enter >> a word. >> >> If the word is not 'quit', then add it to the list of words collected so >> far, in lower case. Then ask for the next word and so on. >> >> If they enter 'quit', do not add this word to the list, but print the >> list >> of words collected so far and exit the program. >> >> My input. >> a = input("Enter a word: ") >> sentence = sentence , a >> while a != ("quit"): >> sentence = sentence , a >> a = input("Enter a word: ") >> print(sentence) >> >> My output. >> Enter a word: orange >> ((), 'orange') >> Enter a word: apple >> (((), 'orange'), 'orange') >> Enter a word: quit >> ((((), 'orange'), 'orange'), 'apple') >> >> >> Can you help me with this? > > Do you know about the key word 'break'? > > use it as follows: > > while True: > ? # get input > ? # if input means quit > ?????? break?? # break out of the loop > ? # proceed with whatever you want to do I am 'breaking rules'* here... The above always looks so untidy to my eye. Could we use the 'walrus operator' instead of while True:? * 1 I haven't loaded v3.8 at home, to be able to test for myself. 2 'walrus' is likely beyond the OP's level of learning -- Regards =dn From akleider at sonic.net Tue Mar 31 04:47:43 2020 From: akleider at sonic.net (Alex Kleider) Date: Tue, 31 Mar 2020 01:47:43 -0700 Subject: [Tutor] Beginners question In-Reply-To: <54af6ab0-936c-0e63-38e6-1d7b6130645f@DancesWithMice.info> References: <9ce8306447a1a36279947ed0e514c3ad@sonic.net> <54af6ab0-936c-0e63-38e6-1d7b6130645f@DancesWithMice.info> Message-ID: <79f2d4c9bda941b781d87e96a735703b@sonic.net> >> while True: >> ? # get input >> ? # if input means quit >> ?????? break?? # break out of the loop >> ? # proceed with whatever you want to do > > > I am 'breaking rules'* here... > > The above always looks so untidy to my eye. Could we use the 'walrus > operator' instead of while True:? > > * > 1 I haven't loaded v3.8 at home, to be able to test for myself. > 2 'walrus' is likely beyond the OP's level of learning Agreed, and probably beyond mine as well but I for one would very much like to see how it could make this look less 'untidy.' (Follow up question will be how to install p3.8: Ubuntu 18.4LTS, virtualenvwrapper: pip install python3.8 ... ???? ) From __peter__ at web.de Tue Mar 31 07:50:35 2020 From: __peter__ at web.de (Peter Otten) Date: Tue, 31 Mar 2020 13:50:35 +0200 Subject: [Tutor] Beginners question References: <9ce8306447a1a36279947ed0e514c3ad@sonic.net> <54af6ab0-936c-0e63-38e6-1d7b6130645f@DancesWithMice.info> <79f2d4c9bda941b781d87e96a735703b@sonic.net> Message-ID: Alex Kleider wrote: > >>> while True: >>> # get input >>> # if input means quit >>> break # break out of the loop >>> # proceed with whatever you want to do >> >> >> I am 'breaking rules'* here... >> >> The above always looks so untidy to my eye. Could we use the 'walrus >> operator' instead of while True:? >> >> * >> 1 I haven't loaded v3.8 at home, to be able to test for myself. >> 2 'walrus' is likely beyond the OP's level of learning > > Agreed, and probably beyond mine as well but I for one would very much > like to see how it could make this look less 'untidy.' While I prefer the old-fashioned way here's how to spell the while loop without break: >>> while (word:=input("Enter a word: ")) != "quit": ... print(f"The word is {word!r}") ... Enter a word: hello The word is 'hello' Enter a word: world The word is 'world' Enter a word: quit >>> > (Follow up question will be how to install p3.8: Ubuntu 18.4LTS, > virtualenvwrapper: > pip install python3.8 ... ???? > ) Dunno, I've always done the $ ./configure $ make $ sudo make altinstall dance. This should get you a python3.8 while not interfering with the system pythons. You can then proceed to make a virtual environment with $ python3.8 -m venv whatever From PyTutor at danceswithmice.info Tue Mar 31 18:37:10 2020 From: PyTutor at danceswithmice.info (DL Neil) Date: Wed, 1 Apr 2020 11:37:10 +1300 Subject: [Tutor] Beginners question In-Reply-To: References: <9ce8306447a1a36279947ed0e514c3ad@sonic.net> <54af6ab0-936c-0e63-38e6-1d7b6130645f@DancesWithMice.info> <79f2d4c9bda941b781d87e96a735703b@sonic.net> Message-ID: <30e589e2-626e-0ce2-6688-dbbefcf52f52@DancesWithMice.info> With apologies to the OP for 'hi-jacking' the thread, a further question, if I may:- On 1/04/20 12:50 AM, Peter Otten wrote: >>>> while True: >>>> # get input >>>> # if input means quit >>>> break # break out of the loop >>>> # proceed with whatever you want to do >>> The above always looks so untidy to my eye. Could we use the 'walrus >>> operator' instead of while True:? > While I prefer the old-fashioned way here's how to spell the while loop > without break: >>>> while (word:=input("Enter a word: ")) != "quit": > ... print(f"The word is {word!r}") > ... > Enter a word: hello > The word is 'hello' > Enter a word: world > The word is 'world' > Enter a word: quit @Peter: why the preference for "the old-fashioned way"? (perhaps answered below...) Earlier, I opined that the first code-snippet is "untidy". Regrettably, so is the second (equally, an opinion), in that it is starting to look as if we are attempting to do 'too much' in one line of code. Hey, isn't that the 'virtue' of the walrus operator? Has such become liable to a similar judgment in deciding whether, for example; a complex list-comprehension expression should be coded in its compact form, or broken-out into a more readable for-loop? (particularly when dealing with lesser-mortals such as I). What more could we do? - users may have become habituated to typing "semaphores" such as "quit" to end input. However, Python allows considerable flexibility over previous generations of languages. Could we instead invite the user to hit Enter (with no data)? - how about Ctrl-Z (which after-all means EoF ("End of File") ) or some similar Exception-raising practice? I guess try-ing for Ctrl-Z would necessitate an additional two blocks/indentation. Might dispensing with the 'quit rule', allow the following code? while word:=input("Enter a word: "): print(f"The word is {word!r}") Does that satisfy the above (and any other) coding-criteria? (again: apologies for not having v3.8 to test for myself) -- Regards =dn