From mats at wichmann.us Tue May 1 09:08:24 2018 From: mats at wichmann.us (Mats Wichmann) Date: Tue, 1 May 2018 07:08:24 -0600 Subject: [Tutor] updating stock list In-Reply-To: References: Message-ID: On 04/30/2018 04:15 PM, Shannon Evans via Tutor wrote: > Hi, i'm wanting to update the stock list at the end so that the fruit > that's given is taken subtracted from the original stock list. The code > i've written isn't updating it it's just staying the same. Any idea what i > can do to fix this? > so a few notes in addition to what Alan has already written. COnsider: if stock[i[1]]>0: # if it reads awkwardly, look for a better way to write it. # how quickly would you know what stock[i[1]] is if you looked # at it a week later? # instead consider - what is an "i" here? It's a list, # with a typical entry being # ["Ronald Crawford", "Bananas"] # Why not unpack that into named variables right in the loop? for (person, fruit) in queue: # now you can refer to things by useful names: if stock[fruit]>0: print("Gave {} to {}".format(person,fruit)) # Hint: this is the ideal place to decrement the stock count does that help? From jf_byrnes at comcast.net Thu May 3 15:10:36 2018 From: jf_byrnes at comcast.net (Jim) Date: Thu, 3 May 2018 14:10:36 -0500 Subject: [Tutor] pip stopped working gives error Message-ID: I have python 3.6 installed in a virtual environment on Mint 18. Today I wanted to use pip and got this error when I tried to use it. (env36) jfb at jims-mint18 ~ $ pip help Traceback (most recent call last): File "/home/jfb/EVs/env36/bin/pip", line 7, in from pip import main File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/__init__.py", line 43, in from pip.utils import get_installed_distributions, get_prog File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/utils/__init__.py", line 23, in from pip.locations import ( File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/locations.py", line 9, in from distutils import sysconfig ImportError: cannot import name 'sysconfig' I searched for sysconfig and found this: /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/__pycache__/sysconfig.cpython-36.pyc /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.cfg /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.py The results seem to be the same as when I searched a python 3.5 virtual environment I have setup. It has worked in the past as I have installed pylint and pykeyboard with it. As I type this I just remembered Mint updated python 3.6 earlier today. So now I suspect the update is involved. Has anyone else experienced this and know how to fix it? Thanks, Jim From mats at wichmann.us Thu May 3 15:42:58 2018 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 3 May 2018 13:42:58 -0600 Subject: [Tutor] pip stopped working gives error In-Reply-To: References: Message-ID: On 05/03/2018 01:10 PM, Jim wrote: > I have python 3.6 installed in a virtual environment on Mint 18. Today I > wanted to use pip and got this error when I tried to use it. > > ?(env36) jfb at jims-mint18 ~ $ pip help > Traceback (most recent call last): > ? File "/home/jfb/EVs/env36/bin/pip", line 7, in > ??? from pip import main > ? File > "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/__init__.py", line > 43, in > ??? from pip.utils import get_installed_distributions, get_prog > ? File > "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/utils/__init__.py", > line 23, in > ??? from pip.locations import ( > ? File > "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/locations.py", line > 9, in > ??? from distutils import sysconfig > ImportError: cannot import name 'sysconfig' > > I searched for sysconfig and found this: > > /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/__pycache__/sysconfig.cpython-36.pyc > > /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.cfg > > /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.py > > > The results seem to be the same as when I searched a python 3.5 virtual > environment I have setup. > > It has worked in the past as I have installed pylint and pykeyboard with > it. As I type this I just remembered Mint updated python 3.6 earlier today. > > So now I suspect the update is involved. Has anyone else experienced > this and know how to fix it? I heard distutils may have been split out... see if you have a package python3-distutils and if not installed, can you install it? From jf_byrnes at comcast.net Thu May 3 16:27:28 2018 From: jf_byrnes at comcast.net (Jim) Date: Thu, 3 May 2018 15:27:28 -0500 Subject: [Tutor] pip stopped working gives error In-Reply-To: References: Message-ID: On 05/03/2018 02:42 PM, Mats Wichmann wrote: > On 05/03/2018 01:10 PM, Jim wrote: >> I have python 3.6 installed in a virtual environment on Mint 18. Today I >> wanted to use pip and got this error when I tried to use it. >> >> ?(env36) jfb at jims-mint18 ~ $ pip help >> Traceback (most recent call last): >> ? File "/home/jfb/EVs/env36/bin/pip", line 7, in >> ??? from pip import main >> ? File >> "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/__init__.py", line >> 43, in >> ??? from pip.utils import get_installed_distributions, get_prog >> ? File >> "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/utils/__init__.py", >> line 23, in >> ??? from pip.locations import ( >> ? File >> "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/locations.py", line >> 9, in >> ??? from distutils import sysconfig >> ImportError: cannot import name 'sysconfig' >> >> I searched for sysconfig and found this: >> >> /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/__pycache__/sysconfig.cpython-36.pyc >> >> /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.cfg >> >> /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.py >> >> >> The results seem to be the same as when I searched a python 3.5 virtual >> environment I have setup. >> >> It has worked in the past as I have installed pylint and pykeyboard with >> it. As I type this I just remembered Mint updated python 3.6 earlier today. >> >> So now I suspect the update is involved. Has anyone else experienced >> this and know how to fix it? > > I heard distutils may have been split out... see if you have a package > python3-distutils and if not installed, can you install it? I have: //usr/lib/python3.5/distutils and //usr/lib/python3.6/distutils, but no python3-distutils. Checking in Synaptic there is no python3-distutils but there is a python3-distutils-extra. Regards, Jim From zachary.ware+pytut at gmail.com Thu May 3 16:40:32 2018 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Thu, 3 May 2018 15:40:32 -0500 Subject: [Tutor] pip stopped working gives error In-Reply-To: References: Message-ID: On Thu, May 3, 2018 at 2:10 PM, Jim wrote: > I have python 3.6 installed in a virtual environment on Mint 18. Today I > wanted to use pip and got this error when I tried to use it. > > (env36) jfb at jims-mint18 ~ $ pip help > Traceback (most recent call last): > File "/home/jfb/EVs/env36/bin/pip", line 7, in > from pip import main > File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/__init__.py", > line 43, in > from pip.utils import get_installed_distributions, get_prog > File > "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/utils/__init__.py", > line 23, in > from pip.locations import ( > File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/locations.py", > line 9, in > from distutils import sysconfig > ImportError: cannot import name 'sysconfig' > > I searched for sysconfig and found this: > > /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/__pycache__/sysconfig.cpython-36.pyc > /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.cfg > /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.py > > The results seem to be the same as when I searched a python 3.5 virtual > environment I have setup. > > It has worked in the past as I have installed pylint and pykeyboard with it. > As I type this I just remembered Mint updated python 3.6 earlier today. > > So now I suspect the update is involved. Has anyone else experienced this > and know how to fix it? First, try a clean venv (python3.6 -m venv venv && ./venv/bin/pip help). If that works, then one of the nice things about virtual environments is that they're easy to recreate, especially if you have a handy list of the packages you want, say in a `requirements.txt` file. Then all you need to do is `python3.6 -m venv --clear /path/to/your/old/venv && /path/to/your/old/venv/bin/pip install -r requirements.txt`. If you don't already have a requirements.txt file, you can create one by listing the names of the packages you want in a file, each on its own line. -- Zach From mats at wichmann.us Thu May 3 16:48:19 2018 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 3 May 2018 14:48:19 -0600 Subject: [Tutor] pip stopped working gives error In-Reply-To: References: Message-ID: <5d3603cc-7161-5494-7153-ad72698905d9@wichmann.us> On 05/03/2018 02:27 PM, Jim wrote: >> I heard distutils may have been split out... see if you have a package >> python3-distutils and if not installed, can you install it? > > I have: > > //usr/lib/python3.5/distutils > and > //usr/lib/python3.6/distutils, but no python3-distutils. > > Checking in Synaptic there is no python3-distutils but there is a > python3-distutils-extra. it was a guess... this change seems to have just happened in Ubuntu (bionic/18.04 only), perhaps that's not the thing affecting you in Mint (yet). $ dpkg -l python3-distutils Desired=Unknown/Install/Remove/Purge/Hold | Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend |/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad) ||/ Name Version Architecture Description +++-====================================-=======================-=======================-============================================================================= ii python3-distutils 3.6.5-3 all distutils package for Python 3.x $ dpkg -L python3 | grep sysconfig $ dpkg -L python3-distutils | grep sysconfig /usr/lib/python3.6/distutils/sysconfig.py /usr/lib/python3.7/distutils/sysconfig.py $ From jf_byrnes at comcast.net Fri May 4 16:15:23 2018 From: jf_byrnes at comcast.net (Jim) Date: Fri, 4 May 2018 15:15:23 -0500 Subject: [Tutor] pip stopped working gives error In-Reply-To: References: Message-ID: On 05/03/2018 03:40 PM, Zachary Ware wrote: > On Thu, May 3, 2018 at 2:10 PM, Jim wrote: >> I have python 3.6 installed in a virtual environment on Mint 18. Today I >> wanted to use pip and got this error when I tried to use it. >> >> (env36) jfb at jims-mint18 ~ $ pip help >> Traceback (most recent call last): >> File "/home/jfb/EVs/env36/bin/pip", line 7, in >> from pip import main >> File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/__init__.py", >> line 43, in >> from pip.utils import get_installed_distributions, get_prog >> File >> "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/utils/__init__.py", >> line 23, in >> from pip.locations import ( >> File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/locations.py", >> line 9, in >> from distutils import sysconfig >> ImportError: cannot import name 'sysconfig' >> >> I searched for sysconfig and found this: >> >> /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/__pycache__/sysconfig.cpython-36.pyc >> /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.cfg >> /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.py >> >> The results seem to be the same as when I searched a python 3.5 virtual >> environment I have setup. >> >> It has worked in the past as I have installed pylint and pykeyboard with it. >> As I type this I just remembered Mint updated python 3.6 earlier today. >> >> So now I suspect the update is involved. Has anyone else experienced this >> and know how to fix it? > > First, try a clean venv (python3.6 -m venv venv && ./venv/bin/pip help). Ok, I just tried this and got this error. jfb at jims-mint18 ~ $ python3.6 -m venv /home/jfb/EVs/env365 && ./venv/bin/pip help The virtual environment was not created successfully because ensurepip is not available. On Debian/Ubuntu systems, you need to install the python3-venv package using the following command. apt-get install python3-venv You may need to use sudo with that command. After installing the python3-venv package, recreate your virtual environment. Failing command: ['/home/jfb/EVs/env365/bin/python3.6', '-Im', 'ensurepip', '--upgrade', '--default-pip'] Couple of things troubling about this message. I just checked and python3-venv is installed, in fact I used it to install the python3.6 environment I'm having problems with. I did a search and ensurepip is on my system at //usr/lib/python3.6/ensurepip. Regards, Jim From jf_byrnes at comcast.net Fri May 4 22:47:29 2018 From: jf_byrnes at comcast.net (Jim) Date: Fri, 4 May 2018 21:47:29 -0500 Subject: [Tutor] pip stopped working gives error In-Reply-To: <5d3603cc-7161-5494-7153-ad72698905d9@wichmann.us> References: <5d3603cc-7161-5494-7153-ad72698905d9@wichmann.us> Message-ID: On 05/03/2018 03:48 PM, Mats Wichmann wrote: > On 05/03/2018 02:27 PM, Jim wrote: > >>> I heard distutils may have been split out... see if you have a package >>> python3-distutils and if not installed, can you install it? >> >> I have: >> >> //usr/lib/python3.5/distutils >> and >> //usr/lib/python3.6/distutils, but no python3-distutils. >> >> Checking in Synaptic there is no python3-distutils but there is a >> python3-distutils-extra. > > it was a guess... this change seems to have just happened in Ubuntu > (bionic/18.04 only), perhaps that's not the thing affecting you in Mint > (yet). > > $ dpkg -l python3-distutils > Desired=Unknown/Install/Remove/Purge/Hold > | > Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend > |/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad) > ||/ Name Version > Architecture Description > +++-====================================-=======================-=======================-============================================================================= > ii python3-distutils 3.6.5-3 all > distutils package for Python 3.x > $ dpkg -L python3 | grep sysconfig > $ dpkg -L python3-distutils | grep sysconfig > /usr/lib/python3.6/distutils/sysconfig.py > /usr/lib/python3.7/distutils/sysconfig.py > $ I don't know if I missed it or a late update pulled it in but I just did sudo apt install python3-distutils and now my problem is fixed. Thanks to you and Zachary for helping me out. Regards, Jim From thebigwurst at gmail.com Fri May 4 05:30:25 2018 From: thebigwurst at gmail.com (Brad M) Date: Fri, 4 May 2018 17:30:25 +0800 Subject: [Tutor] Python C extension - which method? Message-ID: Hi all: I want to create a C-based memory scanner for Python, and so far this is how I do it: Python: from ctypes import cdll mydll = cdll.LoadLibrary('hello.dll') print(mydll.say_something()) and hello.dll: #include __declspec(dllexport) int say_something() { return 1980; } so the printout is "1980" Is this alright? I am aware that there is another much more complicated method such as this: https://tutorialedge.net/python/python-c-extensions-tutorial/#building-and-installing-our-module Is my method alright? Thanks! From dbosah at buffalo.edu Fri May 4 15:53:41 2018 From: dbosah at buffalo.edu (Daniel Bosah) Date: Fri, 4 May 2018 15:53:41 -0400 Subject: [Tutor] Figuring out selective actions in Python Message-ID: Hello, I'm trying to figure out how to do blank in blank things. For example, if I want to delete 5 MB ( or anything ) for every 20 MB, how would the could look like? I'm essentially trying to do an action in one order of the sequence out of an entire sequence. Thank you for your help From scopensource at gmail.com Sat May 5 13:59:24 2018 From: scopensource at gmail.com (Simon Connah) Date: Sat, 5 May 2018 18:59:24 +0100 Subject: [Tutor] Extract main text from HTML document Message-ID: Hi, I'm writing a very simple web scraper. It'll download a page from a website and then store the result in a database of some sort. The problem is that this will obviously include a whole heap of HTML, JavaScript and maybe even some CSS. None of which is useful to me. I was wondering if there was a way in which I could download a web page and then just extract the main body of text without all of the HTML. The title is obviously easy but the main body of text could contain all sorts of HTML and I'm interested to know how I might go about removing the bits that are not needed but still keep the meaning of the document intact. Does anyone have any suggestions on this front at all? Thanks for any help. Simon. From mats at wichmann.us Sat May 5 17:39:37 2018 From: mats at wichmann.us (Mats Wichmann) Date: Sat, 5 May 2018 15:39:37 -0600 Subject: [Tutor] Extract main text from HTML document In-Reply-To: References: Message-ID: <320529bc-b5a6-2668-37ca-d12c85137f45@wichmann.us> On 05/05/2018 11:59 AM, Simon Connah wrote: > Hi, > > I'm writing a very simple web scraper. It'll download a page from a > website and then store the result in a database of some sort. The > problem is that this will obviously include a whole heap of HTML, > JavaScript and maybe even some CSS. None of which is useful to me. > > I was wondering if there was a way in which I could download a web > page and then just extract the main body of text without all of the > HTML. > > The title is obviously easy but the main body of text could contain > all sorts of HTML and I'm interested to know how I might go about > removing the bits that are not needed but still keep the meaning of > the document intact. > > Does anyone have any suggestions on this front at all? there's so much prior art in this space it's not really worth reinventing this, unless you're using it as an exercise to teach yourself more Python (always a worth goal!) Here's one guy's summary of _some_ of the existing practice, albeit probably the best known. https://elitedatascience.com/python-web-scraping-libraries From robertvstepp at gmail.com Sat May 5 17:43:01 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 5 May 2018 16:43:01 -0500 Subject: [Tutor] Extract main text from HTML document In-Reply-To: References: Message-ID: On Sat, May 5, 2018 at 12:59 PM, Simon Connah wrote: > I was wondering if there was a way in which I could download a web > page and then just extract the main body of text without all of the > HTML. I do not have any experience with this, but I like to collect books. One of them [1] says on page 245: "Beautiful Soup is a module for extracting information from an HTML page (and is much better for this purpose than regular expressions)." I believe this topic has come up before on this list as well as the main Python list. You may want to check it out. It can be installed with pip. [1] "Automate the Boring Stuff with Python -- Practical Programming for Total Beginners" by Al Sweigart. HTH! -- boB From stefan_ml at behnel.de Sat May 5 17:44:45 2018 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 5 May 2018 23:44:45 +0200 Subject: [Tutor] Python C extension - which method? In-Reply-To: References: Message-ID: Hi, Brad M schrieb am 04.05.2018 um 11:30: > I want to create a C-based memory scanner for Python, and so far this is > how I do it: > > Python: > > from ctypes import cdll > mydll = cdll.LoadLibrary('hello.dll') > print(mydll.say_something()) > > and hello.dll: > > #include > __declspec(dllexport) int say_something() > { > return 1980; > } > > so the printout is "1980" > > Is this alright? Depends on your needs and your C/C++ knowledge. If you have a shared library that provides the ready-made functionality, and accessing that native code at all is more important than calling it very quickly (e.g. you only do a few longish-running calls into it), then wrapping a shared library with ctypes (or preferably cffi) is a good way to do it. Otherwise, try either a native wrapper generator like pybind11, or write your wrapper in Cython. Specifically, if you are not just calling into an external library 1:1, but need to do (or can benefit from doing) non-trivial operations in native code, definitely use Cython. http://cython.org > I am aware that there is another much more complicated > method such as this: > > https://tutorialedge.net/python/python-c-extensions-tutorial/#building-and-installing-our-module Well, yes, it exists, but I advise against wrapping C code manually that way. It's just too cumbersome and error prone. Leave it to the experts who have already written their tools for you. Stefan Disclosure: I'm a Cython core dev, so I'm biased and I absolutely know what I'm talking about. From steve at pearwood.info Sun May 6 06:04:52 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 6 May 2018 20:04:52 +1000 Subject: [Tutor] Figuring out selective actions in Python In-Reply-To: References: Message-ID: <20180506100451.GQ9562@ando.pearwood.info> On Fri, May 04, 2018 at 03:53:41PM -0400, Daniel Bosah wrote: > Hello, > > I'm trying to figure out how to do blank in blank things. For example, if I > want to delete 5 MB ( or anything ) for every 20 MB, how would the could > look like? I'm essentially trying to do an action in one order of the > sequence out of an entire sequence. Huh? Does your question have anything to do with Python? What do you mean, "do blank in blank things"? Sounds like the old "Blankety-Blanks" game show... https://en.wikipedia.org/wiki/Blankety_Blanks_%28Australian_game_show%29#Gameplay -- Steve From jf_byrnes at comcast.net Sun May 6 12:05:30 2018 From: jf_byrnes at comcast.net (Jim) Date: Sun, 6 May 2018 11:05:30 -0500 Subject: [Tutor] Need help with a virtual environment mess Message-ID: In a prior thread you guys helped me fix a problem with pip after I upgraded an installed version of python 3.6 on my Mint 18 system. Pip would not run in my python 3.6 virtual environment. The fix was to use synaptic to install python3-distutils. I thought everything was ok until I tried to run a old script from a different VE using python 3.5 which could not import tkinter. I have 4 versions of python on this system: system Python2 = 2.7.12 (default) system Python3 = 3.5.2 (default) a VE called env = 3.5.2 a Ve called env36 = 3.6.5 This is the error I get trying to import tkinter in env, I also get the same error if I try to import it in system python3. jfb at jims-mint18 ~ $ source /home/jfb/EVs/env/bin/activate (env) jfb at jims-mint18 ~ $ python Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import tkinter as tk Traceback (most recent call last): File "/usr/lib/python3.5/tkinter/__init__.py", line 36, in import _tkinter ImportError: No module named '_tkinter' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 1, in File "/usr/lib/python3.5/tkinter/__init__.py", line 38, in raise ImportError(str(msg) + ', please install the python3-tk package') ImportError: No module named '_tkinter', please install the python3-tk package >>> If I go to synaptic and install the python3-tk it installs version 3.6.5 of the package and I can still not import tkinter in env with python 3.5.2, but I can in env36 with python 3.6.5. I don't know if it makes a difference but I installed python3.6 from LP-PPA-jonathonf-python-3.6/now. Thanks, Jim From breamoreboy at gmail.com Sun May 6 12:32:38 2018 From: breamoreboy at gmail.com (Mark Lawrence) Date: Sun, 6 May 2018 17:32:38 +0100 Subject: [Tutor] Extract main text from HTML document In-Reply-To: References: Message-ID: On 05/05/18 18:59, Simon Connah wrote: > Hi, > > I'm writing a very simple web scraper. It'll download a page from a > website and then store the result in a database of some sort. The > problem is that this will obviously include a whole heap of HTML, > JavaScript and maybe even some CSS. None of which is useful to me. > > I was wondering if there was a way in which I could download a web > page and then just extract the main body of text without all of the > HTML. > > The title is obviously easy but the main body of text could contain > all sorts of HTML and I'm interested to know how I might go about > removing the bits that are not needed but still keep the meaning of > the document intact. > > Does anyone have any suggestions on this front at all? > > Thanks for any help. > > Simon. A combination of requests http://docs.python-requests.org/en/master/ and beautiful soup https://www.crummy.com/software/BeautifulSoup/bs4/doc/ should fit the bill. Both are installable with pip and are regarded as best of breed. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From scopensource at gmail.com Sun May 6 06:47:25 2018 From: scopensource at gmail.com (Simon Connah) Date: Sun, 6 May 2018 11:47:25 +0100 Subject: [Tutor] Extract main text from HTML document In-Reply-To: References: Message-ID: Thanks for the replies, everyone. Beautiful Soup looks like a good option. My primary goal is to extract the main body text, the title and the meta description from a web page and run it through one of the cloud Natural Language processing services to find out some information that I'd like to know and I'd like to do it to quite a few websites. This is all for a little project I have in mind. I'm not even sure if it'll work but it'll be fun to try. I might have to do some custom work on top of what Beautiful Soup offers though as I need to get very specific data in a certain format. On 5 May 2018 at 22:43, boB Stepp wrote: > On Sat, May 5, 2018 at 12:59 PM, Simon Connah wrote: > >> I was wondering if there was a way in which I could download a web >> page and then just extract the main body of text without all of the >> HTML. > > I do not have any experience with this, but I like to collect books. > One of them [1] says on page 245: > > "Beautiful Soup is a module for extracting information from an HTML > page (and is much better for this purpose than regular expressions)." > > I believe this topic has come up before on this list as well as the > main Python list. You may want to check it out. It can be installed > with pip. > > [1] "Automate the Boring Stuff with Python -- Practical Programming > for Total Beginners" by Al Sweigart. > > HTH! > -- > boB > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From t100ss at gmail.com Sat May 5 17:31:33 2018 From: t100ss at gmail.com (Brian Lockwood) Date: Sat, 05 May 2018 21:31:33 +0000 Subject: [Tutor] Extract main text from HTML document In-Reply-To: References: Message-ID: Two things. The first thing is that you can download the page as a string and delete a everything between tags. Secondly It might be worth looking at Udacity cs101 as this course is all about a search engine. On Sat, 5 May 2018 at 22:27, Simon Connah wrote: > Hi, > > I'm writing a very simple web scraper. It'll download a page from a > website and then store the result in a database of some sort. The > problem is that this will obviously include a whole heap of HTML, > JavaScript and maybe even some CSS. None of which is useful to me. > > I was wondering if there was a way in which I could download a web > page and then just extract the main body of text without all of the > HTML. > > The title is obviously easy but the main body of text could contain > all sorts of HTML and I'm interested to know how I might go about > removing the bits that are not needed but still keep the meaning of > the document intact. > > Does anyone have any suggestions on this front at all? > > Thanks for any help. > > Simon. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From thebigwurst at gmail.com Sat May 5 20:39:06 2018 From: thebigwurst at gmail.com (Brad M) Date: Sun, 6 May 2018 08:39:06 +0800 Subject: [Tutor] Python C extension - which method? In-Reply-To: References: Message-ID: Does this have any downside? I have noticed that printf("HI") in my .DLL; doesn't really print anything. I am on windows. cdll.LoadLibrary('helloworld.dll') My next question is that I need to return an array or a list of address or int or some type of data, but if I returned a pointer to the array of some data type, how does the python cope with it? For instance, my plan is to have 3 functions: 1) a function that return all addresses that have a given value to python, say, 9001 2) then I do something with python so that values change, the target value is now 1009. 3) a second function that takes all the addresses as input and then return adddress that have values of 1009. 4) repeat 2 and 3 until there is only 1 or so of address which correct values. 5) A 3rd function that takes only 1 address and simply return the values at that address. So the whole point of having 1-4 is to find the one address that contain that values I want, and then all I do is to call the 3rd function to find the values at that address. So basically what I need to know is if the method I am using, cdll.LoadLibrary('helloworld.dll') is proper or I need some other method, and then I would like to find out how to handle the data returned. (address) Thanks!!! On Sun, May 6, 2018 at 5:44 AM, Stefan Behnel wrote: > Hi, > > Brad M schrieb am 04.05.2018 um 11:30: > > I want to create a C-based memory scanner for Python, and so far this is > > how I do it: > > > > Python: > > > > from ctypes import cdll > > mydll = cdll.LoadLibrary('hello.dll') > > print(mydll.say_something()) > > > > and hello.dll: > > > > #include > > __declspec(dllexport) int say_something() > > { > > return 1980; > > } > > > > so the printout is "1980" > > > > Is this alright? > > > Depends on your needs and your C/C++ knowledge. > > If you have a shared library that provides the ready-made functionality, > and accessing that native code at all is more important than calling it > very quickly (e.g. you only do a few longish-running calls into it), then > wrapping a shared library with ctypes (or preferably cffi) is a good way to > do it. > > Otherwise, try either a native wrapper generator like pybind11, or write > your wrapper in Cython. > > Specifically, if you are not just calling into an external library 1:1, but > need to do (or can benefit from doing) non-trivial operations in native > code, definitely use Cython. > > http://cython.org > > > > I am aware that there is another much more complicated > > method such as this: > > > > https://tutorialedge.net/python/python-c-extensions- > tutorial/#building-and-installing-our-module > > Well, yes, it exists, but I advise against wrapping C code manually that > way. It's just too cumbersome and error prone. Leave it to the experts who > have already written their tools for you. > > Stefan > > > Disclosure: I'm a Cython core dev, so I'm biased and I absolutely know what > I'm talking about. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From thebigwurst at gmail.com Sat May 5 20:49:59 2018 From: thebigwurst at gmail.com (Brad M) Date: Sun, 6 May 2018 08:49:59 +0800 Subject: [Tutor] Python C extension - which method? In-Reply-To: References: Message-ID: If I may ask, what's the difference between these two? 1) import ctypes hello = ctypes.WinDLL('hello', use_last_error=True) 2) from ctypes import cdll hello = cdll.LoadLibrary('hello.dll') Both of them can return "1980" from this: hello.c #include __declspec(dllexport) int say_something() { return 1980; } On Sun, May 6, 2018 at 8:39 AM, Brad M wrote: > Does this have any downside? I have noticed that printf("HI") in my .DLL; > doesn't really print anything. > I am on windows. > > cdll.LoadLibrary('helloworld.dll') > > > > My next question is that I need to return an array or a list of address or > int or some type of data, but > if I returned a pointer to the array of some data type, how does the > python cope with it? > > For instance, my plan is to have 3 functions: > > 1) a function that return all addresses that have a given value to python, > say, 9001 > 2) then I do something with python so that values change, the target value > is now 1009. > 3) a second function that takes all the addresses as input and then return > adddress that have values of 1009. > > 4) repeat 2 and 3 until there is only 1 or so of address which correct > values. > 5) A 3rd function that takes only 1 address and simply return the values > at that address. > > So the whole point of having 1-4 is to find the one address that contain > that values I want, and then > all I do is to call the 3rd function to find the values at that address. > > > > So basically what I need to know is if the method I am using, > cdll.LoadLibrary('helloworld.dll') > is proper or I need some other method, and then I would like to find out > how to handle the data returned. > (address) > > Thanks!!! > > > > On Sun, May 6, 2018 at 5:44 AM, Stefan Behnel wrote: > >> Hi, >> >> Brad M schrieb am 04.05.2018 um 11:30: >> > I want to create a C-based memory scanner for Python, and so far this is >> > how I do it: >> > >> > Python: >> > >> > from ctypes import cdll >> > mydll = cdll.LoadLibrary('hello.dll') >> > print(mydll.say_something()) >> > >> > and hello.dll: >> > >> > #include >> > __declspec(dllexport) int say_something() >> > { >> > return 1980; >> > } >> > >> > so the printout is "1980" >> > >> > Is this alright? >> >> >> Depends on your needs and your C/C++ knowledge. >> >> If you have a shared library that provides the ready-made functionality, >> and accessing that native code at all is more important than calling it >> very quickly (e.g. you only do a few longish-running calls into it), then >> wrapping a shared library with ctypes (or preferably cffi) is a good way >> to >> do it. >> >> Otherwise, try either a native wrapper generator like pybind11, or write >> your wrapper in Cython. >> >> Specifically, if you are not just calling into an external library 1:1, >> but >> need to do (or can benefit from doing) non-trivial operations in native >> code, definitely use Cython. >> >> http://cython.org >> >> >> > I am aware that there is another much more complicated >> > method such as this: >> > >> > https://tutorialedge.net/python/python-c-extensions-tutorial >> /#building-and-installing-our-module >> >> Well, yes, it exists, but I advise against wrapping C code manually that >> way. It's just too cumbersome and error prone. Leave it to the experts who >> have already written their tools for you. >> >> Stefan >> >> >> Disclosure: I'm a Cython core dev, so I'm biased and I absolutely know >> what >> I'm talking about. >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > > From thebigwurst at gmail.com Sat May 5 21:49:22 2018 From: thebigwurst at gmail.com (Brad M) Date: Sun, 6 May 2018 09:49:22 +0800 Subject: [Tutor] ValueError: Procedure probably called with too many arguments (8 bytes in excess) Message-ID: Hi all: I am experimenting with python calling some .DLL and this is my setup: scan.py memscan = ctypes.WinDLL('mahdll', use_last_error=True) print(memscan.say_something(1,2)) # So I pass to int to the DLL function. DLL: #include __declspec(dllexport) int say_something(int a, int b) { printf("Hello World"); return math(a, b); } int math(int a, int b) { return a + b; } # So I found it wont print "hello world" and it give this error: ValueError: Procedure probably called with too many arguments (8 bytes in excess) # Also, if I pass no argument to the function, it won't printf("Hello world") on the python interpreter or opens a console window to print it. So what's the right thing to do to pass arguments to a DLL function? Thanks! From thebigwurst at gmail.com Sat May 5 22:17:20 2018 From: thebigwurst at gmail.com (Brad M) Date: Sun, 6 May 2018 10:17:20 +0800 Subject: [Tutor] passing values and C pointers Message-ID: Hi all: Although I have college C++ 101 and Python 101 down my belt, I wan't taught how to read a reference manual to figure this out :( Say I have an array of values, say addresses or int produced by a c module/ c function that's in a DLL , how do I pass that array back to the python code? from ctypes import cdll mydll = cdll.LoadLibrary('mydll') a = mydll.c_get_data() or, as I have learned in C, I can use malloc to create a linked list(new beast for me) and then return the head pointer to the previous C function. But eventually I am going to pass that C pointer back to python, right? 1) how do i do that, 2) how do do work on that data on that pointer? let's say the pointer points to a linked list. Thanks all! From eryksun at gmail.com Sun May 6 15:15:37 2018 From: eryksun at gmail.com (eryk sun) Date: Sun, 6 May 2018 19:15:37 +0000 Subject: [Tutor] Python C extension - which method? In-Reply-To: References: Message-ID: On Sun, May 6, 2018 at 12:49 AM, Brad M wrote: > If I may ask, what's the difference between these two? > > 1) > import ctypes > hello = ctypes.WinDLL('hello', use_last_error=True) > > 2) > from ctypes import cdll > hello = cdll.LoadLibrary('hello.dll') Use ctypes.CDLL and ctypes.WinDLL instead of cdll.LoadLibrary and windll.LoadLibrary. The latter is more typing for no benefit and prevents using the constructor arguments: handle, mode (POSIX), use_errno, and use_last_error (Windows). You need the latter two options if the library requires C errno or Windows GetLastError(), in which case you should use ctypes.get_errno() or ctypes.get_last_error() to get the error values after a C function call. > Both of them can return "1980" from this: > > hello.c > > #include > > __declspec(dllexport) int say_something() > { > return 1980; > } CDLL is the cdecl calling convention, and WinDLL is stdcall. There is no difference in 64-bit Windows (x64 ABI). In 32-bit Windows (x86 ABI), cdecl has the caller clean the stack (i.e. pop arguments), and stdcall has the callee (the called function) clean the stack. cdecl allows functions with a variable number of arguments, such as the CRT printf function. In MSVC, cdecl is the default convention if you don't declare a function as __stdcall. A library can export functions with varying calling conventions, so in general you may need to mix CDLL and WinDLL. From eryksun at gmail.com Sun May 6 16:02:12 2018 From: eryksun at gmail.com (eryk sun) Date: Sun, 6 May 2018 20:02:12 +0000 Subject: [Tutor] passing values and C pointers In-Reply-To: References: Message-ID: On Sun, May 6, 2018 at 2:17 AM, Brad M wrote: > > Say I have an array of values, say addresses or int produced by a c module/ > c function that's in a DLL , how do I pass that array back to > the python code? C arrays are passed and returned automatically as pointers to the first element. The array length has to be passed separately, unless there's a known sentinel value. A simple pattern is to let the caller allocate the array and pass a pointer and the length. This gives the caller explicit control over the lifetime of the array, which is especially simple for ctypes since it uses reference-counted objects. Say you have a function in C such as the following: int DLLAPI get_data(int *data, size_t length) { size_t i; for (i=0, i < length; i++) { if (do_something(i, &data[i]) == -1) { return -1; /* failure */ } } return 0; /* success */ } In Python, set up and call this function as follows: import ctypes mydll = ctypes.CDLL('mydll') # setup mydll.get_data.argtypes = ( ctypes.POINTER(ctypes.c_int), # data ctypes.c_size_t) # length # call data = (ctypes.c_int * 10)() status = mydll.get_data(data, len(data)) if status == -1: raise MyDllException('get_data: ...') for i, value in enumerate(data): result = do_something_else(i, value) From robertvstepp at gmail.com Sun May 6 17:59:58 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 6 May 2018 16:59:58 -0500 Subject: [Tutor] How to separate UI code from program logic? Message-ID: I was solving a programming problem in one of my books concerning the generation of a Collatz sequence (https://en.wikipedia.org/wiki/Collatz_conjecture), and started to wonder how I should separate my program's output from its logic. It seems like this should be obvious to me, but, unfortunately, it isn't. The core functions from my program are: #---------------------------------------------------------------------------- def collatz(integer): """Returns the Collatz sequence number corresponding to integer. integer must be > 0, or the sequence will not converge to 1.""" if integer % 2 == 0: return integer // 2 else: return 3 * integer + 1 def generate_collatz_sequence(seed): """Generates a Collatz sequence starting from seed. seed must be a positive integer, or the sequence will not coverge to 1.""" counter = 0 collatz_number = seed print("Collatz seed number: ", collatz_number) while True: counter += 1 collatz_number = collatz(collatz_number) print("Collatz number", counter, ": ", collatz_number) if collatz_number == 1: print("The Collatz sequence has once again converged to 1!") break #---------------------------------------------------------------------------- My understanding of best practice here is that I should not have any print() calls inside my generate_collatz_sequence() function. I _could_ store the generated sequence in a list and return it, but that does not seem like good use of RAM if some user-supplied seed value led to kazillions of Collatz sequence numbers being generated. As it stands there will be no theoretical RAM issues as the numbers are being generated and then outputted one at a time. OTOH, if I created some kind of display messages function, I don't see how I have gained anything as these calls to a display message function would just be taking the place of the print() calls. The end result would be the same -- display code interleaved with program logic code. What am I being dense about here? -- boB From robertvstepp at gmail.com Sun May 6 18:16:34 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 6 May 2018 17:16:34 -0500 Subject: [Tutor] Need help with a virtual environment mess In-Reply-To: References: Message-ID: On Sun, May 6, 2018 at 11:05 AM, Jim wrote: > In a prior thread you guys helped me fix a problem with pip after I upgraded > an installed version of python 3.6 on my Mint 18 system. Pip would not run > in my python 3.6 virtual environment. The fix was to use synaptic to install > python3-distutils. I thought everything was ok until I tried to run a old > script from a different VE using python 3.5 which could not import tkinter. > > I have 4 versions of python on this system: > system Python2 = 2.7.12 (default) > system Python3 = 3.5.2 (default) > a VE called env = 3.5.2 > a Ve called env36 = 3.6.5 > > This is the error I get trying to import tkinter in env, I also get the same > error if I try to import it in system python3. > > jfb at jims-mint18 ~ $ source /home/jfb/EVs/env/bin/activate > (env) jfb at jims-mint18 ~ $ python > Python 3.5.2 (default, Nov 23 2017, 16:37:01) > [GCC 5.4.0 20160609] on linux > Type "help", "copyright", "credits" or "license" for more information. >>>> import tkinter as tk > Traceback (most recent call last): > File "/usr/lib/python3.5/tkinter/__init__.py", line 36, in > import _tkinter > ImportError: No module named '_tkinter' > > During handling of the above exception, another exception occurred: > > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python3.5/tkinter/__init__.py", line 38, in > raise ImportError(str(msg) + ', please install the python3-tk package') > ImportError: No module named '_tkinter', please install the python3-tk > package >>>> > > If I go to synaptic and install the python3-tk it installs version 3.6.5 of > the package and I can still not import tkinter in env with python 3.5.2, but > I can in env36 with python 3.6.5. > As I have not yet tried to play around with virtual environments, I may be about to do more harm than help, but I will plow ahead anyway! ~(:>)) My primitive understanding of installing Python versions that are different from the system Python version into a virtual environment, is that you have to install all dependencies you need from within that virtual environment you created. If I am correct about this then your error messages suggest you need to install the tkinter stuff from within that virtual environment using that virtual environment's pip. Hopefully I am too far off from the truth here, but in any event, I hope this helps you in your problem! -- boB From alan.gauld at yahoo.co.uk Sun May 6 18:05:28 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 06 May 2018 23:05:28 +0100 Subject: [Tutor] How to separate UI code from program logic? Message-ID: On 6 May 2018, at 23:00, boB Stepp wrote: >I was solving a programming problem in one of my books concerning the >generation of a Collatz sequence >(https://en.wikipedia.org/wiki/Collatz_conjecture), and started to >wonder how I should separate my program's output from its logic.? It >seems like this should be obvious to me, but, unfortunately, it isn't. >The core functions from my program are: >#---------------------------------------------------------------------------- >def collatz(integer): >??? """Returns the Collatz sequence number corresponding to integer.? integer >??? must be > 0, or the sequence will not converge to 1.""" >??? if integer % 2 == 0: >??????? return integer // 2 >??? else: >??????? return 3 * integer + 1 >def generate_collatz_sequence(seed): >??? """Generates a Collatz sequence starting from seed. >??? seed must be a positive integer, or the sequence will not >??? coverge to 1.""" >??? counter = 0 >??? collatz_number = seed >??? print("Collatz seed number: ", collatz_number) >??? while True: >??????? counter += 1 >??????? collatz_number = collatz(collatz_number) >??????? print("Collatz number", counter, ": ", collatz_number) >??????? if collatz_number == 1: >??????????? print("The Collatz sequence has once again converged to 1!") >??????????? break >#---------------------------------------------------------------------------- >My understanding of best practice here is that I should not have any >print() calls inside my generate_collatz_sequence() function.? I >_could_ store the generated sequence in a list and return it, but that >does not seem like good use of RAM if some user-supplied seed value >led to kazillions of Collatz sequence numbers being generated.? The clue is in that last word. Write a generator function that yields the intermediate results. Alan g. From robertvstepp at gmail.com Sun May 6 18:29:09 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 6 May 2018 17:29:09 -0500 Subject: [Tutor] How to separate UI code from program logic? In-Reply-To: References: Message-ID: On Sun, May 6, 2018 at 5:05 PM, Alan Gauld wrote: > On 6 May 2018, at 23:00, boB Stepp wrote: >>My understanding of best practice here is that I should not have any >>print() calls inside my generate_collatz_sequence() function. I >>_could_ store the generated sequence in a list and return it, but that >>does not seem like good use of RAM if some user-supplied seed value >>led to kazillions of Collatz sequence numbers being generated. > > The clue is in that last word. > Write a generator function that yields the intermediate results. Aha! Of course the book I am poking around in does not even cover generator functions ... But I will plow ahead as usual and implement your suggestion. Thanks, Alan! -- boB From breamoreboy at gmail.com Sun May 6 18:35:51 2018 From: breamoreboy at gmail.com (Mark Lawrence) Date: Sun, 6 May 2018 23:35:51 +0100 Subject: [Tutor] How to separate UI code from program logic? In-Reply-To: References: Message-ID: On 06/05/18 22:59, boB Stepp wrote: > I was solving a programming problem in one of my books concerning the > generation of a Collatz sequence > (https://en.wikipedia.org/wiki/Collatz_conjecture), and started to > wonder how I should separate my program's output from its logic. It > seems like this should be obvious to me, but, unfortunately, it isn't. > The core functions from my program are: > > #---------------------------------------------------------------------------- > def collatz(integer): > """Returns the Collatz sequence number corresponding to integer. integer > must be > 0, or the sequence will not converge to 1.""" > > if integer % 2 == 0: > return integer // 2 > else: > return 3 * integer + 1 > > def generate_collatz_sequence(seed): > """Generates a Collatz sequence starting from seed. > seed must be a positive integer, or the sequence will not > coverge to 1.""" > > counter = 0 > collatz_number = seed > print("Collatz seed number: ", collatz_number) > while True: > counter += 1 > collatz_number = collatz(collatz_number) > print("Collatz number", counter, ": ", collatz_number) > if collatz_number == 1: > print("The Collatz sequence has once again converged to 1!") > break > #---------------------------------------------------------------------------- > > My understanding of best practice here is that I should not have any > print() calls inside my generate_collatz_sequence() function. I > _could_ store the generated sequence in a list and return it, but that > does not seem like good use of RAM if some user-supplied seed value > led to kazillions of Collatz sequence numbers being generated. As it > stands there will be no theoretical RAM issues as the numbers are > being generated and then outputted one at a time. OTOH, if I created > some kind of display messages function, I don't see how I have gained > anything as these calls to a display message function would just be > taking the place of the print() calls. The end result would be the > same -- display code interleaved with program logic code. What am I > being dense about here? > You're not being dense, you're just trying to wrap your head around a difficult concept. I suggest you read up on the model view controller pattern. First hit on google https://www.tomdalling.com/blog/software-design/model-view-controller-explained/ seems as good as any. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From robertvstepp at gmail.com Mon May 7 01:26:08 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Mon, 7 May 2018 00:26:08 -0500 Subject: [Tutor] How to separate UI code from program logic? In-Reply-To: References: Message-ID: On Sun, May 6, 2018 at 5:05 PM, Alan Gauld wrote: > On 6 May 2018, at 23:00, boB Stepp wrote: >>My understanding of best practice here is that I should not have any >>print() calls inside my generate_collatz_sequence() function. I >>_could_ store the generated sequence in a list and return it, but that >>does not seem like good use of RAM if some user-supplied seed value >>led to kazillions of Collatz sequence numbers being generated. > > The clue is in that last word. > Write a generator function that yields the intermediate results. Ok. I've been reading up on generators and playing around with them today. And then, per Alan's hint, tried to separate all display code from my program logic code. What was originally meant to be a throw-away effort, has somehow mushroomed into something I hope resembles a finished product. The results I came up with are as follows: #-------------------------------------------------------------------------------- #!/usr/bin/env python3 """This program will generate a Collatz sequence from a user-supplied positive integer. According to Wikipedia (https://en.wikipedia.org/wiki/Collatz_conjecture): "The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n. Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term. Otherwise, the next term is 3 times the previous term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1." """ def get_positive_integer(): """Get a positive integer from the user.""" while True: try: integer = int(input("Please enter a positive integer: ")) if integer > 0: return integer else: print("That was not a positive integer!") continue except ValueError: print("That was not an integer!") continue def display_collatz_numbers(seed, collatz_generator): """Display a Collatz sequence, one value per line, given the seed (Which will be the first number in the sequence.) and a generator which will yield the Collatz sequence.""" print("\nThe seed number: ", seed) for sequence_index, number in enumerate(collatz_generator): print("Sequence number", sequence_index + 1, ": ", number) def ask_to_continue(): choice = input("Do you wish to generate another Collatz sequence?").lower() return choice.startswith('y') def get_collatz_number(integer): """Returns the Collatz sequence number corresponding to integer. integer must be > 0, or the sequence will not converge to 1.""" if integer % 2 == 0: return integer // 2 else: return 3 * integer + 1 def generate_collatz_sequence(seed): """Creates a generator, which will yield a Collatz sequence starting from seed. seed must be a positive integer, or the sequence will not converge to 1.""" collatz_number = seed while True: collatz_number = get_collatz_number(collatz_number) yield collatz_number if collatz_number == 1: return def main(): """Run program.""" while True: seed = get_positive_integer() display_collatz_numbers(seed, generate_collatz_sequence(seed)) if ask_to_continue(): continue else: break if __name__ == '__main__': main() #-------------------------------------------------------------------------------- Questions and comments: 1) I am open to a general critique on making this code better. 2) I spent a lot of effort trying to come up with a way to combine the two functions, get_collatz_number() and generate_collatz_sequence(), into something both more compact and more readable, but I was unsuccessful. I suspect there is a better way. Is there? And how would I do it? 3) Is this the correct way to separate display code from program logic code? Is there a better way to do this? 4) I think this is the first time I've actually tried to implement a generator function. Did I do a good Pythonic implementation of this? As always, thanks! -- boB From glennmschultz at me.com Sun May 6 18:38:00 2018 From: glennmschultz at me.com (Glenn Schultz) Date: Sun, 06 May 2018 18:38:00 -0400 Subject: [Tutor] PMML vs. Pickel Message-ID: All, have a Python prepayment model that must be integrated into 3rd party vendor software considering translating to PMML. I have been researching this. Any potential downside? Glenn Sent from my iPhone From alan.gauld at yahoo.co.uk Mon May 7 07:52:53 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 07 May 2018 12:52:53 +0100 Subject: [Tutor] PMML vs. Pickel In-Reply-To: Message-ID: <3527a251-b33c-428d-ba7c-1cccd3bfc8c1@email.android.com> The tutor list is for those learning python and its standard library. I suspect you will get a better response asking on the main python list. Alan g. From eryksun at gmail.com Mon May 7 10:01:18 2018 From: eryksun at gmail.com (eryk sun) Date: Mon, 7 May 2018 14:01:18 +0000 Subject: [Tutor] Python C extension - which method? In-Reply-To: References: Message-ID: On Mon, May 7, 2018 at 9:57 AM, Michael C wrote: > Sorry I don't understand your suggestion. > > Use "ctypes.CDLL" and "ctypes.WinDLL" > > this works, > mydll = cdll.LoadLibrary('test.dll') > print(mydll.sum(3,2)) > > and this doens't > mydll = cdll('test.dll') > print(mydll.sum(3,2)) > > What's the syntax of what you suggested? Loading the library is simply `mydll = ctypes.CDLL('test')`. Note that CDLL is uppercase. Python is a case-sensitive language. The base shared library class is CDLL. The constructor takes the following parameters: name, mode=DEFAULT_MODE, handle=None, use_errno=False, and use_last_error=False. For the first 3 parameters, if the shared library `handle` isn't provided, it calls ctypes._dlopen(mode, name) to load the library. The CDLL constructor dynamically defines a function-pointer subclass, with custom _flags_ and _restype_. The _restype_ is c_int (i.e. a 32-bit C integer). The base _flags_ value is _FUNCFLAG_CDECL because CDLL uses the cdecl calling convention. For the last two constructor parameters, use_errno includes _FUNCFLAG_USE_ERRNO, and use_last_error includes _FUNCFLAG_USE_LASTERROR. The above function pointer class is used by the __getitem__ method of a CDLL instance, which calls self._FuncPtr((name_or_ordinal, self)) to return a function pointer instance, e.g. mydll['sum']. (Using a subscript also allows ordinal look-up, such as mydll[42].) The function pointer is not cached, so it has to be instantiated ever time it's accessed this way. On the other hand, the __getattr__ method of CDLL calls __getitem__ and caches the function pointer via setattr(self, name, func). For example, with mydll.sum, the `sum` function pointer is cached. WinDLL subclasses CDLL to change the default function pointer _flags_ value to _FUNCFLAG_STDCALL because the Windows API uses the stdcall calling convention, as do many shared libraries on Windows. ctypes also defines a LibraryLoader class, of which ctypes.cdll and ctypes.windll are instances, i.e. cdll = LibraryLoader(CDLL). The constructor simply sets the shared library class as the attribute self._dlltype. In turn, the LoadLibrary method returns self._dlltype(name). This is silly because it's extra typing, an extra call, and prevents passing constructor arguments (e.g. use_last_error). Where this goes from silly to smelly is the __getattr__ method of LibraryLoader. This method makes the mistake of caching loaded libraries. For example, ctypes.windll.kernel32 caches a WinDLL('kernel32') instance on ctypes.windll. Remember that __getattr__ is a fallback method called by __getattribute__. Thus subsequent references to ctypes.windll.kernel32 will use the cached library instance. This is bad because multiple packages will end up sharing the same library instance. Recall that the __getattr__ method of CDLL caches function pointers. That's a good thing because function pointer look-up and instantiation is relatively expensive. I can understand the good intentions of carrying this over to caching entire library instances across multiple packages. But the savings is not worth the ensuing chaos of super-global cached state, especially for commonly used Windows libraries such as kernel32.dll. The problem is that every function pointer defines a prototype that consists of its errcheck, restype, and argtypes properties, but not every package or script will define these exactly the same, for various reasons. Thus the last one to define the prototype wins. All other users of the library in the process will be broken. In short, avoid ctypes.[cdll | windll].LoadLibrary because it's silly, and avoid ctypes.[cdll | windll].[library name] because it's smelly. From mysecretrobotfactory at gmail.com Mon May 7 05:57:00 2018 From: mysecretrobotfactory at gmail.com (Michael C) Date: Mon, 7 May 2018 17:57:00 +0800 Subject: [Tutor] Python C extension - which method? In-Reply-To: References: Message-ID: Sorry I don't understand your suggestion. Use "ctypes.CDLL" and "ctypes.WinDLL" this works, mydll = cdll.LoadLibrary('test.dll') print(mydll.sum(3,2)) and this doens't mydll = cdll('test.dll') print(mydll.sum(3,2)) What's the syntax of what you suggested? Thanks On Mon, May 7, 2018 at 3:15 AM, eryk sun wrote: > On Sun, May 6, 2018 at 12:49 AM, Brad M wrote: > > If I may ask, what's the difference between these two? > > > > 1) > > import ctypes > > hello = ctypes.WinDLL('hello', use_last_error=True) > > > > 2) > > from ctypes import cdll > > hello = cdll.LoadLibrary('hello.dll') > > Use ctypes.CDLL and ctypes.WinDLL instead of cdll.LoadLibrary and > windll.LoadLibrary. The latter is more typing for no benefit and > prevents using the constructor arguments: handle, mode (POSIX), > use_errno, and use_last_error (Windows). You need the latter two > options if the library requires C errno or Windows GetLastError(), in > which case you should use ctypes.get_errno() or > ctypes.get_last_error() to get the error values after a C function > call. > > > Both of them can return "1980" from this: > > > > hello.c > > > > #include > > > > __declspec(dllexport) int say_something() > > { > > return 1980; > > } > > CDLL is the cdecl calling convention, and WinDLL is stdcall. There is > no difference in 64-bit Windows (x64 ABI). In 32-bit Windows (x86 > ABI), cdecl has the caller clean the stack (i.e. pop arguments), and > stdcall has the callee (the called function) clean the stack. cdecl > allows functions with a variable number of arguments, such as the CRT > printf function. In MSVC, cdecl is the default convention if you don't > declare a function as __stdcall. A library can export functions with > varying calling conventions, so in general you may need to mix CDLL > and WinDLL. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From scopensource at gmail.com Mon May 7 07:05:15 2018 From: scopensource at gmail.com (Simon Connah) Date: Mon, 7 May 2018 12:05:15 +0100 Subject: [Tutor] Extract main text from HTML document In-Reply-To: References: Message-ID: That looks like a useful combination. Thanks. On 6 May 2018 at 17:32, Mark Lawrence wrote: > On 05/05/18 18:59, Simon Connah wrote: >> >> Hi, >> >> I'm writing a very simple web scraper. It'll download a page from a >> website and then store the result in a database of some sort. The >> problem is that this will obviously include a whole heap of HTML, >> JavaScript and maybe even some CSS. None of which is useful to me. >> >> I was wondering if there was a way in which I could download a web >> page and then just extract the main body of text without all of the >> HTML. >> >> The title is obviously easy but the main body of text could contain >> all sorts of HTML and I'm interested to know how I might go about >> removing the bits that are not needed but still keep the meaning of >> the document intact. >> >> Does anyone have any suggestions on this front at all? >> >> Thanks for any help. >> >> Simon. > > > A combination of requests http://docs.python-requests.org/en/master/ and > beautiful soup https://www.crummy.com/software/BeautifulSoup/bs4/doc/ should > fit the bill. Both are installable with pip and are regarded as best of > breed. > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From r-yan14 at mails.tsinghua.edu.cn Mon May 7 07:53:32 2018 From: r-yan14 at mails.tsinghua.edu.cn (ruiyan) Date: Mon, 7 May 2018 19:53:32 +0800 (GMT+08:00) Subject: [Tutor] use python to log to a remote supercomputer and transfer files Message-ID: <5c116c33.696e.1633a731aae.Coremail.r-yan14@mails.tsinghua.edu.cn> Hello everyone, I need to conduct massive simulation computations using a software called 'lammps' on a remote supercomputer whose operating system is Linux every day. It's extremely annoying to log to the remote supercomputer, upload files to and download files from the supercomputer using WinSCP and Putty on my windows desktop computer. I want to know whether it is possible to write some scripts and let python do these things for me, i.e., I want to log to the remote supercomputer automatically, upload and download files with a simple hit in python (of course with the files specified). Is this possible? If it is possible, which packages do I need? Thanks and best wishes, Rui From alan.gauld at yahoo.co.uk Mon May 7 10:15:53 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 07 May 2018 15:15:53 +0100 Subject: [Tutor] use python to log to a remote supercomputer and transfer files Message-ID: On 7 May 2018, at 15:08, ruiyan wrote: > I want to log to the remote supercomputer automatically, upload and download files If it supports ftp then there is an ftp module. There are also http and ssh modules, depending on the complexity of your needs and the protocols available. Ftp sounds simplest in this case. Alan g. From mats at wichmann.us Mon May 7 11:28:26 2018 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 7 May 2018 09:28:26 -0600 Subject: [Tutor] use python to log to a remote supercomputer and transfer files In-Reply-To: <5c116c33.696e.1633a731aae.Coremail.r-yan14@mails.tsinghua.edu.cn> References: <5c116c33.696e.1633a731aae.Coremail.r-yan14@mails.tsinghua.edu.cn> Message-ID: On 05/07/2018 05:53 AM, ruiyan wrote: > Hello everyone, > > > I need to conduct massive simulation computations using a software called 'lammps' on a remote supercomputer whose operating system is Linux every day. It's extremely annoying to log to the remote supercomputer, upload files to and download files from the supercomputer using WinSCP and Putty on my windows desktop computer. I want to know whether it is possible to write some scripts and let python do these things for me, i.e., I want to log to the remote supercomputer automatically, upload and download files with a simple hit in python (of course with the files specified). Is this possible? If it is possible, which packages do I need? There are lots of methods for this. If you're already using Putty, you probably want to continue using ssh protocol, so you can look into a Python package called Paramiko. From jf_byrnes at comcast.net Mon May 7 12:16:16 2018 From: jf_byrnes at comcast.net (Jim) Date: Mon, 7 May 2018 11:16:16 -0500 Subject: [Tutor] Need help with a virtual environment mess In-Reply-To: References: Message-ID: On 05/06/2018 05:16 PM, boB Stepp wrote: > On Sun, May 6, 2018 at 11:05 AM, Jim wrote: >> In a prior thread you guys helped me fix a problem with pip after I upgraded >> an installed version of python 3.6 on my Mint 18 system. Pip would not run >> in my python 3.6 virtual environment. The fix was to use synaptic to install >> python3-distutils. I thought everything was ok until I tried to run a old >> script from a different VE using python 3.5 which could not import tkinter. >> >> I have 4 versions of python on this system: >> system Python2 = 2.7.12 (default) >> system Python3 = 3.5.2 (default) >> a VE called env = 3.5.2 >> a Ve called env36 = 3.6.5 >> >> This is the error I get trying to import tkinter in env, I also get the same >> error if I try to import it in system python3. >> >> jfb at jims-mint18 ~ $ source /home/jfb/EVs/env/bin/activate >> (env) jfb at jims-mint18 ~ $ python >> Python 3.5.2 (default, Nov 23 2017, 16:37:01) >> [GCC 5.4.0 20160609] on linux >> Type "help", "copyright", "credits" or "license" for more information. >>>>> import tkinter as tk >> Traceback (most recent call last): >> File "/usr/lib/python3.5/tkinter/__init__.py", line 36, in >> import _tkinter >> ImportError: No module named '_tkinter' >> >> During handling of the above exception, another exception occurred: >> >> Traceback (most recent call last): >> File "", line 1, in >> File "/usr/lib/python3.5/tkinter/__init__.py", line 38, in >> raise ImportError(str(msg) + ', please install the python3-tk package') >> ImportError: No module named '_tkinter', please install the python3-tk >> package >>>>> >> >> If I go to synaptic and install the python3-tk it installs version 3.6.5 of >> the package and I can still not import tkinter in env with python 3.5.2, but >> I can in env36 with python 3.6.5. >> > > As I have not yet tried to play around with virtual environments, I > may be about to do more harm than help, but I will plow ahead anyway! > ~(:>)) > > My primitive understanding of installing Python versions that are > different from the system Python version into a virtual environment, > is that you have to install all dependencies you need from within that > virtual environment you created. If I am correct about this then your > error messages suggest you need to install the tkinter stuff from > within that virtual environment using that virtual environment's pip. > Hopefully I am too far off from the truth here, but in any event, I > hope this helps you in your problem! > My understanding of VE's, based on some feedback from here, is you install install the python you want on the system then use it to install your VE. Then you install what ever you need to the VE. In my case I had a working VE based on python 3.5 then I received an upgrade to the python version 3.6 I had installed. After that I had problems with the 3.5 VE that had been working. Regards, Jim From wolfgang.maier at biologie.uni-freiburg.de Mon May 7 11:17:43 2018 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Mon, 7 May 2018 17:17:43 +0200 Subject: [Tutor] use python to log to a remote supercomputer and transfer files In-Reply-To: References: Message-ID: <9387e9f3-e07d-fca0-bf27-9fff2ea9ab71@biologie.uni-freiburg.de> On 05/07/2018 04:15 PM, Alan Gauld via Tutor wrote: > > > On 7 May 2018, at 15:08, ruiyan wrote: > >> I want to log to the remote supercomputer automatically, upload and download files > > If it supports ftp then there is an ftp module. > > There are also http and ssh modules, depending on the complexity of your needs and the protocols available. Ftp sounds simplest in this case. > ... but the question is what kind of simplification / comfort increase you are hoping to get from a custom python script of your own compared to what WinSCP or Putty already offer. How are they making things "extremely annoying" for you? You can certainly learn a lot from writing or even just trying to write such a Python script, but in terms of functionality gain vs time invested I doubt the endeavor is worth it. Wolfgang From mats at wichmann.us Mon May 7 13:02:44 2018 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 7 May 2018 11:02:44 -0600 Subject: [Tutor] Need help with a virtual environment mess In-Reply-To: References: Message-ID: On 05/07/2018 10:16 AM, Jim wrote: > My understanding of VE's, based on some feedback from here, is you > install install the python you want on the system then use it to install > your VE. Then you install what ever you need to the VE. In my case I had > a working VE based on python 3.5 then I received an upgrade to the > python version 3.6 I had installed. After that I had problems with the > 3.5 VE that had been working. yes, this happens. the default behavior for virtualenv is to make links when creating the VE, which saves copying things but is vulnerable to breakage if the Python it's linking to receives major changes. In the case of a distribution upgrading the Python version, a VE constructed against the old version will break if the links are version-specific. Looking at one virtualenv I have, {VEPATH}/lib/python3.6 is full of such symlinks, e.g.: lrwxrwxrwx. 1 mats mats 26 Aug 17 2017 re.py -> /usr/lib64/python3.6/re.py Virtualenvs are cheap to recreate, so one approach is to just throw away the old one and make a new one. you can also give virtualenv an option (--always-copy) to cause the created virtualenv to be more self-contained, at a cost of some space and tiem. There are plenty of tools for managing python versions and virtualenv. The python community changed directions a little bit recently, 'venv' is now the recommended approach: https://docs.python.org/3/library/venv.html pyenv can manage different Python versions if you're interested in that. From jf_byrnes at comcast.net Mon May 7 14:04:23 2018 From: jf_byrnes at comcast.net (Jim) Date: Mon, 7 May 2018 13:04:23 -0500 Subject: [Tutor] Need help with a virtual environment mess In-Reply-To: References: Message-ID: On 05/07/2018 12:02 PM, Mats Wichmann wrote: > On 05/07/2018 10:16 AM, Jim wrote: > >> My understanding of VE's, based on some feedback from here, is you >> install install the python you want on the system then use it to install >> your VE. Then you install what ever you need to the VE. In my case I had >> a working VE based on python 3.5 then I received an upgrade to the >> python version 3.6 I had installed. After that I had problems with the >> 3.5 VE that had been working. > > yes, this happens. > > the default behavior for virtualenv is to make links when creating the > VE, which saves copying things but is vulnerable to breakage if the > Python it's linking to receives major changes. In the case of a > distribution upgrading the Python version, a VE constructed against the > old version will break if the links are version-specific. Looking at > one virtualenv I have, {VEPATH}/lib/python3.6 is full of such symlinks, > e.g.: > > lrwxrwxrwx. 1 mats mats 26 Aug 17 2017 re.py -> > /usr/lib64/python3.6/re.py > > > Virtualenvs are cheap to recreate, so one approach is to just throw away > the old one and make a new one. My problem is right now the default python3 for my system is also affected. If I type python3 I will see python version 3.5.2 and I cannot import tkinter there either. > you can also give virtualenv an option (--always-copy) to cause the > created virtualenv to be more self-contained, at a cost of some space > and tiem. > > There are plenty of tools for managing python versions and virtualenv. > The python community changed directions a little bit recently, 'venv' is > now the recommended approach: > > https://docs.python.org/3/library/venv.html That is what I used to setup my VE's. > pyenv can manage different Python versions if you're interested in that. > I am going to see if I can find some log file that would give me a clue about what happened during the update. Regards, Jim From kmurphy at easton.k12.ma.us Tue May 8 04:26:59 2018 From: kmurphy at easton.k12.ma.us (Kerri Murphy) Date: Tue, 8 May 2018 04:26:59 -0400 Subject: [Tutor] guess my number game Message-ID: My students are creating a guess my number game. They are trying to take this type of code (the flow of it), and turn it into a code using a while loop. Here is the first code n = int(input('Guess my number: '))if (n <= 172 and n >= 174): print('Correct')elif (n >= 174): a = int(input('Go Down')) if (a >= 174): c = int(input('Go Down')) if (c >= 174): g = int(input('Last Guess Go Down')) if (g == 173): print('Correct') elif (c <= 172): i = int(input('Last Guess Go Up')) if (i == 173): print('Correct') else: print('Correct') elif (a <= 172): e = int(input('Go up')) if (e >= 174): f = int(input('Last Guess Go Down')) if (f == 173): print('Correct') elif (e <= 172): h = int(input('Last Guess Go Up')) if (h == 173): print('Correct') else: print('Correct') else: print('Correct')elif (n <= 172): b = int(input('Go Up')) if (b >= 174): d = int(input('Go Down')) if (d >= 174): j = int(input('Last Guess Go Down')) if (j == 173): print('Correct') elif (d <= 172): m = int(input('Last Guess Go Up')) if (m == 173): print('Correct') else: print('Correct') elif (b <= 172): e = int(input('Go Up')) if (e >= 174): k = int(input('Last Guess Go Down')) if (k == 173): print('Correct') elif (e <= 172): l = int(input('Last Guess Go Up')) if (l == 173): print('Correct') else: print('Correct') else: print('Correct')else: print('Correct') Here is the code with the while loop import random n = (random.randint(0,100)) g = int(input('Guess my number, 0 to 100, you have 10 chances')) c = 0 while (c < 10): g = int(input('Guess my number, 0 to 100, you have 10 chances')) c = c + 1 if (g >= n): print('Lower!') elif (g <= n): print('Higher!') elif (g == n): break if (g == n): print('You guess my number! It took you ' + str(c) + ' tries!') Everyone's code just keeps asking for numbers without giving feedback, except for the longer code above. Can you help us consolidate the code? We are using random.randint. Thank you! From lists at mostrom.pp.se Tue May 8 08:04:51 2018 From: lists at mostrom.pp.se (Jan Erik =?utf-8?q?Mostr=C3=B6m?=) Date: Tue, 08 May 2018 14:04:51 +0200 Subject: [Tutor] guess my number game In-Reply-To: References: Message-ID: <6DBCC9DA-96AB-4807-9F99-5F643F9B7FED@mostrom.pp.se> > Here is the code with the while loop > import random > n = (random.randint(0,100)) > g = int(input('Guess my number, 0 to 100, you have 10 chances')) > c = 0 > while (c < 10): > g = int(input('Guess my number, 0 to 100, you have 10 chances')) > c = c + 1 > if (g >= n): > print('Lower!') > elif (g <= n): > print('Higher!') > elif (g == n): > break > if (g == n): > print('You guess my number! It took you ' + str(c) + ' tries!') > > > Everyone's code just keeps asking for numbers without giving feedback, > except for the longer code above. For me it prints out Lower/higher but not for the first time since the code asks a second time before doing anything with the reply. Here is a modified version where I kept most of the structure you have. Note that '>=' and '<=' was changed to '>' and '<'. import random n = (random.randint(0,100)) g = int(input('Guess my number, 0 to 100, you have 10 chances')) c = 0 while (c < 10 and g != n): if (g > n): print('Lower!') elif (g < n): print('Higher!') c = c + 1 g = int(input('Guess my number, 0 to 100, you have {} left'.format(10-c))) if (g == n): print('You guess my number! It took you ' + str(c) + ' tries!') From mats at wichmann.us Tue May 8 10:12:20 2018 From: mats at wichmann.us (Mats Wichmann) Date: Tue, 8 May 2018 08:12:20 -0600 Subject: [Tutor] guess my number game In-Reply-To: <6DBCC9DA-96AB-4807-9F99-5F643F9B7FED@mostrom.pp.se> References: <6DBCC9DA-96AB-4807-9F99-5F643F9B7FED@mostrom.pp.se> Message-ID: <5c8b020d-98bf-552f-b23e-3487ea578253@wichmann.us> On 05/08/2018 06:04 AM, Jan Erik Mostr?m wrote: > >> Here is the code with the while loop >> import random >> n = (random.randint(0,100)) >> g = int(input('Guess my number, 0 to 100, you have 10 chances')) you should get your students into good programming habits right away. Here you are taking data from outside the program's own control, and in the current terminology that data is "tainted" until you validate it - there should be a check that you got back a number in the range that you specify. Yes in this simple example you don't do anything with the guess that could be harmful, but they should still be learning to keep such considerations in mind. From robertvstepp at gmail.com Tue May 8 14:55:34 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 8 May 2018 13:55:34 -0500 Subject: [Tutor] How to separate UI code from program logic? In-Reply-To: References: Message-ID: On Mon, May 7, 2018 at 12:26 AM, boB Stepp wrote: > def get_collatz_number(integer): > """Returns the Collatz sequence number corresponding to integer. integer > must be > 0, or the sequence will not converge to 1.""" > > if integer % 2 == 0: > return integer // 2 > else: > return 3 * integer + 1 > > def generate_collatz_sequence(seed): > """Creates a generator, which will yield a Collatz sequence starting from > seed. seed must be a positive integer, or the sequence will not converge to > 1.""" > > collatz_number = seed > while True: > collatz_number = get_collatz_number(collatz_number) > yield collatz_number > if collatz_number == 1: > return > Questions and comments: After taking a break from this and coming at this afresh, I immediately saw an answer to this question: > 2) I spent a lot of effort trying to come up with a way to combine > the two functions, get_collatz_number() and > generate_collatz_sequence(), into something both more compact and more > readable, but I was unsuccessful. I suspect there is a better way. > Is there? And how would I do it? def generate_collatz_sequence(seed): """Creates a generator, which will yield a Collatz sequence starting from seed. seed must be a positive integer, or the sequence will not converge to 1.""" collatz_number = seed while True: if collatz_number % 2 == 0: collatz_number //= 2 else: collatz_number = 3 * collatz_number + 1 yield collatz_number if collatz_number == 1: return Judging from the lack of responses, I guess I must have been on track on the other questions. -- boB From thebigwurst at gmail.com Tue May 8 05:39:02 2018 From: thebigwurst at gmail.com (Brad M) Date: Tue, 8 May 2018 17:39:02 +0800 Subject: [Tutor] calling printf() in a C language DLL using ctypes.CDLL Message-ID: Hi all: I am trying out some c based module in a .dll file on windows. // helloworld.c #include __declspec(dllexport) void helloworld() { printf("Hello Everyone!!!"); } I compile this by typing this in the command line: cl /LD /I C:\python\include helloworld.c C:\python\libs\python36.lib I get helloworld.dll for the above. and the following is the python caller import ctypes mydll = ctypes.CDLL('helloworld') mydll.helloworld() However, this doesn't print anything on the python window. What I would like is to do is to be able to use printf() in my .dll by having the c code pop up a console window to print or to have something that can print() in the python window somehow. Is this possible? Thanks! From alan.gauld at yahoo.co.uk Tue May 8 18:13:07 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 08 May 2018 23:13:07 +0100 Subject: [Tutor] calling printf() in a C language DLL using ctypes.CDLL Message-ID: I'm guessing at the answer here because I'm on vacation with no access to a pc of any kind let alone Windows. But are you running python inside an ide? If so you might find you get the expected result if you use a command prompt, since printf usually sends output to stdout. This is another example of the rule that you should never mix display and logic. If the dll returned the string instead of printing it you could display it from python easily, but by using print you make your code dependant on a stdout being visible. Hth Alan g On 8 May 2018, at 23:03, Brad M wrote: Hi all: I am trying out some c based module in a .dll file on windows. // helloworld.c #include __declspec(dllexport) void helloworld() { printf("Hello Everyone!!!"); } I compile this by typing this in the command line: cl /LD /I C:\python\include helloworld.c C:\python\libs\python36.lib I get helloworld.dll for the above. and the following is the python caller import ctypes mydll = ctypes.CDLL('helloworld') mydll.helloworld() However, this doesn't print anything on the python window. What I would like is to do is to be able to use printf() in my .dll by having the c code pop up a console window to print or to have something that can print() in the python window somehow. Is this possible? Thanks! _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From alan.gauld at yahoo.co.uk Tue May 8 18:23:25 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 08 May 2018 23:23:25 +0100 Subject: [Tutor] How to separate UI code from program logic? Message-ID: Bob, On 8 May 2018, at 19:56, boB Stepp < >Judging from the lack of responses, I guess I must have been on track >on the other questions. On The basics yes. There were a few picky details I would normally have mentioned but I'm on vacation and replying inline via gmail on my tablet is just too painful! ? Alan g From alan.gauld at yahoo.co.uk Tue May 8 18:18:02 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 08 May 2018 23:18:02 +0100 Subject: [Tutor] guess my number game Message-ID: The first block of code is full of errors and couldn't work so I have no idea what you were really doing! The second block should kind of work. From your description I'd guess you have an indentation error such that most of the code that should be inside the loop is being bypassed. Are you sure the code you sent us exactly what you are running? Alan g On 8 May 2018, at 10:39, Kerri Murphy wrote: My students are creating a guess my number game. They are trying to take this type of code (the flow of it), and turn it into a code using a while loop. Here is the first code n = int(input('Guess my number: '))if (n <= 172 and n >= 174): print('Correct')elif (n >= 174): a = int(input('Go Down')) if (a >= 174): c = int(input('Go Down')) if (c >= 174): g = int(input('Last Guess Go Down')) if (g == 173): print('Correct') elif (c <= 172): i = int(input('Last Guess Go Up')) if (i == 173): print('Correct') else: print('Correct') elif (a <= 172): e = int(input('Go up')) if (e >= 174): f = int(input('Last Guess Go Down')) if (f == 173): print('Correct') elif (e <= 172): h = int(input('Last Guess Go Up')) if (h == 173): print('Correct') else: print('Correct') else: print('Correct')elif (n <= 172): b = int(input('Go Up')) if (b >= 174): d = int(input('Go Down')) if (d >= 174): j = int(input('Last Guess Go Down')) if (j == 173): print('Correct') elif (d <= 172): m = int(input('Last Guess Go Up')) if (m == 173): print('Correct') else: print('Correct') elif (b <= 172): e = int(input('Go Up')) if (e >= 174): k = int(input('Last Guess Go Down')) if (k == 173): print('Correct') elif (e <= 172): l = int(input('Last Guess Go Up')) if (l == 173): print('Correct') else: print('Correct') else: print('Correct')else: print('Correct') Here is the code with the while loop import random n = (random.randint(0,100)) g = int(input('Guess my number, 0 to 100, you have 10 chances')) c = 0 while (c < 10): g = int(input('Guess my number, 0 to 100, you have 10 chances')) c = c + 1 if (g >= n): print('Lower!') elif (g <= n): print('Higher!') elif (g == n): break if (g == n): print('You guess my number! It took you ' + str(c) + ' tries!') Everyone's code just keeps asking for numbers without giving feedback, except for the longer code above. Can you help us consolidate the code? We are using random.randint. Thank you! _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From glenuk at gmail.com Tue May 8 18:33:55 2018 From: glenuk at gmail.com (Glen) Date: Tue, 8 May 2018 23:33:55 +0100 Subject: [Tutor] Return keys with unique values from a dict Message-ID: Hello, I had a task to define a function that would take a dict input and return only the keys with unique values into a list. Here is my code, which was awarded full marks, but I am pretty unhappy with it. I feel like I did a band-aid job after my first submission did pass mall the unit tests. I'd appreciate any advice on a better way to do this if anyone has some extra time. Thanks, def uniqueValues(theDict): ''' theDict: a dictionary ''' ans = [] rev = {} toDel = [] for key, value in aDict.items(): if value not in rev: rev[value] = key elif value in rev: toDel.append(value) for item in toDel: try: del rev[item] except: pass for item in rev: ans.append(rev[item]) return sorted(ans) Virus-free. www.avast.com <#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2> From mats at wichmann.us Tue May 8 19:51:21 2018 From: mats at wichmann.us (Mats Wichmann) Date: Tue, 8 May 2018 17:51:21 -0600 Subject: [Tutor] Return keys with unique values from a dict In-Reply-To: References: Message-ID: <572bb0b5-5adc-f9bb-8568-3e4384c1bc3a@wichmann.us> On 05/08/2018 04:33 PM, Glen wrote: > Hello, > > I had a task to define a function that would take a dict input and return > only the keys with unique values into a list. > > Here is my code, which was awarded full marks, but I am pretty unhappy with > it. I feel like I did a band-aid job after my first submission did pass > mall the unit tests. I'd appreciate any advice on a better way to do this > if anyone has some extra time. > > Thanks, > > def uniqueValues(theDict): > ''' > theDict: a dictionary > ''' > ans = [] > rev = {} > toDel = [] > for key, value in aDict.items(): > if value not in rev: > rev[value] = key > elif value in rev: > toDel.append(value) > > for item in toDel: > try: > del rev[item] > except: > pass > > for item in rev: > ans.append(rev[item]) > > return sorted(ans) There are many ways to tackle this - if you get six answers you'll probably get six different ones :) You're already using the trick of flipping, or reversing the dictionary, so we can maybe tweak that a little bit - this is not the only way, you could use try/except instead of get() to handle the case of the not-yet-added key: for key, value in theDict.items(): rev[value] = rev.get(value, []) rev[value].append(key) Having reversed the dict, you can build your answer list on the fly by knowing that value lists (of keys from the original) which have a size of 1 are "unique", if the (new) key has multiple values, then those were not unique. You then pull out the value from that list and add it to your answer list. ans = [value[0] for key, value in rev.items() if len(value) == 1] Whether that's "better" than your answer is up for discussion, but something to think about. The choice of answers may also depend a bit on the character of the data. From eryksun at gmail.com Tue May 8 20:16:34 2018 From: eryksun at gmail.com (eryk sun) Date: Wed, 9 May 2018 00:16:34 +0000 Subject: [Tutor] calling printf() in a C language DLL using ctypes.CDLL In-Reply-To: References: Message-ID: On Tue, May 8, 2018 at 9:39 AM, Brad M wrote: > > I compile this by typing this in the command line: > cl /LD /I C:\python\include helloworld.c C:\python\libs\python36.lib You're not using Python's C API, so you only need `cl /LD helloworld.c`. > However, this doesn't print anything on the python window. > What I would like is to do is to be able to use printf() in my .dll > by having the c code pop up a console window to print or > to have something that can print() in the python window somehow. By Python window, do you mean the IDLE GUI? If the library is loaded in a GUI program in which stdout is invalid, it will have to manually allocate a console via `AllocConsole` and open the screen buffer using the reserved filename "CONOUT$". Then it can print to the opened FILE stream using fprintf(). But I'll reiterate Alan here that this would be unusual behavior for a shared library, unless it's specifically intended as a UI library. From eryksun at gmail.com Tue May 8 22:12:12 2018 From: eryksun at gmail.com (eryk sun) Date: Wed, 9 May 2018 02:12:12 +0000 Subject: [Tutor] calling printf() in a C language DLL using ctypes.CDLL In-Reply-To: References: Message-ID: On Wed, May 9, 2018 at 1:30 AM, Brad M wrote: > > If you want to know where your program went when something went wrong or > when it triggers a if condition, how do you do it? Look into use the logging module [1] and debuggers [2], either dedicated like Winpdb or in an IDE such as PyCharm. [1]: https://docs.python.org/3/howto/logging.html#logging-basic-tutorial [2]: https://wiki.python.org/moin/PythonDebuggingTools For debugging a DLL, learn to use a native debugger, such as Microsoft's WinDbg, cdb, or the Visual Studio debugger. OutputDebugString [3] writes a string to an attached debugger. [3]: https://msdn.microsoft.com/en-us/library/aa363362 From alan.gauld at yahoo.co.uk Wed May 9 03:38:36 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 09 May 2018 08:38:36 +0100 Subject: [Tutor] guess my number game In-Reply-To: Message-ID: <84a33bc0-cf55-4935-ba09-630f35acefbc@email.android.com> On 9 May 2018 2:30 am, Kerri Murphy wrote: Hi there, Yes, the first code does a good job by asking them to go higher or lower after each guess, in the pop up window. My point is that the code you posted can't even run, let alone do a good job. The indentation is all messed up and will yield errors. The 2nd code works, but only outputs all the higher and lower outputs after the 10 guesses. How are you running the code? Are you using the interactive prompt to type it in? Are you running it in an ide like idle? If you put it in a file and run it from the OS command line the second version should more or less work. point, but we just wanted the game to tell the user if he should go lower or higher after every guess. Does this make sense? Yes and your code should do that if you put it in a file. If you try typing it at the python prompt you may well get the result you describe. Alan g. On Tue, May 8, 2018 at 6:18 PM, Alan Gauld <[1]alan.gauld at yahoo.co.uk> wrote: The first block of code is full of errors and couldn't work so I have no idea what you were really doing! The second block should kind of work. From your description I'd guess you have an indentation error such that most of the code that should be inside the loop is being bypassed. Are you sure the code you sent us exactly what you are running? Alan g On 8 May 2018, at 10:39, Kerri Murphy <[2]kmurphy at easton.k12.ma.us> wrote: My students are creating a guess my number game. They are trying to take this type of code (the flow of it), and turn it into a code using a while loop. Here is the first code n = int(input('Guess my number: '))if (n <= 172 and n >= 174): print('Correct')elif (n >= 174): a = int(input('Go Down')) if (a >= 174): c = int(input('Go Down')) if (c >= 174): g = int(input('Last Guess Go Down')) if (g == 173): print('Correct') elif (c <= 172): i = int(input('Last Guess Go Up')) if (i == 173): print('Correct') else: print('Correct') elif (a <= 172): e = int(input('Go up')) if (e >= 174): f = int(input('Last Guess Go Down')) if (f == 173): print('Correct') elif (e <= 172): h = int(input('Last Guess Go Up')) if (h == 173): print('Correct') else: print('Correct') else: print('Correct')elif (n <= 172): b = int(input('Go Up')) if (b >= 174): d = int(input('Go Down')) if (d >= 174): j = int(input('Last Guess Go Down')) if (j == 173): print('Correct') elif (d <= 172): m = int(input('Last Guess Go Up')) if (m == 173): print('Correct') else: print('Correct') elif (b <= 172): e = int(input('Go Up')) if (e >= 174): k = int(input('Last Guess Go Down')) if (k == 173): print('Correct') elif (e <= 172): l = int(input('Last Guess Go Up')) if (l == 173): print('Correct') else: print('Correct') else: print('Correct')else: print('Correct') Here is the code with the while loop import random n = (random.randint(0,100)) g = int(input('Guess my number, 0 to 100, you have 10 chances')) c = 0 while (c < 10): g = int(input('Guess my number, 0 to 100, you have 10 chances')) c = c + 1 if (g >= n): print('Lower!') elif (g <= n): print('Higher!') elif (g == n): break if (g == n): print('You guess my number! It took you ' + str(c) + ' tries!') Everyone's code just keeps asking for numbers without giving feedback, except for the longer code above. Can you help us consolidate the code? We are using random.randint. Thank you! _______________________________________________ Tutor maillist - [3]Tutor at python.org To unsubscribe or change subscription options: [4]https://mail.python.org/mailman/listinfo/tutor References Visible links 1. mailto:alan.gauld at yahoo.co.uk 2. mailto:kmurphy at easton.k12.ma.us 3. mailto:Tutor at python.org 4. https://mail.python.org/mailman/listinfo/tutor From james at uplinkzero.com Wed May 9 11:29:22 2018 From: james at uplinkzero.com (James Chapman) Date: Wed, 9 May 2018 16:29:22 +0100 Subject: [Tutor] calling printf() in a C language DLL using ctypes.CDLL In-Reply-To: References: Message-ID: A long time ago when I was working with Python and DLLs I slapped together a basic and ugly example. You can find it here: https://github.com/James-Chapman/python-code-snippets/ tree/master/DLL_C_funcs_w_callbacks The whole thing should load into Visual Studio. I can't guarantee that it works in its current state though. It was created mainly as a reminder to myself. -- James From thebigwurst at gmail.com Tue May 8 21:30:04 2018 From: thebigwurst at gmail.com (Brad M) Date: Wed, 9 May 2018 09:30:04 +0800 Subject: [Tutor] calling printf() in a C language DLL using ctypes.CDLL In-Reply-To: References: Message-ID: Hmmm, I guess then it's time for me to ask this question: Is how I do this the way you do it? I have been inserting lines like this: print("The program got here!") all over my python code whenever I want to know where the program went. If you want to know where your program went when something went wrong or when it triggers a if condition, how do you do it? Thanks! On Wed, May 9, 2018 at 8:16 AM, eryk sun wrote: > On Tue, May 8, 2018 at 9:39 AM, Brad M wrote: > > > > I compile this by typing this in the command line: > > cl /LD /I C:\python\include helloworld.c C:\python\libs\python36.lib > > You're not using Python's C API, so you only need `cl /LD helloworld.c`. > > > However, this doesn't print anything on the python window. > > What I would like is to do is to be able to use printf() in my .dll > > by having the c code pop up a console window to print or > > to have something that can print() in the python window somehow. > > By Python window, do you mean the IDLE GUI? If the library is loaded > in a GUI program in which stdout is invalid, it will have to manually > allocate a console via `AllocConsole` and open the screen buffer using > the reserved filename "CONOUT$". Then it can print to the opened FILE > stream using fprintf(). But I'll reiterate Alan here that this would > be unusual behavior for a shared library, unless it's specifically > intended as a UI library. > From kmurphy at easton.k12.ma.us Tue May 8 21:30:13 2018 From: kmurphy at easton.k12.ma.us (Kerri Murphy) Date: Tue, 8 May 2018 21:30:13 -0400 Subject: [Tutor] guess my number game In-Reply-To: References: Message-ID: Hi there, Yes, the first code does a good job by asking them to go higher or lower after each guess, in the pop up window. The 2nd code works, but only outputs all the higher and lower outputs after the 10 guesses. Everyone in the class has the same result basically. When I searched on various sites, they also work this way. I can allow them to be finished at this point, but we just wanted the game to tell the user if he should go lower or higher after every guess. Does this make sense? Thank you, Kerri On Tue, May 8, 2018 at 6:18 PM, Alan Gauld wrote: > The first block of code is full of errors and couldn't work so I have no > idea what you were really doing! > > The second block should kind of work. From your description I'd guess you > have an indentation error such that most of the code that should be inside > the loop is being bypassed. Are you sure the code you sent us exactly what > you are running? > > Alan g > > On 8 May 2018, at 10:39, Kerri Murphy wrote: > > My students are creating a guess my number game. > > They are trying to take this type of code (the flow of it), and turn it > into a code using a while loop. > Here is the first code > > n = int(input('Guess my number: '))if (n <= 172 and n >= 174): > print('Correct')elif (n >= 174): > a = int(input('Go Down')) > if (a >= 174): > c = int(input('Go Down')) > if (c >= 174): > g = int(input('Last Guess Go Down')) > if (g == 173): > print('Correct') > elif (c <= 172): > i = int(input('Last Guess Go Up')) > if (i == 173): > print('Correct') > else: > print('Correct') > elif (a <= 172): > e = int(input('Go up')) > if (e >= 174): > f = int(input('Last Guess Go Down')) > if (f == 173): > print('Correct') > elif (e <= 172): > h = int(input('Last Guess Go Up')) > if (h == 173): > print('Correct') > else: > print('Correct') > else: > print('Correct')elif (n <= 172): > b = int(input('Go Up')) > if (b >= 174): > d = int(input('Go Down')) > if (d >= 174): > j = int(input('Last Guess Go Down')) > if (j == 173): > print('Correct') > elif (d <= 172): > m = int(input('Last Guess Go Up')) > if (m == 173): > print('Correct') > else: > print('Correct') > elif (b <= 172): > e = int(input('Go Up')) > if (e >= 174): > k = int(input('Last Guess Go Down')) > if (k == 173): > print('Correct') > elif (e <= 172): > l = int(input('Last Guess Go Up')) > if (l == 173): > print('Correct') > else: > print('Correct') > else: > print('Correct')else: > print('Correct') > > > > Here is the code with the while loop > import random > n = (random.randint(0,100)) > g = int(input('Guess my number, 0 to 100, you have 10 chances')) > c = 0 > while (c < 10): > g = int(input('Guess my number, 0 to 100, you have 10 chances')) > c = c + 1 > if (g >= n): > print('Lower!') > elif (g <= n): > print('Higher!') > elif (g == n): > break > if (g == n): > print('You guess my number! It took you ' + str(c) + ' tries!') > > > Everyone's code just keeps asking for numbers without giving feedback, > except for the longer code above. > > Can you help us consolidate the code? We are using random.randint. > > Thank you! > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From thebigwurst at gmail.com Wed May 9 05:10:39 2018 From: thebigwurst at gmail.com (Brad M) Date: Wed, 9 May 2018 17:10:39 +0800 Subject: [Tutor] Choice of tools Message-ID: Hi all, I have a question about how to choose a proper IDE for C/C++ I have been using visual studio ever since my C++ 101 days, but now I realized there is a problem: feature lock-in! As an aside, I can't get "Error squiggles" to show up in my .c project in visual studio 2017, where as in my .cpp project it promptly notifies me of anything it doesn't like, such as printffffff("Hello world! \n ); Anyone know how to make it work for .c? So I have been happily letting MS VS 2017 community do my thinking for me, so to speak, when it comes to error checking. Now I found out I can't do any work since there isn't that Error squiggles feature for me, I have to hunt down my next IDE! Well, Notepad++ has this really cool "VIM dark blue" theme that is gorgeous! However, I am a lose for choosing my next editor/IDE... 1) is it ok to get used to a feature that only some products feature 2) is there anything else that has Error squiggles? 3) recommend a C/C++ editor? Thanks all... From kmurphy at easton.k12.ma.us Wed May 9 08:04:08 2018 From: kmurphy at easton.k12.ma.us (Kerri Murphy) Date: Wed, 9 May 2018 08:04:08 -0400 Subject: [Tutor] guess my number game In-Reply-To: <84a33bc0-cf55-4935-ba09-630f35acefbc@email.android.com> References: <84a33bc0-cf55-4935-ba09-630f35acefbc@email.android.com> Message-ID: Perhaps the indentation was changed when I copy and pasted it, but also we've only been using codeskulptor to run our answers. That code did work on ours, so that is weird. But yes there are a lot of errors. We just type it into code skulptor and press play. A box pops up for any user input. The display is covered by the box, so you can't see any results as you are guessing. We will still be trying to work on this code. We will try the file option you suggested. We don't have access to the OS at school... Thank you, Kerri On Wed, May 9, 2018 at 3:38 AM, Alan Gauld wrote: > > > On 9 May 2018 2:30 am, Kerri Murphy wrote: > > Hi there, > > Yes, the first code does a good job by asking them to go higher or lower > after each guess, in the pop up window. > > > My point is that the code you posted can't even run, let alone do a good > job. The indentation is all messed up and will yield errors. > > > The 2nd code works, but only outputs all the higher and lower outputs > after the 10 guesses. > > How are you running the code? > Are you using the interactive prompt to type it in? Are you running it in > an ide like idle? > > If you put it in a file and run it from the OS command line the second > version should more or less work. > > > > point, but we just wanted the game to tell the user if he should go lower > or higher after every guess. > > Does this make sense? > > > > Yes and your code should do that if you put it in a file. If you try > typing it at the python prompt you may well get the result you describe. > > Alan g. > > > > > > On Tue, May 8, 2018 at 6:18 PM, Alan Gauld wrote: > > The first block of code is full of errors and couldn't work so I have no > idea what you were really doing! > > The second block should kind of work. From your description I'd guess you > have an indentation error such that most of the code that should be inside > the loop is being bypassed. Are you sure the code you sent us exactly what > you are running? > > Alan g > > On 8 May 2018, at 10:39, Kerri Murphy wrote: > > My students are creating a guess my number game. > > They are trying to take this type of code (the flow of it), and turn it > into a code using a while loop. > Here is the first code > > n = int(input('Guess my number: '))if (n <= 172 and n >= 174): > print('Correct')elif (n >= 174): > a = int(input('Go Down')) > if (a >= 174): > c = int(input('Go Down')) > if (c >= 174): > g = int(input('Last Guess Go Down')) > if (g == 173): > print('Correct') > elif (c <= 172): > i = int(input('Last Guess Go Up')) > if (i == 173): > print('Correct') > else: > print('Correct') > elif (a <= 172): > e = int(input('Go up')) > if (e >= 174): > f = int(input('Last Guess Go Down')) > if (f == 173): > print('Correct') > elif (e <= 172): > h = int(input('Last Guess Go Up')) > if (h == 173): > print('Correct') > else: > print('Correct') > else: > print('Correct')elif (n <= 172): > b = int(input('Go Up')) > if (b >= 174): > d = int(input('Go Down')) > if (d >= 174): > j = int(input('Last Guess Go Down')) > if (j == 173): > print('Correct') > elif (d <= 172): > m = int(input('Last Guess Go Up')) > if (m == 173): > print('Correct') > else: > print('Correct') > elif (b <= 172): > e = int(input('Go Up')) > if (e >= 174): > k = int(input('Last Guess Go Down')) > if (k == 173): > print('Correct') > elif (e <= 172): > l = int(input('Last Guess Go Up')) > if (l == 173): > print('Correct') > else: > print('Correct') > else: > print('Correct')else: > print('Correct') > > > > Here is the code with the while loop > import random > n = (random.randint(0,100)) > g = int(input('Guess my number, 0 to 100, you have 10 chances')) > c = 0 > while (c < 10): > g = int(input('Guess my number, 0 to 100, you have 10 chances')) > c = c + 1 > if (g >= n): > print('Lower!') > elif (g <= n): > print('Higher!') > elif (g == n): > break > if (g == n): > print('You guess my number! It took you ' + str(c) + ' tries!') > > > Everyone's code just keeps asking for numbers without giving feedback, > except for the longer code above. > > Can you help us consolidate the code? We are using random.randint. > > Thank you! > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > > > From rck.learn at gmail.com Wed May 9 13:56:45 2018 From: rck.learn at gmail.com (Rick Jaramillo) Date: Wed, 9 May 2018 10:56:45 -0700 Subject: [Tutor] Append to list Message-ID: Hello, I?m having trouble understanding the following behavior and would greatly appreciate any insight. l = [1,2,3,4] b=[] for i in range(l): print l b.append(l) l.pop(0) print b OUTPUT [1,2,3,4] [2,3,4] [3,4] [4] [[],[],[],[]] My confusions is the output for b. I don?t understand why it?s empty. I?m expecting for b to equal [[1,2,3,4], [2,3,4], [3,4], [4]]. Best Regards, Rick From ben+python at benfinney.id.au Wed May 9 18:58:12 2018 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 10 May 2018 08:58:12 +1000 Subject: [Tutor] Choice of tools References: Message-ID: <85lgcso2rf.fsf@benfinney.id.au> Brad M writes: > Hi all, I have a question about how to choose a proper IDE for C/C++ You will likely get better-informed advice from a forum specific to C and C++, then. This forum is for people learning Python. -- \ ?If you don't fail at least 90 percent of the time, you're not | `\ aiming high enough.? ?Alan Kay | _o__) | Ben Finney From alan.gauld at yahoo.co.uk Wed May 9 19:05:05 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 10 May 2018 00:05:05 +0100 Subject: [Tutor] Append to list Message-ID: On 9 May 2018, at 23:57, Rick Jaramillo wrote: > >Hello, >I?m having trouble understanding the following behavior and would greatly appreciate any insight. >l = [1,2,3,4] >b=[] >for i in range(l): >??? print l >??? b.append(l) >??? l.pop(0) >print b >OUTPUT >[1,2,3,4] >[2,3,4] >[3,4] >[4] >[[],[],[],[]] >My confusions is the output for b. I don?t understand why it?s empty. I?m expecting for b to equal [[1,2,3,4], [2,3,4], [3,4], [4]].? You append l each time. The same l, not a copy of its current state. You also modify l each time. But there is only one list object. It is just being referenced from several places. So all of the references reflect your changes. Alan g From alan.gauld at yahoo.co.uk Wed May 9 19:14:35 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 10 May 2018 00:14:35 +0100 Subject: [Tutor] Choice of tools Message-ID: <5rq9fxxp4cpu8okcbyjh2uqw.1525907675920@email.android.com> On 9 May 2018, at 23:54, Brad M wrote: > >As an aside, I can't get "Error squiggles" to show up in my .c project in >visual studio 2017, where as in my .cpp project it promptly notifies me I don't know visual studio so this is a guess. But remember that c and c++ are very different. C++ is much more strict than c so it is possible that the ide is simply following the rules of c and allowing you to do dubious but legal things in c... But that is just a guess. > However, I am a lose for choosing my next editor/IDE... I'm a vim and shell man myself but when working in c++ and java, as I occasionally must, I use eclipse. But if possible I avoid ides and keep things as simple as possible, especially for python. Alan g. From steve at pearwood.info Wed May 9 19:46:17 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 10 May 2018 09:46:17 +1000 Subject: [Tutor] Append to list In-Reply-To: References: Message-ID: <20180509234617.GL9562@ando.pearwood.info> On Wed, May 09, 2018 at 10:56:45AM -0700, Rick Jaramillo wrote: > > Hello, > > I?m having trouble understanding the following behavior and would greatly appreciate any insight. > > l = [1,2,3,4] > b=[] > > for i in range(l): That's not actually your code, is it? Because range(l) gives a TypeError. In future, please copy and paste your code, don't retype it from memory. > print l > b.append(l) > l.pop(0) You are appending the same list each time, not a copy. Instead make a copy by taking a slice from the current position to the end of the list: for i in range(len(l)): b.append(l[i:]) print b will do what you want. -- Steve From breamoreboy at gmail.com Thu May 10 04:32:24 2018 From: breamoreboy at gmail.com (Mark Lawrence) Date: Thu, 10 May 2018 09:32:24 +0100 Subject: [Tutor] Choice of tools In-Reply-To: References: Message-ID: On 09/05/18 10:10, Brad M wrote: > Hi all, I have a question about how to choose a proper IDE for C/C++ > > I have been using visual studio ever since my C++ 101 days, but now I > realized there is a problem: feature lock-in! > > As an aside, I can't get "Error squiggles" to show up in my .c project in > visual studio 2017, where as in my .cpp project it promptly notifies me > of anything it doesn't like, such as printffffff("Hello world! \n ); > Anyone know how to make it work for .c? > > So I have been happily letting MS VS 2017 community do my thinking > for me, so to speak, when it comes to error checking. Now I found out > I can't do any work since there isn't that Error squiggles feature for me, > I have to hunt down my next IDE! > > Well, Notepad++ has this really cool "VIM dark blue" theme that is > gorgeous! However, I am a lose for choosing my next editor/IDE... > > > 1) is it ok to get used to a feature that only some products feature > 2) is there anything else that has Error squiggles? > 3) recommend a C/C++ editor? > > Thanks all... Check out Visual Studio Code as it's open source, is cross platform and supports most languages. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From rls4jc at gmail.com Wed May 9 19:27:59 2018 From: rls4jc at gmail.com (Roger Lea Scherer) Date: Wed, 9 May 2018 16:27:59 -0700 Subject: [Tutor] Iteration issues Message-ID: Hello, again. I want to count words in a text file. If a word repeats I want to increase the count by 1; if the word is new to the dictionary, I want to add the word to the dictionary. Everything works like I would like and expect, except for it only adds the last word of each line to the dictionary. What am I missing? import string file_name = 'oxford.txt' wordset = {} with open(file_name, 'r') as f: for line in f: sentence = line.strip() sentence = sentence.strip(string.punctuation) print(sentence) sentence = sentence.lower() word_list = sentence.strip() word_list = word_list.split(' ') for i in range(len(word_list)): word_list[i] = word_list[i].strip(string.punctuation) print(word_list) if word_list[i] in wordset: wordset[word_list[i]] += 1 else: wordset[word_list[i]] = 1 print(wordset) The output is: (I included only the first four lines) The Project Gutenberg EBook of Advice to a Young Man upon First Going to ['the', 'project', 'gutenberg', 'ebook', 'of', 'advice', 'to', 'a', 'young', 'man', 'upon', 'first', 'going', 'to'] {'to': 1} Oxford, by Edward Berens ['oxford', 'by', 'edward', 'berens'] {'to': 1, 'berens': 1} [''] {'to': 1, 'berens': 1, '': 1} This eBook is for the use of anyone anywhere at no cost and with ['this', 'ebook', 'is', 'for', 'the', 'use', 'of', 'anyone', 'anywhere', 'at', 'no', 'cost', 'and', 'with'] {'to': 1, 'berens': 1, '': 1, 'with': 1} Thank you as always. -- Roger Lea Scherer 623.255.7719 From thebigwurst at gmail.com Thu May 10 04:39:54 2018 From: thebigwurst at gmail.com (Brad M) Date: Thu, 10 May 2018 16:39:54 +0800 Subject: [Tutor] Choice of tools In-Reply-To: References: Message-ID: Ya I am using that and the command line to compile at this point before I can get VS to work for me again. Thanks!! On Thu, May 10, 2018 at 4:32 PM, Mark Lawrence wrote: > On 09/05/18 10:10, Brad M wrote: > >> Hi all, I have a question about how to choose a proper IDE for C/C++ >> >> I have been using visual studio ever since my C++ 101 days, but now I >> realized there is a problem: feature lock-in! >> >> As an aside, I can't get "Error squiggles" to show up in my .c project in >> visual studio 2017, where as in my .cpp project it promptly notifies me >> of anything it doesn't like, such as printffffff("Hello world! \n ); >> Anyone know how to make it work for .c? >> >> So I have been happily letting MS VS 2017 community do my thinking >> for me, so to speak, when it comes to error checking. Now I found out >> I can't do any work since there isn't that Error squiggles feature for me, >> I have to hunt down my next IDE! >> >> Well, Notepad++ has this really cool "VIM dark blue" theme that is >> gorgeous! However, I am a lose for choosing my next editor/IDE... >> >> >> 1) is it ok to get used to a feature that only some products feature >> 2) is there anything else that has Error squiggles? >> 3) recommend a C/C++ editor? >> >> Thanks all... >> > > Check out Visual Studio Code as it's open source, is cross platform and > supports most languages. > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From mats at wichmann.us Thu May 10 09:11:51 2018 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 10 May 2018 07:11:51 -0600 Subject: [Tutor] Append to list In-Reply-To: References: Message-ID: <9615424b-6de2-f721-568b-9cc967a27826@wichmann.us> On 05/09/2018 11:56 AM, Rick Jaramillo wrote: > > Hello, > > I?m having trouble understanding the following behavior and would greatly appreciate any insight. > > l = [1,2,3,4] > b=[] > > for i in range(l): > print l > b.append(l) > l.pop(0) > > print b You've had some other comments, but let me add: sequence types in Python don't work the way you seem to be expecting. you can just loop over a sequence like a list directly. OR you can use the range function to create a sequence, but you wouldn't do both. In the interpreter: >>> l = [1, 2, 3, 4] >>> for i in l: ... print(i) ... 1 2 3 4 >>> for i in range(1, 5): ... print(i) ... 1 2 3 4 >>> Python provides syntax called a list comprehension that lets you build a list on the fly, rather that writing out a loop with an append inside it, at first it looks a little strange but it soon becomes very comfortable (life will *really* get better if you stop using single-character variable names that look alike!): >>> l = [1, 2, 3, 4] >>> b = [i for i in l] >>> print(b) [1, 2, 3, 4] >>> From robertvstepp at gmail.com Thu May 10 09:18:44 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Thu, 10 May 2018 08:18:44 -0500 Subject: [Tutor] Iteration issues In-Reply-To: References: Message-ID: Greetings! On Wed, May 9, 2018 at 6:27 PM, Roger Lea Scherer wrote: > Hello, again. > > I want to count words in a text file. If a word repeats I want to increase > the count by 1; if the word is new to the dictionary, I want to add the > word to the dictionary. Everything works like I would like and expect, > except for it only adds the last word of each line to the dictionary. What > am I missing? > > import string > > file_name = 'oxford.txt' > wordset = {} > with open(file_name, 'r') as f: > for line in f: > sentence = line.strip() A small quibble: Unless you get lucky, the identifier 'sentence' is unlikely to be an actual sentence. > sentence = sentence.strip(string.punctuation) This will only remove punctuation at the beginning or the end of the line. > print(sentence) > sentence = sentence.lower() > word_list = sentence.strip() Haven't you already done this above? > word_list = word_list.split(' ') > > for i in range(len(word_list)): It is better style and more direct to write this as for word in word_list: If you need the index of the word in the word_list (as you do below) then you can use enumerate: for index, word in enumerate(word_list): > word_list[i] = word_list[i].strip(string.punctuation) > print(word_list) > > if word_list[i] in wordset: > wordset[word_list[i]] += 1 > else: > wordset[word_list[i]] = 1 > print(wordset) And here we come to the answer to the actual question you asked. Look at your indentation. Your if/else construct is not within your for loop's scope/block, so you are only checking for the last value of i, which corresponds to the last word in word_list. So, as you have written your code: with ... for line in f: ... for i in range(len(word_list)): ... if word_list[i] = ... wordset[word_list[i]] += 1 else: wordset[word_list[i]] = 1 I used "..." to replace much of your code so you can see the needed indentation levels better. HTH! -- boB From mats at wichmann.us Thu May 10 09:20:47 2018 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 10 May 2018 07:20:47 -0600 Subject: [Tutor] Iteration issues In-Reply-To: References: Message-ID: On 05/09/2018 05:27 PM, Roger Lea Scherer wrote: > Hello, again. > > I want to count words in a text file. If a word repeats I want to increase > the count by 1; if the word is new to the dictionary, I want to add the > word to the dictionary. Everything works like I would like and expect, > except for it only adds the last word of each line to the dictionary. What > am I missing? > > import string > > file_name = 'oxford.txt' > wordset = {} > with open(file_name, 'r') as f: > for line in f: > sentence = line.strip() > sentence = sentence.strip(string.punctuation) > print(sentence) > sentence = sentence.lower() > word_list = sentence.strip() > word_list = word_list.split(' ') > > for i in range(len(word_list)): > word_list[i] = word_list[i].strip(string.punctuation) # notice the following lines are not inside the loop, as seen # by the indentation. Thus the value of i will be the value at # the end of the loop. Exactly "the last word in the line". > print(word_list) > > if word_list[i] in wordset: > wordset[word_list[i]] += 1 > else: > wordset[word_list[i]] = 1 > print(wordset) > > The output is: (I included only the first four lines) > > The Project Gutenberg EBook of Advice to a Young Man upon First Going to > ['the', 'project', 'gutenberg', 'ebook', 'of', 'advice', 'to', 'a', > 'young', 'man', 'upon', 'first', 'going', 'to'] > {'to': 1} > Oxford, by Edward Berens > ['oxford', 'by', 'edward', 'berens'] > {'to': 1, 'berens': 1} > > [''] > {'to': 1, 'berens': 1, '': 1} > This eBook is for the use of anyone anywhere at no cost and with > ['this', 'ebook', 'is', 'for', 'the', 'use', 'of', 'anyone', 'anywhere', > 'at', 'no', 'cost', 'and', 'with'] > {'to': 1, 'berens': 1, '': 1, 'with': 1} > > Thank you as always. > From mats at wichmann.us Thu May 10 09:48:31 2018 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 10 May 2018 07:48:31 -0600 Subject: [Tutor] Choice of tools In-Reply-To: References: Message-ID: <5203e01b-52fe-14a3-7a3c-9a32d22caa19@wichmann.us> On 05/09/2018 03:10 AM, Brad M wrote: > Hi all, I have a question about how to choose a proper IDE for C/C++ > > I have been using visual studio ever since my C++ 101 days, but now I > realized there is a problem: feature lock-in! > > As an aside, I can't get "Error squiggles" to show up in my .c project in > visual studio 2017, where as in my .cpp project it promptly notifies me > of anything it doesn't like, such as printffffff("Hello world! \n ); > Anyone know how to make it work for .c? The "squiggles" are a feature Microsoft calls Intellisense, which works in C++ and C# projects, and an unspecified set of "some features" on .c files in a C++ project. Apparently "some" doesn't include your beloved squiggles. > So I have been happily letting MS VS 2017 community do my thinking > for me, so to speak, when it comes to error checking. Now I found out > I can't do any work since there isn't that Error squiggles feature for me, > I have to hunt down my next IDE! that very much sounds like the argument against colored syntax highlighting, for what it's worth: in addition to being distracting (typographers have known for eons not to change colors midstream because it disrupts concentration. IDE writers somehow know better?), it's a case of "doing your thinking for you" - you end up focusing on syntax errors and don't think about real bugs. A simplified version of the argument, but contained that same core concept. However... see comments at end. > Well, Notepad++ has this really cool "VIM dark blue" theme that is > gorgeous! However, I am a lose for choosing my next editor/IDE... > > > 1) is it ok to get used to a feature that only some products feature > 2) is there anything else that has Error squiggles? > 3) recommend a C/C++ editor? > > Thanks all... 1) of course. you do what works for you, and what makes you productive. If you have to IDE on many different platforms, you may or may not be willing to accept differences between them - that might color your choice of IDE. 3) No. It's a terribly personal choice, and there are a disturbing number of them. Some integrate more bits than other, Visual Studio being one of largest collections of bits, not always to its own benefit. There should be plenty of commentary on the Internet, some of it probably quite heated. Dating back to the UNIX days, programmers on UNIX/Linux/BSD systems have debated the merits of the editors vi and emacs with akin to religious fervor, IDE systems are just a new incarnation of those old editor wars. Since you wrote to a Python group, there are some editors that do a pretty good job of handling Python and also do well at C/C++ - PyCharm has a relative called CLion; the Atom editor has lots of IDE-like features and is constantly being extended by contributed code since it's all open; SublimeText is popular (particularly on the Mac side); the list goes on. Oh, and VS Code supports Intellisense too, so that's probably why it feels comfortable (I read your later reply to indicate you had been using VS Code) From robertvstepp at gmail.com Thu May 10 09:49:37 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Thu, 10 May 2018 08:49:37 -0500 Subject: [Tutor] Iteration issues In-Reply-To: References: Message-ID: On Wed, May 9, 2018 at 6:27 PM, Roger Lea Scherer wrote: > Hello, again. > > I want to count words in a text file. If a word repeats I want to increase > the count by 1; if the word is new to the dictionary, I want to add the > word to the dictionary. Everything works like I would like and expect, > except for it only adds the last word of each line to the dictionary. What > am I missing? > > import string > > file_name = 'oxford.txt' > wordset = {} > with open(file_name, 'r') as f: > for line in f: > sentence = line.strip() > sentence = sentence.strip(string.punctuation) > print(sentence) > sentence = sentence.lower() > word_list = sentence.strip() > word_list = word_list.split(' ') > > for i in range(len(word_list)): > word_list[i] = word_list[i].strip(string.punctuation) I was wondering if you might want to write a small function so that you can remove all punctuation symbols from each line in one fell swoop? Something like (in pseudocode): Iterate over string.punctuation. If a punctuation symbol is in your string: Replace that symbol with an empty string. That might make your code more direct and compact. boB From davidemanuelsandoval at gmail.com Thu May 10 10:15:05 2018 From: davidemanuelsandoval at gmail.com (emanuel sandoval) Date: Thu, 10 May 2018 14:15:05 +0000 Subject: [Tutor] How to maximize a window in tkinter Message-ID: I want to know how to maximize a window in tkinter. I was using something like: root =Tk() root.status("zoomed") But I want to know another way to do it. Thank you. From alan.gauld at yahoo.co.uk Thu May 10 12:05:51 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 10 May 2018 17:05:51 +0100 Subject: [Tutor] How to maximize a window in tkinter Message-ID: On 10 May 2018, at 16:52, emanuel sandoval wrote: >I want to know how to maximize a window in tkinter. There are several options, of which your solution is probably the best! The others involve setting the window position to top left and the width and height to the screen size. All the solutions fail when the window manager does not make room for any window decorations such as the title bar... In that case you need to set height and subtract enough space yourself. Messy... >I was using something like: >root =Tk() >root.status("zoomed") Alan g. From mats at wichmann.us Thu May 10 12:43:05 2018 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 10 May 2018 10:43:05 -0600 Subject: [Tutor] Iteration issues In-Reply-To: References: Message-ID: <3e51e3e1-7073-558b-eb35-83acfa9924de@wichmann.us> On 05/09/2018 05:27 PM, Roger Lea Scherer wrote: > Hello, again. > > I want to count words in a text file. If a word repeats I want to increase > the count by 1; if the word is new to the dictionary, I want to add the > word to the dictionary. Everything works like I would like and expect, > except for it only adds the last word of each line to the dictionary. What > am I missing? So let's add some more comments... > import string > > file_name = 'oxford.txt' > wordset = {} > with open(file_name, 'r') as f: > for line in f: > sentence = line.strip() > sentence = sentence.strip(string.punctuation) > print(sentence) > sentence = sentence.lower() > word_list = sentence.strip() > word_list = word_list.split(' ') > > for i in range(len(word_list)): > word_list[i] = word_list[i].strip(string.punctuation) Not sure why this step is needed at all - you've _already_ stripped punctuation a few lines above. However, if you think you still need to do this, you usually don't want to iterate over a list by index this way. (If you do need an index, look up how the enumerate() function works). I'd just make a new list, which is cheap and easy, rather than trying to replace each list member individually. Like this, using a "list comprehension" words = [word.strip(string.punctuation) for word in word_list] > print(word_list) > > if word_list[i] in wordset: > wordset[word_list[i]] += 1 > else: > wordset[word_list[i]] = 1 > print(wordset) this chunk is fine (excepting my previous comment that it needs to be inside a loop to have any useful meaning as you intend it) - increment the occurrence counter if the key is already present in the dict, add it if it isn't. But you could do this with a try/except block too (i.e., don't "ask permission", just "try and fix it up"). So using the newly created "words" from above, like this: for word in words: try: wordset[word] += 1 except KeyError: wordset[word] = 1 Does this help? From sjeik_appie at hotmail.com Thu May 10 11:20:49 2018 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Thu, 10 May 2018 15:20:49 +0000 Subject: [Tutor] Iteration issues Message-ID: Verzonden vanaf mijn Samsung Galaxy-smartphone. -------- Oorspronkelijk bericht -------- Van: boB Stepp Datum: 10-05-18 21:53 (GMT+08:00) Aan: tutor Onderwerp: Re: [Tutor] Iteration issues On Wed, May 9, 2018 at 6:27 PM, Roger Lea Scherer wrote: > Hello, again. > > I want to count words in a text file. If a word repeats I want to increase > the count by 1; if the word is new to the dictionary, I want to add the > word to the dictionary. Everything works like I would like and expect, > except for it only adds the last word of each line to the dictionary. What > am I missing? > > import string > > file_name = 'oxford.txt' > wordset = {} > with open(file_name, 'r') as f: > for line in f: > sentence = line.strip() > sentence = sentence.strip(string.punctuation) > print(sentence) > sentence = sentence.lower() > word_list = sentence.strip() > word_list = word_list.split(' ') > > for i in range(len(word_list)): > word_list[i] = word_list[i].strip(string.punctuation) I was wondering if you might want to write a small function so that you can remove all punctuation symbols from each line in one fell swoop? Something like (in pseudocode): Iterate over string.punctuation. If a punctuation symbol is in your string: Replace that symbol with an empty string. =>>> maybe something like import re no_interpunction = re.sub("[%s]" % re.escape(string.punctuation), '', sentence) From neilc at norwich.edu Fri May 11 09:43:59 2018 From: neilc at norwich.edu (Neil Cerutti) Date: Fri, 11 May 2018 13:43:59 +0000 (UTC) Subject: [Tutor] Iteration issues References: Message-ID: On 2018-05-10, Albert-Jan Roskam wrote: > If a punctuation symbol is in your string: Replace that symbol > with an empty string. > >=>>> maybe something like > > import re > no_interpunction = re.sub("[%s]" % re.escape(string.punctuation), '', sentence) str.translate can be used instead of re. # Compute only once somewhere punctuation_removal_table = str.maketrans({c: None for c in string.punctuation}) no_interpunction = sentence.translate(punctuation_removal_table) Unfortunately you'll remove all the apostrophes and dashes, both of which could be considered parts of words. -- Neil Cerutti From kevinhulshof at live.nl Wed May 9 08:14:47 2018 From: kevinhulshof at live.nl (kevin hulshof) Date: Wed, 9 May 2018 12:14:47 +0000 Subject: [Tutor] Question about a python finction Message-ID: Hello, Is there a function that allows you to grab the numbers between two numbers? Eg. If you input the numbers 1 and 4 To make a list like this [1,2,3,4] Thank you for you?re time Sent from my iPhone From pcpanchal123 at gmail.com Thu May 10 20:43:44 2018 From: pcpanchal123 at gmail.com (Pareshkumar Panchal) Date: Thu, 10 May 2018 20:43:44 -0400 Subject: [Tutor] ImportError: No module named openpyxl.workbook Message-ID: Hi, I am trying to write the pandas dataframe to excel but it shows following error: Error: from openpyxl.workbook import Workbook ImportError: No module named openpyxl.workbook I am using only pandas however it still works fine on one computer having openpyxl already installed eventhough i am not using openpyxl in the program while shows above error on other computer where openpyxl is not installed. both computers are running on the same python version. my code below: import pandas as pd writer = pd.ExcelWriter('summary.xlsx') df.to_excel(writer, index=False) writer.save() any help appreciated. Thank you, Paresh From breamoreboy at gmail.com Fri May 11 18:56:29 2018 From: breamoreboy at gmail.com (Mark Lawrence) Date: Fri, 11 May 2018 23:56:29 +0100 Subject: [Tutor] Question about a python finction In-Reply-To: References: Message-ID: On 09/05/18 13:14, kevin hulshof wrote: > Hello, > > Is there a function that allows you to grab the numbers between two numbers? > > Eg. If you input the numbers 1 and 4 > To make a list like this [1,2,3,4] > > Thank you for you?re time > Seems like 'range' should fit your needs https://docs.python.org/3/library/stdtypes.html#typesseq -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From david at graniteweb.com Fri May 11 18:58:44 2018 From: david at graniteweb.com (David Rock) Date: Fri, 11 May 2018 17:58:44 -0500 Subject: [Tutor] Question about a python finction In-Reply-To: References: Message-ID: > On May 9, 2018, at 07:14, kevin hulshof wrote: > > Hello, > > Is there a function that allows you to grab the numbers between two numbers? > > Eg. If you input the numbers 1 and 4 > To make a list like this [1,2,3,4] One option is range range(1,5) >>> range(1,5) [1, 2, 3, 4] https://docs.python.org/2/library/functions.html#range ? David Rock david at graniteweb.com From alan.gauld at yahoo.co.uk Fri May 11 19:08:01 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 12 May 2018 00:08:01 +0100 Subject: [Tutor] ImportError: No module named openpyxl.workbook In-Reply-To: References: Message-ID: On 11/05/18 01:43, Pareshkumar Panchal wrote: > Error: > from openpyxl.workbook import Workbook > ImportError: No module named openpyxl.workbook > > I am using only pandas however it still works fine on one computer having > openpyxl already installed eventhough i am not using openpyxl in the > program while shows above error on other computer where openpyxl is not > installed. So install openpyxl? The error says there are no module named openpyxl.workbook That seems very likely if openpyxl is mossing. -- 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 sjeik_appie at hotmail.com Fri May 11 22:22:41 2018 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Sat, 12 May 2018 02:22:41 +0000 Subject: [Tutor] Iteration issues In-Reply-To: Message-ID: Op 11 mei 2018 21:43 schreef Neil Cerutti : On 2018-05-10, Albert-Jan Roskam wrote: > If a punctuation symbol is in your string: Replace that symbol > with an empty string. > >=>>> maybe something like > > import re > no_interpunction = re.sub("[%s]" % re.escape(string.punctuation), '', sentence) str.translate can be used instead of re. # Compute only once somewhere punctuation_removal_table = str.maketrans({c: None for c in string.punctuation}) no_interpunction = sentence.translate(punctuation_removal_table) Unfortunately you'll remove all the apostrophes and dashes, both of which could be considered parts of words. Nice, I did not think of str.translate. It appears to be the fastest (and most readable) method, though a compiled regex is also pretty fast: http://bbs.bugcode.cn/t/3320#IDb95ffe2791c1a59f0ac8175905705f34 From __peter__ at web.de Sat May 12 03:40:15 2018 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 May 2018 09:40:15 +0200 Subject: [Tutor] Iteration issues References: Message-ID: Neil Cerutti wrote: > punctuation_removal_table = str.maketrans({c: None for c in > string.punctuation}) Alternative spellings: >>> from string import punctuation >>> (str.maketrans({c: None for c in punctuation}) ... == str.maketrans(dict.fromkeys(punctuation)) ... == str.maketrans("", "", punctuation)) True From peterrisley47 at gmail.com Sat May 12 01:40:44 2018 From: peterrisley47 at gmail.com (peter) Date: Fri, 11 May 2018 19:40:44 -1000 Subject: [Tutor] Question about a python finction In-Reply-To: References: Message-ID: range does not work the same for 2.7 and my 3.6.5. Seems they have changed the nature of range. It is a built in listed along with lists and tuples >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> tuple(range(10)) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) seems they have changed range for python3.6.5 I do not know about the earlier python3 versions.? range(10) will not work with python3.6.5 check out https://docs.python.org/3.6/library/stdtypes.html#typesseq On 05/11/2018 12:58 PM, David Rock wrote: >> On May 9, 2018, at 07:14, kevin hulshof wrote: >> >> Hello, >> >> Is there a function that allows you to grab the numbers between two numbers? >> >> Eg. If you input the numbers 1 and 4 >> To make a list like this [1,2,3,4] > One option is range > > range(1,5) > >>>> range(1,5) > [1, 2, 3, 4] > > https://docs.python.org/2/library/functions.html#range > > ? > David Rock > david at graniteweb.com > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at yahoo.co.uk Sat May 12 06:34:46 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 12 May 2018 11:34:46 +0100 Subject: [Tutor] Question about a python finction In-Reply-To: References: Message-ID: On 12/05/18 06:40, peter wrote: > range does not work the same for 2.7 and my 3.6.5. Seems they have > changed the nature of range. It is a built in listed along with lists > and tuples You are correct in that it has changed slightly and now returns a range object. but you can convert it to a list(or tuple) easily > >>>> list(range(10)) > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > >>> tuple(range(10)) > (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) Just as you have done here. And if you don;t mneed the explicot list you can use it in a for loop etc exactly as before: for n in range(10):... > ...range(10) will not work with python3.6.5 Yes it will, it just returns a slightly different value that you must explicitly convert to a list if needed. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From animalwatchingsam at gmail.com Tue May 15 15:49:54 2018 From: animalwatchingsam at gmail.com (Sam Hoffman) Date: Tue, 15 May 2018 14:49:54 -0500 Subject: [Tutor] Help Message-ID: <666B62E1-7D69-4E23-A834-C889416A5C6D@gmail.com> Traceback (most recent call last): File "/Users/samhoffman/Documents/test.py", line 54, in Battle() File "/Users/samhoffman/Documents/test.py", line 41, in Battle Move = input('What Will You Do? Fight or Run: ') File "", line 1, in NameError: name 'Run' is not defined import time import random #Pokemon Stats Bulbasaur = {'N' : 'Bulby', 'HP' : 20, 'Level' : 5, 'Atk' : 8, 'Def' : 9, 'Spd' : 6} Rattata = {'N' : 'Rattata', 'HP' : 15, 'Level' : 3, 'Atk' : 5, 'Def' : 6, 'Spd' : 4} #Move damages BM = {'Vinewhip' : 45, 'Tackle' : 40, 'Razorleaf' : 55} RM = {'Tackle' : 40, 'Quick Attack' : 40, 'Bite' : 60} #Damage is (((((2xLevel)/5)+2)xPower)xAtk/Def)+2)/50 #Battle Function def Battle(): print('Wild '+Rattata['N']+' Appeared!') time.sleep(1) print('Go, '+Bulbasaur['N']+'!') time.sleep(1) print(Bulbasaur['N']+ ' is out.') while Bulbasaur['HP'] >= 1 and Rattata['HP'] >= 1: Move = input('What Will You Do? Fight or Run: ') if Move == Fight: pass elif Move == Run: RC = random.randint(1,3) if RC == 1 or 3: print('You Didn\'t Get Away!') else: print('You Got Away!') break else: print('Typo') break Battle() From robertvstepp at gmail.com Tue May 15 20:39:35 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 15 May 2018 19:39:35 -0500 Subject: [Tutor] Help In-Reply-To: <666B62E1-7D69-4E23-A834-C889416A5C6D@gmail.com> References: <666B62E1-7D69-4E23-A834-C889416A5C6D@gmail.com> Message-ID: Greetings! On Tue, May 15, 2018 at 2:49 PM, Sam Hoffman wrote: > Traceback (most recent call last): > File "/Users/samhoffman/Documents/test.py", line 54, in > Battle() > File "/Users/samhoffman/Documents/test.py", line 41, in Battle > Move = input('What Will You Do? Fight or Run: ') > File "", line 1, in > NameError: name 'Run' is not defined The Python interpreter believes that Run is a variable to which no value has been assigned. > > import time > import random > #Pokemon Stats > Bulbasaur = {'N' : 'Bulby', > 'HP' : 20, > 'Level' : 5, > 'Atk' : 8, > 'Def' : 9, > 'Spd' : 6} > > > Rattata = {'N' : 'Rattata', > 'HP' : 15, > 'Level' : 3, > 'Atk' : 5, > 'Def' : 6, > 'Spd' : 4} > > #Move damages > BM = {'Vinewhip' : 45, > 'Tackle' : 40, > 'Razorleaf' : 55} > > > RM = {'Tackle' : 40, > 'Quick Attack' : 40, > 'Bite' : 60} > > > #Damage is (((((2xLevel)/5)+2)xPower)xAtk/Def)+2)/50 > > > > #Battle Function > def Battle(): > print('Wild '+Rattata['N']+' Appeared!') > time.sleep(1) > print('Go, '+Bulbasaur['N']+'!') > time.sleep(1) > print(Bulbasaur['N']+ ' is out.') > while Bulbasaur['HP'] >= 1 and Rattata['HP'] >= 1: > Move = input('What Will You Do? Fight or Run: ') > if Move == Fight: > pass > elif Move == Run: # This appears to be the problem. Make Run into a string, "Run" or 'Run'. > RC = random.randint(1,3) > if RC == 1 or 3: # This probably does not do what you think it does! > print('You Didn\'t Get Away!') > else: > print('You Got Away!') > break > else: > print('Typo') > break > Battle() HTH! -- boB From steve at pearwood.info Tue May 15 20:51:22 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 16 May 2018 10:51:22 +1000 Subject: [Tutor] Help In-Reply-To: <666B62E1-7D69-4E23-A834-C889416A5C6D@gmail.com> References: <666B62E1-7D69-4E23-A834-C889416A5C6D@gmail.com> Message-ID: <20180516005122.GV12683@ando.pearwood.info> On Tue, May 15, 2018 at 02:49:54PM -0500, Sam Hoffman wrote: > Traceback (most recent call last): > File "/Users/samhoffman/Documents/test.py", line 54, in > Battle() > File "/Users/samhoffman/Documents/test.py", line 41, in Battle > Move = input('What Will You Do? Fight or Run: ') > File "", line 1, in > NameError: name 'Run' is not defined You need to either define a value for Run: Run = 2468 or you need to quote it, making it a string. Same applies to your Fight: > if Move == Fight: > pass > elif Move == Run: Both of these ought to be "Fight" and "Run" in quotes. You also seem to be using Python 2. In Python 2, you should never use the input() function. Instead, use raw_input() instead. -- Steve From robertvstepp at gmail.com Tue May 15 21:01:13 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 15 May 2018 20:01:13 -0500 Subject: [Tutor] Help In-Reply-To: <20180516005122.GV12683@ando.pearwood.info> References: <666B62E1-7D69-4E23-A834-C889416A5C6D@gmail.com> <20180516005122.GV12683@ando.pearwood.info> Message-ID: On Tue, May 15, 2018 at 7:51 PM, Steven D'Aprano wrote: > You also seem to be using Python 2. In Python 2, you should never use > the input() function. Instead, use raw_input() instead. What are you seeing that suggests the OP is using Python 2? I am missing what you are seeing/understanding. -- boB From steve at pearwood.info Tue May 15 21:43:10 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 16 May 2018 11:43:10 +1000 Subject: [Tutor] Help In-Reply-To: References: <666B62E1-7D69-4E23-A834-C889416A5C6D@gmail.com> <20180516005122.GV12683@ando.pearwood.info> Message-ID: <20180516014310.GW12683@ando.pearwood.info> On Tue, May 15, 2018 at 08:01:13PM -0500, boB Stepp wrote: > On Tue, May 15, 2018 at 7:51 PM, Steven D'Aprano wrote: > > > You also seem to be using Python 2. In Python 2, you should never use > > the input() function. Instead, use raw_input() instead. > > What are you seeing that suggests the OP is using Python 2? I am > missing what you are seeing/understanding. Excellent question :-) The traceback Sam posted says (in part): Move = input('What Will You Do? Fight or Run: ') File "", line 1, in NameError: name 'Run' is not defined so the failed line was the call to input(). In Python 3, it would return a string. In Python 2, input() evaluates whatever the user types as code, hence I infer Sam typed: Run and input() tries to evaluate it, which fails. Also, the following line says: if Move == Fight: pass If input() returned a string, as in Python 3, then the next line would run and Sam would have got a name error for Fight. This didn't happen. -- Steve From alan.gauld at yahoo.co.uk Wed May 16 03:55:43 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 16 May 2018 08:55:43 +0100 Subject: [Tutor] Help In-Reply-To: <20180516014310.GW12683@ando.pearwood.info> References: <666B62E1-7D69-4E23-A834-C889416A5C6D@gmail.com> <20180516005122.GV12683@ando.pearwood.info> <20180516014310.GW12683@ando.pearwood.info> Message-ID: On 16/05/18 02:43, Steven D'Aprano wrote: > The traceback Sam posted says (in part): > > Move = input('What Will You Do? Fight or Run: ') > File "", line 1, in > NameError: name 'Run' is not defined > > so the failed line was the call to input(). In Python 3, it would return > a string. In Python 2, input() evaluates whatever the user types as > code, hence I infer Sam typed: > > Run > > and input() tries to evaluate it, which fails. Shneaky! I was trying to figure out why the traceback highlighted that line instead of the if... I never thought about it being a Python 2 issue. Good catch! -- 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 muhammet.ahmet10 at outlook.com.tr Tue May 15 17:26:28 2018 From: muhammet.ahmet10 at outlook.com.tr (Mahamed Ahmed) Date: Tue, 15 May 2018 21:26:28 +0000 Subject: [Tutor] Python Question Message-ID: Hello, Please I would like you to help me solve the problem above which is related to loops and prime numbers so please get back to me, I also want to know how to sign up and get a online tutor for this python course Here is what is supposed to be done: The prime numbers and their code has already been given but what is need to be done is making the lines and correcting it in a organized way If you run the code above, you?ll see the result then will just need to make the small lines and writing Line1,Line2,Line3,Line4 and Line 5 at the left side of the list Hope you understand what the problem is about and would love to hear about you Regards[cid:image002.jpg at 01D3ECD5.44D97ED0] Sent from Mail for Windows 10 From yosi.levy99 at gmail.com Wed May 16 04:53:25 2018 From: yosi.levy99 at gmail.com (Yosef Levy) Date: Wed, 16 May 2018 11:53:25 +0300 Subject: [Tutor] redirecting testing output to file, using two different options Message-ID: Hello All, I have testing environment. Code is written under Python 2.6. testing output should be redirected to log file. I am using two different file handling, in order to log output: 1. logging module: import unittest2 import logging import sys class TestMyEnvClass (unittest2.TestCase): def setUp (self): pass def testMyEnv (self): logging.debug ( "In testMyEnv.." ) def tearDown (self): pass if __name__ == "__main__": logging.basicConfig( filename='log_file.txt', stream=sys.stderr, level=logging.DEBUG) logging.getLogger( "TestMyEnvClass.testMyEnv" ).setLevel( logging.DEBUG ) unittest2.main() running: python test.py output: # cat log_file.txt DEBUG:root:In testMyEnv.. # 2. but if I want to redirect assert messages to file, I have to: import unittest2 class TestMyEnvClass (unittest2.TestCase): def setUp (self): pass def testMyEnv (self): res = True self.assertEqual(res, True, 'Testing my environment..') def tearDown (self): pass if __name__ == "__main__": f = open('log_file.txt', "a") runner = unittest2.TextTestRunner(f) unittest2.main(testRunner=runner) f.close () running: # python test2.py output: # cat log_file.txt . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK Question: Is the a way to 'merge' the above two different ways output to file? Or, is there a way to redirect assert messages to logging module methods? Rgds. From mats at wichmann.us Wed May 16 09:12:36 2018 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 16 May 2018 07:12:36 -0600 Subject: [Tutor] Python Question In-Reply-To: References: Message-ID: On 05/15/2018 03:26 PM, Mahamed Ahmed wrote: > Hello, > > Please I would like you to help me solve the problem above which is related to loops and prime numbers so please get back to me, I also want to know how to sign up and get a online tutor for this python course > > Here is what is supposed to be done: > The prime numbers and their code has already been given but what is need to be done is making the lines and correcting it in a organized way > If you run the code above, you?ll see the result then will just need to make the small lines and writing Line1,Line2,Line3,Line4 and Line 5 at the left side of the list > > Hope you understand what the problem is about and would love to hear about you I am afraid there is no code or description. If you sent it as a link to an image, it did not survive through email. If you can paste the code into a new message, people here will be happy to comment on it - that's the way this (volunteer) effort works, by the way: we don't want to solve your homework problems for you, but if you show what you have done and what the question or error is, people are happy to help with that. As far as finding a personal tutor for a Python course, that's a different problem and I'm afraid we can't help with that. There are people providing that kind of service (for a fee, I'm sure), should be able to find through some internet searching. From alan.gauld at yahoo.co.uk Wed May 16 13:14:32 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 16 May 2018 18:14:32 +0100 Subject: [Tutor] Python Question In-Reply-To: References: Message-ID: On 15/05/18 22:26, Mahamed Ahmed wrote: > Please I would like you to help me solve the problem above We see no problem. this is a text only list so if you included a binary attachment the server will have stripped it off for security reasons. Please repost the text of the problem description and any code using plain text not HTML (since HTML will lose the code formatting) > I also want to know how to sign up and get a online tutor for > this python course We will comment on your code and answer questions but we don't do one on one mentoring. Also we don't know your course. But if you post any questions here we will do our best to assist you. > Here is what is supposed to be done: > The prime numbers and their code has already been given but> what is need to be done is making the lines and correcting > it in a organized way. One of the first things you learn about programming is that the more clearly you can explain the problem (even to yourself) the easier it is to find an answer in code. Avoid vague and woolly descriptions. What exactly does "making the lines" and "correcting it in an organized way" mean? What do the lines look like? What is organized about it? How is it "corrected"? English may not be your first language and if that is the case try explaining it in your language first before translating into English (or even into Python). The important step is getting the requirement absolutely clear in your own head. > If you run the code above, We can't see the code. > just need to make the small lines and writing Line1,Line2,... > at the left side of the list So what does "make the small lines mean? How small? What should they contain? > Hope you understand what the problem is Sorry, but without the original problem statement or code and with only your description to go on it is impossible to know what you need. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Wed May 16 13:30:57 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 16 May 2018 18:30:57 +0100 Subject: [Tutor] redirecting testing output to file, using two different options In-Reply-To: References: Message-ID: On 16/05/18 09:53, Yosef Levy wrote: > Hello All, > > I have testing environment. > Code is written under Python 2.6. > testing output should be redirected to log file. You don't say which OS you are using but if it's a Unix variant you could just use command line redirection of stdout/stderr. That is probably the simplest option and requires no code changes. I think asserts and the logging module both use stderr by default. At least I would hope that they do! Redirect stderr to a logfile with $ python myscript.py arg1 arg2...argn 2> mylogfile.txt Windows supports redirection too but I don't recall how (or if) you can isolate stderr... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From mats at wichmann.us Wed May 16 14:48:37 2018 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 16 May 2018 12:48:37 -0600 Subject: [Tutor] redirecting testing output to file, using two different options In-Reply-To: References: Message-ID: On 05/16/2018 02:53 AM, Yosef Levy wrote: > Hello All, > > I have testing environment. > Code is written under Python 2.6. Why? 2.6 was retired in October 2013. For long life of your code you should be using Python 3, but at least 2.7 is still current and getting updates (for another 18 months or so). > testing output should be redirected to log file. > I am using two different file handling, in order to log output: > > > > 1. logging module: > 2. but if I want to redirect assert messages to file, I have to: > > import unittest2 > Question: > Is the a way to 'merge' the above two different ways output to file? > Or, is there a way to redirect assert messages to logging module methods? If you use pytest, this should be fairly straightforward. It normally captures stdout and stderr (the latter should have your asserts), and with a plugin, puts logging output on the same basis, so you get get everything going the same place: https://pypi.org/project/pytest-catchlog/#description From yosi.levy99 at gmail.com Thu May 17 02:20:41 2018 From: yosi.levy99 at gmail.com (Yosef Levy) Date: Thu, 17 May 2018 09:20:41 +0300 Subject: [Tutor] redirecting testing output to file, using two different options In-Reply-To: References: Message-ID: As I understand from documentation reading, pytest does not support advanced file handling like logging module.. for example: log file rotate, limit file size etc. I am using OS Centos6 2018-05-16 21:48 GMT+03:00 Mats Wichmann : > On 05/16/2018 02:53 AM, Yosef Levy wrote: > > Hello All, > > > > I have testing environment. > > Code is written under Python 2.6. > > Why? 2.6 was retired in October 2013. For long life of your code you > should be using Python 3, but at least 2.7 is still current and getting > updates (for another 18 months or so). > > > > testing output should be redirected to log file. > > I am using two different file handling, in order to log output: > > > > > > > > 1. logging module: > > > 2. but if I want to redirect assert messages to file, I have to: > > > > import unittest2 > > > Question: > > Is the a way to 'merge' the above two different ways output to file? > > Or, is there a way to redirect assert messages to logging module methods? > > If you use pytest, this should be fairly straightforward. It normally > captures stdout and stderr (the latter should have your asserts), and > with a plugin, puts logging output on the same basis, so you get get > everything going the same place: > > https://pypi.org/project/pytest-catchlog/#description > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From __peter__ at web.de Thu May 17 04:29:24 2018 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 May 2018 10:29:24 +0200 Subject: [Tutor] redirecting testing output to file, using two different options References: Message-ID: Yosef Levy wrote: > Hello All, > > I have testing environment. > Code is written under Python 2.6. > testing output should be redirected to log file. > I am using two different file handling, in order to log output: > > > > 1. logging module: > > import unittest2 > import logging > import sys > > class TestMyEnvClass (unittest2.TestCase): > def setUp (self): > pass > def testMyEnv (self): > logging.debug ( "In testMyEnv.." ) > def tearDown (self): > pass > > if __name__ == "__main__": > logging.basicConfig( filename='log_file.txt', stream=sys.stderr, > level=logging.DEBUG) > logging.getLogger( "TestMyEnvClass.testMyEnv" ).setLevel( > logging.DEBUG > ) > unittest2.main() > > > running: > python test.py > > output: > # cat log_file.txt > DEBUG:root:In testMyEnv.. > # > > > > > > 2. but if I want to redirect assert messages to file, I have to: > > import unittest2 > > class TestMyEnvClass (unittest2.TestCase): > def setUp (self): > pass > def testMyEnv (self): > res = True > self.assertEqual(res, True, 'Testing my environment..') > def tearDown (self): > pass > > if __name__ == "__main__": > f = open('log_file.txt', "a") > runner = unittest2.TextTestRunner(f) > unittest2.main(testRunner=runner) > f.close () > > > > running: > # python test2.py > > output: > # cat log_file.txt > . > ---------------------------------------------------------------------- > Ran 1 test in 0.000s > > OK > > > > Question: > Is the a way to 'merge' the above two different ways output to file? > Or, is there a way to redirect assert messages to logging module methods? You can either write a file-like object that uses Logger methods under the hood or write your own test runner that uses Logger methods. A basic example targeting Python 3: $ cat log_unittest.py import logging import unittest import os logger = logging.getLogger() class TestMyEnvClass (unittest.TestCase): def setUp(self): pass def testMyEnv(self): res = os.environ.get("res") == "1" self.assertEqual(res, True, 'Testing my environment..') def tearDown(self): pass class LogStream: def __init__(self, logger): self.logger = logger def writeln(self, s=""): self.logger.info(s) def write(self, s): self.logger.info(s) def flush(self): pass class MyTextTestRunner(unittest.TextTestRunner): def __init__(self, logger): super().__init__(None) self.stream = LogStream(logger) if __name__ == "__main__": logging.basicConfig(level=logging.INFO) logging.info("hello world") runner = MyTextTestRunner(logger) unittest.main(testRunner=runner) $ res=1 python3 log_unittest.py INFO:root:hello world INFO:root:. INFO:root: INFO:root:---------------------------------------------------------------------- INFO:root:Ran 1 test in 0.000s INFO:root: INFO:root:OK INFO:root: $ res=0 python3 log_unittest.py INFO:root:hello world INFO:root:F INFO:root: INFO:root:====================================================================== INFO:root:FAIL: testMyEnv (__main__.TestMyEnvClass) INFO:root:---------------------------------------------------------------------- INFO:root:Traceback (most recent call last): File "log_unittest.py", line 14, in testMyEnv self.assertEqual(res, True, 'Testing my environment..') AssertionError: False != True : Testing my environment.. INFO:root:---------------------------------------------------------------------- INFO:root:Ran 1 test in 0.001s INFO:root: INFO:root:FAILED INFO:root: (failures=1) If you want more control you have to rewrite more code ;) From matej.taferner at gmail.com Thu May 17 06:47:37 2018 From: matej.taferner at gmail.com (matej taferner) Date: Thu, 17 May 2018 11:47:37 +0100 Subject: [Tutor] Scraping old twitter posts Message-ID: Hi guys ! I didn't use Python for c. 2 years hence my skills are a little bit rusty. I will really appreciate some hints or a guideline. I would like to search my Twitter feed and search/scrape for some "specific words" and create a list for further analysis. Can someone recommend me some quality resources on this topic? Thanks Matej From mats at wichmann.us Thu May 17 10:16:42 2018 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 17 May 2018 08:16:42 -0600 Subject: [Tutor] Scraping old twitter posts In-Reply-To: References: Message-ID: <70c827e4-0c32-bf79-042e-b944a7210f1c@wichmann.us> On 05/17/2018 04:47 AM, matej taferner wrote: > Hi guys ! > I didn't use Python for c. 2 years hence my skills are a little bit rusty. > I will really appreciate some hints or a guideline. > I would like to search my Twitter feed and search/scrape for some "specific > words" and create a list for further analysis. > Can someone recommend me some quality resources on this topic? Don't know if anyone has enough experience to comment on "quality" - we'll wait and see. But it's not really the kind of question this list is set up for. Getting data out of a website like Twitter should be done using their API, not by scraping, if at all possible: the API delivers data in a way that Twitter is okay with; scraping is against the terms of service unless you have explicit permission - and don't take that too lightly, LinkedIn has been busy suing people for scraping their site, for example. There are several existing projects that get data out of Twitter which you can search for (look on pypi.org for example, or github). If your objective is a Python learning project you might want to look for some of the tutorials on the subject and avoid ready-made projects. Python Tutor list will be more useful to you if you come with specific coding questions - I tried this and it doesn't work; I don't understand this; etc. Best of luck! From vadud3 at gmail.com Sun May 20 23:01:33 2018 From: vadud3 at gmail.com (Asif Iqbal) Date: Sun, 20 May 2018 23:01:33 -0400 Subject: [Tutor] Adding a new row to the dataframe with datetime as index Message-ID: Hi, I am trying to add a new row to a new date in the dataframe like below df.loc['2018-01-24'] = [0,1,2,3,4,5] And I am getting the following error ValueError: cannot set using a list-like indexer with a different length than the value I do have the right number of columns and I can lookup a row by the date df.loc['2018-01-23'] df.shape (8034, 6) df.index DatetimeIndex(['2018-01-23', '2018-01-22', '2018-01-19', '2018-01-18', '2018-01-17', '2018-01-16', '2018-01-12', '2018-01-11', '2018-01-10', '2018-01-09', ... '1986-03-25', '1986-03-24', '1986-03-21', '1986-03-20', '1986-03-19', '1986-03-18', '1986-03-17', '1986-03-14', '1986-03-13', '2018-01-24'], dtype='datetime64[ns]', name='date', length=8034, freq=None) Any idea how to add a new row to a new date? -- Asif Iqbal PGP Key: 0xE62693C5 KeyServer: pgp.mit.edu A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From __peter__ at web.de Mon May 21 09:28:11 2018 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 May 2018 15:28:11 +0200 Subject: [Tutor] Adding a new row to the dataframe with datetime as index References: Message-ID: Asif Iqbal wrote: > Hi, > > I am trying to add a new row to a new date in the dataframe like below > > df.loc['2018-01-24'] = [0,1,2,3,4,5] > > And I am getting the following error > > ValueError: cannot set using a list-like indexer with a different length > than the value > > I do have the right number of columns and I can lookup a row by the date > > df.loc['2018-01-23'] > > df.shape > (8034, 6) > > df.index > DatetimeIndex(['2018-01-23', '2018-01-22', '2018-01-19', '2018-01-18', > '2018-01-17', '2018-01-16', '2018-01-12', '2018-01-11', > '2018-01-10', '2018-01-09', > ... > '1986-03-25', '1986-03-24', '1986-03-21', '1986-03-20', > '1986-03-19', '1986-03-18', '1986-03-17', '1986-03-14', > '1986-03-13', '2018-01-24'], > dtype='datetime64[ns]', name='date', length=8034, freq=None) > > Any idea how to add a new row to a new date? My experiments indicate that there may be multiple values with the same key: > >>> import pandas as pd >>> df = pd.DataFrame([[1,2], [3,4], [5,6], [7,8]], index=["a", "b", "a", "a"]) >>> df.loc["a"] 0 1 a 1 2 a 5 6 a 7 8 [3 rows x 2 columns] >>> df.loc["a"] = [10, 20] Traceback (most recent call last): File "", line 1, in File "/usr/lib/python3/dist-packages/pandas/core/indexing.py", line 98, in __setitem__ self._setitem_with_indexer(indexer, value) File "/usr/lib/python3/dist-packages/pandas/core/indexing.py", line 422, in _setitem_with_indexer self.obj._data = self.obj._data.setitem(indexer, value) File "/usr/lib/python3/dist-packages/pandas/core/internals.py", line 2396, in setitem return self.apply('setitem', *args, **kwargs) File "/usr/lib/python3/dist-packages/pandas/core/internals.py", line 2376, in apply applied = getattr(blk, f)(*args, **kwargs) File "/usr/lib/python3/dist-packages/pandas/core/internals.py", line 615, in setitem raise ValueError("cannot set using a list-like indexer " ValueError: cannot set using a list-like indexer with a different length than the value If found two ways to resolve this, (1) the obvious, ensure that the lengths are the same: >>> df.loc["a"] = [[10, 20], [30, 40], [50, 60]] >>> df 0 1 a 10 20 b 3 4 a 30 40 a 50 60 (2) pass the key as a tuple: >>> df.loc["a",] = [1000, 2000] >>> df 0 1 a 1000 2000 b 3 4 a 1000 2000 a 1000 2000 [4 rows x 2 columns] I suspect that you want neither, and instead avoid duplicate keys. From vadud3 at gmail.com Mon May 21 13:17:03 2018 From: vadud3 at gmail.com (Asif Iqbal) Date: Mon, 21 May 2018 13:17:03 -0400 Subject: [Tutor] Adding a new row to the dataframe with datetime as index In-Reply-To: References: Message-ID: On Mon, May 21, 2018 at 9:28 AM, Peter Otten <__peter__ at web.de> wrote: > Asif Iqbal wrote: > > > Hi, > > > > I am trying to add a new row to a new date in the dataframe like below > > > > df.loc['2018-01-24'] = [0,1,2,3,4,5] > > > > And I am getting the following error > > > > ValueError: cannot set using a list-like indexer with a different > length > > than the value > > > > I do have the right number of columns and I can lookup a row by the date > > > > df.loc['2018-01-23'] > > > > df.shape > > (8034, 6) > > > > df.index > > DatetimeIndex(['2018-01-23', '2018-01-22', '2018-01-19', '2018-01-18', > > '2018-01-17', '2018-01-16', '2018-01-12', '2018-01-11', > > '2018-01-10', '2018-01-09', > > ... > > '1986-03-25', '1986-03-24', '1986-03-21', '1986-03-20', > > '1986-03-19', '1986-03-18', '1986-03-17', '1986-03-14', > > '1986-03-13', '2018-01-24'], > > dtype='datetime64[ns]', name='date', length=8034, > freq=None) > > > > Any idea how to add a new row to a new date? > > My experiments indicate that there may be multiple values with the same > key: > > > >>> import pandas as pd > >>> df = pd.DataFrame([[1,2], [3,4], [5,6], [7,8]], index=["a", "b", "a", > "a"]) > >>> df.loc["a"] > 0 1 > a 1 2 > a 5 6 > a 7 8 > > [3 rows x 2 columns] > >>> df.loc["a"] = [10, 20] > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python3/dist-packages/pandas/core/indexing.py", line 98, > in > __setitem__ > self._setitem_with_indexer(indexer, value) > File "/usr/lib/python3/dist-packages/pandas/core/indexing.py", line > 422, > in _setitem_with_indexer > self.obj._data = self.obj._data.setitem(indexer, value) > File "/usr/lib/python3/dist-packages/pandas/core/internals.py", line > 2396, > in setitem > return self.apply('setitem', *args, **kwargs) > File "/usr/lib/python3/dist-packages/pandas/core/internals.py", line > 2376, > in apply > applied = getattr(blk, f)(*args, **kwargs) > File "/usr/lib/python3/dist-packages/pandas/core/internals.py", line > 615, > in setitem > raise ValueError("cannot set using a list-like indexer " > ValueError: cannot set using a list-like indexer with a different length > than the value > > If found two ways to resolve this, > > (1) the obvious, ensure that the lengths are the same: > > >>> df.loc["a"] = [[10, 20], [30, 40], [50, 60]] > >>> df > 0 1 > a 10 20 > b 3 4 > a 30 40 > a 50 60 > > (2) pass the key as a tuple: > > >>> df.loc["a",] = [1000, 2000] > >>> df > 0 1 > a 1000 2000 > b 3 4 > a 1000 2000 > a 1000 2000 > > [4 rows x 2 columns] > > I suspect that you want neither, and instead avoid duplicate keys. I want to overwrite the row print ( df.loc['2018-01-24'] ) 2018-01-24 0.0 1.0 2.0 3.0 4.0 NaN df.loc['2018-01-24'] = [0,1,2,3,4,5] ValueError: cannot set using a list-like indexer with a different length than the value > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Asif Iqbal PGP Key: 0xE62693C5 KeyServer: pgp.mit.edu A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From mats at wichmann.us Mon May 21 15:36:03 2018 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 21 May 2018 13:36:03 -0600 Subject: [Tutor] Adding a new row to the dataframe with datetime as index In-Reply-To: References: Message-ID: <50206679-f36b-81ea-1cf2-e7bd500ad9a7@wichmann.us> On 05/21/2018 11:17 AM, Asif Iqbal wrote: > I want to overwrite the row > > print ( df.loc['2018-01-24'] ) > 2018-01-24 0.0 1.0 2.0 3.0 4.0 NaN > > > df.loc['2018-01-24'] = [0,1,2,3,4,5] > ValueError: cannot set using a list-like indexer with a different length > than the value given what you have reported above, your current entry contains the date, so a list of seven entries; you're trying to replace it with a list of six entries, so the error seems as expected. From __peter__ at web.de Mon May 21 16:59:19 2018 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 May 2018 22:59:19 +0200 Subject: [Tutor] Adding a new row to the dataframe with datetime as index References: Message-ID: Asif Iqbal wrote: > On Mon, May 21, 2018 at 9:28 AM, Peter Otten <__peter__ at web.de> wrote: > >> Asif Iqbal wrote: >> >> > Hi, >> > >> > I am trying to add a new row to a new date in the dataframe like below >> > >> > df.loc['2018-01-24'] = [0,1,2,3,4,5] >> > >> > And I am getting the following error >> > >> > ValueError: cannot set using a list-like indexer with a different >> length >> > than the value >> > >> > I do have the right number of columns and I can lookup a row by the >> > date >> > >> > df.loc['2018-01-23'] >> > >> > df.shape >> > (8034, 6) >> > >> > df.index >> > DatetimeIndex(['2018-01-23', '2018-01-22', '2018-01-19', >> > '2018-01-18', >> > '2018-01-17', '2018-01-16', '2018-01-12', '2018-01-11', >> > '2018-01-10', '2018-01-09', >> > ... >> > '1986-03-25', '1986-03-24', '1986-03-21', '1986-03-20', >> > '1986-03-19', '1986-03-18', '1986-03-17', '1986-03-14', >> > '1986-03-13', '2018-01-24'], >> > dtype='datetime64[ns]', name='date', length=8034, >> freq=None) >> > >> > Any idea how to add a new row to a new date? >> >> My experiments indicate that there may be multiple values with the same >> key: >> >> > >>> import pandas as pd >> >>> df = pd.DataFrame([[1,2], [3,4], [5,6], [7,8]], index=["a", "b", "a", >> "a"]) >> >>> df.loc["a"] >> 0 1 >> a 1 2 >> a 5 6 >> a 7 8 >> >> [3 rows x 2 columns] >> >>> df.loc["a"] = [10, 20] >> Traceback (most recent call last): >> File "", line 1, in >> File "/usr/lib/python3/dist-packages/pandas/core/indexing.py", line 98, >> in >> __setitem__ >> self._setitem_with_indexer(indexer, value) >> File "/usr/lib/python3/dist-packages/pandas/core/indexing.py", line >> 422, >> in _setitem_with_indexer >> self.obj._data = self.obj._data.setitem(indexer, value) >> File "/usr/lib/python3/dist-packages/pandas/core/internals.py", line >> 2396, >> in setitem >> return self.apply('setitem', *args, **kwargs) >> File "/usr/lib/python3/dist-packages/pandas/core/internals.py", line >> 2376, >> in apply >> applied = getattr(blk, f)(*args, **kwargs) >> File "/usr/lib/python3/dist-packages/pandas/core/internals.py", line >> 615, >> in setitem >> raise ValueError("cannot set using a list-like indexer " >> ValueError: cannot set using a list-like indexer with a different length >> than the value >> >> If found two ways to resolve this, >> >> (1) the obvious, ensure that the lengths are the same: >> >> >>> df.loc["a"] = [[10, 20], [30, 40], [50, 60]] >> >>> df >> 0 1 >> a 10 20 >> b 3 4 >> a 30 40 >> a 50 60 >> >> (2) pass the key as a tuple: >> >> >>> df.loc["a",] = [1000, 2000] >> >>> df >> 0 1 >> a 1000 2000 >> b 3 4 >> a 1000 2000 >> a 1000 2000 >> >> [4 rows x 2 columns] >> >> I suspect that you want neither, and instead avoid duplicate keys. > > > > I want to overwrite the row > > print ( df.loc['2018-01-24'] ) > 2018-01-24 0.0 1.0 2.0 3.0 4.0 NaN > > > df.loc['2018-01-24'] = [0,1,2,3,4,5] > ValueError: cannot set using a list-like indexer with a different length > than the value Can you post a self-contained example, i. e. a small script that also creates a -- hopefully small -- DataFrame and then triggers the ValueError? From vadud3 at gmail.com Mon May 21 18:08:44 2018 From: vadud3 at gmail.com (Asif Iqbal) Date: Mon, 21 May 2018 18:08:44 -0400 Subject: [Tutor] Adding a new row to the dataframe with datetime as index In-Reply-To: References: Message-ID: On Mon, May 21, 2018 at 4:59 PM, Peter Otten <__peter__ at web.de> wrote: > Asif Iqbal wrote: > > > On Mon, May 21, 2018 at 9:28 AM, Peter Otten <__peter__ at web.de> wrote: > > > >> Asif Iqbal wrote: > >> > >> > Hi, > >> > > >> > I am trying to add a new row to a new date in the dataframe like below > >> > > >> > df.loc['2018-01-24'] = [0,1,2,3,4,5] > >> > > >> > And I am getting the following error > >> > > >> > ValueError: cannot set using a list-like indexer with a different > >> length > >> > than the value > >> > > >> > I do have the right number of columns and I can lookup a row by the > >> > date > >> > > >> > df.loc['2018-01-23'] > >> > > >> > df.shape > >> > (8034, 6) > >> > > >> > df.index > >> > DatetimeIndex(['2018-01-23', '2018-01-22', '2018-01-19', > >> > '2018-01-18', > >> > '2018-01-17', '2018-01-16', '2018-01-12', '2018-01-11', > >> > '2018-01-10', '2018-01-09', > >> > ... > >> > '1986-03-25', '1986-03-24', '1986-03-21', '1986-03-20', > >> > '1986-03-19', '1986-03-18', '1986-03-17', '1986-03-14', > >> > '1986-03-13', '2018-01-24'], > >> > dtype='datetime64[ns]', name='date', length=8034, > >> freq=None) > >> > > >> > Any idea how to add a new row to a new date? > >> > >> My experiments indicate that there may be multiple values with the same > >> key: > >> > >> > >>> import pandas as pd > >> >>> df = pd.DataFrame([[1,2], [3,4], [5,6], [7,8]], index=["a", "b", > "a", > >> "a"]) > >> >>> df.loc["a"] > >> 0 1 > >> a 1 2 > >> a 5 6 > >> a 7 8 > >> > >> [3 rows x 2 columns] > >> >>> df.loc["a"] = [10, 20] > >> Traceback (most recent call last): > >> File "", line 1, in > >> File "/usr/lib/python3/dist-packages/pandas/core/indexing.py", line > 98, > >> in > >> __setitem__ > >> self._setitem_with_indexer(indexer, value) > >> File "/usr/lib/python3/dist-packages/pandas/core/indexing.py", line > >> 422, > >> in _setitem_with_indexer > >> self.obj._data = self.obj._data.setitem(indexer, value) > >> File "/usr/lib/python3/dist-packages/pandas/core/internals.py", line > >> 2396, > >> in setitem > >> return self.apply('setitem', *args, **kwargs) > >> File "/usr/lib/python3/dist-packages/pandas/core/internals.py", line > >> 2376, > >> in apply > >> applied = getattr(blk, f)(*args, **kwargs) > >> File "/usr/lib/python3/dist-packages/pandas/core/internals.py", line > >> 615, > >> in setitem > >> raise ValueError("cannot set using a list-like indexer " > >> ValueError: cannot set using a list-like indexer with a different length > >> than the value > >> > >> If found two ways to resolve this, > >> > >> (1) the obvious, ensure that the lengths are the same: > >> > >> >>> df.loc["a"] = [[10, 20], [30, 40], [50, 60]] > >> >>> df > >> 0 1 > >> a 10 20 > >> b 3 4 > >> a 30 40 > >> a 50 60 > >> > >> (2) pass the key as a tuple: > >> > >> >>> df.loc["a",] = [1000, 2000] > >> >>> df > >> 0 1 > >> a 1000 2000 > >> b 3 4 > >> a 1000 2000 > >> a 1000 2000 > >> > >> [4 rows x 2 columns] > >> > >> I suspect that you want neither, and instead avoid duplicate keys. > > > > > > > > I want to overwrite the row > > > > print ( df.loc['2018-01-24'] ) > > 2018-01-24 0.0 1.0 2.0 3.0 4.0 NaN > > > > > > df.loc['2018-01-24'] = [0,1,2,3,4,5] > > ValueError: cannot set using a list-like indexer with a different > length > > than the value > > Can you post a self-contained example, i. e. a small script that also > creates a -- hopefully small -- DataFrame and then triggers the ValueError? > > It is working after I ran a df = df.sort_index() I was looping through new dates and feeding predicted data to new row for next day, but I was going in the wrong direction. -- Asif Iqbal PGP Key: 0xE62693C5 KeyServer: pgp.mit.edu A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From aishwaryaselvaraj1708 at gmail.com Tue May 22 06:16:50 2018 From: aishwaryaselvaraj1708 at gmail.com (aishwarya selvaraj) Date: Tue, 22 May 2018 15:46:50 +0530 Subject: [Tutor] Calling class from another class Message-ID: Dear all, I have created 2 classes in 2 separate files.File 1 named atcore_py.pyx with class andorCameraSDK3, and file 2 with name AndorCameraGUI making use of TKinter. I was able to import andorCameraSDK3 into AndorCameraGUI, but I was not able to do the other way around, as I need to call the function Plot() in file 2 inside function acquireimage() in file 1. When I define self.master = master in file 1 and pass this from file 2 as self.camera = andorCameraSDK3(self) , I get an error saying : > ? Exception in Tkinter callback > Traceback (most recent call last): > File "/home/ravindra/anaconda2/lib/python2.7/lib-tk/Tkinter.py", line 1541, > in __call__ > return self.func(*args) > File "/home/ravindra/PycharmProjects/LiveMode/GUI.py", line 278, in > getCameraStringGU > self.camera = AndorCameraSDK(self) > File "atcore_py.pyx", line 77, in AndorCameraDriver. > andorCameraSDK3.__cinit__ > self.master = master > AttributeError: 'AndorCameraDriver.andorCameraSDK3' object has no attribute > 'master' > Process finished with exit code 0 ? > > ? I'm attaching both the files along with this email. It would be great if someone could help me out here. Thanks in advance ? -- Regards, Aishwarya Selvaraj ? From glennmschultz at me.com Tue May 22 13:13:31 2018 From: glennmschultz at me.com (Glenn Schultz) Date: Tue, 22 May 2018 17:13:31 +0000 (GMT) Subject: [Tutor] help with Pandas Message-ID: <5b8c28e0-32c1-4add-9851-77151756ac13@me.com> All, I have a dataframe with the column 'loanage' and a function to transform loanage, which will be part of a pipline, I am trying to apply the function to the data frame as follows: df['loanage'].apply(myfunction(x = 2, y = 10, z = 10, df['loanage]), axis = 0) I get value error: The truth in the series is ambigous..... However, if I write a for loop indexing into the dataframe the function works. ?I am of the understanding based on the docs and online research I should be able to do the above. ?I cannot figure out what I am doing wrong and have tried every possible combination I have seen in the docs and online. ?Any help is appreciated. Glenn From guest0x013 at gmail.com Tue May 22 15:06:13 2018 From: guest0x013 at gmail.com (Pi) Date: Tue, 22 May 2018 21:06:13 +0200 Subject: [Tutor] os.walk() with multiple paths Message-ID: <13905fd8-a379-34b2-9e0f-98b976f24e11@gmail.com> Hello Tutor, I'm stuck and i really need help. Google and I can't find answer for my problem. I've wrote app searching through directories database files. It works fine, but only for one path. And I need to use more than one path. This is my code: import os files = [] def find_db(paths): ??? for path in paths.split(): ??????? for root, dirs, filenames in os.walk(path): ??????????? for name in filenames: ??????????????? if name.endswith((".db", ".sqlite", ".sqlite3")): ??????????????????? files.append(name + ', ' + os.path.join(root, name)) ??? return sorted(set(files)) With one path given works great: >>> find_db("/dbbs") ['april.db, /dbbs/analysis/april.db', 'important.sqlite, /dbbs/temp/important.sqlite', 'march.db, /dbbs/analysis/march.db', 'weelky.sqlite3, /dbbs/analysis/queue/weelky.sqlite3'] But with more paths gives files only for last path given: >>> find_db("/home/user/Desktop, /dbbs") ['april.db, /dbbs/analysis/april.db', 'important.sqlite, /dbbs/temp/important.sqlite', 'march.db, /dbbs/analysis/march.db', 'weelky.sqlite3, /dbbs/analysis/queue/weelky.sqlite3'] I was trying to debug this code and I think problem is somewhere here: ??? for path in paths.split(): ??????? for root, dirs, filenames in os.walk(path): Can You guide me where i've made mistake? os.walk() accepts one path to look, so was searching something like chain from itertools, or argparse. But none of them works. I couldn't find anything suits my needs. Is there some way do what i need without import anything else than os module? If not what I should search for? Best Regards From alan.gauld at btinternet.com Tue May 22 17:25:14 2018 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 May 2018 22:25:14 +0100 Subject: [Tutor] Calling class from another class In-Reply-To: References: Message-ID: <0d0b84f8-c3d2-8656-cd66-ed5a3ad65c81@btinternet.com> On 22/05/18 11:16, aishwarya selvaraj wrote: > I'm attaching both the files along with this email. It would be great if > someone could help me out here. Thanks in advance I don't see the attachments, even though they may just be text the server probably sees them as potentially executable and strips them out for security reasons. Please repost with the files included rather than attached (or if a lot of code link to a pastebin page) In general you should not need to have a two way import, it suggests a problem with the design. Are you sure you need to import both ways? Can't you simply pass an instance across the interface in one of the directions? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Tue May 22 19:06:43 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 23 May 2018 00:06:43 +0100 Subject: [Tutor] help with Pandas In-Reply-To: <5b8c28e0-32c1-4add-9851-77151756ac13@me.com> References: <5b8c28e0-32c1-4add-9851-77151756ac13@me.com> Message-ID: On 22/05/18 18:13, Glenn Schultz wrote: Cavbeat: I'm no dataframe expert so I'm going on general principles here... > I am trying to apply the function to the data frame as follows: > > df['loanage'].apply(myfunction(x = 2, y = 10, z = 10, df['loanage]), axis = 0) This looks wrong on several counts: 1) apply() usually takes a function object as the first argument not the return value of a function call as here. 2) When calling a function using keyword arguments you re not allowe to have non-keyword arguments following the keyword ones, so the df[...] bit should be an error 3) The df['loanage] does not have a closing quote. > I get value error: The truth in the series is ambigous..... I'm not sure if any of the above would result in a ValueError but its possible. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Tue May 22 19:09:01 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 23 May 2018 00:09:01 +0100 Subject: [Tutor] os.walk() with multiple paths In-Reply-To: <13905fd8-a379-34b2-9e0f-98b976f24e11@gmail.com> References: <13905fd8-a379-34b2-9e0f-98b976f24e11@gmail.com> Message-ID: On 22/05/18 20:06, Pi wrote: > works fine, but only for one path. And I need to use more than one path. > With one path given works great: > > >>> find_db("/dbbs") > ['april.db, /dbbs/analysis/april.db', 'important.sqlite, > /dbbs/temp/important.sqlite', 'march.db, /dbbs/analysis/march.db', > 'weelky.sqlite3, /dbbs/analysis/queue/weelky.sqlite3'] > > > But with more paths gives files only for last path given: > > >>> find_db("/home/user/Desktop, /dbbs") Note that split() will split based on whitespace so the comma will be included in the first path. That probably renders it invalid and so you don't get any results. Either split by , or use strip() to remove it. 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 roel at roelschroeven.net Wed May 23 17:17:24 2018 From: roel at roelschroeven.net (Roel Schroeven) Date: Wed, 23 May 2018 23:17:24 +0200 Subject: [Tutor] os.walk() with multiple paths In-Reply-To: <13905fd8-a379-34b2-9e0f-98b976f24e11@gmail.com> References: <13905fd8-a379-34b2-9e0f-98b976f24e11@gmail.com> Message-ID: Pi schreef op 22/05/2018 21:06: > import os > > files = [] > > def find_db(paths): > for path in paths.split(): > for root, dirs, filenames in os.walk(path): > for name in filenames: > if name.endswith((".db", ".sqlite", ".sqlite3")): > files.append(name + ', ' + os.path.join(root, name)) > > return sorted(set(files)) > > But with more paths gives files only for last path given: > > >>> find_db("/home/user/Desktop, /dbbs") Do you really need to pass your paths as a comma-separated string? Commas and spaces are legal characters in paths. There could, in theory, really exist a path "/home/user/Desktop, /ddbs". Probably not in your use case, but still. If possible, depending on where your paths come from, it's better to pass the paths as a list to avoid the ambiguity: def find_db(paths): for path in paths: .... find_db(["/home/user/Desktop", "/ddbs"]) Another point: it's far better to make files a local variable in the function instead of a global one. Also you can make it a set from the beginning: that will avoid duplicates earlier: def find_db(paths): files = set() for path in paths: for root, dirs, filenames in os.walk(path): for name in filenames: if name.endswith(('.db', '.sqlite', '.sqlite3')): files.add(name + ',' + os.path.join(root, name)) return sorted(files) Last point: I didn't know endswith can take a tuple of suffixes instead of one single suffix. Cool, I learned something new! -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From steve at pearwood.info Wed May 23 21:27:54 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 24 May 2018 11:27:54 +1000 Subject: [Tutor] Calling class from another class In-Reply-To: References: Message-ID: <20180524012754.GN12683@ando.pearwood.info> On Tue, May 22, 2018 at 03:46:50PM +0530, aishwarya selvaraj wrote: > Dear all, > I have created 2 classes in 2 separate files. If you have learned the bad habit from Java of putting every class in a separate file, you should unlearn that habit for your Python code. There is no need to put every class in a separate file, and it usually leads to complicated dependencies and circular imports. > File 1 named atcore_py.pyx "pyx" file extension? Surely not? > with class andorCameraSDK3, and file 2 with name AndorCameraGUI making use > of TKinter. > I was able to import andorCameraSDK3 into AndorCameraGUI, but I was not > able to do the other way around, as I need to call the function Plot() in > file 2 inside function acquireimage() in file 1. There are ways to safely handle circular dependencies in Python: file 1 needs to load file 2; but file 2 needs to load file 1 but they are annoying, fragile and best left for people with experience, not for beginners. The better solution is to put the two classes in the one file, and that way there is no import dependency. > I'm attaching both the files along with this email. It would be great if > someone could help me out here. Thanks in advance Please read this: http://sscce.org/ Thank you! -- Steve From __peter__ at web.de Thu May 24 12:29:56 2018 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 May 2018 18:29:56 +0200 Subject: [Tutor] Calling class from another class References: Message-ID: aishwarya selvaraj wrote: > Dear all, > I have created 2 classes in 2 separate files.File 1 named atcore_py.pyx > with class andorCameraSDK3, and file 2 with name AndorCameraGUI making > use of TKinter. > I was able to import andorCameraSDK3 into AndorCameraGUI, but I was not > able to do the other way around, as I need to call the function Plot() in > file 2 inside function acquireimage() in file 1. > When I define self.master = master in file 1 and pass this from file 2 as > self.camera = andorCameraSDK3(self) , I get an error saying : > >> ? Exception in Tkinter callback >> > > Traceback (most recent call last): >> > File "/home/ravindra/anaconda2/lib/python2.7/lib-tk/Tkinter.py", line > 1541, >> in __call__ >> > > return self.func(*args) >> > File "/home/ravindra/PycharmProjects/LiveMode/GUI.py", line 278, in >> getCameraStringGU >> > > self.camera = AndorCameraSDK(self) >> > File "atcore_py.pyx", line 77, in AndorCameraDriver. >> andorCameraSDK3.__cinit__ >> > self.master = master >> > AttributeError: 'AndorCameraDriver.andorCameraSDK3' object has no > attribute >> 'master' The attachments didn't make it, but it looks like you are using Cython. According to http://cython.readthedocs.io/en/latest/src/userguide/extension_types.html#dynamic-attributes you cannot add arbitrary attributes to a class written in Cython, you have to declare them: cdef class andorCameraSDK3: cdef object master ... > Process finished with exit code 0 ? >> >> > > ? > I'm attaching both the files along with this email. It would be great if > someone could help me out here. Thanks in advance > > ? > From robertvstepp at gmail.com Thu May 24 23:33:56 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Thu, 24 May 2018 22:33:56 -0500 Subject: [Tutor] Nested use of replication operator on lists Message-ID: On Python-list Steve started a thread, "List replication operator" (https://mail.python.org/pipermail/python-list/2018-May/733513.html) and wrote the following: Python has a sequence replication operator: py> [1, 2]*3 [1, 2, 1, 2, 1, 2] Unfortunately, it is prone to a common "gotcha": py> x = [[]]*5 # make a multi-dimensional list py> x [[], [], [], [], []] py> x[0].append(1) py> x [[1], [1], [1], [1], [1]] The reason for this behaviour is that * does not copy the original list's items, it simply replicates the references to the items. So we end up with a new list containing five references to the same inner list. I am having trouble correlating the behavior of the one-dimensional case with the two-dimensional case. The result of [1, 2]*3 seems to be an actual list, not a replication of the references to the items in the original list, [1, 2]. Or if it is, then I do not know how to demonstrate it. Also the "replication operator" does not seem to be replicating anything list-wise if it is instead replicating references to the original list's members. I request explanation/clarification please. -- boB From dyoo at hashcollision.org Fri May 25 01:39:17 2018 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 24 May 2018 22:39:17 -0700 Subject: [Tutor] Nested use of replication operator on lists In-Reply-To: References: Message-ID: Each value in Python has an associated numeric address associated to it. We can probe for it: https://docs.python.org/3/library/functions.html#id For example: ######################### >>> x = [1, 2, 3] >>> y = x[:] >>> id(x) 139718082542336 >>> id(y) 139718082556776 ######################### Here, we create a list and point the name 'x' to it. We point another name, 'y', to a slice of the first list. Slicing creates a new list. Let's make one more name: ######################### >>> z = x >>> id(z) 139718082542336 ######################### Note that the numeric id() that we get from 'z' is the same number as the id() we get from 'x'. These indicate that both names are referring to the identical list value. Identity matters because some values can be changed, or mutated. It means that two values can start looking the same, like the two lists that we created: ######################### >>> x [1, 2, 3] >>> y [1, 2, 3] ######################### but after a mutation: ########################## >>> x.append('four') >>> x [1, 2, 3, 'four'] >>> y [1, 2, 3] ########################## we can see that they are now different. If we try using 'z', we see: ########################## >>> z [1, 2, 3, 'four'] ########################## and that squares with what we said earlier: we gave the list we see here two names: 'x' and 'z'. But it's the same list. To come to your example, to get an intuition of what's happening, try applying id() on individual elements of the list, to probe which ones are unique and which ones are the same. You can also use a graphical tool like pythontutor.com. Take a look: https://goo.gl/HBLTw9 A slight revision to the scenario might make things a little clearer. Try: ########################## nested_lists = [['a'], ['b']] * 2 first_element = nested_lists[0] second_element = nested_lists[1] first_element.append('c') second_element.append('d') ########################## Visualization: https://goo.gl/k4TLvi See if the graphical view squares away with your internal mental model. Please feel free to ask questions. From steve at pearwood.info Fri May 25 02:34:55 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 May 2018 16:34:55 +1000 Subject: [Tutor] Nested use of replication operator on lists In-Reply-To: References: Message-ID: <20180525063454.GU12683@ando.pearwood.info> On Thu, May 24, 2018 at 10:39:17PM -0700, Danny Yoo wrote: > Each value in Python has an associated numeric address associated to it. No they don't :-) Each object in Python has an arbitrary numeric ID associated with it. The Python language has no supported way to get the address of an object. The id() function returns an opaque and officially meaningless ID number, that is all. It so happens that CPython uses the (memory) address of the object as that ID number, but not all Python interpreters do the same. Jython and IronPython, for example, assign IDs in consecutive order, so you will get IDs like 20, 21, 22, 23, 24, etc. (By memory, IronPython allocates the ID when the object is first created, while Jython allocates an ID only when you ask for one.) The reason IronPython and Jython do that is because they run inside an environment where objects can be moved around memory by the memory manager and garbage collector. So if an object X has address 1234 at one moment, a little later it could be moved to address 9516. Using the address would not be stable. -- Steve From steve at pearwood.info Fri May 25 02:27:33 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 May 2018 16:27:33 +1000 Subject: [Tutor] Nested use of replication operator on lists In-Reply-To: References: Message-ID: <20180525062732.GT12683@ando.pearwood.info> On Thu, May 24, 2018 at 10:33:56PM -0500, boB Stepp wrote: [...] > I am having trouble correlating the behavior of the one-dimensional > case with the two-dimensional case. The result of [1, 2]*3 seems to > be an actual list, not a replication of the references to the items in > the original list, [1, 2]. The result of list * 3 is always a list. What matters is the items inside the list. What the * operator does is create a new list containing the entries of the old list repeated. We can write our own version: def replicate(alist, count): newlist = [] for i in range(count): newlist.extend(alist) return newlist Notice that we don't copy the items in alist. We just shove them into the new list, repeatedly. If the items are immutable, like integers, that is perfectly fine. Copying an immutable object is a waste of time, and in fact the standard copy function will usually refuse to do so: py> import copy py> a, b = 1234567, [] # immutable int, mutable list py> copy.copy(a) is a # is the copy the same object as the original? True py> copy.copy(b) is b # is the copy the same object as the original? False (To be precise, it is not the copy() function that refuses to make a copy. It the object itself: each object knows how to copy itself, and immutable ones will typically return themselves because they know it makes no difference.) Let us go back to * the replicator operator. We can use "is" to check for object identity: py> obj = 987654321 py> alist = [obj] py> assert alist[0] is obj py> blist = alist*5 py> all(x is obj for x in blist) True So our blist contains five references to the same int object. For integers, floats, strings and other immutable objects, this is exactly what you want. There is no operation we can do to an immutable operation to change its value, so there is no way to distinguish between the same object twice or an object and a fresh copy. (Except for using the "is" operator, or the id() function.) So when we have a list full of ints (or floats, strings, etc) the only way we can change the value of the list is to *replace* the individual objects with a brand new object: py> blist [987654321, 987654321, 987654321, 987654321, 987654321] py> blist[0] = -1 py> blist[3] = -1 py> blist [-1, 987654321, 987654321, -1, 987654321] Since we're *replacing* the objects with a new object, the remaining 987654321 items don't change (indeed they can't change). Now let us do the same with a list instead of an int: py> obj = [] py> alist = [obj] py> assert alist[0] is obj py> blist = alist*5 py> all(x is obj for x in blist) True So far, the behaviour is identical. And replacing items works just like it does with ints: py> blist [[], [], [], [], []] py> blist[0] = [1, 2, 3] py> blist [[1, 2, 3], [], [], [], []] But because mutable objects like lists can be modified in place, not just replaced, we can do this: py> blist[4].append(999) py> blist [[1, 2, 3], [999], [999], [999], [999]] Touching the last item modifies all the other references to that same list object, since the * operator doesn't make copies. Think of it this way: I got into a fight the other day, on one side there was Tom, Dick and Harry, but fortunately it was a fair fight because on the other side there was me, myself and I. > Also the "replication operator" does not seem to be replicating > anything list-wise if it is instead replicating references to the > original list's members. It replicates the *contents* of the list into a new list, not the list itself. -- Steve From robertvstepp at gmail.com Sat May 26 02:10:06 2018 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 26 May 2018 01:10:06 -0500 Subject: [Tutor] Nested use of replication operator on lists In-Reply-To: <20180525062732.GT12683@ando.pearwood.info> References: <20180525062732.GT12683@ando.pearwood.info> Message-ID: The subtleties of the interactions between the concepts of references to objects, mutable objects, immutable objects, shallow copy of objects and deep copy of objects continue to surprise me! On Fri, May 25, 2018 at 1:27 AM, Steven D'Aprano wrote: > On Thu, May 24, 2018 at 10:33:56PM -0500, boB Stepp wrote: > The result of list * 3 is always a list. What matters is the items > inside the list. > > What the * operator does is create a new list containing the entries of > the old list repeated. I was not properly appreciating that that these repeated objects were the *same identical* objects that were in the pre-replicated list. > > If the items are immutable, like integers, that is perfectly fine. > Copying an immutable object is a waste of time, and in fact the standard > copy function will usually refuse to do so: > > py> import copy > py> a, b = 1234567, [] # immutable int, mutable list > py> copy.copy(a) is a # is the copy the same object as the original? > True > py> copy.copy(b) is b # is the copy the same object as the original? > False > > (To be precise, it is not the copy() function that refuses to make a > copy. It the object itself: each object knows how to copy itself, and > immutable ones will typically return themselves because they know it > makes no difference.) It appears to me that a logical consequence of a particular object being immutable is that it also must be unique. > For integers, floats, strings and other immutable objects, this is > exactly what you want. There is no operation we can do to an immutable > operation to change its value, so there is no way to distinguish between > the same object twice or an object and a fresh copy. > > (Except for using the "is" operator, or the id() function.) I should have thought to use "is". I had seen "id()", but had not previously investigated its usage. Danny's answer inspired me to read up on id() tonight. Useful investigative tools! There is another subtlety that I am not certain I am truly understanding: py3: empty = [] py3: a = copy.copy(empty) py3: a is empty False py3: a = [empty] py3: b = copy.copy(a) py3: a is b False py3: a[0] is b[0] True py3: c = copy.deepcopy(a) py3: a is c False py3: a[0] is c[0] False Up to this point I am fine, but ... py3: e = a*5 py3: e [[], [], [], [], []] py3: all(x is empty for x in e) True OK, I was expecting this. py3: f = copy.deepcopy(e) py3: any(x is empty for x in f) False Still OK ... py3: all(x is f[0] for x in f) True But this I found mildly surprising. I guess I was thinking that f = copy.deepcopy(e) would be equivalent to manually entering "[]" five times inside an enclosing list: py3: f = [[], [], [], [], []] py3: f[0] is f[1] False py3: all(x is f[0] for x in f) False So it surprised me that the deep copy created the same reference for all members, just like in the original list. -- boB From bhavna.soni108 at gmail.com Sat May 26 23:43:42 2018 From: bhavna.soni108 at gmail.com (Bhavna Soni) Date: Sun, 27 May 2018 09:13:42 +0530 Subject: [Tutor] Problem importing pandas library Message-ID: I installed pandas library using pip9. I get errors while importing it, Uninstalling and Re-installing won't help. It says DLL load failed as window file is not found. The next time I import it says pandas don't have core attribute, ut core folder is present in the directory. I am using Python 3.6 and Windows 10. How to remove this error? -- Bhavna Soni Electronics and Telecommunications National Institute of Technology, Raipur From alan.gauld at yahoo.co.uk Sun May 27 03:18:07 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 27 May 2018 08:18:07 +0100 Subject: [Tutor] Problem importing pandas library In-Reply-To: References: Message-ID: On 27/05/18 04:43, Bhavna Soni wrote: > I installed pandas library using pip9. I get errors while importing > it, Uninstalling and Re-installing won't help. It says DLL load failed > as window file is not found. The next time I import it says pandas > don't have core attribute, ut core folder is present in the directory. > I am using Python 3.6 and Windows 10. How to remove this error? > It may be a hammer to a nut solution but it may be simpler to just install an all-in-one distibution like Anaconda. It may be a step behind leading edge but most folks don;t need leading edge and it avoids all the hassles of sorting out dependencies etc. https://www.anaconda.com/download Especially since your sig suggests you might want to use more than just pandas from the SciPy/Scikit package collection. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From mats at wichmann.us Sun May 27 09:28:18 2018 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 27 May 2018 07:28:18 -0600 Subject: [Tutor] Problem importing pandas library In-Reply-To: References: Message-ID: On 05/27/2018 01:18 AM, Alan Gauld via Tutor wrote: > On 27/05/18 04:43, Bhavna Soni wrote: >> I installed pandas library using pip9. I get errors while importing >> it, Uninstalling and Re-installing won't help. It says DLL load failed >> as window file is not found. The next time I import it says pandas >> don't have core attribute, ut core folder is present in the directory. >> I am using Python 3.6 and Windows 10. How to remove this error? >> > > It may be a hammer to a nut solution but it may be simpler to just > install an all-in-one distibution like Anaconda. It may be a step > behind leading edge but most folks don;t need leading edge and > it avoids all the hassles of sorting out dependencies etc. > > https://www.anaconda.com/download > > Especially since your sig suggests you might want to use more > than just pandas from the SciPy/Scikit package collection. > Second the suggestion since Anaconda exists pretty much to make it easier for folks to work with this exact scenario. For some reason, installs of these have proven notoriously hard to get right on Windows. The lighter weight Miniconda may also suit your purposes, this page has some tips to help you choose if you choose to go this route: https://conda.io/docs/user-guide/install/download.html From acb001 at yahoo.com Sun May 27 11:18:47 2018 From: acb001 at yahoo.com (Alejandro Chirife) Date: Sun, 27 May 2018 15:18:47 +0000 (UTC) Subject: [Tutor] Tkinter widget (label) updated by TCP/IP message References: <504307975.5860800.1527434327234.ref@mail.yahoo.com> Message-ID: <504307975.5860800.1527434327234@mail.yahoo.com> Hi all, I am having a hard time to create what at first looked like a simple program with Python 3 and Tkinter: The UI consist of a window with a label and a button.?? The label shows "waiting for a message" and the button shows "reset display".?? The handler for the button click just resets the label text to "waiting for a message".? ?? The program would draw the window with the two widgets with root.mainloop()?while it is capable of listening? on a TCP port for an arriving message like "hello world", and when it arrives it would show the text in the label.? ?? The received message should show in the label until any of the following occurs: - Has been shown for 10 seconds- Another packet arrived with new message (will show the new message in the label)- User clicks on the "reset display" button I will really appreciate if someone could give me some guidance on how to manage this with Python 3. Thanks!AC From wpmartin at gmail.com Sun May 27 12:08:29 2018 From: wpmartin at gmail.com (Pat Martin) Date: Sun, 27 May 2018 09:08:29 -0700 Subject: [Tutor] Storing passwords and version control Message-ID: Hello all, I am writing a script that will be using an API to connect to some systems to pull info for a search. Since it will be a script I will be running through cron I won't be able to type the password at time of running. I also am going to be putting this in source control, using git specifically. The process I am currently thinking of using is having a separate file with the username and password in it and just having that ignored by source control. That of course doesn't solve the problem of the password sitting in a file on the system unencrypted. Is there a better or more accepted way to do this in python? Thanks From joel.goldstick at gmail.com Sun May 27 12:21:16 2018 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 27 May 2018 12:21:16 -0400 Subject: [Tutor] Storing passwords and version control In-Reply-To: References: Message-ID: On Sun, May 27, 2018 at 12:08 PM, Pat Martin wrote: > Hello all, > > I am writing a script that will be using an API to connect to some systems > to pull info for a search. Since it will be a script I will be running > through cron I won't be able to type the password at time of running. I > also am going to be putting this in source control, using git specifically. > > The process I am currently thinking of using is having a separate file with > the username and password in it and just having that ignored by source > control. That of course doesn't solve the problem of the password sitting > in a file on the system unencrypted. Is there a better or more accepted way > to do this in python? > > Thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor You can set environment variables on the system that runs the script. Then the script reads the environment variables. This keeps the secrets out of code anywhere. On your local machine you can ssh into the target machine and set the environment as required -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays From alan.gauld at yahoo.co.uk Sun May 27 13:03:29 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 27 May 2018 18:03:29 +0100 Subject: [Tutor] Tkinter widget (label) updated by TCP/IP message In-Reply-To: <504307975.5860800.1527434327234@mail.yahoo.com> References: <504307975.5860800.1527434327234.ref@mail.yahoo.com> <504307975.5860800.1527434327234@mail.yahoo.com> Message-ID: On 27/05/18 16:18, Alejandro Chirife via Tutor wrote: > > Hi all, I am having a hard time to create what at first looked like a simple program with Python 3 and Tkinter: > The UI consist of a window with a label and a button.?? > The label shows "waiting for a message" and the button shows "reset display".?? > The handler for the button click just resets the label text to "waiting for a message".? ? So far so good, it is all standard Tkinter programming but.... > The program would draw the window with the two widgets with root.mainloop()> while it is capable of listening? on a TCP port for an arriving message This is not so good. You can't do anything in your code after you call mainloop(). Thats just the nature of event driven programming. Once mainloop() is called all control rests with the GUI and you can only respond to events. Sooo.... > like "hello world", and when it arrives it would show the text in the label.? ? You need to put your network listener in a separate thread started before you call mainloop(). Then when a message is received you need to generate an event in your Tkinter GUI (or you could just call an event handler directly but that's considered bad practice (for some good reasons!). > The received message should show in the label until any of the following occurs: > > - Has been shown for 10 seconds Set a timer in the GUI that expires after 10 seconds - Another packet arrived with new message (will show the new message in the label) Generate (or call) the same event as before but don't forget to cancel the current timer. - User clicks on the "reset display" button In the button event handler - Cancel the timer. - Display whatever the reset message says So in pseudo code you need: import tkinter as tk def button_click() cancel timer display default message def display_message(msg): display msg on label cancel current timer create new 10s timer def timeout(): display ??? def get_network_message() your network receiving code here .... if is_valid_message(msg): display_message(msg) def main(): create GUI bind events create thread to run get_network_message mainloop() HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Sun May 27 13:08:00 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 27 May 2018 18:08:00 +0100 Subject: [Tutor] Storing passwords and version control In-Reply-To: References: Message-ID: On 27/05/18 17:21, Joel Goldstick wrote: > On Sun, May 27, 2018 at 12:08 PM, Pat Martin wrote: >> ... Since it will be a script I will be running >> through cron I won't be able to type the password > You can set environment variables on the system that runs the script. EV was my initial thought but...Would that work for a cron job? I didn't think cron picked up the user environment? Or have I got that wrong? Very possible, since I rarely use cron... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From mats at wichmann.us Sun May 27 13:50:58 2018 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 27 May 2018 11:50:58 -0600 Subject: [Tutor] Storing passwords and version control In-Reply-To: References: Message-ID: <81f3cd10-8bc5-81c0-2bbd-d1302fc4f7b0@wichmann.us> On 05/27/2018 11:08 AM, Alan Gauld via Tutor wrote: > On 27/05/18 17:21, Joel Goldstick wrote: >> On Sun, May 27, 2018 at 12:08 PM, Pat Martin wrote: >>> ... Since it will be a script I will be running >>> through cron I won't be able to type the password > >> You can set environment variables on the system that runs the script. > > EV was my initial thought but...Would that work for a cron job? > I didn't think cron picked up the user environment? > Or have I got that wrong? Very possible, since I rarely use cron... > It doesn't pick up your login environment, but it can still be given EVs. However that's not (much) more safe: the way a process was called can be examined, so you can fish the passwords out while it is active. More classical schemes for this involve using a third party to make things work: read up on using a token, OAuth style; or if the environment is more local and you're really only looking for a login password, a password agent like ssh uses. From dyoo at hashcollision.org Sun May 27 13:59:28 2018 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 27 May 2018 10:59:28 -0700 Subject: [Tutor] Storing passwords and version control In-Reply-To: <81f3cd10-8bc5-81c0-2bbd-d1302fc4f7b0@wichmann.us> References: <81f3cd10-8bc5-81c0-2bbd-d1302fc4f7b0@wichmann.us> Message-ID: The recommendations in https://stackoverflow.com/questions/7014953/i-need-to-securely-store-a-username-and-password-in-python-what-are-my-options might apply. From silviuchiric at gmail.com Sun May 27 14:31:26 2018 From: silviuchiric at gmail.com (Silviu Chiric) Date: Sun, 27 May 2018 20:31:26 +0200 Subject: [Tutor] get key value from Redis instance Message-ID: Dear all I need to get the value of given key from Redis, or both key and value, the below code snippet fails always, even the connection is okay StrictRedis>> Connected! My code import redis try: conn = redis.StrictRedis( host=' redis-15838.c44.us-east-1-2.ec2.cloud.redislabs.com', port=15838, password='DavidLavinia2') print (conn) conn.ping() print ('Connected!') print 'Set Record:', conn.set("best_car_ever", "Tesla Model S") print 'Get Record:', conn.get("best_car_ever") print 'Delete Record:', conn.delete("best_car_ever") print 'Get Deleted Record:', conn.get("best_car_ever") except Exception as ex: print ('Error:', ex) exit('Failed to connect, terminating.') Thanks! From dyoo at hashcollision.org Sun May 27 18:11:53 2018 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 27 May 2018 15:11:53 -0700 Subject: [Tutor] get key value from Redis instance In-Reply-To: References: Message-ID: On Sun, May 27, 2018 at 3:02 PM Silviu Chiric wrote: > Dear all > I need to get the value of given key from Redis, or both key and value, the > below code snippet fails always, even the connection is okay What is the error you see? Please also include the error message, verbatim. Computer systems are complex. You've made an assumption that something in your program is causing the error that you're seeing. But there might be some other cause. In order to help the volunteers here to accurately diagnose problems, you should try to also include error message output in your report. Also, it is normally a bad idea to include password information in a program's source code. I would *strongly* suggest you change your password to your Redis database if it's a real password, as you've just inadvertently shared it with the rest of the open Internet. From a first glance: it looks like one of your print statements is not vertically aligned with the rest of your print statements, so I would expect Python to be reporting a SyntaxError because of this misalignment. I would also recommend not to combine mutation statements with print statements. That is, rather than: ############## print 'Set Record:', conn.set("best_car_ever", "Tesla Model S") ############## do this instead: ############## set_result = conn.set("best_car_ever", "Tesla Model S") print 'Set Record:', set_result ############## Likewise, I'd recommend separating out: ############## print 'Delete Record:', conn.delete("best_car_ever") ############## into: ############## delete_result = conn.delete("best_car_ever") print 'Delete Record', delete_result ############## These changes are intended to help with the readability of the program, because the important statements that modify the database will stand out. Compare with the previous, where because those modification statements are nested within the 'print' statement, they are easier to overlook. Hope that makes sense. Good luck to you! From dyoo at hashcollision.org Sun May 27 18:14:17 2018 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 27 May 2018 15:14:17 -0700 Subject: [Tutor] get key value from Redis instance In-Reply-To: References: Message-ID: > From a first glance: it looks like one of your print statements is not > vertically aligned with the rest of your print statements, so I would > expect Python to be reporting a SyntaxError because of this misalignment. Substitute the word "vertical" with "horizontal". Sorry: I made yet another mental typo there. :P From dyoo at hashcollision.org Sun May 27 18:22:44 2018 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 27 May 2018 15:22:44 -0700 Subject: [Tutor] get key value from Redis instance In-Reply-To: References: Message-ID: One other recommendation: remove the try/except block for now. Don't use exception handling. We want to use exception handling if we have any significant recovery logic, or if it's important not to expose program errors to the end user. But your situation doesn't match this. In fact, you want to see errors as they happen, and as close to their root cause as possible. Exception handling, in that case, is harmful: it allows the programmer to accidentally make their debugging job *harder*. Hope this helps! From alan.gauld at yahoo.co.uk Sun May 27 18:16:00 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 27 May 2018 23:16:00 +0100 Subject: [Tutor] get key value from Redis instance In-Reply-To: References: Message-ID: On 27/05/18 19:31, Silviu Chiric wrote: > Dear all > > I need to get the value of given key from Redis, or both key and value, the > below code snippet fails always, even the connection is okay Please post the output. You print the error trace but we cant see it. Or if that is the the whole output please remove the try/except clause since it may be hiding valuable error information. > import redis > > try: > conn = redis.StrictRedis( host=' > redis-15838.c44.us-east-1-2.ec2.cloud.redislabs.com', port=15838, > password='DavidLavinia2') > print (conn) > conn.ping() > print ('Connected!') > print 'Set Record:', conn.set("best_car_ever", "Tesla Model S") This appears to break indentation, but I'd expect an error so I assume its an email issue. If not, fix this first! > print 'Get Record:', conn.get("best_car_ever") > print 'Delete Record:', conn.delete("best_car_ever") > print 'Get Deleted Record:', conn.get("best_car_ever") > except Exception as ex: > print ('Error:', ex) > exit('Failed to connect, terminating.') -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Sun May 27 19:40:57 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 May 2018 09:40:57 +1000 Subject: [Tutor] get key value from Redis instance In-Reply-To: References: Message-ID: <20180527234057.GA12683@ando.pearwood.info> On Sun, May 27, 2018 at 08:31:26PM +0200, Silviu Chiric wrote: > try: > conn = redis.StrictRedis( host=' > redis-15838.c44.us-east-1-2.ec2.cloud.redislabs.com', port=15838, > password='DavidLavinia2') You just shared your password with the entire world. > print (conn) > conn.ping() > print ('Connected!') > print 'Set Record:', conn.set("best_car_ever", "Tesla Model S") > print 'Get Record:', conn.get("best_car_ever") > print 'Delete Record:', conn.delete("best_car_ever") > print 'Get Deleted Record:', conn.get("best_car_ever") > except Exception as ex: > print ('Error:', ex) > exit('Failed to connect, terminating.') Get rid of the try...except block. It is evil. If a problem occurs, it could happen in any one of twelve operations. Six of them are calls to print, so they are probably okay, but the other six are complex operations that could go wrong for a billion different reasons. Nevertheless, whatever the *real* reason the code fails, your try...except block catches the exception, strips out the useful traceback which is indispensible for debugging, and prints a LIE that you failed to connect. You didn't fail to connect, as you can see: the connection was successfully made. Don't let your code lie to you. Debugging is hard. When your program deliberately strips away the useful traceback information showing which line failed, and then lies about the error that occurred, it becomes nearly impossible. (1) Change your password. Immediately. (2) Remove the try...except block. (3) When an error occurs, the interpreter will print a full traceback showing which line failed as well as the failure type and error message, and then exit. There is no need for you to catch the exception and then exit yourself. (4) COPY AND PASTE (don't summarise it, don't retype it from memory) the ENTIRE traceback and post it for us to see. We can't debug a problem we can't see. -- Steve From steve at pearwood.info Sun May 27 19:44:52 2018 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 May 2018 09:44:52 +1000 Subject: [Tutor] Storing passwords and version control In-Reply-To: References: Message-ID: <20180527234451.GB12683@ando.pearwood.info> On Sun, May 27, 2018 at 09:08:29AM -0700, Pat Martin wrote: > The process I am currently thinking of using is having a separate file with > the username and password in it and just having that ignored by source > control. That of course doesn't solve the problem of the password sitting > in a file on the system unencrypted. Is there a better or more accepted way > to do this in python? The usual way is to use the netrc module. https://docs.python.org/3/library/netrc.html -- Steve From silviuchiric at gmail.com Sun May 27 18:35:05 2018 From: silviuchiric at gmail.com (Silviu Chiric) Date: Mon, 28 May 2018 00:35:05 +0200 Subject: [Tutor] get key value from Redis instance In-Reply-To: References: Message-ID: Thank you Danny, indentation and separation of code worked out as you mentioned :) Have a nice day! On Mon, May 28, 2018 at 12:14 AM, Danny Yoo wrote: > > From a first glance: it looks like one of your print statements is not > > vertically aligned with the rest of your print statements, so I would > > expect Python to be reporting a SyntaxError because of this misalignment. > > Substitute the word "vertical" with "horizontal". Sorry: I made yet > another mental typo there. :P > From acb001 at yahoo.com Mon May 28 14:56:07 2018 From: acb001 at yahoo.com (Alejandro Chirife) Date: Mon, 28 May 2018 18:56:07 +0000 (UTC) Subject: [Tutor] Tkinter widget (label) updated by TCP/IP message In-Reply-To: References: <504307975.5860800.1527434327234.ref@mail.yahoo.com> <504307975.5860800.1527434327234@mail.yahoo.com> Message-ID: <946493988.6197927.1527533767185@mail.yahoo.com> Hi Alan, Thank you very much for your help.? ?I will start working on ti.? There's a lot to chew on here :) Two questions:? 1. Got it that nothing to do when mainloop() gets called.? How do you send an event of data arriving when the events for tkinter are all about user interaction? 2. You mentioned "? ? create thread to run get_network_message" in your pseudocode (in main() ).? Could you guide me towards which Class to use for this? Thanks!AC On Sunday, May 27, 2018, 1:04:22 PM EDT, Alan Gauld via Tutor wrote: On 27/05/18 16:18, Alejandro Chirife via Tutor wrote: > > Hi all, I am having a hard time to create what at first looked like a simple program with Python 3 and Tkinter: > The UI consist of a window with a label and a button.?? > The label shows "waiting for a message" and the button shows "reset display".?? > The handler for the button click just resets the label text to "waiting for a message".? ? So far so good, it is all standard Tkinter programming but.... > The program would draw the window with the two widgets with root.mainloop()> while it is capable of listening? on a TCP port for an arriving message This is not so good. You can't do anything in your code after you call mainloop(). Thats just the nature of event driven programming. Once mainloop() is called all control rests with the GUI and you can only respond to events. Sooo.... > like "hello world", and when it arrives it would show the text in the label.? ? You need to put your network listener in a separate thread started before you call mainloop(). Then when a message is received you need to generate an event in your Tkinter GUI (or you could just call an event handler directly but that's considered bad practice (for some good reasons!). > The received message should show in the label until any of the following occurs: > > - Has been shown for 10 seconds Set a timer in the GUI that expires after 10 seconds - Another packet arrived with new message (will show the new message in the label) Generate (or call) the same event as before but don't forget to cancel the current timer. - User clicks on the "reset display" button In the button event handler - Cancel the timer. - Display whatever the reset message says So in pseudo code you need: import tkinter as tk def button_click() ? ? cancel timer ? ? display default message def display_message(msg): ? ? display msg on label ? ? cancel current timer ? ? create new 10s timer def timeout(): ? ? display ??? def get_network_message() ? ? your network receiving code here ? ? .... ? ? if is_valid_message(msg): ? ? ? display_message(msg) def main(): ? ? create GUI ? ? bind events ? ? create thread to run get_network_message ? ? mainloop() 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 _______________________________________________ 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 May 28 18:10:51 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 28 May 2018 23:10:51 +0100 Subject: [Tutor] Tkinter widget (label) updated by TCP/IP message In-Reply-To: <946493988.6197927.1527533767185@mail.yahoo.com> References: <504307975.5860800.1527434327234.ref@mail.yahoo.com> <504307975.5860800.1527434327234@mail.yahoo.com> <946493988.6197927.1527533767185@mail.yahoo.com> Message-ID: On 28/05/18 19:56, Alejandro Chirife via Tutor wrote: > Two questions:? > 1. ...? How do you send an event of data arriving > when the events for tkinter are all about user interaction? The easiest way is to set a global variable and use a timer event (after()) to poll the variable periodically and update the UI. The downside of this is that you could miss an event if they arrive faster than the timer fires. If you only have a single background thread running you can just call the event handlers directly, but it gets iffy when you have multiple threads trying to do updates at the same time. Or if you can do manual updates via the UI - but I don't think that's an issue here. Most GUIs also allow you to create an event object and insert it into the main event queue. In Tkinter its the event_generate() command. I confess I've never had to use it but here is a stackoverflow simplified example: https://stackoverflow.com/questions/270648/tkinter-invoke-event-in-main-loop This is the purest solution that lets the GUI mainloop take care of all the sequencing conflicts implicit in the other options. > 2. You mentioned "? ? create thread to run get_network_message" > in your pseudocode (in main() ). > Could you guide me towards which Class to use for this? Check out the threading module in the standard library and its documentation. There is also a very simple example in my tutorial in the "Concurrent Processing" topic. -- 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 May 28 18:20:41 2018 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 28 May 2018 16:20:41 -0600 Subject: [Tutor] Tkinter widget (label) updated by TCP/IP message In-Reply-To: <946493988.6197927.1527533767185@mail.yahoo.com> References: <504307975.5860800.1527434327234.ref@mail.yahoo.com> <504307975.5860800.1527434327234@mail.yahoo.com> <946493988.6197927.1527533767185@mail.yahoo.com> Message-ID: <4b7364dc-4086-bb00-62bd-23dc9060be81@wichmann.us> On 05/28/2018 12:56 PM, Alejandro Chirife via Tutor wrote: > Hi Alan, > Thank you very much for your help.? ?I will start working on ti.? There's a lot to chew on here :) > Two questions:? > 1. Got it that nothing to do when mainloop() gets called.? How do you send an event of data arriving when the events for tkinter are all about user interaction? > 2. You mentioned "? ? create thread to run get_network_message" in your pseudocode (in main() ).? Could you guide me towards which Class to use for this? > Thanks!AC You're going to want to look at the threading module for threads, and the socket and the select modules for networking. threading.Event and threading.Timer may be of interest as to communicating with the other thread and setting a timeout. This isn't actually as trivial a problem as it may sound on the surface, by the way, so don't worry if it takes a while to get right! From erich027 at outlook.com Wed May 30 06:09:36 2018 From: erich027 at outlook.com (erich callahana) Date: Wed, 30 May 2018 10:09:36 +0000 Subject: [Tutor] i really need help Message-ID: I need to know how to access the window where in the menu at the top it says run and that?s where I can test my script, basically I have no idea how to test my script Thankyou Kind Regards Erich.C From alan.gauld at yahoo.co.uk Wed May 30 12:31:58 2018 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 30 May 2018 17:31:58 +0100 Subject: [Tutor] i really need help In-Reply-To: References: Message-ID: On 30/05/18 11:09, erich callahana wrote: > I need to know how to access the window where > in the menu at the top it says run You need to help us out here. What program are you running or trying to run that has this Window? It sounds like an IDE of some kind, maybe IDLE? But most IDEs have a Run menu so its hard to know where you should look unless we know the program you are using. What OS are you using and which Python version? Are you following a tutorial/video or book? If so which? > and that?s where I can test my script, basicall> I have no idea how to test my script The simplest way is to use the OS prompt (CMD.EXE in Windows or Terminal application in MacOS or a shell window/console in Linux) That should give you a prompt ending in either $ or >. Type > python full/path/to/myscript.py And your code will run in that window. -- 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 t100ss at gmail.com Wed May 30 12:34:59 2018 From: t100ss at gmail.com (Brian Lockwood) Date: Wed, 30 May 2018 17:34:59 +0100 Subject: [Tutor] i really need help In-Reply-To: References: Message-ID: If you only have the command line. Use the command line to navigate the folder where your script is. Then use the command python Followed by your scrutiny On Wed, 30 May 2018 at 17:13, erich callahana wrote: > > > I need to know how to access the window where in the menu at the top it > says run and that?s where I can test my script, basically I have no idea > how to test my script > > Thankyou > > Kind Regards > > Erich.C > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From arj.python at gmail.com Wed May 30 14:27:13 2018 From: arj.python at gmail.com (Abdur-Rahmaan Janhangeer) Date: Wed, 30 May 2018 22:27:13 +0400 Subject: [Tutor] i really need help In-Reply-To: References: Message-ID: did you attach a screenshot? if so i think it did not reach us ! Abdur-Rahmaan Janhangeer https://github.com/Abdur-rahmaanJ On Wed, 30 May 2018, 20:11 erich callahana, wrote: > > > I need to know how to access the window where in the menu at the top it > says run and that?s where I can test my script, basically I have no idea > how to test my script > > Thankyou > > Kind Regards > > Erich.C > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From sergio_r at mail.com Thu May 31 12:22:37 2018 From: sergio_r at mail.com (Sergio Rojas) Date: Thu, 31 May 2018 18:22:37 +0200 Subject: [Tutor] Prealgebra via Python programmin In-Reply-To: References: Message-ID: Hello folks, Released under the Creative Commons Attribution-NonCommercial 4.0 International License [1]http://creativecommons.org/licenses/by-nc/4.0/ Prealgebra via Python programming is available at: [2]https://www.researchgate.net/publication/325473565 In case you find yourself in the mood to collaborate to improve the readability and/or enhance/enrich the content of the book, feel free to contact me at the above email address. Sergio -- Enhance your [3]#MachineLearning and [4]#BigData skills via [5]#Python and [6]#SciPy 1. [7]https://www.packtpub.com/big-data-and-business-intelligence/numerical-and-scientific-computing-scipy-video
2. [8]https://www.packtpub.com/big-data-and-business-intelligence/learning-scipy-numerical-and-scientific-computing-second-edition
3. Python book en Castellano (distribucion gratuita): [9]https://www.researchgate.net/publication/301293668 References Visible links 1. http://creativecommons.org/licenses/by-nc/4.0/ 2. https://www.researchgate.net/publication/325473565 3. https://twitter.com/hashtag/machinelearning 4. https://twitter.com/hashtag/bigdata 5. https://twitter.com/hashtag/python 6. https://twitter.com/hashtag/scipy 7. https://www.packtpub.com/big-data-and-business-intelligence/numerical-and-scientific-computing-scipy-video 8. https://www.packtpub.com/big-data-and-business-intelligence/learning-scipy-numerical-and-scientific-computing-second-edition 9. https://www.researchgate.net/publication/301293668 From erich027 at outlook.com Thu May 31 02:06:13 2018 From: erich027 at outlook.com (erich callahana) Date: Thu, 31 May 2018 06:06:13 +0000 Subject: [Tutor] (no subject) Message-ID: I?m not sure how to access this window -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: ATT00001.txt URL: