From george at fischhof.hu  Sat Jul  1 10:57:52 2017
From: george at fischhof.hu (George Fischhof)
Date: Sat, 1 Jul 2017 16:57:52 +0200
Subject: [Tutor] Query regarding output
In-Reply-To: <CAN1d+1_OCUxT8X5z9PQ1B5Ec-tAHP2WG+ViHv_2hh0uOF-kQOw@mail.gmail.com>
References: <CAN1d+1-hpEhE26hbd92jwdsPTva=-5_U5jJ2Jm-25nd=EWpX1w@mail.gmail.com>
 <oj2fmh$klg$1@blaine.gmane.org>
 <3bf08769-d8dd-7650-4a99-207183d49f4a@wichmann.us>
 <CAN1d+19xENAMX7TM+TCXY4drJDWcUjJC-vo98kH5iPR9Fvz3Ww@mail.gmail.com>
 <CAN1d+1-uvQnYGZt9_qBQcWu57u_W38Z9S0AhzNVSqn1gcUtDaA@mail.gmail.com>
 <CAN1d+1_OCUxT8X5z9PQ1B5Ec-tAHP2WG+ViHv_2hh0uOF-kQOw@mail.gmail.com>
Message-ID: <CAFwcP0i727sak+5zaiNBrLxTpJmiYHvO4yZ8wbnPYszAM9FUOQ@mail.gmail.com>

2017-06-29 15:55 GMT+02:00 shubham goyal <skgoyal721 at gmail.com>:

> Thanks all
> Great place to learn Python.
>
> On Jun 29, 2017 7:24 PM, "shubham goyal" <skgoyal721 at gmail.com> wrote:
>
> Thankyou all.
>
> Great place to learn.
>
> On Jun 29, 2017 5:55 PM, "Mats Wichmann" <mats at wichmann.us> wrote:
>
> > On 06/29/2017 03:02 AM, Alan Gauld via Tutor wrote:
> > > On 29/06/17 03:14, shubham goyal wrote:
> > >
> > >> This Question is asked in some exam. i am not able to figure it out.
> > >>
> > >> a = [0, 1, 2, 3]
> > >> for a[-1] in a:
> > >>     print(a[-1])
> > >>
> > >> its giving output 0 1 2 2
> > >>
> > >> it should be 3 3 3 3 as a[-1] belongs to 3.
> > >> can anyone help me figuring it out.
> > >
> > > This is quite subtle and it took me a few minutes to figure
> > > it out myself.
> > >
> > > It might be clearer if we print all of 'a' instead
> > > of a[-1]:
> > >
> > >>>> for a[-1] in a:
> > > ...    print(a)
> > > ...
> > > [0, 1, 2, 0]
> > > [0, 1, 2, 1]
> > > [0, 1, 2, 2]
> > > [0, 1, 2, 2]
> > >
> > > What is happening is that a[-1] is being assigned the value
> > > of each item in a in turn. The final iteration assigns a[-1]
> > > to itself, thus we repeat the 2.
> >
> >
> > Ugh.  I guess on an exam where they're trying to see if you can tease it
> > out, as you may one day have to debug such a sequence... but don't write
> > code like that.  One of the reasons people like "functional programming"
> > is it avoids these kind of side effects.
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > https://mail.python.org/mailman/listinfo/tutor
> >
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



Hi All,

just a comment ;-)
Actually I do not know why it is good to ask similar things on a Python
exam... Yes, I know that if one can answer these questions they show that
they understand it.  (Just a side question: Really understand? ;-) )

But a Pythonista never will write a code like this.

I think this behaviour is just to "show" to the student that this is very
strong school... :-(

I think it would be better to teach how to write Pythonic code...

BR,
George

From longleggedlunatic at gmail.com  Sun Jul  2 06:03:09 2017
From: longleggedlunatic at gmail.com (Richard Grose)
Date: Sun, 02 Jul 2017 10:03:09 +0000
Subject: [Tutor] 
 =?utf-8?q?program_code_for_Python_Programming_for_the_Ab?=
 =?utf-8?q?solute=09Beginner=2C_3rd_ed=2E=3F?=
In-Reply-To: <<CALMxxxn=6w5F+9YOXd7BN4-5d6_5qSGG+G=sGBPC73SEVj-DHQ@mail.gmail.com>>
References: <<CALMxxxn=6w5F+9YOXd7BN4-5d6_5qSGG+G=sGBPC73SEVj-DHQ@mail.gmail.com>>
Message-ID: <em30e7b975-4725-42e8-aa8d-3441c3ff8c1e@mo>

https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwiw1tD3qurUAhULKlAKHWMOAPMQFggkMAA&url=https%3A%2F%2Fgithub.com%2FCWade3051%2FPy%2Ftree%2Fmaster%2FAbsolute%2520Book%2Fpy3e_source&usg=AFQjCNG36WhZfh5ftqWncjtgZy3z6xgh6g&cad=rjt

Py/Absolute Book/py3e_source at master ? CWade3051/Py ? GitHub 
<https://github.com/CWade3051/Py/tree/master/Absolute%20Book/py3e_source>
Richard G

From marie_jos_v at yahoo.com  Sun Jul  2 11:06:07 2017
From: marie_jos_v at yahoo.com (Joseph VOGTEMBING)
Date: Sun, 2 Jul 2017 15:06:07 +0000 (UTC)
Subject: [Tutor] Installing Python3.6.1 on Ubuntu 16.04.2
References: <1851656955.2858074.1499007968088.ref@mail.yahoo.com>
Message-ID: <1851656955.2858074.1499007968088@mail.yahoo.com>

I have a fresh install of Ubuntu 16.04.2, on which I try to install Python3.6.1, and I have done this multiple times in the past, but for some reason I tried it 3 times since yesterday but I kept having the same error message. here are the steps that i have taken for my installation.
mariejosv at ubuntu:~$? sudo apt-get update
mariejosv at ubuntu:~$? sudo apt-get upgrade
mariejosv at ubuntu:~$ wget https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tar.xz


mariejosv at ubuntu:~$ tar xvf Python-3.6.1.tar.xz????

mariejosv at ubuntu:~$ sudo apt-get installbuild-essential checkinstall? ?

mariejosv at ubuntu:~$ sudo apt-get installlibreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-devlibgdbm-dev libc6-dev libbz2-dev? ?

mariejosv at ubuntu:~$ cd Python-3.6.1

mariejosv at ubuntu:~/Python-3.6.1$ ./configure?? 
mariejosv at ubuntu:~/Python-3.6.1$sudo make altinstall? # after this line, the following message will popup at some point




Please help.
Thanks
Joseph

From alan.gauld at yahoo.co.uk  Sun Jul  2 17:35:06 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 2 Jul 2017 22:35:06 +0100
Subject: [Tutor] program code for Python Programming for the Absolute
 Beginner, 3rd ed.?
In-Reply-To: <em30e7b975-4725-42e8-aa8d-3441c3ff8c1e@mo>
References: <<CALMxxxn=6w5F+9YOXd7BN4-5d6_5qSGG+G=sGBPC73SEVj-DHQ@mail.gmail.com>
 <em30e7b975-4725-42e8-aa8d-3441c3ff8c1e@mo>
Message-ID: <ojbou4$43e$1@blaine.gmane.org>

On 02/07/17 11:03, Richard Grose wrote:
> https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwiw1tD3qurUAhULKlAKHWMOAPMQFggkMAA&url=https%3A%2F%2Fgithub.com%2FCWade3051%2FPy%2Ftree%2Fmaster%2FAbsolute%2520Book%2Fpy3e_source&usg=AFQjCNG36WhZfh5ftqWncjtgZy3z6xgh6g&cad=rjt
> 
> Py/Absolute Book/py3e_source at master ? CWade3051/Py ? GitHub 
> <https://github.com/CWade3051/Py/tree/master/Absolute%20Book/py3e_source>
> Richard G

Your subject line ends with a question mark so, are you asking
us something? Or telling us something?

Its not very clear which...

If you are asking you need to ask again, being a bit more specific.

-- 
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 itetteh34 at hotmail.com  Sun Jul  2 16:13:41 2017
From: itetteh34 at hotmail.com (isaac tetteh)
Date: Sun, 2 Jul 2017 20:13:41 +0000
Subject: [Tutor] Installing Python3.6.1 on Ubuntu 16.04.2
Message-ID: <AM5PR0701MB2354D3EC448CFE445B246122BDD10@AM5PR0701MB2354.eurprd07.prod.outlook.com>

Sudo apt install Python 3.6 should be enough. But I would advise to use a virtual environment since you don't want to mess up Ubuntu configuration.

Sent from my Verizon LG Smartphone

------ Original message------
From: Joseph VOGTEMBING via Tutor
Date: Sun, Jul 2, 2017 2:48 PM
To: tutor at python.org;
Cc:
Subject:[Tutor] Installing Python3.6.1 on Ubuntu 16.04.2


From mats at wichmann.us  Sun Jul  2 19:46:04 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Sun, 02 Jul 2017 17:46:04 -0600
Subject: [Tutor] Installing Python3.6.1 on Ubuntu 16.04.2
In-Reply-To: <1851656955.2858074.1499007968088@mail.yahoo.com>
References: <1851656955.2858074.1499007968088.ref@mail.yahoo.com>
 <1851656955.2858074.1499007968088@mail.yahoo.com>
Message-ID: <CB2C358C-A578-4ED0-ABA2-A22B20BE407C@wichmann.us>

what was the error? nothing came through

On July 2, 2017 9:06:07 AM MDT, Joseph VOGTEMBING via Tutor <tutor at python.org> wrote:
>I have a fresh install of Ubuntu 16.04.2, on which I try to install
>Python3.6.1, and I have done this multiple times in the past, but for
>some reason I tried it 3 times since yesterday but I kept having the
>same error message. here are the steps that i have taken for my
>installation.
>mariejosv at ubuntu:~$? sudo apt-get update
>mariejosv at ubuntu:~$? sudo apt-get upgrade
>mariejosv at ubuntu:~$ wget
>https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tar.xz
>
>
>mariejosv at ubuntu:~$ tar xvf Python-3.6.1.tar.xz????
>
>mariejosv at ubuntu:~$ sudo apt-get installbuild-essential checkinstall? ?
>
>mariejosv at ubuntu:~$ sudo apt-get installlibreadline-gplv2-dev
>libncursesw5-dev libssl-dev libsqlite3-dev tk-devlibgdbm-dev libc6-dev
>libbz2-dev? ?
>
>mariejosv at ubuntu:~$ cd Python-3.6.1
>
>mariejosv at ubuntu:~/Python-3.6.1$ ./configure?? 
>mariejosv at ubuntu:~/Python-3.6.1$sudo make altinstall? # after this
>line, the following message will popup at some point
>
>
>
>
>Please help.
>Thanks
>Joseph
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>To unsubscribe or change subscription options:
>https://mail.python.org/mailman/listinfo/tutor

-- 
Sent from my Android device with K-9 Mail. Please excuse my brevity.

From marie_jos_v at yahoo.com  Mon Jul  3 00:29:49 2017
From: marie_jos_v at yahoo.com (Joseph VOGTEMBING)
Date: Mon, 3 Jul 2017 04:29:49 +0000 (UTC)
Subject: [Tutor] Installing Python3.6.1 on Ubuntu 16.04.2
In-Reply-To: <CALt_PJTpfe+G7X1Xo+LkJRChD3F1tHo1DaJUwkqu5yVC6gu4AQ@mail.gmail.com>
References: <1851656955.2858074.1499007968088.ref@mail.yahoo.com>
 <1851656955.2858074.1499007968088@mail.yahoo.com>
 <CB2C358C-A578-4ED0-ABA2-A22B20BE407C@wichmann.us>
 <CALt_PJTpfe+G7X1Xo+LkJRChD3F1tHo1DaJUwkqu5yVC6gu4AQ@mail.gmail.com>
Message-ID: <1868189.3131184.1499056189174@mail.yahoo.com>

HEY GUYS,SORRY, BUT HERE IS THE ERROR MESSAGE."The directory '/home/mariejosv/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/mariejosv/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag."?


On Sunday, July 2, 2017, 8:55:05 PM EDT, Mike Lisanke <mikelisanke at gmail.com> wrote:

looks like python3.6 isn't in the stable repo for arm64 ubuntu 16.04... so articles exist for building it. None appear to mention .configure --<options> used and there's a lot of options... if anyone has a reference to what to configure, let me know.?
On Sun, Jul 2, 2017 at 7:46 PM, Mats Wichmann <mats at wichmann.us> wrote:

what was the error? nothing came through

On July 2, 2017 9:06:07 AM MDT, Joseph VOGTEMBING via Tutor <tutor at python.org> wrote:
>I have a fresh install of Ubuntu 16.04.2, on which I try to install
>Python3.6.1, and I have done this multiple times in the past, but for
>some reason I tried it 3 times since yesterday but I kept having the
>same error message. here are the steps that i have taken for my
>installation.
>mariejosv at ubuntu:~$? sudo apt-get update
>mariejosv at ubuntu:~$? sudo apt-get upgrade
>mariejosv at ubuntu:~$ wget
>https://www.python.org/ftp/ python/3.6.1/Python-3.6.1.tar. xz
>
>
>mariejosv at ubuntu:~$ tar xvf Python-3.6.1.tar.xz????
>
>mariejosv at ubuntu:~$ sudo apt-get installbuild-essential checkinstall? ?
>
>mariejosv at ubuntu:~$ sudo apt-get installlibreadline-gplv2-dev
>libncursesw5-dev libssl-dev libsqlite3-dev tk-devlibgdbm-dev libc6-dev
>libbz2-dev? ?
>
>mariejosv at ubuntu:~$ cd Python-3.6.1
>
>mariejosv at ubuntu:~/Python-3. 6.1$ ./configure??
>mariejosv at ubuntu:~/Python-3. 6.1$sudo make altinstall? # after this
>line, the following message will popup at some point
>The directory '/home/mariejosv/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/mariejosv/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
?>
>
>
>Please help.
>Thanks
>Joseph
>_____________________________ __________________
>Tutor maillist? -? Tutor at python.org
>To unsubscribe or change subscription options:
>https://mail.python.org/ mailman/listinfo/tutor

--
Sent from my Android device with K-9 Mail. Please excuse my brevity.
______________________________ _________________
Tutor maillist? -? Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/ mailman/listinfo/tutor




-- 
Best regards,? Mike

From mikelisanke at gmail.com  Sun Jul  2 20:54:24 2017
From: mikelisanke at gmail.com (Mike Lisanke)
Date: Sun, 2 Jul 2017 20:54:24 -0400
Subject: [Tutor] Installing Python3.6.1 on Ubuntu 16.04.2
In-Reply-To: <CB2C358C-A578-4ED0-ABA2-A22B20BE407C@wichmann.us>
References: <1851656955.2858074.1499007968088.ref@mail.yahoo.com>
 <1851656955.2858074.1499007968088@mail.yahoo.com>
 <CB2C358C-A578-4ED0-ABA2-A22B20BE407C@wichmann.us>
Message-ID: <CALt_PJTpfe+G7X1Xo+LkJRChD3F1tHo1DaJUwkqu5yVC6gu4AQ@mail.gmail.com>

looks like python3.6 isn't in the stable repo for arm64 ubuntu 16.04... so
articles exist for building it. None appear to mention .configure
--<options> used and there's a lot of options... if anyone has a reference
to what to configure, let me know.

On Sun, Jul 2, 2017 at 7:46 PM, Mats Wichmann <mats at wichmann.us> wrote:

> what was the error? nothing came through
>
> On July 2, 2017 9:06:07 AM MDT, Joseph VOGTEMBING via Tutor <
> tutor at python.org> wrote:
> >I have a fresh install of Ubuntu 16.04.2, on which I try to install
> >Python3.6.1, and I have done this multiple times in the past, but for
> >some reason I tried it 3 times since yesterday but I kept having the
> >same error message. here are the steps that i have taken for my
> >installation.
> >mariejosv at ubuntu:~$  sudo apt-get update
> >mariejosv at ubuntu:~$  sudo apt-get upgrade
> >mariejosv at ubuntu:~$ wget
> >https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tar.xz
> >
> >
> >mariejosv at ubuntu:~$ tar xvf Python-3.6.1.tar.xz
> >
> >mariejosv at ubuntu:~$ sudo apt-get installbuild-essential checkinstall
> >
> >mariejosv at ubuntu:~$ sudo apt-get installlibreadline-gplv2-dev
> >libncursesw5-dev libssl-dev libsqlite3-dev tk-devlibgdbm-dev libc6-dev
> >libbz2-dev
> >
> >mariejosv at ubuntu:~$ cd Python-3.6.1
> >
> >mariejosv at ubuntu:~/Python-3.6.1$ ./configure
> >mariejosv at ubuntu:~/Python-3.6.1$sudo make altinstall  # after this
> >line, the following message will popup at some point
> >
> >
> >
> >
> >Please help.
> >Thanks
> >Joseph
> >_______________________________________________
> >Tutor maillist  -  Tutor at python.org
> >To unsubscribe or change subscription options:
> >https://mail.python.org/mailman/listinfo/tutor
>
> --
> Sent from my Android device with K-9 Mail. Please excuse my brevity.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Best regards,  Mike

From alan.gauld at yahoo.co.uk  Mon Jul  3 04:13:20 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 3 Jul 2017 09:13:20 +0100
Subject: [Tutor] Fwd: Re: program code for Python Programming for the
 Absolute Beginner, 3rd ed.?
In-Reply-To: <550716929.3135198.1499055718444@mail.yahoo.com>
References: <550716929.3135198.1499055718444@mail.yahoo.com>
Message-ID: <bc155415-80b5-10ff-77da-00bed199a61b@yahoo.co.uk>

forwarding to list.

Sorry,
I still have no idea what you are trying to do and what you want help with?

-------- Forwarded Message --------

Alan,
my bad, here is the error message.
*The directory '/home/mariejosv/.cache/pip/http' or its parent directory
is not owned by the current user and the cache has been disabled. Please
check the permissions and owner of that directory. If executing pip with
sudo, you may want sudo's -H flag.
The directory '/home/mariejosv/.cache/pip' or its parent directory is
not owned by the current user and caching wheels has been disabled.
check the permissions and owner of that directory. If executing pip with
sudo, you may want sudo's -H flag. *


On Sunday, July 2, 2017, 5:36:34 PM EDT, Alan Gauld via Tutor
<tutor at python.org> wrote:


On 02/07/17 11:03, Richard Grose wrote:
>
https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwiw1tD3qurUAhULKlAKHWMOAPMQFggkMAA&url=https%3A%2F%2Fgithub.com%2FCWade3051%2FPy%2Ftree%2Fmaster%2FAbsolute%2520Book%2Fpy3e_source&usg=AFQjCNG36WhZfh5ftqWncjtgZy3z6xgh6g&cad=rjt
>
> Py/Absolute Book/py3e_source at master ? CWade3051/Py ? GitHub
> <https://github.com/CWade3051/Py/tree/master/Absolute%20Book/py3e_source>
> Richard G

Your subject line ends with a question mark so, are you asking
us something? Or telling us something?

Its not very clear which...

If you are asking you need to ask again, being a bit more specific.

-- 
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 <mailto:Tutor at python.org>
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

From alan.gauld at yahoo.co.uk  Mon Jul  3 05:54:47 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 3 Jul 2017 10:54:47 +0100
Subject: [Tutor] Ubuntu install [was: Re: Fwd: Re: program code for Python
 Programming for the Absolute Beginner, 3rd ed.?]
In-Reply-To: <bc155415-80b5-10ff-77da-00bed199a61b@yahoo.co.uk>
References: <550716929.3135198.1499055718444@mail.yahoo.com>
 <bc155415-80b5-10ff-77da-00bed199a61b@yahoo.co.uk>
Message-ID: <ojd491$b0h$1@blaine.gmane.org>

On 03/07/17 09:13, Alan Gauld via Tutor wrote:
> forwarding to list.
> 
> Sorry,
> I still have no idea what you are trying to do and what you want help with?

OK, I just realized that you replied to the wrong post
and this is actually about the thread on installing 3.6
on Ubuntu.

> 
> -------- Forwarded Message --------
> 
> Alan,
> my bad, here is the error message.
> *The directory '/home/mariejosv/.cache/pip/http' or its parent directory
> is not owned by the current user and the cache has been disabled. Please
> check the permissions and owner of that directory. If executing pip with
> sudo, you may want sudo's -H flag.
> The directory '/home/mariejosv/.cache/pip' or its parent directory is
> not owned by the current user and caching wheels has been disabled.
> check the permissions and owner of that directory. If executing pip with
> sudo, you may want sudo's -H flag. *
> 
> 

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From cs at zip.com.au  Mon Jul  3 05:37:15 2017
From: cs at zip.com.au (Cameron Simpson)
Date: Mon, 3 Jul 2017 19:37:15 +1000
Subject: [Tutor] Fwd: Re: program code for Python Programming for the
 Absolute Beginner, 3rd ed.?
In-Reply-To: <bc155415-80b5-10ff-77da-00bed199a61b@yahoo.co.uk>
References: <bc155415-80b5-10ff-77da-00bed199a61b@yahoo.co.uk>
Message-ID: <20170703093715.GA5695@cskk.homeip.net>

On 03Jul2017 09:13, Alan Gauld <alan.gauld at yahoo.co.uk> wrote:
[...]
>Sorry,
>I still have no idea what you are trying to do and what you want help with?
>-------- Forwarded Message --------
>Alan,
>my bad, here is the error message.
>*The directory '/home/mariejosv/.cache/pip/http' or its parent directory
>is not owned by the current user and the cache has been disabled. Please
>check the permissions and owner of that directory. If executing pip with
>sudo, you may want sudo's -H flag.

I would guess that the poster has done some pip installs as root, but with 
$HOME still as their personal home directory, and is now doing some pip install 
stuff as themselves.

My advice would be to simply remove the .cache/pip directory.

Then in future, do your pip work from a proper login shell as whichever user.  
So either as yourself, or if you become root, do an "su -" to get a root login 
shell before proceeding.

Personally my practice is to mostly use pip only with virtualenvs, as myself.

Using pip as root tends to conflict with Python packages supplied by the OS 
vendor/supplier; better to stay out of the way of that and work as oneself on 
data the OS vendor doesn't want to own.

Cheers,
Cameron Simpson <cs at zip.com.au>

From alan.gauld at yahoo.co.uk  Mon Jul  3 13:58:09 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 3 Jul 2017 18:58:09 +0100
Subject: [Tutor] Fwd: Re: Ubuntu install [was: Re: Fwd: Re: program code for
 Python Programming for the Absolute Beginner, 3rd ed.?]
In-Reply-To: <19487.82498.bm@smtp228.mail.gq1.yahoo.com>
References: <19487.82498.bm@smtp228.mail.gq1.yahoo.com>
Message-ID: <debb61db-13da-5792-adf8-60c28df5c831@yahoo.co.uk>

Forwarding to group.

Please always use ReplyAll (or ReplyList) when responding to list emails.





-------- Forwarded Message --------


I have a fresh install of Ubuntu 16.04.2, on which I try to install
Python 3.6.1. I have done this multiple times in the past, but for some
reason I tried it 3 times since yesterday but I kept having the same
error message. Here are the steps that i have taken for my installation:

|$ sudo apt-get update $ sudo apt-get upgrade $ wget
https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tar.xz $ tar xvf
Python-3.6.1.tar.xz $ sudo apt-get install build-essential checkinstall
$ sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev
libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev $ cd
Python-3.6.1$ ./configure $ sudo make altinstall|

After the last command the following message will popup at some point:

    The directory '/home/mariejosv/.cache/pip/http' or its parent
    directory is not owned by the current user and the cache has been
    disabled. Please check the permissions and owner of that directory.
    If executing pip with sudo, you may want sudo's -H flag.

    The directory '/home/mariejosv/.cache/pip' or its parent directory
    is not owned by the current user and caching wheels has been
    disabled. check the permissions and owner of that directory. If
    executing pip with sudo, you may want sudo's -H flag.

How can I fix this?



Sent from my T-Mobile 4G LTE Device



From quazi.ashfaq at gmail.com  Tue Jul  4 01:58:42 2017
From: quazi.ashfaq at gmail.com (Ashfaq)
Date: Tue, 4 Jul 2017 11:58:42 +0600
Subject: [Tutor] [Python2.7] Convert (2,188,1) into (188,1)
In-Reply-To: <1137976406.539519.1498664914573@mail.yahoo.com>
References: <1137976406.539519.1498664914573.ref@mail.yahoo.com>
 <1137976406.539519.1498664914573@mail.yahoo.com>
Message-ID: <CAMih+LFq_HS=yTT=J=4amrnSg5n3A17=+gTo5uPyOmTXFVi-rw@mail.gmail.com>

Is it a 3-item tuple?

On Wed, Jun 28, 2017 at 9:48 PM, Allan Tanaka via Tutor <tutor at python.org>
wrote:

> Hi. I have array shape like: (2,188,1). I want to make it like this:
> (188,1). I try that using .reshape(188,1) but throws an error: total size
> of an array must be unchanged
> Thank you for the help!
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From rskovron at gmail.com  Mon Jul  3 22:40:11 2017
From: rskovron at gmail.com (Rafael Skovron)
Date: Mon, 3 Jul 2017 19:40:11 -0700
Subject: [Tutor] Not returning out the series
Message-ID: <CABXYKTrh9K3hJ3yT2Utk=fAd8mMubNAihUGLK9Qoz+z2Z-3BPA@mail.gmail.com>

Hi as a challenge I have got to sum a series i / (i+1). My code isn't
summing right. Any ideas why?


def main():
    print("{0:15s}{1:20s}".format("i","m(i)"))
    for i in range(1,20):
        print("{0:<15d}{1:<20.4f}".format(i,m(i)))

def m(i):
    total = 0
    for i in range(1,i+1,1):
        total+=(i/(i+1))
    return total

From alan.gauld at yahoo.co.uk  Tue Jul  4 04:32:44 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 4 Jul 2017 09:32:44 +0100
Subject: [Tutor] Not returning out the series
In-Reply-To: <CABXYKTrh9K3hJ3yT2Utk=fAd8mMubNAihUGLK9Qoz+z2Z-3BPA@mail.gmail.com>
References: <CABXYKTrh9K3hJ3yT2Utk=fAd8mMubNAihUGLK9Qoz+z2Z-3BPA@mail.gmail.com>
Message-ID: <ojfjr6$cnh$1@blaine.gmane.org>

On 04/07/17 03:40, Rafael Skovron wrote:

> def m(i):
>     total = 0
>     for i in range(1,i+1,1):
>         total+=(i/(i+1))
>     return total

convert the numerator to a float. Otherwise you
are using integer division. (I'm guessing you
are running Python 2.7?)

You could also import division from future:

from __future__ import division

Alternatively you could try running Python v3.

PS, Its probably not a great idea to use i as both
the iteration variable and the input parameter.
It easily causes confusion.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Tue Jul  4 04:37:46 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 4 Jul 2017 09:37:46 +0100
Subject: [Tutor] [Python2.7] Convert (2,188,1) into (188,1)
In-Reply-To: <1137976406.539519.1498664914573@mail.yahoo.com>
References: <1137976406.539519.1498664914573.ref@mail.yahoo.com>
 <1137976406.539519.1498664914573@mail.yahoo.com>
Message-ID: <ojfk4k$2gj$1@blaine.gmane.org>

On 28/06/17 16:48, Allan Tanaka via Tutor wrote:
> Hi. I have array shape like: (2,188,1). 

I assume this is a numpy array rather than the standard
library array? If so consider asking on the scipy/numpy
support forum for more specialised help.

> I want to make it like this: (188,1). I try that 
> using .reshape(188,1) 

.reshape() is not a valid function name. What object
are you attaching it to?

Show us at least a code snippet so we don't need
to guess. We need to see how you create the initial
array, then how you try to use reshape. Ideally a short
but complete example that exhibits the problem.

> but throws an error: total size of an array must be unchanged

Show us the full error trace, they contain a lot of information.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From nulla.epistola at web.de  Tue Jul  4 04:57:45 2017
From: nulla.epistola at web.de (Sibylle Koczian)
Date: Tue, 4 Jul 2017 10:57:45 +0200
Subject: [Tutor] Not returning out the series
In-Reply-To: <CABXYKTrh9K3hJ3yT2Utk=fAd8mMubNAihUGLK9Qoz+z2Z-3BPA@mail.gmail.com>
References: <CABXYKTrh9K3hJ3yT2Utk=fAd8mMubNAihUGLK9Qoz+z2Z-3BPA@mail.gmail.com>
Message-ID: <0c179a4e-ac12-383e-50d0-9560895b9e87@web.de>

Am 04.07.2017 um 04:40 schrieb Rafael Skovron:
> Hi as a challenge I have got to sum a series i / (i+1). My code isn't
> summing right. Any ideas why?
> 
> 
> def main():
>      print("{0:15s}{1:20s}".format("i","m(i)"))
>      for i in range(1,20):
>          print("{0:<15d}{1:<20.4f}".format(i,m(i)))
> 
> def m(i):
>      total = 0
>      for i in range(1,i+1,1):
>          total+=(i/(i+1))
>      return total

Python 2 or Python 3? What sums do you get and what sums do you expect?

BTW in your function m(i) it's very confusing that you use the name i 
both for the range limit and for the loop variable. It seems to be 
syntactically correct, but it's certainly not readable.

HTH
Sibylle


From nulla.epistola at web.de  Tue Jul  4 04:57:45 2017
From: nulla.epistola at web.de (Sibylle Koczian)
Date: Tue, 4 Jul 2017 10:57:45 +0200
Subject: [Tutor] Not returning out the series
In-Reply-To: <CABXYKTrh9K3hJ3yT2Utk=fAd8mMubNAihUGLK9Qoz+z2Z-3BPA@mail.gmail.com>
References: <CABXYKTrh9K3hJ3yT2Utk=fAd8mMubNAihUGLK9Qoz+z2Z-3BPA@mail.gmail.com>
Message-ID: <0c179a4e-ac12-383e-50d0-9560895b9e87@web.de>

Am 04.07.2017 um 04:40 schrieb Rafael Skovron:
> Hi as a challenge I have got to sum a series i / (i+1). My code isn't
> summing right. Any ideas why?
> 
> 
> def main():
>      print("{0:15s}{1:20s}".format("i","m(i)"))
>      for i in range(1,20):
>          print("{0:<15d}{1:<20.4f}".format(i,m(i)))
> 
> def m(i):
>      total = 0
>      for i in range(1,i+1,1):
>          total+=(i/(i+1))
>      return total

Python 2 or Python 3? What sums do you get and what sums do you expect?

BTW in your function m(i) it's very confusing that you use the name i 
both for the range limit and for the loop variable. It seems to be 
syntactically correct, but it's certainly not readable.

HTH
Sibylle

From noflaco at gmail.com  Tue Jul  4 04:50:12 2017
From: noflaco at gmail.com (Carlton Banks)
Date: Tue, 4 Jul 2017 10:50:12 +0200
Subject: [Tutor] call key on_press event multiple times when key is held down
Message-ID: <2B208211-1037-4106-849A-91C0B38318EF@gmail.com>

I am trying to record from my microphone while i press down a button, problem is that the library I am using is not able to detect on hold event. It only detect on press, which happens once, which means that the microphone only records one sample..

import pyaudio
import wave
from pynput import keyboard

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)         
frames = []

def on_press(key):
    if key == keyboard.Key.cmd_l:
        print('- Started recording -'.format(key))
        try:
            data = stream.read(CHUNK)
            frames.append(data)
        except IOError: 
            print 'warning: dropped frame' # can replace with 'pass' if no message desired 
    else:
        print('incorrect character {0}, press cmd_l'.format(key))


def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.cmd_l:
        print('{0} stop'.format(key))
        keyboard.Listener.stop
        return False

print("* recording")


with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
I am using pynput <https://pypi.python.org/pypi/pynput> for keyboard events and pyaudio for recording. I am pretty sure that this should be the error, as the example script for recording, picks up samples in a for loop, which works. 

So does any of you know any libraries that monitors state of the keyboard, or any ideas on how to get this working?.. I tried with a while look inside the on_press callback but that resulted in me getting stuck that callback.


How can i fix this?



From alan.gauld at yahoo.co.uk  Tue Jul  4 05:35:36 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 4 Jul 2017 10:35:36 +0100
Subject: [Tutor] call key on_press event multiple times when key is held
 down
In-Reply-To: <2B208211-1037-4106-849A-91C0B38318EF@gmail.com>
References: <2B208211-1037-4106-849A-91C0B38318EF@gmail.com>
Message-ID: <ojfnh2$eap$1@blaine.gmane.org>

On 04/07/17 09:50, Carlton Banks wrote:
> I am trying to record from my microphone while i press down a button,

First question is which OS?
That makes a big difference in this kind of scenario.

> the library I am using is not able to detect on hold event. 

There isn't really any concept of a hold event, you usually
have to detect repeated press events. However I don;t know
the library you are using, I normally just use the standard
library for such things, or build a simple GUI...

> It only detect on press, which happens once, 

That's unusual, usually you get a repeated stream of
press events when you hold a key down. But it does
depend on the OS and environment. Your library may
indeed just be detecting the initial key down and
be waiting for the key up event.

> So does any of you know any libraries that monitor> state of the keyboard,

There are several but it depends on your OS.
In the standard library
Unix variants can use curses.
Windows users have msvcrt.

And there are several 3rd party libraries that try
to do in a platform independent way - I'm guessing
the one you are using is one such.

Another way to tackle it is to switch your code so
it works with a toggle. Set the toggle to on in
the on_press handler. Set it to off in the
on_release handler

Then trigger a timer loop that runs for as long
as the toggle is set. This is probably easiest
done within a GUI.

-- 
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  Tue Jul  4 05:46:01 2017
From: sjeik_appie at hotmail.com (Albert-Jan Roskam)
Date: Tue, 4 Jul 2017 09:46:01 +0000
Subject: [Tutor] [Python2.7] Convert (2,188,1) into (188,1)
In-Reply-To: <ojfk4k$2gj$1@blaine.gmane.org>
References: <1137976406.539519.1498664914573.ref@mail.yahoo.com>
 <1137976406.539519.1498664914573@mail.yahoo.com>,
 <ojfk4k$2gj$1@blaine.gmane.org>
Message-ID: <HE1PR1001MB130886803F8F7EDB35E05DCB83D70@HE1PR1001MB1308.EURPRD10.PROD.OUTLOOK.COM>


________________________________________
From: Tutor [tutor-bounces+sjeik_appie=hotmail.com at python.org] on behalf of Alan Gauld via Tutor [tutor at python.org]
Sent: Tuesday, July 4, 2017 8:37 AM
To: tutor at python.org
Subject: Re: [Tutor] [Python2.7] Convert (2,188,1) into (188,1)

On 28/06/17 16:48, Allan Tanaka via Tutor wrote:
> Hi. I have array shape like: (2,188,1).

I assume this is a numpy array rather than the standard
library array? If so consider asking on the scipy/numpy
support forum for more specialised help.

> I want to make it like this: (188,1). I try that
> using .reshape(188,1)

Assuming this is a numpy array: If you want a 1D array you can use ravel (faster) or flatten (better name IMHO): https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html
arr.reshape(2*188, 1) may also work.

From alan.gauld at yahoo.co.uk  Tue Jul  4 07:00:38 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 4 Jul 2017 12:00:38 +0100
Subject: [Tutor] Fwd: Re: call key on_press event multiple times when key is
 held down
In-Reply-To: <29FACF89-C690-40CC-9AE4-7064516A971F@gmail.com>
References: <29FACF89-C690-40CC-9AE4-7064516A971F@gmail.com>
Message-ID: <e32c7b7b-52c2-da14-a7aa-39d2052ab0b3@yahoo.co.uk>

Forwarding to Tutor list


Please always use reply-All or reply-List to respond to tutor posts.



-------- Forwarded Message --------

> Den 4. jul. 2017 kl. 11.35 skrev Alan Gauld via Tutor <tutor at python.org>:
> 
> On 04/07/17 09:50, Carlton Banks wrote:
>> I am trying to record from my microphone while i press down a button,
> 
> First question is which OS?
> That makes a big difference in this kind of scenario.

I am currently testing it on OS X, but should also be working on a ubuntu machine.  

>> the library I am using is not able to detect on hold event. 
> 
> There isn't really any concept of a hold event, you usually
> have to detect repeated press events. However I don;t know
> the library you are using, I normally just use the standard
> library for such things, or build a simple GUI?

Standard library being?.. 

> 
>> It only detect on press, which happens once, 
> 
> That's unusual, usually you get a repeated stream of
> press events when you hold a key down. But it does
> depend on the OS and environment. Your library may
> indeed just be detecting the initial key down and
> be waiting for the key up event.

Hmm.. interesting but again it is currently being tested on OSX,
as it was the only machine available atm. 
> 
>> So does any of you know any libraries that monitor> state of the keyboard,
> 
> There are several but it depends on your OS.
> In the standard library
> Unix variants can use curses.
> Windows users have msvcrt.
> 
> And there are several 3rd party libraries that try
> to do in a platform independent way - I'm guessing
> the one you are using is one such.
> 
> Another way to tackle it is to switch your code so
> it works with a toggle. Set the toggle to on in
> the on_press handler. Set it to off in the
> on_release handler
> 
> Then trigger a timer loop that runs for as long
> as the toggle is set. This is probably easiest
> done within a GUI.
> 

Interesting solution, but still find a bit "dirty hackish?
to involve a timer in this..  I guess it just would be neat if 
it just worked as i thought it to be.  But i guess i have to look into curses.




From alan.gauld at yahoo.co.uk  Tue Jul  4 07:33:14 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 4 Jul 2017 12:33:14 +0100
Subject: [Tutor] Fwd: Re: call key on_press event multiple times when
 key is held down
In-Reply-To: <e32c7b7b-52c2-da14-a7aa-39d2052ab0b3@yahoo.co.uk>
References: <29FACF89-C690-40CC-9AE4-7064516A971F@gmail.com>
 <e32c7b7b-52c2-da14-a7aa-39d2052ab0b3@yahoo.co.uk>
Message-ID: <ojfudk$nf3$1@blaine.gmane.org>

On 04/07/17 12:00, Alan Gauld via Tutor wrote:

>> the library you are using, I normally just use the standard
>> library for such things, or build a simple GUI?
> 
> Standard library being?.. 

The Python standard library that ships with Python and
is documented on python.org. As in:

>> There are several but it depends on your OS.
>> In the standard library
>> Unix variants can use curses.
>> Windows users have msvcrt.


> Interesting solution, but still find a bit "dirty hackish?
> to involve a timer in this..  I guess it just would be neat if 
> it just worked as i thought it to be.  But i guess i have to look into curses.

A timer based loop is actually the standard pattern for
implementing a loop in an event driven environment (the
main alternative is to launch a background thread).
It's how most GUIs handle such scenarios.

The problem in a CLI solution is that you have to build your
own timer event system (usually based on time.sleep() or
similar). Hence the suggestion to use a GUI.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From noflaco at gmail.com  Tue Jul  4 08:45:49 2017
From: noflaco at gmail.com (Carlton Banks)
Date: Tue, 4 Jul 2017 14:45:49 +0200
Subject: [Tutor] Fwd: Re: call key on_press event multiple times when
 key is held down
In-Reply-To: <ojfudk$nf3$1@blaine.gmane.org>
References: <29FACF89-C690-40CC-9AE4-7064516A971F@gmail.com>
 <e32c7b7b-52c2-da14-a7aa-39d2052ab0b3@yahoo.co.uk>
 <ojfudk$nf3$1@blaine.gmane.org>
Message-ID: <6025937C-F701-4C41-87B6-5805B14ED4DC@gmail.com>

> 
>> Interesting solution, but still find a bit "dirty hackish?
>> to involve a timer in this..  I guess it just would be neat if 
>> it just worked as i thought it to be.  But i guess i have to look into curses.
> 
> A timer based loop is actually the standard pattern for
> implementing a loop in an event driven environment (the
> main alternative is to launch a background thread).
> It's how most GUIs handle such scenarios.
> 
> The problem in a CLI solution is that you have to build your
> own timer event system (usually based on time.sleep() or
> similar). Hence the suggestion to use a GUI.
> 

Any suggestion on any GUI solutions?


Regards 
Carl


From eryksun at gmail.com  Tue Jul  4 15:55:51 2017
From: eryksun at gmail.com (eryk sun)
Date: Tue, 4 Jul 2017 19:55:51 +0000
Subject: [Tutor] call key on_press event multiple times when key is held
 down
In-Reply-To: <2B208211-1037-4106-849A-91C0B38318EF@gmail.com>
References: <2B208211-1037-4106-849A-91C0B38318EF@gmail.com>
Message-ID: <CACL+1au7BQ6_RGGsMQnBwTjnOGTGuybVfQ_Q8opRtAUbHpzoGA@mail.gmail.com>

On Tue, Jul 4, 2017 at 8:50 AM, Carlton Banks <noflaco at gmail.com> wrote:
> I am using pynput <https://pypi.python.org/pypi/pynput> for keyboard events

You could use an event that enables a recording loop. The on_press and
on_release callbacks of the Listener [1] would set() and clear() this
event, respectively. For example:

    import threading
    from pynput import keyboard

    def main():
        do_record = threading.Event()

        def on_press(key):
            if key == keyboard.Key.cmd_l:
                do_record.set()

        def on_release(key):
            if key == keyboard.Key.cmd_l:
                do_record.clear()

        with keyboard.Listener(on_press=on_press,
                               on_release=on_release) as listener:

            do_record.wait()

            frames = []

            while do_record.is_set():
                print('Started recording')
                # record and append audio frame

            print('Stopped recording')
            listener.join()

[1]: http://pythonhosted.org/pynput/keyboard.html#pynput.keyboard.Listener

From skgoyal721 at gmail.com  Wed Jul  5 04:47:07 2017
From: skgoyal721 at gmail.com (shubham goyal)
Date: Wed, 5 Jul 2017 14:17:07 +0530
Subject: [Tutor] dictionaries are same but returning false
Message-ID: <CAN1d+183Ai+T-cqg2j9E6j+mPDQ-oYFPXjChWaqW4Si0n57iyQ@mail.gmail.com>

null=None
x={'_udp_options': None, '_icmp_options': None, 'attribute_map':
{'icmp_options': 'icmpOptions', 'protocol': 'protocol', 'source': 'source',
'tcp_options': 'tcpOptions', 'is_stateless': 'isStateless', 'udp_options':
'udpOptions'}, '_is_stateless': False, 'swagger_types': {'icmp_options':
'IcmpOptions', 'protocol': 'str', 'source': 'str', 'tcp_options':
'TcpOptions', 'is_stateless': 'bool', 'udp_options': 'UdpOptions'},
'_protocol': '6', '_source': '0.0.4.0/24', '_tcp_options': {
  "destination_port_range": {
    "max": "22",
    "min": "22"
  },
  "source_port_range": null
}}

y={'_udp_options': None, '_icmp_options': None, 'attribute_map':
{'icmp_options': 'icmpOptions', 'protocol': 'protocol', 'source': 'source',
'tcp_options': 'tcpOptions', 'is_stateless': 'isStateless', 'udp_options':
'udpOptions'}, '_is_stateless': False, 'swagger_types': {'icmp_options':
'IcmpOptions', 'protocol': 'str', 'source': 'str', 'tcp_options':
'TcpOptions', 'is_stateless': 'bool', 'udp_options': 'UdpOptions'},
'_protocol': '6', '_source': '0.0.4.0/24', '_tcp_options': {
  "destination_port_range": {
    "max": 22,
    "min": 22
  },
  "source_port_range": null
}}
if x==y:
    print "true"
else:
    print "false"


These dictionaries are same exactly. but its returning false. i don't
understand
what to do?

From __peter__ at web.de  Wed Jul  5 07:39:54 2017
From: __peter__ at web.de (Peter Otten)
Date: Wed, 05 Jul 2017 13:39:54 +0200
Subject: [Tutor] dictionaries are same but returning false
References: <CAN1d+183Ai+T-cqg2j9E6j+mPDQ-oYFPXjChWaqW4Si0n57iyQ@mail.gmail.com>
Message-ID: <ojij65$gdt$1@blaine.gmane.org>

shubham goyal wrote:

> null=None
> x={'_udp_options': None, '_icmp_options': None, 'attribute_map':
> {'icmp_options': 'icmpOptions', 'protocol': 'protocol', 'source':
> {'source',
> 'tcp_options': 'tcpOptions', 'is_stateless': 'isStateless', 'udp_options':
> 'udpOptions'}, '_is_stateless': False, 'swagger_types': {'icmp_options':
> 'IcmpOptions', 'protocol': 'str', 'source': 'str', 'tcp_options':
> 'TcpOptions', 'is_stateless': 'bool', 'udp_options': 'UdpOptions'},
> '_protocol': '6', '_source': '0.0.4.0/24', '_tcp_options': {
>   "destination_port_range": {
>     "max": "22",
>     "min": "22"
>   },
>   "source_port_range": null
> }}
> 
> y={'_udp_options': None, '_icmp_options': None, 'attribute_map':
> {'icmp_options': 'icmpOptions', 'protocol': 'protocol', 'source':
> {'source',
> 'tcp_options': 'tcpOptions', 'is_stateless': 'isStateless', 'udp_options':
> 'udpOptions'}, '_is_stateless': False, 'swagger_types': {'icmp_options':
> 'IcmpOptions', 'protocol': 'str', 'source': 'str', 'tcp_options':
> 'TcpOptions', 'is_stateless': 'bool', 'udp_options': 'UdpOptions'},
> '_protocol': '6', '_source': '0.0.4.0/24', '_tcp_options': {
>   "destination_port_range": {
>     "max": 22,
>     "min": 22
>   },
>   "source_port_range": null
> }}
> if x==y:
>     print "true"
> else:
>     print "false"
> 
> 
> These dictionaries are same exactly. but its returning false. i don't
> understand
> what to do?

Let's narrow down the problem, with the help of the interactive interpreter:

>>> changed = [k for k in x if x[k] != y[k]]
>>> changed
['_tcp_options']
>>> k, = changed

A closer look:

>>> x[k]
{'source_port_range': None, 'destination_port_range': {'max': '22', 'min': 
'22'}}
>>> y[k]
{'source_port_range': None, 'destination_port_range': {'max': 22, 'min': 
22}}

So x uses strings for min/max while y uses integers, and those do not 
compare equal in Python:

>>> 22 == "22"
False

Once you fix this

>>> x[k]["destination_port_range"]["max"] = 22
>>> x[k]["destination_port_range"]["min"] = 22

you get the expected result:

>>> x == y
True



From skgoyal721 at gmail.com  Wed Jul  5 08:10:22 2017
From: skgoyal721 at gmail.com (shubham goyal)
Date: Wed, 5 Jul 2017 17:40:22 +0530
Subject: [Tutor] dictionaries are same but returning false
In-Reply-To: <ojij65$gdt$1@blaine.gmane.org>
References: <CAN1d+183Ai+T-cqg2j9E6j+mPDQ-oYFPXjChWaqW4Si0n57iyQ@mail.gmail.com>
 <ojij65$gdt$1@blaine.gmane.org>
Message-ID: <CAN1d+1--0K8jRe4qX76yPWhiD_tWW7w-bo53RL0p2=MSJV3xfQ@mail.gmail.com>

Thank you Peter.
Silly mistakes ?

On Jul 5, 2017 5:10 PM, "Peter Otten" <__peter__ at web.de> wrote:

> shubham goyal wrote:
>
> > null=None
> > x={'_udp_options': None, '_icmp_options': None, 'attribute_map':
> > {'icmp_options': 'icmpOptions', 'protocol': 'protocol', 'source':
> > {'source',
> > 'tcp_options': 'tcpOptions', 'is_stateless': 'isStateless',
> 'udp_options':
> > 'udpOptions'}, '_is_stateless': False, 'swagger_types': {'icmp_options':
> > 'IcmpOptions', 'protocol': 'str', 'source': 'str', 'tcp_options':
> > 'TcpOptions', 'is_stateless': 'bool', 'udp_options': 'UdpOptions'},
> > '_protocol': '6', '_source': '0.0.4.0/24', '_tcp_options': {
> >   "destination_port_range": {
> >     "max": "22",
> >     "min": "22"
> >   },
> >   "source_port_range": null
> > }}
> >
> > y={'_udp_options': None, '_icmp_options': None, 'attribute_map':
> > {'icmp_options': 'icmpOptions', 'protocol': 'protocol', 'source':
> > {'source',
> > 'tcp_options': 'tcpOptions', 'is_stateless': 'isStateless',
> 'udp_options':
> > 'udpOptions'}, '_is_stateless': False, 'swagger_types': {'icmp_options':
> > 'IcmpOptions', 'protocol': 'str', 'source': 'str', 'tcp_options':
> > 'TcpOptions', 'is_stateless': 'bool', 'udp_options': 'UdpOptions'},
> > '_protocol': '6', '_source': '0.0.4.0/24', '_tcp_options': {
> >   "destination_port_range": {
> >     "max": 22,
> >     "min": 22
> >   },
> >   "source_port_range": null
> > }}
> > if x==y:
> >     print "true"
> > else:
> >     print "false"
> >
> >
> > These dictionaries are same exactly. but its returning false. i don't
> > understand
> > what to do?
>
> Let's narrow down the problem, with the help of the interactive
> interpreter:
>
> >>> changed = [k for k in x if x[k] != y[k]]
> >>> changed
> ['_tcp_options']
> >>> k, = changed
>
> A closer look:
>
> >>> x[k]
> {'source_port_range': None, 'destination_port_range': {'max': '22', 'min':
> '22'}}
> >>> y[k]
> {'source_port_range': None, 'destination_port_range': {'max': 22, 'min':
> 22}}
>
> So x uses strings for min/max while y uses integers, and those do not
> compare equal in Python:
>
> >>> 22 == "22"
> False
>
> Once you fix this
>
> >>> x[k]["destination_port_range"]["max"] = 22
> >>> x[k]["destination_port_range"]["min"] = 22
>
> you get the expected result:
>
> >>> x == y
> True
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From david.rock at gmail.com  Wed Jul  5 11:37:10 2017
From: david.rock at gmail.com (David Rock)
Date: Wed, 5 Jul 2017 10:37:10 -0500
Subject: [Tutor] Why use main() ?
Message-ID: <20170705153710.GA12705@apple.graniteweb.com>

This is not a question about using if __name__ == '__main__':.  I know
what the difference is between running the script or importing it and
using the value of __name__ to determine behavior.

This is a question about the benefits of using a main() function vs not.
ie,

    if __name__ == '__main__':
        #code goes here

vs


    def main():
        #code goes here

    if __name__ == '__main__':
        main()


I personally find using main() cumbersome, but many examples I come
across use main().  Is there some fundamental benefit to using main()
that I'm missing?


-- 
David Rock
david at graniteweb.com

From zachary.ware+pytut at gmail.com  Wed Jul  5 11:45:29 2017
From: zachary.ware+pytut at gmail.com (Zachary Ware)
Date: Wed, 5 Jul 2017 10:45:29 -0500
Subject: [Tutor] Why use main() ?
In-Reply-To: <20170705153710.GA12705@apple.graniteweb.com>
References: <20170705153710.GA12705@apple.graniteweb.com>
Message-ID: <CAKJDb-MtuBuA+0VmNqfZpeW1wK+0iB3uUfj2kMFT+PjvKR1qBw@mail.gmail.com>

On Wed, Jul 5, 2017 at 10:37 AM, David Rock <david.rock at gmail.com> wrote:
> This is not a question about using if __name__ == '__main__':.  I know
> what the difference is between running the script or importing it and
> using the value of __name__ to determine behavior.
>
> This is a question about the benefits of using a main() function vs not.
> ie,
>
>     if __name__ == '__main__':
>         #code goes here
>
> vs
>
>
>     def main():
>         #code goes here
>
>     if __name__ == '__main__':
>         main()
>
>
> I personally find using main() cumbersome, but many examples I come
> across use main().  Is there some fundamental benefit to using main()
> that I'm missing?

In no particular order: testing, encapsulation, and reusability.  With
a "main()" function (which, recall, can be named whatever you like; it
doesn't have to be "main") you can directly call the function in your
tests to make sure it acts the way you want.  The encapsulation of the
"main" code in a "main()" function also reduces your global state (and
makes global state a bit more difficult to use), which is usually a
good thing.  And finally, it makes it possible to use the "main()"
function in some other piece of code that imports it.

-- 
Zach

From quazi.ashfaq at gmail.com  Wed Jul  5 12:51:10 2017
From: quazi.ashfaq at gmail.com (Ashfaq)
Date: Wed, 5 Jul 2017 22:51:10 +0600
Subject: [Tutor] dictionaries are same but returning false
In-Reply-To: <CAN1d+1--0K8jRe4qX76yPWhiD_tWW7w-bo53RL0p2=MSJV3xfQ@mail.gmail.com>
References: <CAN1d+183Ai+T-cqg2j9E6j+mPDQ-oYFPXjChWaqW4Si0n57iyQ@mail.gmail.com>
 <ojij65$gdt$1@blaine.gmane.org>
 <CAN1d+1--0K8jRe4qX76yPWhiD_tWW7w-bo53RL0p2=MSJV3xfQ@mail.gmail.com>
Message-ID: <CAMih+LHCVVRQfqxd4ycU6FOO7hbNF4z-qFV-nKF5xukmdOhNbw@mail.gmail.com>

Hi Peter,
The way you find the issue is really cool! Very cool! :)

On Wed, Jul 5, 2017 at 6:10 PM, shubham goyal <skgoyal721 at gmail.com> wrote:

> Thank you Peter.
> Silly mistakes ?
>
> On Jul 5, 2017 5:10 PM, "Peter Otten" <__peter__ at web.de> wrote:
>
> > shubham goyal wrote:
> >
> > > null=None
> > > x={'_udp_options': None, '_icmp_options': None, 'attribute_map':
> > > {'icmp_options': 'icmpOptions', 'protocol': 'protocol', 'source':
> > > {'source',
> > > 'tcp_options': 'tcpOptions', 'is_stateless': 'isStateless',
> > 'udp_options':
> > > 'udpOptions'}, '_is_stateless': False, 'swagger_types':
> {'icmp_options':
> > > 'IcmpOptions', 'protocol': 'str', 'source': 'str', 'tcp_options':
> > > 'TcpOptions', 'is_stateless': 'bool', 'udp_options': 'UdpOptions'},
> > > '_protocol': '6', '_source': '0.0.4.0/24', '_tcp_options': {
> > >   "destination_port_range": {
> > >     "max": "22",
> > >     "min": "22"
> > >   },
> > >   "source_port_range": null
> > > }}
> > >
> > > y={'_udp_options': None, '_icmp_options': None, 'attribute_map':
> > > {'icmp_options': 'icmpOptions', 'protocol': 'protocol', 'source':
> > > {'source',
> > > 'tcp_options': 'tcpOptions', 'is_stateless': 'isStateless',
> > 'udp_options':
> > > 'udpOptions'}, '_is_stateless': False, 'swagger_types':
> {'icmp_options':
> > > 'IcmpOptions', 'protocol': 'str', 'source': 'str', 'tcp_options':
> > > 'TcpOptions', 'is_stateless': 'bool', 'udp_options': 'UdpOptions'},
> > > '_protocol': '6', '_source': '0.0.4.0/24', '_tcp_options': {
> > >   "destination_port_range": {
> > >     "max": 22,
> > >     "min": 22
> > >   },
> > >   "source_port_range": null
> > > }}
> > > if x==y:
> > >     print "true"
> > > else:
> > >     print "false"
> > >
> > >
> > > These dictionaries are same exactly. but its returning false. i don't
> > > understand
> > > what to do?
> >
> > Let's narrow down the problem, with the help of the interactive
> > interpreter:
> >
> > >>> changed = [k for k in x if x[k] != y[k]]
> > >>> changed
> > ['_tcp_options']
> > >>> k, = changed
> >
> > A closer look:
> >
> > >>> x[k]
> > {'source_port_range': None, 'destination_port_range': {'max': '22',
> 'min':
> > '22'}}
> > >>> y[k]
> > {'source_port_range': None, 'destination_port_range': {'max': 22, 'min':
> > 22}}
> >
> > So x uses strings for min/max while y uses integers, and those do not
> > compare equal in Python:
> >
> > >>> 22 == "22"
> > False
> >
> > Once you fix this
> >
> > >>> x[k]["destination_port_range"]["max"] = 22
> > >>> x[k]["destination_port_range"]["min"] = 22
> >
> > you get the expected result:
> >
> > >>> x == y
> > True
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > https://mail.python.org/mailman/listinfo/tutor
> >
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From marc.tompkins at gmail.com  Wed Jul  5 13:09:45 2017
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 5 Jul 2017 10:09:45 -0700
Subject: [Tutor] dictionaries are same but returning false
In-Reply-To: <CAMih+LHCVVRQfqxd4ycU6FOO7hbNF4z-qFV-nKF5xukmdOhNbw@mail.gmail.com>
References: <CAN1d+183Ai+T-cqg2j9E6j+mPDQ-oYFPXjChWaqW4Si0n57iyQ@mail.gmail.com>
 <ojij65$gdt$1@blaine.gmane.org>
 <CAN1d+1--0K8jRe4qX76yPWhiD_tWW7w-bo53RL0p2=MSJV3xfQ@mail.gmail.com>
 <CAMih+LHCVVRQfqxd4ycU6FOO7hbNF4z-qFV-nKF5xukmdOhNbw@mail.gmail.com>
Message-ID: <CAKK8jXZJ8tS8dPhPh3Nu5=988h6y5V2g=zwVqW8_Vd026q7j=w@mail.gmail.com>

On Wed, Jul 5, 2017 at 9:51 AM, Ashfaq <quazi.ashfaq at gmail.com> wrote:

> Hi Peter,
> The way you find the issue is really cool! Very cool! :)
>
>
I agree - that is very cool.  But I have also made this sort of mistake a
few times, and found it by using a very quick, low-tech method...
"Unfold" the lines of the two dictionary specifications and put them one
above the other - I usually just cut'n'paste into a text editor and delete
the newlines.  If the two unfolded lines don't line up (which these
wouldn't, because one has extra quotes in it) the error will be immediately
visible.  Subtler typos will be harder to spot, but still much easier than
trying to compare two folded paragraphs several lines apart.

Not nearly as sophisticated, but sometimes quick'n'dirty is best.


> On Wed, Jul 5, 2017 at 6:10 PM, shubham goyal <skgoyal721 at gmail.com>
> wrote:
>
> > Thank you Peter.
> > Silly mistakes ?
> >
> > On Jul 5, 2017 5:10 PM, "Peter Otten" <__peter__ at web.de> wrote:
> >
> > > shubham goyal wrote:
> > >
> > > > null=None
> > > > x={'_udp_options': None, '_icmp_options': None, 'attribute_map':
> > > > {'icmp_options': 'icmpOptions', 'protocol': 'protocol', 'source':
> > > > {'source',
> > > > 'tcp_options': 'tcpOptions', 'is_stateless': 'isStateless',
> > > 'udp_options':
> > > > 'udpOptions'}, '_is_stateless': False, 'swagger_types':
> > {'icmp_options':
> > > > 'IcmpOptions', 'protocol': 'str', 'source': 'str', 'tcp_options':
> > > > 'TcpOptions', 'is_stateless': 'bool', 'udp_options': 'UdpOptions'},
> > > > '_protocol': '6', '_source': '0.0.4.0/24', '_tcp_options': {
> > > >   "destination_port_range": {
> > > >     "max": "22",
> > > >     "min": "22"
> > > >   },
> > > >   "source_port_range": null
> > > > }}
> > > >
> > > > y={'_udp_options': None, '_icmp_options': None, 'attribute_map':
> > > > {'icmp_options': 'icmpOptions', 'protocol': 'protocol', 'source':
> > > > {'source',
> > > > 'tcp_options': 'tcpOptions', 'is_stateless': 'isStateless',
> > > 'udp_options':
> > > > 'udpOptions'}, '_is_stateless': False, 'swagger_types':
> > {'icmp_options':
> > > > 'IcmpOptions', 'protocol': 'str', 'source': 'str', 'tcp_options':
> > > > 'TcpOptions', 'is_stateless': 'bool', 'udp_options': 'UdpOptions'},
> > > > '_protocol': '6', '_source': '0.0.4.0/24', '_tcp_options': {
> > > >   "destination_port_range": {
> > > >     "max": 22,
> > > >     "min": 22
> > > >   },
> > > >   "source_port_range": null
> > > > }}
> > > > if x==y:
> > > >     print "true"
> > > > else:
> > > >     print "false"
> > > >
> > > >
> > > > These dictionaries are same exactly. but its returning false. i don't
> > > > understand
> > > > what to do?
> > >
> > > Let's narrow down the problem, with the help of the interactive
> > > interpreter:
> > >
> > > >>> changed = [k for k in x if x[k] != y[k]]
> > > >>> changed
> > > ['_tcp_options']
> > > >>> k, = changed
> > >
> > > A closer look:
> > >
> > > >>> x[k]
> > > {'source_port_range': None, 'destination_port_range': {'max': '22',
> > 'min':
> > > '22'}}
> > > >>> y[k]
> > > {'source_port_range': None, 'destination_port_range': {'max': 22,
> 'min':
> > > 22}}
> > >
> > > So x uses strings for min/max while y uses integers, and those do not
> > > compare equal in Python:
> > >
> > > >>> 22 == "22"
> > > False
> > >
> > > Once you fix this
> > >
> > > >>> x[k]["destination_port_range"]["max"] = 22
> > > >>> x[k]["destination_port_range"]["min"] = 22
> > >
> > > you get the expected result:
> > >
> > > >>> x == y
> > > True
> > >
> > >
> > > _______________________________________________
> > > Tutor maillist  -  Tutor at python.org
> > > To unsubscribe or change subscription options:
> > > https://mail.python.org/mailman/listinfo/tutor
> > >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > https://mail.python.org/mailman/listinfo/tutor
> >
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From mats at wichmann.us  Wed Jul  5 13:20:53 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Wed, 5 Jul 2017 11:20:53 -0600
Subject: [Tutor] dictionaries are same but returning false
In-Reply-To: <CAKK8jXZJ8tS8dPhPh3Nu5=988h6y5V2g=zwVqW8_Vd026q7j=w@mail.gmail.com>
References: <CAN1d+183Ai+T-cqg2j9E6j+mPDQ-oYFPXjChWaqW4Si0n57iyQ@mail.gmail.com>
 <ojij65$gdt$1@blaine.gmane.org>
 <CAN1d+1--0K8jRe4qX76yPWhiD_tWW7w-bo53RL0p2=MSJV3xfQ@mail.gmail.com>
 <CAMih+LHCVVRQfqxd4ycU6FOO7hbNF4z-qFV-nKF5xukmdOhNbw@mail.gmail.com>
 <CAKK8jXZJ8tS8dPhPh3Nu5=988h6y5V2g=zwVqW8_Vd026q7j=w@mail.gmail.com>
Message-ID: <55ce10fd-50f4-a8b9-6b64-30be87df7694@wichmann.us>

On 07/05/2017 11:09 AM, Marc Tompkins wrote:
> On Wed, Jul 5, 2017 at 9:51 AM, Ashfaq <quazi.ashfaq at gmail.com> wrote:
> 
>> Hi Peter,
>> The way you find the issue is really cool! Very cool! :)
>>
>>
> I agree - that is very cool.  But I have also made this sort of mistake a
> few times, and found it by using a very quick, low-tech method...
> "Unfold" the lines of the two dictionary specifications and put them one
> above the other - I usually just cut'n'paste into a text editor and delete
> the newlines.  If the two unfolded lines don't line up (which these
> wouldn't, because one has extra quotes in it) the error will be immediately
> visible.  Subtler typos will be harder to spot, but still much easier than
> trying to compare two folded paragraphs several lines apart.
> 
> Not nearly as sophisticated, but sometimes quick'n'dirty is best.

but not terribly useful for dictionaries, which don't have any sense of
order (unless, of course you sort first, or use an ordered dict)



From dyoo at hashcollision.org  Wed Jul  5 15:01:00 2017
From: dyoo at hashcollision.org (Danny Yoo)
Date: Wed, 5 Jul 2017 12:01:00 -0700
Subject: [Tutor] dictionaries are same but returning false
In-Reply-To: <55ce10fd-50f4-a8b9-6b64-30be87df7694@wichmann.us>
References: <CAN1d+183Ai+T-cqg2j9E6j+mPDQ-oYFPXjChWaqW4Si0n57iyQ@mail.gmail.com>
 <ojij65$gdt$1@blaine.gmane.org>
 <CAN1d+1--0K8jRe4qX76yPWhiD_tWW7w-bo53RL0p2=MSJV3xfQ@mail.gmail.com>
 <CAMih+LHCVVRQfqxd4ycU6FOO7hbNF4z-qFV-nKF5xukmdOhNbw@mail.gmail.com>
 <CAKK8jXZJ8tS8dPhPh3Nu5=988h6y5V2g=zwVqW8_Vd026q7j=w@mail.gmail.com>
 <55ce10fd-50f4-a8b9-6b64-30be87df7694@wichmann.us>
Message-ID: <CAGZAPF4+Qsh4-hzUrV6VzcTj-UkeQAvQYsCR8ypSexxhnK2O1w@mail.gmail.com>

The difflib library (https://docs.python.org/2/library/difflib.html)
can also help with some exploratory discovery of the problem.

Here's an example:


####################################################
>>> import difflib
>>> for line in difflib.context_diff(repr(x).split(','), repr(y).split(',')):
...     print line
...
***

---

***************

*** 1,7 ****

  {'_icmp_options': None
   '_tcp_options': {'source_port_range': None
!  'destination_port_range': {'max': '22'
!  'min': '22'}}
   '_protocol': '6'
   'swagger_types': {'protocol': 'str'
   'tcp_options': 'TcpOptions'
--- 1,7 ----

  {'_icmp_options': None
   '_tcp_options': {'source_port_range': None
!  'destination_port_range': {'max': 22
!  'min': 22}}
   '_protocol': '6'
   'swagger_types': {'protocol': 'str'
   'tcp_options': 'TcpOptions'
####################################################


To make the diff comprehensible, we're splitting by commas and
comparing each comma-delimited chunk between the representations of x
and y.  We got lucky here because the dictionaries are printing their
values in the same order here.  Normally we should not depend on this
kind of behavior, but we're just doing exploratory programming, so no
foul.  :P

From dyoo at hashcollision.org  Wed Jul  5 15:06:13 2017
From: dyoo at hashcollision.org (Danny Yoo)
Date: Wed, 5 Jul 2017 12:06:13 -0700
Subject: [Tutor] Why use main() ?
In-Reply-To: <CAKJDb-MtuBuA+0VmNqfZpeW1wK+0iB3uUfj2kMFT+PjvKR1qBw@mail.gmail.com>
References: <20170705153710.GA12705@apple.graniteweb.com>
 <CAKJDb-MtuBuA+0VmNqfZpeW1wK+0iB3uUfj2kMFT+PjvKR1qBw@mail.gmail.com>
Message-ID: <CAGZAPF71Ek+PBNi8A8DiU5-8cfdJhrOkK=dkgSvQG+eiJMSUMQ@mail.gmail.com>

>> I personally find using main() cumbersome, but many examples I come
>> across use main().  Is there some fundamental benefit to using main()
>> that I'm missing?
>
> In no particular order: testing, encapsulation, and reusability.  With
> a "main()" function (which, recall, can be named whatever you like; it
> doesn't have to be "main") you can directly call the function in your
> tests to make sure it acts the way you want.  The encapsulation of the
> "main" code in a "main()" function also reduces your global state (and
> makes global state a bit more difficult to use), which is usually a
> good thing.  And finally, it makes it possible to use the "main()"
> function in some other piece of code that imports it.


I echo Zach.  Python's variables are function scoped by default,
rather than block-scoped, so variables can be inadvertently introduced
that were not intended.

e.g.:

############################
>>> if __name__ == '__main__':
...     x = 42
...
>>> x
42
############################

In many other languages, nesting means a new scope.  In Python,
though, it doesn't, so having the main() function there allows us to
impose a scope to avoid polluting the module namespace.

From alan.gauld at yahoo.co.uk  Wed Jul  5 15:36:26 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 5 Jul 2017 20:36:26 +0100
Subject: [Tutor] Why use main() ?
In-Reply-To: <20170705153710.GA12705@apple.graniteweb.com>
References: <20170705153710.GA12705@apple.graniteweb.com>
Message-ID: <ojjf3l$tqj$1@blaine.gmane.org>

On 05/07/17 16:37, David Rock wrote:

> This is a question about the benefits of using a main() function vs not.


Others have answered for the pros, but I confess that I don't
always use a main(), but only if all I'm doing is, say,
instantiating a class and running a method. For anything
more complex I'd write a main() (or test() or demo() ) to
go inside the
   if name==main
clause.

-- 
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 skgoyal721 at gmail.com  Wed Jul  5 13:39:38 2017
From: skgoyal721 at gmail.com (shubham goyal)
Date: Wed, 5 Jul 2017 23:09:38 +0530
Subject: [Tutor] dictionaries are same but returning false
In-Reply-To: <CAN1d+18Q=PvNckqB6j4-Wx2jVv1eH-n=8x+iz5R-XfcqTivX2Q@mail.gmail.com>
References: <CAN1d+183Ai+T-cqg2j9E6j+mPDQ-oYFPXjChWaqW4Si0n57iyQ@mail.gmail.com>
 <ojij65$gdt$1@blaine.gmane.org>
 <CAN1d+1--0K8jRe4qX76yPWhiD_tWW7w-bo53RL0p2=MSJV3xfQ@mail.gmail.com>
 <CAMih+LHCVVRQfqxd4ycU6FOO7hbNF4z-qFV-nKF5xukmdOhNbw@mail.gmail.com>
 <CAN1d+18EZAPfDgGjqCq5Y2fzhHPkXU2WVouwvKxgPouOg-wiVg@mail.gmail.com>
 <CAN1d+18Q=PvNckqB6j4-Wx2jVv1eH-n=8x+iz5R-XfcqTivX2Q@mail.gmail.com>
Message-ID: <CAN1d+18S3xy7VnevtH3L2Ys5kGWH3y8kUgm81=SocoFvwO2rxQ@mail.gmail.com>

On Jul 5, 2017 11:09 PM, "shubham goyal" <skgoyal721 at gmail.com> wrote:

> Yha that's very smart. Only experience can drive you this way. Otherwise I
> was checking value by value.
>
> On Jul 5, 2017 10:21 PM, "Ashfaq" <quazi.ashfaq at gmail.com> wrote:
>
> Hi Peter,
> The way you find the issue is really cool! Very cool! :)
>
> On Wed, Jul 5, 2017 at 6:10 PM, shubham goyal <skgoyal721 at gmail.com>
> wrote:
>
>> Thank you Peter.
>> Silly mistakes ?
>>
>> On Jul 5, 2017 5:10 PM, "Peter Otten" <__peter__ at web.de> wrote:
>>
>> > shubham goyal wrote:
>> >
>> > > null=None
>> > > x={'_udp_options': None, '_icmp_options': None, 'attribute_map':
>> > > {'icmp_options': 'icmpOptions', 'protocol': 'protocol', 'source':
>> > > {'source',
>> > > 'tcp_options': 'tcpOptions', 'is_stateless': 'isStateless',
>> > 'udp_options':
>> > > 'udpOptions'}, '_is_stateless': False, 'swagger_types':
>> {'icmp_options':
>> > > 'IcmpOptions', 'protocol': 'str', 'source': 'str', 'tcp_options':
>> > > 'TcpOptions', 'is_stateless': 'bool', 'udp_options': 'UdpOptions'},
>> > > '_protocol': '6', '_source': '0.0.4.0/24', '_tcp_options': {
>> > >   "destination_port_range": {
>> > >     "max": "22",
>> > >     "min": "22"
>> > >   },
>> > >   "source_port_range": null
>> > > }}
>> > >
>> > > y={'_udp_options': None, '_icmp_options': None, 'attribute_map':
>> > > {'icmp_options': 'icmpOptions', 'protocol': 'protocol', 'source':
>> > > {'source',
>> > > 'tcp_options': 'tcpOptions', 'is_stateless': 'isStateless',
>> > 'udp_options':
>> > > 'udpOptions'}, '_is_stateless': False, 'swagger_types':
>> {'icmp_options':
>> > > 'IcmpOptions', 'protocol': 'str', 'source': 'str', 'tcp_options':
>> > > 'TcpOptions', 'is_stateless': 'bool', 'udp_options': 'UdpOptions'},
>> > > '_protocol': '6', '_source': '0.0.4.0/24', '_tcp_options': {
>> > >   "destination_port_range": {
>> > >     "max": 22,
>> > >     "min": 22
>> > >   },
>> > >   "source_port_range": null
>> > > }}
>> > > if x==y:
>> > >     print "true"
>> > > else:
>> > >     print "false"
>> > >
>> > >
>> > > These dictionaries are same exactly. but its returning false. i don't
>> > > understand
>> > > what to do?
>> >
>> > Let's narrow down the problem, with the help of the interactive
>> > interpreter:
>> >
>> > >>> changed = [k for k in x if x[k] != y[k]]
>> > >>> changed
>> > ['_tcp_options']
>> > >>> k, = changed
>> >
>> > A closer look:
>> >
>> > >>> x[k]
>> > {'source_port_range': None, 'destination_port_range': {'max': '22',
>> 'min':
>> > '22'}}
>> > >>> y[k]
>> > {'source_port_range': None, 'destination_port_range': {'max': 22, 'min':
>> > 22}}
>> >
>> > So x uses strings for min/max while y uses integers, and those do not
>> > compare equal in Python:
>> >
>> > >>> 22 == "22"
>> > False
>> >
>> > Once you fix this
>> >
>> > >>> x[k]["destination_port_range"]["max"] = 22
>> > >>> x[k]["destination_port_range"]["min"] = 22
>> >
>> > you get the expected result:
>> >
>> > >>> x == y
>> > True
>> >
>> >
>> > _______________________________________________
>> > Tutor maillist  -  Tutor at python.org
>> > To unsubscribe or change subscription options:
>> > https://mail.python.org/mailman/listinfo/tutor
>> >
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
>
>

From __peter__ at web.de  Wed Jul  5 16:01:57 2017
From: __peter__ at web.de (Peter Otten)
Date: Wed, 05 Jul 2017 22:01:57 +0200
Subject: [Tutor] dictionaries are same but returning false
References: <CAN1d+183Ai+T-cqg2j9E6j+mPDQ-oYFPXjChWaqW4Si0n57iyQ@mail.gmail.com>
 <ojij65$gdt$1@blaine.gmane.org>
 <CAN1d+1--0K8jRe4qX76yPWhiD_tWW7w-bo53RL0p2=MSJV3xfQ@mail.gmail.com>
 <CAMih+LHCVVRQfqxd4ycU6FOO7hbNF4z-qFV-nKF5xukmdOhNbw@mail.gmail.com>
Message-ID: <ojjgjh$eao$1@blaine.gmane.org>

Ashfaq wrote:

> Hi Peter,
> The way you find the issue is really cool! Very cool! :)

Thanks ;)

Here's a bonus solution:

>>> import unittest
>>> class T(unittest.TestCase):
...     def test_xy(self):
...         self.maxDiff = None
...         self.assertEqual(x, y)
... 
>>> unittest.main()
F
======================================================================
FAIL: test_xy (__main__.T)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<stdin>", line 4, in test_xy
AssertionError: {'att[483 chars]in': '22', 'max': '22'}}, '_is_stateless': 
Fal[23 chars]/24'} != {'att[483 chars]in': 22, 'max': 22}}, '_is_stateless': 
False, [19 chars]/24'}
  {'_icmp_options': None,
   '_is_stateless': False,
   '_protocol': '6',
   '_source': '0.0.4.0/24',
-  '_tcp_options': {'destination_port_range': {'max': '22', 'min': '22'},
?                                                     -  -         -  -

+  '_tcp_options': {'destination_port_range': {'max': 22, 'min': 22},
                    'source_port_range': None},
   '_udp_options': None,
   'attribute_map': {'icmp_options': 'icmpOptions',
                     'is_stateless': 'isStateless',
                     'protocol': 'protocol',
                     'source': 'source',
                     'tcp_options': 'tcpOptions',
                     'udp_options': 'udpOptions'},
   'swagger_types': {'icmp_options': 'IcmpOptions',
                     'is_stateless': 'bool',
                     'protocol': 'str',
                     'source': 'str',
                     'tcp_options': 'TcpOptions',
                     'udp_options': 'UdpOptions'}}

----------------------------------------------------------------------
Ran 1 test in 0.008s

FAILED (failures=1)
$ 



From david at graniteweb.com  Wed Jul  5 18:38:35 2017
From: david at graniteweb.com (David Rock)
Date: Wed, 5 Jul 2017 17:38:35 -0500
Subject: [Tutor] Why use main() ?
In-Reply-To: <ojjf3l$tqj$1@blaine.gmane.org>
References: <20170705153710.GA12705@apple.graniteweb.com>
 <ojjf3l$tqj$1@blaine.gmane.org>
Message-ID: <20170705223835.GB12705@apple.graniteweb.com>

* Alan Gauld via Tutor <tutor at python.org> [2017-07-05 20:36]:
> On 05/07/17 16:37, David Rock wrote:
> 
> > This is a question about the benefits of using a main() function vs not.
> 
> 
> Others have answered for the pros, but I confess that I don't
> always use a main(), but only if all I'm doing is, say,
> instantiating a class and running a method. For anything
> more complex I'd write a main() (or test() or demo() ) to
> go inside the
>    if name==main
> clause.

Thank you everyone for the input.

-- 
David Rock
david at graniteweb.com

From mats at wichmann.us  Wed Jul  5 18:47:39 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Wed, 5 Jul 2017 16:47:39 -0600
Subject: [Tutor] Why use main() ?
In-Reply-To: <CAKJDb-MtuBuA+0VmNqfZpeW1wK+0iB3uUfj2kMFT+PjvKR1qBw@mail.gmail.com>
References: <20170705153710.GA12705@apple.graniteweb.com>
 <CAKJDb-MtuBuA+0VmNqfZpeW1wK+0iB3uUfj2kMFT+PjvKR1qBw@mail.gmail.com>
Message-ID: <39eb4599-7482-1689-4014-88e51531cd3c@wichmann.us>

On 07/05/2017 09:45 AM, Zachary Ware wrote:
> On Wed, Jul 5, 2017 at 10:37 AM, David Rock <david.rock at gmail.com> wrote:

>> I personally find using main() cumbersome, but many examples I come
>> across use main().  Is there some fundamental benefit to using main()
>> that I'm missing?
> 
> In no particular order: testing, encapsulation, and reusability.  With
> a "main()" function (which, recall, can be named whatever you like; it
> doesn't have to be "main") you can directly call the function in your
> tests to make sure it acts the way you want.  The encapsulation of the
> "main" code in a "main()" function also reduces your global state (and
> makes global state a bit more difficult to use), which is usually a
> good thing.  And finally, it makes it possible to use the "main()"
> function in some other piece of code that imports it.
> 

As a vaguely contradictory position to a part of this (which I in the
main agree with): if your objective is to make a module, and also have
some code (perhaps including test code) which is run in the non-module
(aka not-imported) case, then stuffing that code in a function main()
means you've exposed that not-really-module-code as part of the module,
and might then want to take steps to hide it from clients so it doesn't
end up looking like part of the module API.


From david at graniteweb.com  Wed Jul  5 18:54:05 2017
From: david at graniteweb.com (David Rock)
Date: Wed, 5 Jul 2017 17:54:05 -0500
Subject: [Tutor] Why use main() ?
In-Reply-To: <39eb4599-7482-1689-4014-88e51531cd3c@wichmann.us>
References: <20170705153710.GA12705@apple.graniteweb.com>
 <CAKJDb-MtuBuA+0VmNqfZpeW1wK+0iB3uUfj2kMFT+PjvKR1qBw@mail.gmail.com>
 <39eb4599-7482-1689-4014-88e51531cd3c@wichmann.us>
Message-ID: <20170705225405.GC12705@apple.graniteweb.com>

* Mats Wichmann <mats at wichmann.us> [2017-07-05 16:47]:
> > 
> 
> As a vaguely contradictory position to a part of this (which I in the
> main agree with): if your objective is to make a module, and also have
> some code (perhaps including test code) which is run in the non-module
> (aka not-imported) case, then stuffing that code in a function main()
> means you've exposed that not-really-module-code as part of the module,
> and might then want to take steps to hide it from clients so it doesn't
> end up looking like part of the module API.

In most cases, my scripts tend to be pretty self-contained and written
for my own purposes, so that would rarely be an issue.  

How would you hide main() if you _were_ concerned about it?

-- 
David Rock
david at graniteweb.com

From Mark at information27.com  Wed Jul  5 14:42:45 2017
From: Mark at information27.com (Mark at information27.com)
Date: Wed, 5 Jul 2017 11:42:45 -0700
Subject: [Tutor] Probably a silly question: how to install lxml?
Message-ID: <0c74df74-78ce-b9ee-8ec1-ffab35a4e138@information27.com>

First, I'm not a programmer, but I know a bit about programming techniques.
Had a Python pgm working about a year ago, and now trying to get it 
running on a new machine.
On Windows7, SP1, 64-bit, I installed Python 3.6.1.
Tried to run the Python pgm, and it said ModuleNotFoundError: No module 
named 'lxml'
Ran "python -m pip install --upgrade lxml"
It looked like it worked, even with several red error messages at the end.
Tried to run the Python pgm again, and it said the same error: 
ModuleNotFoundError: No module named 'lxml'

Can ya' tell me?...  How to get past this step?

Thanks very much.

-- 
----

Mark


From quazi.ashfaq at gmail.com  Wed Jul  5 21:30:48 2017
From: quazi.ashfaq at gmail.com (Ashfaq)
Date: Thu, 06 Jul 2017 01:30:48 +0000
Subject: [Tutor] Probably a silly question: how to install lxml?
In-Reply-To: <0c74df74-78ce-b9ee-8ec1-ffab35a4e138@information27.com>
References: <0c74df74-78ce-b9ee-8ec1-ffab35a4e138@information27.com>
Message-ID: <CAMih+LHFk7serczfUtDv=odQhtrvZecfgo_yPJdz4g2tLT5vUA@mail.gmail.com>

Hi Mark
ModuleNotFoundError means the package is not installed.
Can you paste those red error message here? This can shed some light.

Sincerely
Ashfaq

On Thu, Jul 6, 2017 at 5:10 AM Mark at information27.com <
Mark at information27.com> wrote:

> First, I'm not a programmer, but I know a bit about programming techniques.
> Had a Python pgm working about a year ago, and now trying to get it
> running on a new machine.
> On Windows7, SP1, 64-bit, I installed Python 3.6.1.
> Tried to run the Python pgm, and it said ModuleNotFoundError: No module
> named 'lxml'
> Ran "python -m pip install --upgrade lxml"
> It looked like it worked, even with several red error messages at the end.
> Tried to run the Python pgm again, and it said the same error:
> ModuleNotFoundError: No module named 'lxml'
>
> Can ya' tell me?...  How to get past this step?
>
> Thanks very much.
>
> --
> ----
>
> Mark
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From danny.yoo at gmail.com  Wed Jul  5 21:50:38 2017
From: danny.yoo at gmail.com (Danny Yoo)
Date: Wed, 5 Jul 2017 18:50:38 -0700
Subject: [Tutor] Why use main() ?
In-Reply-To: <20170705225405.GC12705@apple.graniteweb.com>
References: <20170705153710.GA12705@apple.graniteweb.com>
 <CAKJDb-MtuBuA+0VmNqfZpeW1wK+0iB3uUfj2kMFT+PjvKR1qBw@mail.gmail.com>
 <39eb4599-7482-1689-4014-88e51531cd3c@wichmann.us>
 <20170705225405.GC12705@apple.graniteweb.com>
Message-ID: <CAGZAPF7Ca_ErjmFxj6gYJTop=biHqy_+_0ZjtFFzp1w0UhMNLg@mail.gmail.com>

In most cases, my scripts tend to be pretty self-contained and written
for my own purposes, so that would rarely be an issue.

How would you hide main() if you _were_ concerned about it?



The "main" option would be to move the body of main() to a separate file,
which imports the original file as a module.


There's alternative trickery that we can do in Python involving "delete",
but I'd steer clear of that, as that approach is a bit overkill.

From steve at pearwood.info  Wed Jul  5 21:51:12 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 6 Jul 2017 11:51:12 +1000
Subject: [Tutor] Probably a silly question: how to install lxml?
In-Reply-To: <0c74df74-78ce-b9ee-8ec1-ffab35a4e138@information27.com>
References: <0c74df74-78ce-b9ee-8ec1-ffab35a4e138@information27.com>
Message-ID: <20170706015112.GJ3149@ando.pearwood.info>

On Wed, Jul 05, 2017 at 11:42:45AM -0700, Mark at information27.com wrote:

> On Windows7, SP1, 64-bit, I installed Python 3.6.1.

Are you positive this is the only Python installed?

What does 

python -c "import sys; print(sys.version)"

do?


> Tried to run the Python pgm, and it said ModuleNotFoundError: No module 
> named 'lxml'
> Ran "python -m pip install --upgrade lxml"
> It looked like it worked, even with several red error messages at the end.

*scratches head*

I dunno, to me it sounds like it *didn't* work, not if it is printing 
red error messages at the end. What do they say?

My guess is that you need Administrator privileges to install the 
packages. Or perhaps to tell pip to install as site packages in your 
home directory, but I'm not sure how to do that.

> Tried to run the Python pgm again, and it said the same error: 
> ModuleNotFoundError: No module named 'lxml'
> 
> Can ya' tell me?...  How to get past this step?
> 
> Thanks very much.



-- 
Steve

From eryksun at gmail.com  Wed Jul  5 22:37:33 2017
From: eryksun at gmail.com (eryk sun)
Date: Thu, 6 Jul 2017 02:37:33 +0000
Subject: [Tutor] Probably a silly question: how to install lxml?
In-Reply-To: <20170706015112.GJ3149@ando.pearwood.info>
References: <0c74df74-78ce-b9ee-8ec1-ffab35a4e138@information27.com>
 <20170706015112.GJ3149@ando.pearwood.info>
Message-ID: <CACL+1at8Q4hNKx9w19g9tU4d0NT-iv-nXa2Qa_pSgTPH=sZ7Jg@mail.gmail.com>

On Thu, Jul 6, 2017 at 1:51 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>
> I dunno, to me it sounds like it *didn't* work, not if it is printing
> red error messages at the end. What do they say?

lxml should install from a wheel (e.g.
lxml-3.8.0-cp36-cp36m-win_amd64.whl). There's nothing to build, so the
most likely reason for failing would be getting denied access to
modify site-packages.

> My guess is that you need Administrator privileges to install the
> packages. Or perhaps to tell pip to install as site packages in your
> home directory, but I'm not sure how to do that.

If you've installed Python for all users in the default location in
%ProgramFiles% or %ProgramFiles(x86), then you will need to use an
elevated command prompt to install to the system site-packages. A
standard user or UAC restricted administrator does not have the right
to modify this directory.

Alternatively you can install a package just for the current user with
pip's "--user" option.

You can also install packages in a virtual environment created with
the venv module, which is convenient for development.

From Mark at information27.com  Wed Jul  5 23:52:07 2017
From: Mark at information27.com (Mark at information27.com)
Date: Wed, 5 Jul 2017 20:52:07 -0700
Subject: [Tutor] Probably a silly question: how to install lxml?
In-Reply-To: <CACL+1at8Q4hNKx9w19g9tU4d0NT-iv-nXa2Qa_pSgTPH=sZ7Jg@mail.gmail.com>
References: <CACL+1at8Q4hNKx9w19g9tU4d0NT-iv-nXa2Qa_pSgTPH=sZ7Jg@mail.gmail.com>
Message-ID: <bcf5c1e6-339c-ca27-0cc8-15ff46dd71fd@information27.com>

   Wow.  Thanks for those replies.

   Those red error messages were several Exceptions and one PermissionError.

   I THINK, but I'm not Positive that 3.6.1 is the only Python installed.

   I'm the only person who uses this PC.  ControlPanel > UserAccounts says I
   am the Administrator.

   I searched for some Folder called lxml...  cannot find it.

   Steven,...  I used that --user option, and it was re-installed With No
   Errors !   Very Cool !
   And then the pgm got past that point. Very Nice !  THANKS.

   So,...  WHY was that necessary?

   Thanks.

   -- ---- Mark

From guest0x013 at gmail.com  Thu Jul  6 04:57:00 2017
From: guest0x013 at gmail.com (Freedom Peacemaker)
Date: Thu, 6 Jul 2017 10:57:00 +0200
Subject: [Tutor] Which DB use with standalone desktop app
Message-ID: <CAL+yi2bkJoriH7DQVCO4mv2aFEgWzQS53e7ay7TmiLMqxN54qQ@mail.gmail.com>

Hi Tutors,
I am working on standalone desktop app with tkinter GUI (Python3), and i
dont know which database should i use. I've tried to find solution on my
own but google cant help me. There are some with SQL in name (eg. sqlite3,
MySql), but there are some other NoSql like MongoDB or Redis. Please help
me which one i should use for my app not only from ones i've mentioned. My
database will have max 100 records described by 6-8 columns. Most of them
will be 25 characters max but one will have up to 60.

Thanks for help,
PP

<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
Wolny
od wirus?w. www.avast.com
<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
<#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>

From zachary.ware+pytut at gmail.com  Thu Jul  6 13:25:05 2017
From: zachary.ware+pytut at gmail.com (Zachary Ware)
Date: Thu, 6 Jul 2017 12:25:05 -0500
Subject: [Tutor] Which DB use with standalone desktop app
In-Reply-To: <CAL+yi2bkJoriH7DQVCO4mv2aFEgWzQS53e7ay7TmiLMqxN54qQ@mail.gmail.com>
References: <CAL+yi2bkJoriH7DQVCO4mv2aFEgWzQS53e7ay7TmiLMqxN54qQ@mail.gmail.com>
Message-ID: <CAKJDb-PdeceQ-RjMFSBjpFmJAcGuagRY+wnPAhQ0qQU8X6a2jw@mail.gmail.com>

On Thu, Jul 6, 2017 at 3:57 AM, Freedom Peacemaker <guest0x013 at gmail.com> wrote:
> Hi Tutors,
> I am working on standalone desktop app with tkinter GUI (Python3), and i
> dont know which database should i use. I've tried to find solution on my
> own but google cant help me. There are some with SQL in name (eg. sqlite3,
> MySql), but there are some other NoSql like MongoDB or Redis. Please help
> me which one i should use for my app not only from ones i've mentioned. My
> database will have max 100 records described by 6-8 columns. Most of them
> will be 25 characters max but one will have up to 60.

That sounds small enough that you probably don't even need a database,
but could just store a JSON file with your data, for example.
Otherwise, I'd suggest sqlite3; it's very lightweight and intended for
single-user applications like this.  You definitely don't need
anything as large as MySQL or MongoDB :)

Hope this helps,
-- 
Zach

From mats at wichmann.us  Thu Jul  6 15:09:32 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Thu, 6 Jul 2017 13:09:32 -0600
Subject: [Tutor] Which DB use with standalone desktop app
In-Reply-To: <CAKJDb-PdeceQ-RjMFSBjpFmJAcGuagRY+wnPAhQ0qQU8X6a2jw@mail.gmail.com>
References: <CAL+yi2bkJoriH7DQVCO4mv2aFEgWzQS53e7ay7TmiLMqxN54qQ@mail.gmail.com>
 <CAKJDb-PdeceQ-RjMFSBjpFmJAcGuagRY+wnPAhQ0qQU8X6a2jw@mail.gmail.com>
Message-ID: <3df40eed-4663-8093-a4c2-68ba778cc8cf@wichmann.us>

On 07/06/2017 11:25 AM, Zachary Ware wrote:
> On Thu, Jul 6, 2017 at 3:57 AM, Freedom Peacemaker <guest0x013 at gmail.com> wrote:
>> Hi Tutors,
>> I am working on standalone desktop app with tkinter GUI (Python3), and i
>> dont know which database should i use. I've tried to find solution on my
>> own but google cant help me. There are some with SQL in name (eg. sqlite3,
>> MySql), but there are some other NoSql like MongoDB or Redis. Please help
>> me which one i should use for my app not only from ones i've mentioned. My
>> database will have max 100 records described by 6-8 columns. Most of them
>> will be 25 characters max but one will have up to 60.
> 
> That sounds small enough that you probably don't even need a database,
> but could just store a JSON file with your data, for example.
> Otherwise, I'd suggest sqlite3; it's very lightweight and intended for
> single-user applications like this.  You definitely don't need
> anything as large as MySQL or MongoDB :)
> 
> Hope this helps,
> 

You don't really say what the use model is for this "database".
Lightweight manipulation of a single table (which is what your
description hints at) can be done just fine in Python (without resorting
to an external db engine) and be given persistence by using a simple
file - json or yaml format, or even Python's included pickle format, as
Zachary says.



From zheng.228 at hotmail.com  Thu Jul  6 13:32:59 2017
From: zheng.228 at hotmail.com (zhenghao li)
Date: Thu, 6 Jul 2017 17:32:59 +0000
Subject: [Tutor] Which DB use with standalone desktop app
In-Reply-To: <CAL+yi2bkJoriH7DQVCO4mv2aFEgWzQS53e7ay7TmiLMqxN54qQ@mail.gmail.com>
References: <CAL+yi2bkJoriH7DQVCO4mv2aFEgWzQS53e7ay7TmiLMqxN54qQ@mail.gmail.com>
Message-ID: <BN6PR10MB12814C4C0A29DCFCAB1C7C52A7D50@BN6PR10MB1281.namprd10.prod.outlook.com>

100 records are not a lot, so sqlite is sufficient. Its database engine 
is included in python and it doesn't need to be run as a stand-alone 
server so that saves you a lot of time for setting things up. If you 
have a lots of tables and data say like more than 10k then you might 
consider switching to a real database server.


On 07/06/2017 04:57 AM, Freedom Peacemaker wrote:
> Hi Tutors,
> I am working on standalone desktop app with tkinter GUI (Python3), and i
> dont know which database should i use. I've tried to find solution on my
> own but google cant help me. There are some with SQL in name (eg. sqlite3,
> MySql), but there are some other NoSql like MongoDB or Redis. Please help
> me which one i should use for my app not only from ones i've mentioned. My
> database will have max 100 records described by 6-8 columns. Most of them
> will be 25 characters max but one will have up to 60.
>
> Thanks for help,
> PP
>
> <https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
> Wolny
> od wirus?w. www.avast.com
> <https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
> <#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


From alan.gauld at alan-g.me.uk  Thu Jul  6 17:02:24 2017
From: alan.gauld at alan-g.me.uk (Alan Gauld)
Date: Thu, 6 Jul 2017 22:02:24 +0100
Subject: [Tutor] Which DB use with standalone desktop app
In-Reply-To: <fea97bbf-94f6-9d1e-ee01-92d61ff0c5cd@yahoo.co.uk>
References: <CAL+yi2bkJoriH7DQVCO4mv2aFEgWzQS53e7ay7TmiLMqxN54qQ@mail.gmail.com>
 <fea97bbf-94f6-9d1e-ee01-92d61ff0c5cd@yahoo.co.uk>
Message-ID: <93206c2b-b122-4017-6748-a1fed58c3859@alan-g.me.uk>

Oops, I forgot the list! Blush...


On 06/07/17 18:30, Alan Gauld wrote:
> On 06/07/17 09:57, Freedom Peacemaker wrote:
>
>> own but google cant help me. There are some with SQL in name (eg. sqlite3,
>> MySql), but there are some other NoSql like MongoDB or Redis. 
> NoSQL databases are best for unstructured data(or flexibly structured)
> and for large volumes.
> For ~100 records where you know the columns you want then a SQL
> database is fine and SQLite3 comes with Python. The big advantaghe
> of SQLite is that everything is stored in a single file which
> can be easily distributed, no server to install etc. The downside is
> that there is no security login, just basic file permissions. For a
> desktop app that's usually not an issue.
>
> To use:
>
> #################
> import sqlite3
>
> db = sqlite3.connect("your/database/filename")
> cursor = db.cursor()
> cursor.execute(<your SQL query here>,
>                (<your variavble parameters here>))
>
> results = cursor.fetchall()
> ##################
>
> If you know SQL you should be able to figure it out from there...
> (And the SQLite web site has a good reference for their SQL syntax.)
>
> If not you can try the database topic in my tutorial(see .sig)
> which teaches basic SQL and how to use it from Python... Use
> the python2 version of the tutorial, but its easy to convert
> that topic to python3...
>
>

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


From alan.gauld at yahoo.co.uk  Thu Jul  6 17:18:21 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 6 Jul 2017 22:18:21 +0100
Subject: [Tutor] Which DB use with standalone desktop app
In-Reply-To: <BN6PR10MB12814C4C0A29DCFCAB1C7C52A7D50@BN6PR10MB1281.namprd10.prod.outlook.com>
References: <CAL+yi2bkJoriH7DQVCO4mv2aFEgWzQS53e7ay7TmiLMqxN54qQ@mail.gmail.com>
 <BN6PR10MB12814C4C0A29DCFCAB1C7C52A7D50@BN6PR10MB1281.namprd10.prod.outlook.com>
Message-ID: <ojm9eo$iad$1@blaine.gmane.org>

On 06/07/17 18:32, zhenghao li wrote:
> 100 records are not a lot, so sqlite is sufficient. Its database engine 
> is included in python and it doesn't need to be run as a stand-alone 
> server so that saves you a lot of time for setting things up. If you 
> have a lots of tables and data say like more than 10k then you might 
> consider switching to a real database server.

Provided it's single-user then SQLite can easily scale up to a million+
records and still perform OK. I have one database with about 250k
records over 8 tables and the file is only 10MB in size and
query performance is effectively instant.

Where a server becomes important is when you have multiple users
and you care about security, locking, etc. or want to use
advanced features like stored procedures etc.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From marcus.luetolf at bluewin.ch  Sat Jul  8 04:05:56 2017
From: marcus.luetolf at bluewin.ch (=?UTF-8?Q?marcus_l=C3=BCtolf?=)
Date: Sat, 8 Jul 2017 10:05:56 +0200
Subject: [Tutor] principal question
Message-ID: <000201d2f7c1$07198ef0$154cacd0$@bluewin.ch>

dear experts,
before I start digging into writing code I'd like your opinion:

Is it possible to have python compare 2   subsequent  *.jpg  images in subtracting
the pixel values of the second from the first image.
If the images and are identical the result should be 0 and the first image could be deletet.
If there is a difference (treshold pixel value  and pixel numer to be determined) another action should be executed.

Many thanks, Marcus.



---
Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft.
https://www.avast.com/antivirus


From alan.gauld at yahoo.co.uk  Sat Jul  8 07:24:26 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 8 Jul 2017 12:24:26 +0100
Subject: [Tutor] principal question
In-Reply-To: <000201d2f7c1$07198ef0$154cacd0$@bluewin.ch>
References: <000201d2f7c1$07198ef0$154cacd0$@bluewin.ch>
Message-ID: <ojqfd4$5v5$1@blaine.gmane.org>

On 08/07/17 09:05, marcus l?tolf wrote:

> Is it possible to have python compare 2   subsequent  *.jpg  images
> in subtracting the pixel values of the second from the first image.

Yes

> If the images and are identical the result should be 0 and the first
> image could be deletet.

That's possible too although thee are easier ways
to compare files than manually comparing them pixel by pixel.
There are libraries that exist that you can use that do
much of the work for you. One of the good things about python
is that it has a huge catalog of existing code libraries
that can do most things you might need.

> If there is a difference (treshold pixel value  and pixel number to
> be determined)another action should be executed. 

That's possible too, if you really need to.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From __peter__ at web.de  Sat Jul  8 07:28:44 2017
From: __peter__ at web.de (Peter Otten)
Date: Sat, 08 Jul 2017 13:28:44 +0200
Subject: [Tutor] Comparing images, was Re: principal question
References: <000201d2f7c1$07198ef0$154cacd0$@bluewin.ch>
Message-ID: <ojqfl8$ks1$1@blaine.gmane.org>

marcus l?tolf wrote:

> dear experts,
> before I start digging into writing code I'd like your opinion:
> 
> Is it possible 

Yes. Now what?

> to have python compare 2   subsequent  *.jpg  images in
> subtracting the pixel values of the second from the first image.
> If the images and are identical the result should be 0 and the first image
> could be deletet.
> If there is a difference (treshold pixel value  and pixel numer to be
> determined) another action should be executed.

I assume you know how to list files in a directory and to remove a file 
given its path?

To process the images you need pillow to load an image and numpy to access 
the pixels in a convenient and efficient format.

Google found 

https://pythonprogramming.net/python-pixel-arrays/

which illustrates the first steps.


From evuraan at gmail.com  Sat Jul  8 19:03:24 2017
From: evuraan at gmail.com (Evuraan)
Date: Sat, 8 Jul 2017 16:03:24 -0700
Subject: [Tutor] @property vs @classmethod
Message-ID: <CA+jJSoQPSLaJ4i=Bn5bhLtYj4G8my6gNtok9HsQmDz0TWNX3LQ@mail.gmail.com>

Greetings!

I was hoping to learn when to use classmethod and when to use property.
They both seem similar (to me at least..), what's the pythonic way to
choose between them?

$ cat ./try.py
#!/usr/bin/python3

class _someclass:
    _tag = "sometag"

    def __init__(self,_text):
        self._text = _text
        print("__init__ says {}".format(self._text) )
        self.class_method_thingy()
        self.class_property_thingy

    @property
    def class_property_thingy(self):
        """class property thing"""
        _txt_cp = "Hello from class property thingy"
        self.a = _txt_cp

    @classmethod
    def class_method_thingy(self):
        """class method thingy"""
        _txt_cm = "Hello from class method thingy"
        self.b = _txt_cm

class _subclass(_someclass):
    pass


if __name__ == "__main__":
    blah = _someclass("input")
    print(blah.a)
    print(blah.b)

$ ./try.py
__init__ says input
Hello from class property thingy
Hello from class method thingy


Thanks!

From alan.gauld at yahoo.co.uk  Sat Jul  8 20:20:12 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 9 Jul 2017 01:20:12 +0100
Subject: [Tutor] @property vs @classmethod
In-Reply-To: <CA+jJSoQPSLaJ4i=Bn5bhLtYj4G8my6gNtok9HsQmDz0TWNX3LQ@mail.gmail.com>
References: <CA+jJSoQPSLaJ4i=Bn5bhLtYj4G8my6gNtok9HsQmDz0TWNX3LQ@mail.gmail.com>
Message-ID: <ojrsrm$955$1@blaine.gmane.org>

On 09/07/17 00:03, Evuraan wrote:

> I was hoping to learn when to use classmethod and when to use property.
> They both seem similar (to me at least..), what's the pythonic way to
> choose between them?

In fact they do completely different things.

A property is a field of an object that you access via a getter or
setter method but use a syntax that looks like direct access to the
field. This allows you to implement data validity rules when setting the
data, or to restrict data access in the getter for example.

You can even create read-only or write-only properties by omitting
one or other of the get/set methods. The pythonic way is to allow
direct access to the data if you have no need of special processing.
If you do need to limit access in some way create a property.

A classmethod by contrast is a method that applies to the class as
a whole rather than the individual instances. You access a normal
method via an instance of the class:

foo = Foo()  # create instance
x = foo.bar()   # call instance method bar()

A class method is accessed via the class, no instance is needed:

y = Foo.baz()  # call class method baz()

It's possible, and even quite common, to have a classmethod being
used when no instances exist at all. This is especially so in
languages like Java, whereas in Python those cases are more
often dealt with by creating a vanilla function in a module.

Typical use cases for class methods include factory methods
to create instances in special cases - for example loading
a specific instance from a database given some arbitrary
criteria. Or it could be that a class keeps a list of all
existing instances and a classmethod reports how many
instances exist. There are many other such cases.

[Note: What is confusing is the difference between staticmethod and
classmethod. Those two are similar but subtly different and I
recommend ignoring staticmethod and just use classmethod.]

-- 
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  Sat Jul  8 20:56:19 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 9 Jul 2017 10:56:19 +1000
Subject: [Tutor] @property vs @classmethod
In-Reply-To: <CA+jJSoQPSLaJ4i=Bn5bhLtYj4G8my6gNtok9HsQmDz0TWNX3LQ@mail.gmail.com>
References: <CA+jJSoQPSLaJ4i=Bn5bhLtYj4G8my6gNtok9HsQmDz0TWNX3LQ@mail.gmail.com>
Message-ID: <20170709005617.GN3149@ando.pearwood.info>

On Sat, Jul 08, 2017 at 04:03:24PM -0700, Evuraan wrote:
> Greetings!
> 
> I was hoping to learn when to use classmethod and when to use property.
> They both seem similar (to me at least..), what's the pythonic way to
> choose between them?

The pythonic way is not to use them at all.

For experts only: you'll know when you need them.

They really aren't even a little bit similar, if you thought they did 
that just means that you haven't understood what they do.

property is for making computed atttributes. The Pythonic way is to just 
use an ordinary attribute:

class K(object):
    def __init__(self, x):
        self.x = x

instance = K(99)
print(instance.x)  # prints 99

which people can then assign to, read or even delete. But occasionally 
you need to run some code whenever instance.x is accessed, and that's 
when you should use property.

If you're familiar with Java, then property can be used to make Java 
getters and setters look like ordinary attribute access.

classmethod is for making methods which don't receive the instance as 
their first argument, but the class instead. In Java they would be 
called static methods (Python has a static method too, but that's a 
completely different thing.) Here is an example demonstrating the 
difference between an ordinary instance method and a class method:

class K(object):
    attr = "Attribute stored on the class object"
    def __init__(self, x):
        print("Before:")
        print(self.attr)
        self.attr = x
        print("After:")
        print(self.attr)
    def method1(self):
        print("self is:", self)
        print("Attr:", self.attr)
    @classmethod
    def method2(cls):
        print("cls is:", cls)
        print("Attr:", cls.attr)


and here is a demo of it in use:

py> instance = K("attribute stored on the instance")
Before:
Attribute stored on the class object
After:
attribute stored on the instance
py>
py> instance.method1()
self is: <__main__.K object at 0xb7a1838c>
Attr: attribute stored on the instance
py> instance.method2()
cls is: <class '__main__.K'>
Attr: Attribute stored on the class object


If you're wondering when classmethod is useful, the answer is, it very 
rarely is. One possible use is if your class has an alternate 
constructor. An example of that is dict.fromkeys().



-- 
Steve

From mats at wichmann.us  Sat Jul  8 21:56:10 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Sat, 8 Jul 2017 19:56:10 -0600
Subject: [Tutor] @property vs @classmethod
In-Reply-To: <20170709005617.GN3149@ando.pearwood.info>
References: <CA+jJSoQPSLaJ4i=Bn5bhLtYj4G8my6gNtok9HsQmDz0TWNX3LQ@mail.gmail.com>
 <20170709005617.GN3149@ando.pearwood.info>
Message-ID: <b5025c8b-1750-6688-1e80-8ab80869d692@wichmann.us>

On 07/08/2017 06:56 PM, Steven D'Aprano wrote:

> The pythonic way is not to use them at all.
> 
> For experts only: you'll know when you need them.
> 
> They really aren't even a little bit similar, if you thought they did 
> that just means that you haven't understood what they do.
> 
> property is for making computed atttributes. 
...
> which people can then assign to, read or even delete. But occasionally 
> you need to run some code whenever instance.x is accessed, and that's 
> when you should use property.

When I use them (rarely), it's seemed to make sense when there's an
attribute which naturally has a relationship to another attribute and it
seems better to store one and compute one on demand rather than store
both as instance attributes and have to update both when either changes.
 I'll admit that this has happened most often when writing a blog post
trying to explain properties :)

>From OO people, though, we get the sputtering But... But... what about
encapsulation, data hiding, etc?


From cs at zip.com.au  Sat Jul  8 20:19:36 2017
From: cs at zip.com.au (Cameron Simpson)
Date: Sun, 9 Jul 2017 10:19:36 +1000
Subject: [Tutor] @property vs @classmethod
In-Reply-To: <CA+jJSoQPSLaJ4i=Bn5bhLtYj4G8my6gNtok9HsQmDz0TWNX3LQ@mail.gmail.com>
References: <CA+jJSoQPSLaJ4i=Bn5bhLtYj4G8my6gNtok9HsQmDz0TWNX3LQ@mail.gmail.com>
Message-ID: <20170709001936.GA14186@cskk.homeip.net>

On 08Jul2017 16:03, Evuraan <evuraan at gmail.com> wrote:
>I was hoping to learn when to use classmethod and when to use property.
>They both seem similar (to me at least..), what's the pythonic way to
>choose between them?

The core distinction is the context that the function needs. Does it depend on 
the particular instance? Or just on the instance's class?

A property is handed the instance as its first argument ("self"), like normal 
methods. It just looks like an attribute from the outside.

  class C:
    @property
    def size(self):
      return len(self.something)

  O = C()
  print("size of O is", O.size)     # no brackets

I tend to use these for "basic" attributes of an object for which a traditional 
"get_size()" method is annoying verbiage and which are cheap to compute, as if 
they were an ordinary attribute.

A classmethod is handed the class, not the instance. (So your "self" in the 
classmethod you wrote is misleading; we normally spell that "klass" or 
something like that). It is for things that do not depend on the instance, but 
do depend on the class (for example they access class attributes).

  class Base:
    TYPE = 0
    ...

  class C(Base):
    TYPE = 1
    @classmethod
    def get_type(klass):
      return klass.TYPE

And a staticmethod is not handed any default argument. It is for methods that 
are like ordinary function, with no class or instance context to their 
behaviour. A typical use might be a factory function, which is like an 
alternate constructor.

  class C:
    def __init__(self, number):
      self.number = number
    @staticmethod
    def from_word(word):
      if word == "one":
        n = 1
      elif word == "two":
        n = 2
      else:
        raise ValueError("unsupported number name: %r" % (word,))
      return C(n)

  O1 = C(3)
  O2 = C.from_word("two")

Here the staticmethod is put in the class (instead of outside) for that is 
nicely associated with the class for readability etc.

Your test code doesn't really show these differences. Try modifying each method 
to print(repr(self)) as the first thing; you should see that for a normal 
method and a property "self" is the instance, for the classmethod it is the 
class, and that it isn't supplied at all for a staticmethod.

Cheers,
Cameron Simpson <cs at zip.com.au>

From alan.gauld at yahoo.co.uk  Sun Jul  9 03:59:16 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 9 Jul 2017 08:59:16 +0100
Subject: [Tutor] @property vs @classmethod
In-Reply-To: <b5025c8b-1750-6688-1e80-8ab80869d692@wichmann.us>
References: <CA+jJSoQPSLaJ4i=Bn5bhLtYj4G8my6gNtok9HsQmDz0TWNX3LQ@mail.gmail.com>
 <20170709005617.GN3149@ando.pearwood.info>
 <b5025c8b-1750-6688-1e80-8ab80869d692@wichmann.us>
Message-ID: <ojsnoe$bro$1@blaine.gmane.org>

On 09/07/17 02:56, Mats Wichmann wrote:

> From OO people, though, we get the sputtering But... But... what about
> encapsulation, data hiding, etc?

Encapsulation isn't really an issue here since Pythons classes
fully encapsulate their data and methods. They just make them
both public.

Data Hiding is the issue for some OO purists, especially those
who learned OO via C++/Java. But data hiding was never
originally enforced by the language, when Parnas wrote
his seminal paper there were very few languages that
explicitly supported making module data (he wasn't writing
about OO at the time) private. Instead data hiding was
achieved by providing such a powerful and complete set of
API functions that there was no temptation to play with
the supporting data.

Python adheres to that philosophy, although for "simple"
attributes it does allow, and even encourage, direct access.
But in most cases we, as class designers, should be striving
to provide sufficiently powerful methods that nobody needs
to mess with the internal state directly.

-- 
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 Jul  9 07:02:49 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 9 Jul 2017 21:02:49 +1000
Subject: [Tutor] @property vs @classmethod
In-Reply-To: <b5025c8b-1750-6688-1e80-8ab80869d692@wichmann.us>
References: <CA+jJSoQPSLaJ4i=Bn5bhLtYj4G8my6gNtok9HsQmDz0TWNX3LQ@mail.gmail.com>
 <20170709005617.GN3149@ando.pearwood.info>
 <b5025c8b-1750-6688-1e80-8ab80869d692@wichmann.us>
Message-ID: <20170709110248.GO3149@ando.pearwood.info>

On Sat, Jul 08, 2017 at 07:56:10PM -0600, Mats Wichmann wrote:

> From OO people, though, we get the sputtering But... But... what about
> encapsulation, data hiding, etc?

Regular attributes are still encapsulated. There's no difference in 
encapsulation between:

obj.x  # a standard attribute
obj.x  # a property
obj.getx()  # a Java-like getter

Whichever way you choose, x is still attached to the instance.

Data hiding is a good point, for those who care about data hiding. But 
Python has an answer to that too: we can hide data by prefixing the name 
with a single underscore.

obj._x

Or at least, hide it in plain sight. Python is for "consenting adults", 
and private attributes and variables are private by agreement, not 
because the language enforces the rule.

(There are a few places in Python where the language does enforce data 
hiding, mostly to do with functions, and anything which could cause a 
segmentation fault. But regular Python code, not so much. The worst that 
happens is you get a regular Python exception.)

Interesting that you refer to "OO people". There's no widespread 
agreement about what makes an Object Oriented Programming language 
(although Java people tend to think that Java offers the One True OOP 
language *wink*) but I think the most critical requirement is for the 
language to offer "objects" as a native data type, where objects are 
structured entities which combine:

  - behaviour (methods)
  - state (data, value)
  - and identity (unique existence).


The first two make up encapsulation, or at least a form of 
encapsulation. Data hiding itself is not a requirement, and even 
inheritence isn't. (Although it is unusual to have OOP without a form of 
inheritence.)



-- 
Steve

From noflaco at gmail.com  Mon Jul 10 02:43:06 2017
From: noflaco at gmail.com (Carlton Banks)
Date: Mon, 10 Jul 2017 08:43:06 +0200
Subject: [Tutor] call key on_press event multiple times when key is held
 down
In-Reply-To: <6025937C-F701-4C41-87B6-5805B14ED4DC@gmail.com>
References: <29FACF89-C690-40CC-9AE4-7064516A971F@gmail.com>
 <e32c7b7b-52c2-da14-a7aa-39d2052ab0b3@yahoo.co.uk>
 <ojfudk$nf3$1@blaine.gmane.org>
 <6025937C-F701-4C41-87B6-5805B14ED4DC@gmail.com>
Message-ID: <F6BBA1C8-FCE1-42EC-A770-33065001EB70@gmail.com>

So i tried a different solution, introducing two threads one handling the keyboard, 
and the other one is a while true, that keeps running. 

https://pastebin.com/U0WVQMYP <https://pastebin.com/U0WVQMYP>

but for some reason, am I constantly running into IOerror, hence 
no frames is being recorded.  Any suggestion on why?
> Den 4. jul. 2017 kl. 14.45 skrev Carlton Banks <noflaco at gmail.com>:
> 
>> 
>>> Interesting solution, but still find a bit "dirty hackish?
>>> to involve a timer in this..  I guess it just would be neat if 
>>> it just worked as i thought it to be.  But i guess i have to look into curses.
>> 
>> A timer based loop is actually the standard pattern for
>> implementing a loop in an event driven environment (the
>> main alternative is to launch a background thread).
>> It's how most GUIs handle such scenarios.
>> 
>> The problem in a CLI solution is that you have to build your
>> own timer event system (usually based on time.sleep() or
>> similar). Hence the suggestion to use a GUI.
>> 
> 
> Any suggestion on any GUI solutions?
> 
> 
> Regards 
> Carl
> 


From __peter__ at web.de  Mon Jul 10 04:54:13 2017
From: __peter__ at web.de (Peter Otten)
Date: Mon, 10 Jul 2017 10:54:13 +0200
Subject: [Tutor] call key on_press event multiple times when key is held
 down
References: <29FACF89-C690-40CC-9AE4-7064516A971F@gmail.com>
 <e32c7b7b-52c2-da14-a7aa-39d2052ab0b3@yahoo.co.uk>
 <ojfudk$nf3$1@blaine.gmane.org>
 <6025937C-F701-4C41-87B6-5805B14ED4DC@gmail.com>
 <F6BBA1C8-FCE1-42EC-A770-33065001EB70@gmail.com>
Message-ID: <ojvfbg$g0q$1@blaine.gmane.org>

Carlton Banks wrote:

> So i tried a different solution, introducing two threads one handling the
> keyboard, and the other one is a while true, that keeps running.
> 
> https://pastebin.com/U0WVQMYP <https://pastebin.com/U0WVQMYP>
> 
> but for some reason, am I constantly running into IOerror, hence
> no frames is being recorded.  Any suggestion on why?

Please remember to always provide the traceback.

> while True:
>     time.sleep(0.1)
>     if listener.key_pressed == True and started == False:
>         started = True
>         listener.stream.start_stream()
>         print "start Stream"
> 
>     elif listener.key_pressed == False and started == True:
>         print "Something coocked"
>         listener.stream.stop_stream()

Did you get a non-empty output.wav?

If yes, my guess is that you can record something the first time you press 
the key, and when you release it and close the audio input with

>         listener.stream.close()

you see the IOError on the second attempt to record something.

>         p.terminate()


As you are only prepared to record once and another record would overwrite 
the file anyway (at least that's what I suppose
 
>         wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')

to do) perhaps you can omit the while-True loop altogether. Or you omit the 
stream.close() call until after that loop (though there seems to be no way 
to exit it cleanly at the moment).

Note that these are just ideas, I'm not familiar with pyaudio, or pynput, or 
wave.

>         wf.setnchannels(CHANNELS)
>         wf.setsampwidth(p.get_sample_size(FORMAT))
>         wf.setframerate(RATE)
>         wf.writeframes(b''.join(frames))
>         wf.close()
> 
>         started = False
> 





From alan.gauld at yahoo.co.uk  Mon Jul 10 05:10:15 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 10 Jul 2017 10:10:15 +0100
Subject: [Tutor] Fwd: Re: call key on_press event multiple times when
 key is held down
In-Reply-To: <6025937C-F701-4C41-87B6-5805B14ED4DC@gmail.com>
References: <29FACF89-C690-40CC-9AE4-7064516A971F@gmail.com>
 <e32c7b7b-52c2-da14-a7aa-39d2052ab0b3@yahoo.co.uk>
 <ojfudk$nf3$1@blaine.gmane.org>
 <6025937C-F701-4C41-87B6-5805B14ED4DC@gmail.com>
Message-ID: <ojvg9h$gov$1@blaine.gmane.org>

On 04/07/17 13:45, Carlton Banks wrote:

> Any suggestion on any GUI solutions?

Here is a Tkinter solution that increments a counter
while the mouse button is pressed. It should give you the idea...
Obviously you need to replace the counter increment
with your desired processing. And the print statements
are just to show the events being processed.

##################################
import tkinter as tk

display = "count: "
flag = False
counter = 0

def do_down(e):
    global flag
    print('Key down')
    flag = True
    after_loop()

def do_up(e):
    global flag
    print('key up')
    flag = False

def after_loop():
    print('looping')
    global counter
    counter += 1
    l['text'] = display +str(counter)
    if flag:
       top.after(10,after_loop)


top = tk.Tk()
l = tk.Label(top,text=display+'0')
l.pack()
l.bind("<Button-1>",do_down)
l.bind("<ButtonRelease-1>",do_up)
top.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 noflaco at gmail.com  Mon Jul 10 05:03:41 2017
From: noflaco at gmail.com (Carlton Banks)
Date: Mon, 10 Jul 2017 11:03:41 +0200
Subject: [Tutor] call key on_press event multiple times when key is held
 down
In-Reply-To: <ojvfbg$g0q$1@blaine.gmane.org>
References: <29FACF89-C690-40CC-9AE4-7064516A971F@gmail.com>
 <e32c7b7b-52c2-da14-a7aa-39d2052ab0b3@yahoo.co.uk>
 <ojfudk$nf3$1@blaine.gmane.org>
 <6025937C-F701-4C41-87B6-5805B14ED4DC@gmail.com>
 <F6BBA1C8-FCE1-42EC-A770-33065001EB70@gmail.com>
 <ojvfbg$g0q$1@blaine.gmane.org>
Message-ID: <104CA68D-6841-4334-A3F6-20D2B5456961@gmail.com>

Thanks for the response :)
> Den 10. jul. 2017 kl. 10.54 skrev Peter Otten <__peter__ at web.de>:
> 
> Carlton Banks wrote:
> 
>> So i tried a different solution, introducing two threads one handling the
>> keyboard, and the other one is a while true, that keeps running.
>> 
>> https://pastebin.com/U0WVQMYP <https://pastebin.com/U0WVQMYP>
>> 
>> but for some reason, am I constantly running into IOerror, hence
>> no frames is being recorded.  Any suggestion on why?
> 
> Please remember to always provide the traceback.
> 
There is no traceback, no error message besides the IOerror caught by the try/execpt. 

>> while True:
>>    time.sleep(0.1)
>>    if listener.key_pressed == True and started == False:
>>        started = True
>>        listener.stream.start_stream()
>>        print "start Stream"
>> 
>>    elif listener.key_pressed == False and started == True:
>>        print "Something coocked"
>>        listener.stream.stop_stream()
> 
> Did you get a non-empty output.wav?

The output.wav is empty

>>        listener.stream.close()
> 
> you see the IOError on the second attempt to record something.

I see the IOerror while i have the key down,  not only on the first or second attempt..

>>        p.terminate()

> As you are only prepared to record once and another record would overwrite 
> the file anyway (at least that's what I suppose
> 

currently I am trying to make one recording work like this,
but would like to have the functionality of keep generating different audio files,
with different utterances..
>>        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
> 
> to do) perhaps you can omit the while-True loop altogether. Or you omit the 
> stream.close() call until after that loop (though there seems to be no way 
> to exit it cleanly at the moment).
> 
Not sure if that is the problem here? 
> Note that these are just ideas, I'm not familiar with pyaudio, or pynput, or 
> wave.
> 
And thanks for suggestioning them :)
>>        wf.setnchannels(CHANNELS)
>>        wf.setsampwidth(p.get_sample_size(FORMAT))
>>        wf.setframerate(RATE)
>>        wf.writeframes(b''.join(frames))
>>        wf.close()
>> 
>>        started = False
>> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


From maiafornaro at yahoo.com.ar  Mon Jul 10 08:44:43 2017
From: maiafornaro at yahoo.com.ar (maia fornaro)
Date: Mon, 10 Jul 2017 12:44:43 +0000 (UTC)
Subject: [Tutor] help with macOS version 10.12.5
References: <1172390051.2448185.1499690683545.ref@mail.yahoo.com>
Message-ID: <1172390051.2448185.1499690683545@mail.yahoo.com>

Hello, My name is maia and I'm train to install python 3 in my macOS  sierra version 10.12.5 and I receive this error went i open python:

Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>> WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable.
Visit http://www.python.org/download/mac/tcltk/ for current information.

I try to install another tcltk version but still have the same error, so I will like for your help.
Thanks !
Maia 

From noflaco at gmail.com  Mon Jul 10 16:55:17 2017
From: noflaco at gmail.com (Carlton Banks)
Date: Mon, 10 Jul 2017 22:55:17 +0200
Subject: [Tutor] help with macOS version 10.12.5
In-Reply-To: <1172390051.2448185.1499690683545@mail.yahoo.com>
References: <1172390051.2448185.1499690683545.ref@mail.yahoo.com>
 <1172390051.2448185.1499690683545@mail.yahoo.com>
Message-ID: <04F8E63F-8B51-4303-B263-39E8AAA6CF50@gmail.com>

Have you tried brew install python3
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 3 taps (caskroom/cask, homebrew/core, homebrew/science).
==> Updated Formulae
berkeley-db                homebrew/science/nco       percona-server
bitrise                    hugo                       percona-server-mongodb
carthage                   jhipster                   percona-toolkit
clang-format               ldc                        percona-xtrabackup
dbxml                      mongodb                    strongswan
exploitdb                  paket                      varnish at 4
folly                      pcre ?                     yadm

Error: python3 3.5.1 is already installed
To install 3.6.1, first run `brew unlink python3`
Error occurs on mine as i?ve already installed it..
> Den 10. jul. 2017 kl. 14.44 skrev maia fornaro via Tutor <tutor at python.org>:
> 
> Hello, My name is maia and I'm train to install python 3 in my macOS  sierra version 10.12.5 and I receive this error went i open python:
> 
> Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04) 
> [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
> Type "copyright", "credits" or "license()" for more information.
>>>> WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable.
> Visit http://www.python.org/download/mac/tcltk/ for current information.
> 
> I try to install another tcltk version but still have the same error, so I will like for your help.
> Thanks !
> Maia 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


From feifan.liu at gmail.com  Tue Jul 11 00:40:15 2017
From: feifan.liu at gmail.com (Feifan Liu)
Date: Tue, 11 Jul 2017 00:40:15 -0400
Subject: [Tutor] pip upgrade issue with virtual env
Message-ID: <CAM4FC_D4Yhgra61s1VVrxPkOyfsJkqd7OYGbbHJJs7GRGCjsuQ@mail.gmail.com>

Hello
I used anaconda to create a virtual envs.
Anaconda location: /usr/local/anaconda
My envs location: ~/.conda/envs/py2713

Then I activated my environment, did pip upgrade using: sudo pip install
--upgrade pip
***************
Collecting pip
  Downloading pip-9.0.1-py2.py3-none-any.whl (1.3MB)
    100%
Installing collected packages: pip
  Found existing installation: pip 9.0.0
    Uninstalling pip-9.0.0:
      Successfully uninstalled pip-9.0.0
Successfully installed pip-9.0.1
****************

But when I do "pip -V", it still using 8.1.1 as follows:
pip 8.1.1 from /usr/local/anaconda/lib/python2.7/site-packages (python 2.7)

when I do "which -a pip", it shows:
~/.conda/envs/py2713/bin/pip
/usr/local/anaconda/bin/pip
/usr/local/anaconda/bin/pip
/usr/bin/pip

But whichever I use, it all triggered the 8.8.1 version from
/usr/local/anaconda/lib/python2.7/site-packages

Just started anaconda, and any help is appreciated.

From JiaYue.Kee at firstsolar.com  Tue Jul 11 10:47:05 2017
From: JiaYue.Kee at firstsolar.com (Jia Yue Kee)
Date: Tue, 11 Jul 2017 14:47:05 +0000
Subject: [Tutor] Python __del__ method
Message-ID: <SN1PR08MB19520431AD76231AB162A25DE2AE0@SN1PR08MB1952.namprd08.prod.outlook.com>

Hi All,

I am new to Python and I came across the Python __del__ method the other day and I have some doubts on the output of the following code.

So, the snippet code goes something like this:

class Robot():

    def __init__(self, name):
        print(name + " has been created!")

    def __del__(self):
        print ("Robot has been destroyed")


if __name__ == "__main__":
    x = Robot("Tik-Tok")
    y = Robot("Jenkins")
    z = x
    z
    x
    del x
    del z
    del y

Case 1: If I were to run the code in  "Script Mode", the following output will be obtained:

Tik-Tok has been created!
Jenkins has been created!
Robot has been destroyed
Robot has been destroyed

Case 2: If I were to run the code in "Interactive Mode", the following output will be obtained:

>>> x = Robot("Tik-Tok")
Tik-Tok has been created!
>>> y = Robot("Jenkins")
Jenkins has been created!
>>> z = x
>>> z
<__main__.Robot object at 0x02D7E910>
>>> x
<__main__.Robot object at 0x02D7E910>
>>> del x
>>> del z
>>> del y
Robot has been destroyed

My question being why is that "Robot has been destroyed" is only printed once in Case 2 (interactive mode) while it is printed out twice in Case 1 (script mode)?
I did some study on garbage collection and based on my understanding, after the del x and del z statements, the refcount to the Robot object should reach zero and subsequently triggers the __del__ method right?
I am hoping someone could provide me a clearer picture on the doubts I have in mind.

Thanks and Regards,
JY

From eryksun at gmail.com  Tue Jul 11 20:07:25 2017
From: eryksun at gmail.com (eryk sun)
Date: Wed, 12 Jul 2017 00:07:25 +0000
Subject: [Tutor] Python __del__ method
In-Reply-To: <SN1PR08MB19520431AD76231AB162A25DE2AE0@SN1PR08MB1952.namprd08.prod.outlook.com>
References: <SN1PR08MB19520431AD76231AB162A25DE2AE0@SN1PR08MB1952.namprd08.prod.outlook.com>
Message-ID: <CACL+1asDbGQ4cZ7Y7z+tbDG8Giu2T5ROR-F7rQk2VKz_aVmnqA@mail.gmail.com>

On Tue, Jul 11, 2017 at 2:47 PM, Jia Yue Kee <JiaYue.Kee at firstsolar.com> wrote:
>
> Case 2: If I were to run the code in "Interactive Mode", the following output will be obtained:
>
>>>> x = Robot("Tik-Tok")
> Tik-Tok has been created!
>>>> y = Robot("Jenkins")
> Jenkins has been created!
>>>> z = x
>>>> z
> <__main__.Robot object at 0x02D7E910>
>>>> x
> <__main__.Robot object at 0x02D7E910>
>>>> del x
>>>> del z
>>>> del y
> Robot has been destroyed
>
> My question being why is that "Robot has been destroyed" is only printed once in Case 2
> (interactive mode) while it is printed out twice in Case 1 (script mode)?

The REPL (interactive mode) keeps a reference to the last non-None
result as builtins `_`, for convenient access to the last result. In
your case, it results from evaluating `x`. Thus you have a hidden
reference that's keeping that object alive. Enter anything except None
or _ to clear that reference.

From eryksun at gmail.com  Tue Jul 11 20:13:07 2017
From: eryksun at gmail.com (eryk sun)
Date: Wed, 12 Jul 2017 00:13:07 +0000
Subject: [Tutor] Python __del__ method
In-Reply-To: <CACL+1asDbGQ4cZ7Y7z+tbDG8Giu2T5ROR-F7rQk2VKz_aVmnqA@mail.gmail.com>
References: <SN1PR08MB19520431AD76231AB162A25DE2AE0@SN1PR08MB1952.namprd08.prod.outlook.com>
 <CACL+1asDbGQ4cZ7Y7z+tbDG8Giu2T5ROR-F7rQk2VKz_aVmnqA@mail.gmail.com>
Message-ID: <CACL+1avhoBoV4K5Te1BJ+1ahx=N1osi1PJDFa1ubEggV=_an9w@mail.gmail.com>

On Wed, Jul 12, 2017 at 12:07 AM, eryk sun <eryksun at gmail.com> wrote:
> On Tue, Jul 11, 2017 at 2:47 PM, Jia Yue Kee <JiaYue.Kee at firstsolar.com> wrote:
>>
>> Case 2: If I were to run the code in "Interactive Mode", the following output will be obtained:
>>
>>>>> x = Robot("Tik-Tok")
>> Tik-Tok has been created!
>>>>> y = Robot("Jenkins")
>> Jenkins has been created!
>>>>> z = x
>>>>> z
>> <__main__.Robot object at 0x02D7E910>
>>>>> x
>> <__main__.Robot object at 0x02D7E910>
>>>>> del x
>>>>> del z
>>>>> del y
>> Robot has been destroyed
>>
>> My question being why is that "Robot has been destroyed" is only printed once in Case 2
>> (interactive mode) while it is printed out twice in Case 1 (script mode)?
>
> The REPL (interactive mode) keeps a reference to the last non-None
> result as builtins `_`, for convenient access to the last result. In
> your case, it results from evaluating `x`. Thus you have a hidden
> reference that's keeping that object alive. Enter anything except None
> or _ to clear that reference.

Well, not just any statement. It has to evaluate to another object
except None or the Robot object that _ currently references. For
example, enter 42.

From robertvstepp at gmail.com  Tue Jul 11 20:20:55 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Tue, 11 Jul 2017 19:20:55 -0500
Subject: [Tutor] Python __del__ method
In-Reply-To: <CACL+1avhoBoV4K5Te1BJ+1ahx=N1osi1PJDFa1ubEggV=_an9w@mail.gmail.com>
References: <SN1PR08MB19520431AD76231AB162A25DE2AE0@SN1PR08MB1952.namprd08.prod.outlook.com>
 <CACL+1asDbGQ4cZ7Y7z+tbDG8Giu2T5ROR-F7rQk2VKz_aVmnqA@mail.gmail.com>
 <CACL+1avhoBoV4K5Te1BJ+1ahx=N1osi1PJDFa1ubEggV=_an9w@mail.gmail.com>
Message-ID: <CANDiX9L9gemsOL6NpLAsa2F_9fiF3CKYWOws7dxcpFHV5W-0PA@mail.gmail.com>

On Tue, Jul 11, 2017 at 7:13 PM, eryk sun <eryksun at gmail.com> wrote:
> On Wed, Jul 12, 2017 at 12:07 AM, eryk sun <eryksun at gmail.com> wrote:
>> On Tue, Jul 11, 2017 at 2:47 PM, Jia Yue Kee <JiaYue.Kee at firstsolar.com> wrote:
>>>
>>> Case 2: If I were to run the code in "Interactive Mode", the following output will be obtained:
>>>
>>>>>> x = Robot("Tik-Tok")
>>> Tik-Tok has been created!
>>>>>> y = Robot("Jenkins")
>>> Jenkins has been created!
>>>>>> z = x
>>>>>> z
>>> <__main__.Robot object at 0x02D7E910>
>>>>>> x
>>> <__main__.Robot object at 0x02D7E910>
>>>>>> del x
>>>>>> del z
>>>>>> del y
>>> Robot has been destroyed
>>>
>>> My question being why is that "Robot has been destroyed" is only printed once in Case 2
>>> (interactive mode) while it is printed out twice in Case 1 (script mode)?
>>
>> The REPL (interactive mode) keeps a reference to the last non-None
>> result as builtins `_`, for convenient access to the last result. In
>> your case, it results from evaluating `x`. Thus you have a hidden
>> reference that's keeping that object alive. Enter anything except None
>> or _ to clear that reference.
>
> Well, not just any statement. It has to evaluate to another object
> except None or the Robot object that _ currently references. For
> example, enter 42.

I found the OP's question and Eryk's answer of interest, too.  To make
it easier for me to understand what was going on I modified the OP's
code slightly so I could see which instance's __del__ method was being
called and got the following:

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64
bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
py3: class Robot:
...     def __init__(self, name):
...             self.name = name
...             print(self.name, "has been created!")
...     def __del__(self):
...             print(self.name, "has been destroyed!")
...
py3: x = Robot("Tik-Tok")
Tik-Tok has been created!
py3: y = Robot("Jenkins")
Jenkins has been created!
py3: z = x
py3: z
<__main__.Robot object at 0x0000000002002160>
py3: x
<__main__.Robot object at 0x0000000002002160>
py3: del x
py3: del z
py3: del y
Jenkins has been destroyed!
py3: x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
py3: z
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'z' is not defined
py3: _
<__main__.Robot object at 0x0000000002002160>
py3: x = 1
py3: _
<__main__.Robot object at 0x0000000002002160>
py3: x
Tik-Tok has been destroyed!
1



-- 
boB

From alan.gauld at yahoo.co.uk  Tue Jul 11 20:24:27 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 12 Jul 2017 01:24:27 +0100
Subject: [Tutor] Python __del__ method
In-Reply-To: <SN1PR08MB19520431AD76231AB162A25DE2AE0@SN1PR08MB1952.namprd08.prod.outlook.com>
References: <SN1PR08MB19520431AD76231AB162A25DE2AE0@SN1PR08MB1952.namprd08.prod.outlook.com>
Message-ID: <ok3q7l$ofa$1@blaine.gmane.org>

On 11/07/17 15:47, Jia Yue Kee wrote:
> I am new to Python and I came across the Python __del__ method 

The __del__() method is a bit of an oddity and often not
used in industrial strength Python code.

> if __name__ == "__main__":
>     x = Robot("Tik-Tok")
>     y = Robot("Jenkins")
>     z = x
>     del x
>     del z
>     del y
> 

> My question being why is that "Robot has been destroyed" 
> is only printed once in Case 2 

Because __del__() only got called once.
Which is really quite good, although you don't know which
object's del() was called!

The problem is that python does not promise to
call __del__() even when it is defined! It only promises
not to call it until all references are deleted.
So we can say when __del__() will not be called but
not when it will be called, if ever. The problem is
that __del__() is called by the garbage collector
when it actually collects the deleted object and that
could be a long time after the reference count goes
to zero, or possibly even never!

This means __del__() is of limited usefulness since
you can't rely on it being called. So you can't safely
use it as a destructor to release resources.

> ...after the del x and del z statements, the refcount 
> to the Robot object should reach zero and subsequently 
> triggers the __del__ method right?

Nearly.
It *might* trigger the __del__() method, eventually.
Or it might not, there is no guarantee. Mostly it
will get called, but you can't count on it.

I confess I don't fully understand the reasons why
it's been done that way, it just is...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From robertvstepp at gmail.com  Tue Jul 11 20:34:16 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Tue, 11 Jul 2017 19:34:16 -0500
Subject: [Tutor] Python __del__ method
In-Reply-To: <ok3q7l$ofa$1@blaine.gmane.org>
References: <SN1PR08MB19520431AD76231AB162A25DE2AE0@SN1PR08MB1952.namprd08.prod.outlook.com>
 <ok3q7l$ofa$1@blaine.gmane.org>
Message-ID: <CANDiX9LYOzBabv-6wnC2YEdQK9BNv3b=c9RDFwRB3jD1bHGihQ@mail.gmail.com>

On Tue, Jul 11, 2017 at 7:24 PM, Alan Gauld via Tutor <tutor at python.org> wrote:
> On 11/07/17 15:47, Jia Yue Kee wrote:
>> I am new to Python and I came across the Python __del__ method
>
> The __del__() method is a bit of an oddity and often not
> used in industrial strength Python code.
>
>> if __name__ == "__main__":
>>     x = Robot("Tik-Tok")
>>     y = Robot("Jenkins")
>>     z = x
>>     del x
>>     del z
>>     del y
>>
>
>> My question being why is that "Robot has been destroyed"
>> is only printed once in Case 2
>
> Because __del__() only got called once.
> Which is really quite good, although you don't know which
> object's del() was called!
>
> The problem is that python does not promise to
> call __del__() even when it is defined! It only promises
> not to call it until all references are deleted.
> So we can say when __del__() will not be called but
> not when it will be called, if ever. The problem is
> that __del__() is called by the garbage collector
> when it actually collects the deleted object and that
> could be a long time after the reference count goes
> to zero, or possibly even never!
>
> This means __del__() is of limited usefulness since
> you can't rely on it being called. So you can't safely
> use it as a destructor to release resources.
>
>> ...after the del x and del z statements, the refcount
>> to the Robot object should reach zero and subsequently
>> triggers the __del__ method right?
>
> Nearly.
> It *might* trigger the __del__() method, eventually.
> Or it might not, there is no guarantee. Mostly it
> will get called, but you can't count on it.
>

I am assuming that when the OP ran his code from a file, that upon the
script's completion, both object instances were garbage collected.
Surely upon program completion, everything _is_ garbage collected?

> I confess I don't fully understand the reasons why
> it's been done that way, it just is...

Now you have me wondering why, too!  ~(:>))

boB

From steve at pearwood.info  Tue Jul 11 20:54:33 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 12 Jul 2017 10:54:33 +1000
Subject: [Tutor] Python __del__ method
In-Reply-To: <CANDiX9LYOzBabv-6wnC2YEdQK9BNv3b=c9RDFwRB3jD1bHGihQ@mail.gmail.com>
References: <SN1PR08MB19520431AD76231AB162A25DE2AE0@SN1PR08MB1952.namprd08.prod.outlook.com>
 <ok3q7l$ofa$1@blaine.gmane.org>
 <CANDiX9LYOzBabv-6wnC2YEdQK9BNv3b=c9RDFwRB3jD1bHGihQ@mail.gmail.com>
Message-ID: <20170712005432.GP3149@ando.pearwood.info>

On Tue, Jul 11, 2017 at 07:34:16PM -0500, boB Stepp wrote:
> On Tue, Jul 11, 2017 at 7:24 PM, Alan Gauld via Tutor <tutor at python.org> wrote:

> I am assuming that when the OP ran his code from a file, that upon the
> script's completion, both object instances were garbage collected.
> Surely upon program completion, everything _is_ garbage collected?

Yes. But some things might not be garbage collected until the shut down 
process has already started garbage collecting other modules and code 
that your __del__ method relies on.

I believe that __del__ has become more reliable recently and will now be 
successfully called in situations that it didn't previously be called, 
but the interation of garbage collectors with destructor methods is 
still fraught with difficulties.


-- 
Steve

From __peter__ at web.de  Wed Jul 12 03:08:02 2017
From: __peter__ at web.de (Peter Otten)
Date: Wed, 12 Jul 2017 09:08:02 +0200
Subject: [Tutor] Python __del__ method
References: <SN1PR08MB19520431AD76231AB162A25DE2AE0@SN1PR08MB1952.namprd08.prod.outlook.com>
 <CACL+1asDbGQ4cZ7Y7z+tbDG8Giu2T5ROR-F7rQk2VKz_aVmnqA@mail.gmail.com>
Message-ID: <ok4hsf$3g8$1@blaine.gmane.org>

eryk sun wrote:

> On Tue, Jul 11, 2017 at 2:47 PM, Jia Yue Kee <JiaYue.Kee at firstsolar.com>
> wrote:
>>
>> Case 2: If I were to run the code in "Interactive Mode", the following
>> output will be obtained:
>>
>>>>> x = Robot("Tik-Tok")
>> Tik-Tok has been created!
>>>>> y = Robot("Jenkins")
>> Jenkins has been created!
>>>>> z = x
>>>>> z
>> <__main__.Robot object at 0x02D7E910>
>>>>> x
>> <__main__.Robot object at 0x02D7E910>
>>>>> del x
>>>>> del z
>>>>> del y
>> Robot has been destroyed
>>
>> My question being why is that "Robot has been destroyed" is only printed
>> once in Case 2 (interactive mode) while it is printed out twice in Case 1
>> (script mode)?
> 
> The REPL (interactive mode) keeps a reference to the last non-None
> result as builtins `_`, for convenient access to the last result. In
> your case, it results from evaluating `x`. Thus you have a hidden
> reference that's keeping that object alive. Enter anything except None
> or _ to clear that reference.

Or remove it explicitly:

>>> x = Robot("Foo")
Foo has been created!
>>> x
<__main__.Robot object at 0x7fe839ab77f0>
>>> del x
>>> import builtins
>>> del builtins._
Robot has been destroyed



From JiaYue.Kee at firstsolar.com  Wed Jul 12 11:12:47 2017
From: JiaYue.Kee at firstsolar.com (Jia Yue Kee)
Date: Wed, 12 Jul 2017 15:12:47 +0000
Subject: [Tutor] Python __del__ method
In-Reply-To: <CACL+1avhoBoV4K5Te1BJ+1ahx=N1osi1PJDFa1ubEggV=_an9w@mail.gmail.com>
References: <SN1PR08MB19520431AD76231AB162A25DE2AE0@SN1PR08MB1952.namprd08.prod.outlook.com>
 <CACL+1asDbGQ4cZ7Y7z+tbDG8Giu2T5ROR-F7rQk2VKz_aVmnqA@mail.gmail.com>
 <CACL+1avhoBoV4K5Te1BJ+1ahx=N1osi1PJDFa1ubEggV=_an9w@mail.gmail.com>
Message-ID: <SN1PR08MB195261ACB33503A4DD9CE499E2AF0@SN1PR08MB1952.namprd08.prod.outlook.com>

Hi Eryk,

Thanks for the detailed explanation given. I think I got it now. :)

Regards,
JY

-----Original Message-----
From: eryk sun [mailto:eryksun at gmail.com] 
Sent: Wednesday, July 12, 2017 8:13 AM
To: tutor at python.org
Cc: Jia Yue Kee <JiaYue.Kee at firstsolar.com>
Subject: Re: [Tutor] Python __del__ method

On Wed, Jul 12, 2017 at 12:07 AM, eryk sun <eryksun at gmail.com> wrote:
> On Tue, Jul 11, 2017 at 2:47 PM, Jia Yue Kee <JiaYue.Kee at firstsolar.com> wrote:
>>
>> Case 2: If I were to run the code in "Interactive Mode", the following output will be obtained:
>>
>>>>> x = Robot("Tik-Tok")
>> Tik-Tok has been created!
>>>>> y = Robot("Jenkins")
>> Jenkins has been created!
>>>>> z = x
>>>>> z
>> <__main__.Robot object at 0x02D7E910>
>>>>> x
>> <__main__.Robot object at 0x02D7E910>
>>>>> del x
>>>>> del z
>>>>> del y
>> Robot has been destroyed
>>
>> My question being why is that "Robot has been destroyed" is only 
>> printed once in Case 2 (interactive mode) while it is printed out twice in Case 1 (script mode)?
>
> The REPL (interactive mode) keeps a reference to the last non-None 
> result as builtins `_`, for convenient access to the last result. In 
> your case, it results from evaluating `x`. Thus you have a hidden 
> reference that's keeping that object alive. Enter anything except None 
> or _ to clear that reference.

Well, not just any statement. It has to evaluate to another object except None or the Robot object that _ currently references. For example, enter 42.

From noflaco at gmail.com  Thu Jul 13 03:36:15 2017
From: noflaco at gmail.com (Carlton Banks)
Date: Thu, 13 Jul 2017 09:36:15 +0200
Subject: [Tutor] call key on_press event multiple times when key is held
 down
In-Reply-To: <ojvg9h$gov$1@blaine.gmane.org>
References: <29FACF89-C690-40CC-9AE4-7064516A971F@gmail.com>
 <e32c7b7b-52c2-da14-a7aa-39d2052ab0b3@yahoo.co.uk>
 <ojfudk$nf3$1@blaine.gmane.org>
 <6025937C-F701-4C41-87B6-5805B14ED4DC@gmail.com>
 <ojvg9h$gov$1@blaine.gmane.org>
Message-ID: <4C09F673-5322-41B7-84C2-14F94AD33E51@gmail.com>

So i finally made it work.. 
My error was caused in the callback function, which
aborted the stream, hence didn?t record. 

This was the solution I ended with:

https://pastebin.com/isW2brW2 <https://pastebin.com/isW2brW2>


> Den 10. jul. 2017 kl. 11.10 skrev Alan Gauld via Tutor <tutor at python.org>:
> 
> On 04/07/17 13:45, Carlton Banks wrote:
> 
>> Any suggestion on any GUI solutions?
> 
> Here is a Tkinter solution that increments a counter
> while the mouse button is pressed. It should give you the idea...
> Obviously you need to replace the counter increment
> with your desired processing. And the print statements
> are just to show the events being processed.
> 
> ##################################
> import tkinter as tk
> 
> display = "count: "
> flag = False
> counter = 0
> 
> def do_down(e):
>    global flag
>    print('Key down')
>    flag = True
>    after_loop()
> 
> def do_up(e):
>    global flag
>    print('key up')
>    flag = False
> 
> def after_loop():
>    print('looping')
>    global counter
>    counter += 1
>    l['text'] = display +str(counter)
>    if flag:
>       top.after(10,after_loop)
> 
> 
> top = tk.Tk()
> l = tk.Label(top,text=display+'0')
> l.pack()
> l.bind("<Button-1>",do_down)
> l.bind("<ButtonRelease-1>",do_up)
> top.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 joel.goldstick at gmail.com  Thu Jul 13 08:20:36 2017
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Thu, 13 Jul 2017 08:20:36 -0400
Subject: [Tutor] call key on_press event multiple times when key is held
 down
In-Reply-To: <4C09F673-5322-41B7-84C2-14F94AD33E51@gmail.com>
References: <29FACF89-C690-40CC-9AE4-7064516A971F@gmail.com>
 <e32c7b7b-52c2-da14-a7aa-39d2052ab0b3@yahoo.co.uk>
 <ojfudk$nf3$1@blaine.gmane.org>
 <6025937C-F701-4C41-87B6-5805B14ED4DC@gmail.com>
 <ojvg9h$gov$1@blaine.gmane.org>
 <4C09F673-5322-41B7-84C2-14F94AD33E51@gmail.com>
Message-ID: <CAPM-O+x5vyEmBHJHcfFGuv4D8xLkjJngaoM1X+xoWkeHAP_bdQ@mail.gmail.com>

On Thu, Jul 13, 2017 at 3:36 AM, Carlton Banks <noflaco at gmail.com> wrote:

> So i finally made it work..
> My error was caused in the callback function, which
> aborted the stream, hence didn?t record.
>
> This was the solution I ended with:
>
> https://pastebin.com/isW2brW2 <https://pastebin.com/isW2brW2>
>
>
Carlton, please don't post above the discusion -- post below or interleave
where appropriate.  Also, paste your code in the message next time (which I
have done below)

>
> > Den 10. jul. 2017 kl. 11.10 skrev Alan Gauld via Tutor <tutor at python.org
> >:
> >
> > On 04/07/17 13:45, Carlton Banks wrote:
> >
> >> Any suggestion on any GUI solutions?
> >
> > Here is a Tkinter solution that increments a counter
> > while the mouse button is pressed. It should give you the idea...
> > Obviously you need to replace the counter increment
> > with your desired processing. And the print statements
> > are just to show the events being processed.
> >
> > ##################################
> > import tkinter as tk
> >
> > display = "count: "
> > flag = False
> > counter = 0
> >
> > def do_down(e):
> >    global flag
> >    print('Key down')
> >    flag = True
> >    after_loop()
> >
> > def do_up(e):
> >    global flag
> >    print('key up')
> >    flag = False
> >
> > def after_loop():
> >    print('looping')
> >    global counter
> >    counter += 1
> >    l['text'] = display +str(counter)
> >    if flag:
> >       top.after(10,after_loop)
> >
> >
> > top = tk.Tk()
> > l = tk.Label(top,text=display+'0')
> > l.pack()
> > l.bind("<Button-1>",do_down)
> > l.bind("<ButtonRelease-1>",do_up)
> > top.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
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

from pynput import keyboard
import time
import pyaudio
import wave
import math

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
WAVE_OUTPUT_FILENAME = "output.wav"



class MyListener(keyboard.Listener):
    def __init__(self):
        super(MyListener, self).__init__(on_press=self.on_press,
on_release=self.on_release)
        self.key_pressed = None


    def on_press(self, key):
        if key == keyboard.Key.cmd_l:
            self.p = pyaudio.PyAudio()
            self.frames = []

            self.stream = self.p.open(format=FORMAT,
                                 channels=CHANNELS,
                                 rate=RATE,
                                 input=True,
                                 frames_per_buffer=CHUNK,
                                 stream_callback = self.callback)

            print ("Stream active? " + str(self.stream.is_active()))
            self.key_pressed = True

    def on_release(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = False

    def callback(self,in_data, frame_count, time_info, status):
        if self.key_pressed == True:
            #stream_queue.put(in_data)
            print("record")
            self.frames.append(in_data)
            return (in_data, pyaudio.paContinue)

        elif self.key_pressed == False:
            #stream_queue.put(in_data)
            self.frames.append(in_data)
            return (in_data, pyaudio.paComplete)

        else:
            return (in_data,pyaudio.paContinue)



class yesno_generator:
    def __init__(self,pattern_length):
        self.pattern_length = pattern_length
        self.limit = math.pow(2,pattern_length)-1
        self.step = 0
    def begin(self):
        if self.step =< self.limit:


    def generate_patter(self):
        pattern = bin(self.step)[2:].zfill(sef.length)




listener = MyListener()
listener.start()
started = False



while True:
    time.sleep(0.1)
    if listener.key_pressed == True and started == False:
        started = True
        listener.stream.start_stream()
        print ("Start stream -  Key is down")

    #   elif listener.key_pressed == True and started == True:
        #print("stream has started and key is still down")
        #print("Stream is active? " + str(listener.stream.is_active()))
        #print("Stream is stopped? " + str(listener.stream.is_stopped()))
        #print("Stream is time? " + str(listener.stream.get_time()))

    elif listener.key_pressed == False and started == True:
        print("Key has been released")
        listener.stream.stop_stream()
        listener.stream.close()
        print("stream has been closed")
        listener.p.terminate()

        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(listener.p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(listener.frames))
        wf.close()

        started = False

-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays

From dvnsarma at gmail.com  Sun Jul 16 12:13:04 2017
From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=)
Date: Sun, 16 Jul 2017 21:43:04 +0530
Subject: [Tutor] Image i/o in python
Message-ID: <CAOZcEcfpnFU_jNY32_zGoS8oQzaxo_e_Rp1V-o=0Qz46zSJ3_g@mail.gmail.com>

In python we have a set of imread and imshow in skimage. In matplotlib.image
we again have imreadand imshow functions. In scipy.misc we again have
another set imread and imshow. Are there anyfunctional differences between
these multiple sets to justify their presence? ?

regards,
Sarma.

From mats at wichmann.us  Sun Jul 16 14:39:42 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Sun, 16 Jul 2017 12:39:42 -0600
Subject: [Tutor] Image i/o in python
In-Reply-To: <CAOZcEcfpnFU_jNY32_zGoS8oQzaxo_e_Rp1V-o=0Qz46zSJ3_g@mail.gmail.com>
References: <CAOZcEcfpnFU_jNY32_zGoS8oQzaxo_e_Rp1V-o=0Qz46zSJ3_g@mail.gmail.com>
Message-ID: <d1df9bf7-93f5-ebad-7c12-4e6d710a4ead@wichmann.us>

On 07/16/2017 10:13 AM, D.V.N.Sarma ??.??.???.???? wrote:
> In python we have a set of imread and imshow in skimage. In matplotlib.image
> we again have imreadand imshow functions. In scipy.misc we again have
> another set imread and imshow. Are there anyfunctional differences between
> these multiple sets to justify their presence? ?
> 
> regards,
> Sarma.

I've got good news for you, Sarma: there's an imread in OpenCV as well.
And I think there's at least one other set, plus I recall there's a
standalone imread package available in PyPi.

Each one of these is an independently developed project and they can
choose whatever they want to call their functions. Not that that helps
someone trying to pick one. Whether some are more useful than others, or
if any are useful in a context outside their own project... I'll leave
that to others to comment (or search the internet)



From alan.gauld at yahoo.co.uk  Sun Jul 16 15:11:32 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 16 Jul 2017 20:11:32 +0100
Subject: [Tutor] Image i/o in python
In-Reply-To: <CAOZcEcfpnFU_jNY32_zGoS8oQzaxo_e_Rp1V-o=0Qz46zSJ3_g@mail.gmail.com>
References: <CAOZcEcfpnFU_jNY32_zGoS8oQzaxo_e_Rp1V-o=0Qz46zSJ3_g@mail.gmail.com>
Message-ID: <okgdou$iml$1@blaine.gmane.org>

On 16/07/17 17:13, D.V.N.Sarma ??.??.???.???? wrote:
> In python we have a set of imread and imshow in skimage. In matplotlib.image
> we again have imreadand imshow functions. In scipy.misc we again have
> another set imread and imshow. Are there anyfunctional differences between
> these multiple sets to justify their presence? ?


None of these are part of the standard Python library
(as documented on python.org).

As a result the functions are named by the developers
of the respective packages. There is no central control
over third party packages so the developers can call
them what they like(*). They may or may not do the same
things - you need to read the documentation and try
a few tests to find out.

(*) And even in the standard library there are several
different open() functions and at least two sets of
time formatting functions with the same names and
functionality. That's what namespaces are for: to
keep them separate.

-- 
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 maxsmith02 at LIVE.CO.UK  Tue Jul 18 06:41:54 2017
From: maxsmith02 at LIVE.CO.UK (Max Smith)
Date: Tue, 18 Jul 2017 10:41:54 +0000
Subject: [Tutor] Python Questions
Message-ID: <DB6PR0901MB14954E3119F82C98AA2752DEE3A10@DB6PR0901MB1495.eurprd09.prod.outlook.com>

I have some questions about python.



What's the easiest way to learn python currently I'm using google's excersise program, I'm just reading and making notes then testing out what I have learnt. Since I' need to understand python fully as I've got a exam in Python for my GCSE's if you could give me some tips. I'd be excited to hear.



Thanks very Much,

Max.

From alan.gauld at yahoo.co.uk  Tue Jul 18 13:42:28 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 18 Jul 2017 18:42:28 +0100
Subject: [Tutor] Python Questions
In-Reply-To: <DB6PR0901MB14954E3119F82C98AA2752DEE3A10@DB6PR0901MB1495.eurprd09.prod.outlook.com>
References: <DB6PR0901MB14954E3119F82C98AA2752DEE3A10@DB6PR0901MB1495.eurprd09.prod.outlook.com>
Message-ID: <oklh9u$6kk$1@blaine.gmane.org>

On 18/07/17 11:41, Max Smith wrote:

> What's the easiest way to learn python currently 

Write a lot of code.

As to which tutorial to follow, that's a very personal choice and
depends on your previous knowledge and learning style. If you can
already program in a similar language(say Perl, PHP or Javascript)
then the official tutorial is just fine. If you are a comp-lete
programming neophite then use one of the non programmers
tutorials on the python web site (eg mine :-)

You can start with some of the many YouTube video courses if you
prefer but none of these will give you the depth that a
written tutorial will.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From mats at wichmann.us  Tue Jul 18 14:02:19 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Tue, 18 Jul 2017 12:02:19 -0600
Subject: [Tutor] Python Questions
In-Reply-To: <oklh9u$6kk$1@blaine.gmane.org>
References: <DB6PR0901MB14954E3119F82C98AA2752DEE3A10@DB6PR0901MB1495.eurprd09.prod.outlook.com>
 <oklh9u$6kk$1@blaine.gmane.org>
Message-ID: <537f7d90-174e-aff6-7604-86b26dd8e356@wichmann.us>

On 07/18/2017 11:42 AM, Alan Gauld via Tutor wrote:
> On 18/07/17 11:41, Max Smith wrote:
> 
>> What's the easiest way to learn python currently 
> 
> Write a lot of code.
> 
> As to which tutorial to follow, that's a very personal choice and
> depends on your previous knowledge and learning style. If you can
> already program in a similar language(say Perl, PHP or Javascript)
> then the official tutorial is just fine. If you are a comp-lete
> programming neophite then use one of the non programmers
> tutorials on the python web site (eg mine :-)
> 
> You can start with some of the many YouTube video courses if you
> prefer but none of these will give you the depth that a
> written tutorial will.

Absolutely, write code.  Some of the tutorials try hard to give you
"real" problems to solve, but they're by their nature prepared to
illustrate some point. It really helps if you supplement by using Python
to try to solve some distinct problem that interests you, because
ultimately what counts is whether you can apply your new knowledge to a
brand new situation, not one that's been hand-crafted by an author. If
you're doing that and get stuck, this is a place that can help with the
unsticking...

I'll just end up parroting Alan so I'll defer mentioning how hard it is
to choose "the best" "the easiest" "the fastest".  Do look at his
material by all means.

Google certainly knows what they're doing with Python, nothing wrong
with pursuing their stuff.

A python learning site that happens to appeal to me (one person's
opinions, and all that) is: http://www.python-course.eu/

AND there's actually one site that claims it is addressing the Computing
GCSE, http://usingpython.com/ - this one I have never looked at but it
might be worth a glance since that's the direction you're coming from.




From shanejoh at cisco.com  Tue Jul 18 13:31:20 2017
From: shanejoh at cisco.com (Shane Johnson (shanejoh))
Date: Tue, 18 Jul 2017 17:31:20 +0000
Subject: [Tutor] if/else statement
Message-ID: <9B84CACD-CB8F-47DA-9DD0-D82E8335913F@cisco.com>

I am doing the codeacademy python class and have the following code:

def greater_less_equal_5(answer):
       if answer is '>' 5
       return 1
       elif answer is < 5:
       return 0
       else:
       return 4

print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)

I?m getting a invalid syntax line 2 error. Any assistance is greatly appreciated.

[cid:image001.png at 01D2FFCA.286FD4E0]
Shane Johnson
Network Consulting Engineer
Cisco Services
shanejoh at cisco.com<mailto:paroche at cisco.com>
Phone: +1 770-236-3970
Mobile: +1 404-966-5334


Cisco.com<http://www.cisco.com/>



[cid:image002.png at 01D2FFCA.286FD4E0]Think before you print.

This email may contain confidential and privileged material for the sole use of the intended recipient. Any review, use, distribution or disclosure by others is strictly prohibited. If you are not the intended recipient (or authorized to receive for the recipient), please contact the sender by reply email and delete all copies of this message.
For corporate legal information go to:
http://www.cisco.com/web/about/doing_business/legal/cri/index.html




From joel.goldstick at gmail.com  Tue Jul 18 19:08:16 2017
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 18 Jul 2017 19:08:16 -0400
Subject: [Tutor] if/else statement
In-Reply-To: <9B84CACD-CB8F-47DA-9DD0-D82E8335913F@cisco.com>
References: <9B84CACD-CB8F-47DA-9DD0-D82E8335913F@cisco.com>
Message-ID: <CAPM-O+y9VZ0XZVcgYsfK2vqJx4hfAjaR2OqGVsuYnqETg-zQNQ@mail.gmail.com>

On Tue, Jul 18, 2017 at 1:31 PM, Shane Johnson (shanejoh) <
shanejoh at cisco.com> wrote:

> I am doing the codeacademy python class and have the following code:
>
> def greater_less_equal_5(answer):
>        if answer is '>' 5
>
indent the line after the if

>        return 1
>        elif answer is < 5:
>
and here

>        return 0
>        else:
>
and here

>        return 4
>
> print greater_less_equal_5(4)
> print greater_less_equal_5(5)
> print greater_less_equal_5(6)
>
> I?m getting a invalid syntax line 2 error. Any assistance is greatly
> appreciated.
>
> [cid:image001.png at 01D2FFCA.286FD4E0]
> Shane Johnson
> Network Consulting Engineer
> Cisco Services
> shanejoh at cisco.com<mailto:paroche at cisco.com>
> Phone: +1 770-236-3970
> Mobile: +1 404-966-5334
>
> In python, indentation is essential
> Cisco.com<http://www.cisco.com/>
>
>
>
> [cid:image002.png at 01D2FFCA.286FD4E0]Think before you print.
>
> This email may contain confidential and privileged material for the sole
> use of the intended recipient. Any review, use, distribution or disclosure
> by others is strictly prohibited. If you are not the intended recipient (or
> authorized to receive for the recipient), please contact the sender by
> reply email and delete all copies of this message.
> For corporate legal information go to:
> http://www.cisco.com/web/about/doing_business/legal/cri/index.html
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays

From alan.gauld at yahoo.co.uk  Tue Jul 18 19:10:30 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 19 Jul 2017 00:10:30 +0100
Subject: [Tutor] if/else statement
In-Reply-To: <9B84CACD-CB8F-47DA-9DD0-D82E8335913F@cisco.com>
References: <9B84CACD-CB8F-47DA-9DD0-D82E8335913F@cisco.com>
Message-ID: <okm4h0$1cq$1@blaine.gmane.org>

On 18/07/17 18:31, Shane Johnson (shanejoh) wrote:

> def greater_less_equal_5(answer):
>        if answer is '>' 5
>        return 1
>        elif answer is < 5:
>        return 0
>        else:
>        return 4

> I?m getting a invalid syntax line 2 error. Any assistance is greatly appreciated.

Thee are two problems.

1) 'is' is a problem, you don't need it here. 'is' is an operator
for testing whether two object references are to the same
actual object
eg.

x = 42
y = x   # y and x both refer to the same number
if x is y: print 'yes!'

You don't use it in mathematical comparisons so your code
should look like:

       if answer > 5
          return 1
       elif answer < 5:
          return 0
       else:
          return 4

Notice I also removed the quotes around the > sign and
added indentation to the return statements which leads
us to...

2) You don't have any indentation in the function body.
Indentation is all important in Python, it's how the
interpreter knows where the conditional block starts
and stops.

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  Tue Jul 18 20:11:48 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Tue, 18 Jul 2017 18:11:48 -0600
Subject: [Tutor] if/else statement
In-Reply-To: <okm4h0$1cq$1@blaine.gmane.org>
References: <9B84CACD-CB8F-47DA-9DD0-D82E8335913F@cisco.com>
 <okm4h0$1cq$1@blaine.gmane.org>
Message-ID: <BEE7CA2C-4055-4917-AF96-29863038D51B@wichmann.us>

And one more, the 'if' needs a colon at the end

On July 18, 2017 5:10:30 PM MDT, Alan Gauld via Tutor <tutor at python.org> wrote:
>On 18/07/17 18:31, Shane Johnson (shanejoh) wrote:
>
>> def greater_less_equal_5(answer):
>>        if answer is '>' 5
>>        return 1
>>        elif answer is < 5:
>>        return 0
>>        else:
>>        return 4
>
>> I?m getting a invalid syntax line 2 error. Any assistance is greatly
>appreciated.
>
>Thee are two problems.
>
>1) 'is' is a problem, you don't need it here. 'is' is an operator
>for testing whether two object references are to the same
>actual object
>eg.
>
>x = 42
>y = x   # y and x both refer to the same number
>if x is y: print 'yes!'
>
>You don't use it in mathematical comparisons so your code
>should look like:
>
>       if answer > 5
>          return 1
>       elif answer < 5:
>          return 0
>       else:
>          return 4
>
>Notice I also removed the quotes around the > sign and
>added indentation to the return statements which leads
>us to...
>
>2) You don't have any indentation in the function body.
>Indentation is all important in Python, it's how the
>interpreter knows where the conditional block starts
>and stops.
>
>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

-- 
Sent from my Android device with K-9 Mail. Please excuse my brevity.

From s.shall at virginmedia.com  Wed Jul 19 11:01:53 2017
From: s.shall at virginmedia.com (Sydney Shall)
Date: Wed, 19 Jul 2017 17:01:53 +0200
Subject: [Tutor] unitest with random inputs
Message-ID: <04d8aedd-0677-a6d1-efb3-864a4d467b58@virginmedia.com>

I am learning to use unittest.

I have written a program that runs as it should.
247 tests give me a satisfactory answer.

I have now added one more test and I get an error which I do not understand.

The two relevant tests are:

  def test_type_capitalsadvanced(self):
         self.assertEqual(type(self.capitalsadvanced), numpy.ndarray)

  def test_zero_in_capitalsadvanced(self):
         self.assertIn(self.capitalsadvanced, 0.0)

The error message is:

Traceback (most recent call last):
   File 
"/Users/sydney/Capital/Capital_with_productivity/Current_Versions/testPOCWP_V2.py", 
line 320, in test_zero_in_capitalsadvanced
     self.assertIn(self.capitalsadvanced, 0.0)
   File "/Users/sydney/anaconda/lib/python3.6/unittest/case.py", line 
1077, in assertIn
     if member not in container:
TypeError: argument of type 'float' is not iterable

Final output from the tests is :

Ran 247 tests in 1.179s

FAILED (failures=9, errors=1)

The failures all arise from a 'nan'.
It is this problem that I am trying to resolve.

My problem is that the first test tells me correctly that the object 
capitalsadvanced is a numpy.ndarray. But the second test error message 
says it is a float.

I should add that the program creates the initial data set by making use 
of the random function which is given a mean to work with. Thus each 
test run will be with different input data. But repeated tests show the 
same errors.

When I run the same tests with predetermined, fixed data I get no errors 
and no 'nan' errors.

Any guidance will be very welcome.


-- 
Sydney

From __peter__ at web.de  Wed Jul 19 11:43:59 2017
From: __peter__ at web.de (Peter Otten)
Date: Wed, 19 Jul 2017 17:43:59 +0200
Subject: [Tutor] unitest with random inputs
References: <04d8aedd-0677-a6d1-efb3-864a4d467b58@virginmedia.com>
Message-ID: <oknunr$9jq$1@blaine.gmane.org>

Sydney Shall wrote:

> I am learning to use unittest.
> 
> I have written a program that runs as it should.
> 247 tests give me a satisfactory answer.
> 
> I have now added one more test and I get an error which I do not
> understand.
> 
> The two relevant tests are:
> 
>   def test_type_capitalsadvanced(self):
>          self.assertEqual(type(self.capitalsadvanced), numpy.ndarray)
> 
>   def test_zero_in_capitalsadvanced(self):
>          self.assertIn(self.capitalsadvanced, 0.0)
> 
> The error message is:
> 
> Traceback (most recent call last):
>    File
> 
"/Users/sydney/Capital/Capital_with_productivity/Current_Versions/testPOCWP_V2.py",
> line 320, in test_zero_in_capitalsadvanced
>      self.assertIn(self.capitalsadvanced, 0.0)
>    File "/Users/sydney/anaconda/lib/python3.6/unittest/case.py", line
> 1077, in assertIn
>      if member not in container:
> TypeError: argument of type 'float' is not iterable
> 
> Final output from the tests is :
> 
> Ran 247 tests in 1.179s
> 
> FAILED (failures=9, errors=1)
> 
> The failures all arise from a 'nan'.

I don't think so. To fix the traceback shown above you have to swap the 
arguments in assertIn():

    def test_zero_in_capitalsadvanced(self):
        self.assertIn(0.0, self.capitalsadvanced)

Digression: once this is done you may still get failures when searching for 
NaN in a sequence as it does not compare equal to itself:

>>> nan = float("nan")
>>> nan == nan
False
>>> a = numpy.array([nan])
>>> nan in a
False

This is how it should be (*), but unfortunately Python's builtin 
list/set/dict/tuple all assume that obj is obj implies obj == obj which 
makes the result of containment test hard to predict:

>>> nan in [nan]
True
>>> nan in [float("nan")]
False


(*) See for example 
<https://en.wikipedia.org/wiki/Floating-point_arithmetic>:
"every NaN compares unequal to every value, including itself"

> It is this problem that I am trying to resolve.
> 
> My problem is that the first test tells me correctly that the object
> capitalsadvanced is a numpy.ndarray. But the second test error message
> says it is a float.
> 
> I should add that the program creates the initial data set by making use
> of the random function which is given a mean to work with. Thus each
> test run will be with different input data. But repeated tests show the
> same errors.
> 
> When I run the same tests with predetermined, fixed data I get no errors
> and no 'nan' errors.
> 
> Any guidance will be very welcome.
> 
> 



From alan.gauld at yahoo.co.uk  Wed Jul 19 12:05:58 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 19 Jul 2017 17:05:58 +0100
Subject: [Tutor] unitest with random inputs
In-Reply-To: <04d8aedd-0677-a6d1-efb3-864a4d467b58@virginmedia.com>
References: <04d8aedd-0677-a6d1-efb3-864a4d467b58@virginmedia.com>
Message-ID: <oko010$u1t$1@blaine.gmane.org>

On 19/07/17 16:01, Sydney Shall wrote:
> I am learning to use unittest.
> 

>   def test_zero_in_capitalsadvanced(self):
>          self.assertIn(self.capitalsadvanced, 0.0)

Remember the interpreter...


>>> help(unittest.case.assertIn)
Help on function assertIn in module unittest.case:

assertIn(self, member, container, msg=None)
    Just like self.assertTrue(a in b), but with a nicer default message.
~

> The error message is:
> 
>      self.assertIn(self.capitalsadvanced, 0.0)
>    File "/Users/sydney/anaconda/lib/python3.6/unittest/case.py", line 
> 1077, in assertIn
>      if member not in container:
> TypeError: argument of type 'float' is not iterable

The obvious float is 0.0
The likely container is self.capitalsadvanced

They are reversed according to the help screen.

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 s.shall at virginmedia.com  Wed Jul 19 12:08:57 2017
From: s.shall at virginmedia.com (Sydney Shall)
Date: Wed, 19 Jul 2017 18:08:57 +0200
Subject: [Tutor] unitest with random inputs
In-Reply-To: <oknunr$9jq$1@blaine.gmane.org>
References: <04d8aedd-0677-a6d1-efb3-864a4d467b58@virginmedia.com>
 <oknunr$9jq$1@blaine.gmane.org>
Message-ID: <bd1e3118-e34c-e1ec-7795-7aaeaa0a015a@virginmedia.com>

On 19/07/2017 17:43, Peter Otten wrote:
> Sydney Shall wrote:
> 
>> I am learning to use unittest.
>>
>> I have written a program that runs as it should.
>> 247 tests give me a satisfactory answer.
>>
>> I have now added one more test and I get an error which I do not
>> understand.
>>
>> The two relevant tests are:
>>
>>    def test_type_capitalsadvanced(self):
>>           self.assertEqual(type(self.capitalsadvanced), numpy.ndarray)
>>
>>    def test_zero_in_capitalsadvanced(self):
>>           self.assertIn(self.capitalsadvanced, 0.0)
>>
>> The error message is:
>>
>> Traceback (most recent call last):
>>     File
>>
> "/Users/sydney/Capital/Capital_with_productivity/Current_Versions/testPOCWP_V2.py",
>> line 320, in test_zero_in_capitalsadvanced
>>       self.assertIn(self.capitalsadvanced, 0.0)
>>     File "/Users/sydney/anaconda/lib/python3.6/unittest/case.py", line
>> 1077, in assertIn
>>       if member not in container:
>> TypeError: argument of type 'float' is not iterable
>>
>> Final output from the tests is :
>>
>> Ran 247 tests in 1.179s
>>
>> FAILED (failures=9, errors=1)
>>
>> The failures all arise from a 'nan'.
> 
> I don't think so. To fix the traceback shown above you have to swap the
> arguments in assertIn():
> 
>      def test_zero_in_capitalsadvanced(self):
>          self.assertIn(0.0, self.capitalsadvanced)
> 
> Digression: once this is done you may still get failures when searching for
> NaN in a sequence as it does not compare equal to itself:
> 
>>>> nan = float("nan")
>>>> nan == nan
> False
>>>> a = numpy.array([nan])
>>>> nan in a
> False
> 
> This is how it should be (*), but unfortunately Python's builtin
> list/set/dict/tuple all assume that obj is obj implies obj == obj which
> makes the result of containment test hard to predict:
> 
>>>> nan in [nan]
> True
>>>> nan in [float("nan")]
> False
> 
> 
> (*) See for example
> <https://en.wikipedia.org/wiki/Floating-point_arithmetic>:
> "every NaN compares unequal to every value, including itself"
> 
>> It is this problem that I am trying to resolve.
>>
>> My problem is that the first test tells me correctly that the object
>> capitalsadvanced is a numpy.ndarray. But the second test error message
>> says it is a float.
>>
>> I should add that the program creates the initial data set by making use
>> of the random function which is given a mean to work with. Thus each
>> test run will be with different input data. But repeated tests show the
>> same errors.
>>
>> When I run the same tests with predetermined, fixed data I get no errors
>> and no 'nan' errors.
>>
>> Any guidance will be very welcome.
>>
>>
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 
Peter,

Thanks for your comment.
This has helped to cure the first error.

For the second error, regarding 'nan' finding 'nan', I received the 
following output.


FAIL: test_nan_in_capitalsadvanced (__main__.TestPOC)
----------------------------------------------------------------------
Traceback (most recent call last):
   File 
"/Users/sydney/Capital/Capital_with_productivity/Current_Versions/testPOCWP_V2.py", 
line 323, in test_nan_in_capitalsadvanced
     self.assertIn('nan', self.capitalsadvanced)
AssertionError: 'nan' not found in array([ 12026.72641072, 
12434.53700436,  12185.56314119, ...,
         12488.04714281,  12479.4662866 ,  12310.66016998])

Could I use assertNotIn with the other problems?

Thanks again.

Sydney

-- 
Sydney

From sydney.shall at kcl.ac.uk  Wed Jul 19 07:35:38 2017
From: sydney.shall at kcl.ac.uk (Shall, Sydney)
Date: Wed, 19 Jul 2017 13:35:38 +0200
Subject: [Tutor] unittest difficulty
Message-ID: <d6e3a140-efad-6dc2-be10-7db9c3f35963@kcl.ac.uk>

I am learning to use unittest.

I have written a program that runs as it should.
247 tests give me a satisfactory answer.

I have now added one more test and I get an error which I do not understand.

The two relevant tests are:

  def test_type_capitalsadvanced(self):
         self.assertEqual(type(self.capitalsadvanced), numpy.ndarray)

  def test_zero_in_capitalsadvanced(self):
         self.assertIn(self.capitalsadvanced, 0.0)

The error message is:

Traceback (most recent call last):
   File 
"/Users/sydney/Capital/Capital_with_productivity/Current_Versions/testPOCWP_V2.py", 
line 320, in test_zero_in_capitalsadvanced
     self.assertIn(self.capitalsadvanced, 0.0)
   File "/Users/sydney/anaconda/lib/python3.6/unittest/case.py", line 
1077, in assertIn
     if member not in container:
TypeError: argument of type 'float' is not iterable

Final output from the tests is :

Ran 247 tests in 1.179s

FAILED (failures=9, errors=1)

The failures all arise from a 'nan'.
It is this problem that I am trying to resolve.

My problem is that the first test tells me correctly that the object 
capitalsadvanced is a numpy.ndarray. But the second test error message 
says it is a float.

I should add that the program creates the initial data set by making use 
of the random function which is given a mean to work with. Thus each 
test run will be with different input data. But repeated tests show the 
same errors.

Any guidance will be very welcome.

Sydney

_________

Professor Sydney Shall
Department of Haematology/Oncology
Phone: +(0)2078489200
E-Mail: sydney.shall
[Correspondents outside the College should add @kcl.ac.uk]

From s.shall at virginmedia.com  Wed Jul 19 12:27:56 2017
From: s.shall at virginmedia.com (Sydney Shall)
Date: Wed, 19 Jul 2017 18:27:56 +0200
Subject: [Tutor] unitest with random inputs
In-Reply-To: <oko010$u1t$1@blaine.gmane.org>
References: <04d8aedd-0677-a6d1-efb3-864a4d467b58@virginmedia.com>
 <oko010$u1t$1@blaine.gmane.org>
Message-ID: <c0b35b6b-4450-bcb4-820b-7fb5cc5ff514@virginmedia.com>

On 19/07/2017 18:05, Alan Gauld via Tutor wrote:
> On 19/07/17 16:01, Sydney Shall wrote:
>> I am learning to use unittest.
>>
> 
>>    def test_zero_in_capitalsadvanced(self):
>>           self.assertIn(self.capitalsadvanced, 0.0)
> 
> Remember the interpreter...
> 
> 
>>>> help(unittest.case.assertIn)
> Help on function assertIn in module unittest.case:
> 
> assertIn(self, member, container, msg=None)
>      Just like self.assertTrue(a in b), but with a nicer default message.
> ~
> 
>> The error message is:
>>
>>       self.assertIn(self.capitalsadvanced, 0.0)
>>     File "/Users/sydney/anaconda/lib/python3.6/unittest/case.py", line
>> 1077, in assertIn
>>       if member not in container:
>> TypeError: argument of type 'float' is not iterable
> 
> The obvious float is 0.0
> The likely container is self.capitalsadvanced
> 
> They are reversed according to the help screen.
> 
> HTH
> 
My apologies for giving you extra work. I am in fact a very long sitting 
member of the list. Ever since kindergarden. You taught me to walk.
I used thw wrong email account.

Thanks. Yes, that cures one problem. Also thanks for the guidance. It is 
most useful.

-- 
Sydney

From steve at pearwood.info  Wed Jul 19 12:42:16 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 20 Jul 2017 02:42:16 +1000
Subject: [Tutor] unitest with random inputs
In-Reply-To: <04d8aedd-0677-a6d1-efb3-864a4d467b58@virginmedia.com>
References: <04d8aedd-0677-a6d1-efb3-864a4d467b58@virginmedia.com>
Message-ID: <20170719164216.GF3149@ando.pearwood.info>

On Wed, Jul 19, 2017 at 05:01:53PM +0200, Sydney Shall wrote:

[...]
>  def test_zero_in_capitalsadvanced(self):
>         self.assertIn(self.capitalsadvanced, 0.0)
> 
> The error message is:
> 
> Traceback (most recent call last):
[...]
> in assertIn
>     if member not in container:
> TypeError: argument of type 'float' is not iterable

You are trying to test whether capitalsadvanced is in 0.0. Reverse the 
arguments:

        self.assertIn(0.0, self.capitalsadvanced)

which will test whether 0.0 is in self.capitalsadvanced.


> FAILED (failures=9, errors=1)
> 
> The failures all arise from a 'nan'.
> It is this problem that I am trying to resolve.

Well, since you don't show us what those failing tests are, we cannot 
possibly tell you how to fix them.

Start by showing us *one* failing test, and what the failure is.


-- 
Steve

From steve at pearwood.info  Wed Jul 19 12:56:49 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 20 Jul 2017 02:56:49 +1000
Subject: [Tutor] unitest with random inputs
In-Reply-To: <bd1e3118-e34c-e1ec-7795-7aaeaa0a015a@virginmedia.com>
References: <04d8aedd-0677-a6d1-efb3-864a4d467b58@virginmedia.com>
 <oknunr$9jq$1@blaine.gmane.org>
 <bd1e3118-e34c-e1ec-7795-7aaeaa0a015a@virginmedia.com>
Message-ID: <20170719165648.GG3149@ando.pearwood.info>

On Wed, Jul 19, 2017 at 06:08:57PM +0200, Sydney Shall wrote:

> For the second error, regarding 'nan' finding 'nan', I received the 
> following output.
> 
> FAIL: test_nan_in_capitalsadvanced (__main__.TestPOC)
> ----------------------------------------------------------------------
> Traceback (most recent call last):
>   File 
> "/Users/sydney/Capital/Capital_with_productivity/Current_Versions/testPOCWP_V2.py", 
> line 323, in test_nan_in_capitalsadvanced
>     self.assertIn('nan', self.capitalsadvanced)
> AssertionError: 'nan' not found in array([ 12026.72641072, 
> 12434.53700436,  12185.56314119, ...,
>         12488.04714281,  12479.4662866 ,  12310.66016998])

NANs are tricky to work with.

To check whether a list contains a NAN value, you cannot reliably use 
"nan in list". How do we fix that?

To begin with, we need to use an actual floating point NAN, not the 
string "nan". So we can try this:

float('nan') in list

Alas, that's not enough. As Peter discussed earlier, for technical 
reasons, "Not A Number" floating point values (NANs) are designed to 
always fail equality tests. And for other technical reasons, Python 
tests for object identity before equality tests when evaluating the "in" 
operator. Don't worry if you don't understand the gory details yet: the 
message to take home is that NANs are special, and you cannot *reliably* 
test for them with the "in" operator.

So 

    self.assertIn(float('nan'), self.capitalsadvanced)


*will not work* reliably, if at all.

Instead, we can create our own test for a NAN:

    self.assertTrue(any(math.isnan(x) for x in self.capitalsadvanced))


Make sure you run "import math" at the top of your module.

(I haven't tested that code myself, so please try it, and if it doesn't 
work for some reason, let us know on the mailing list and somebody can 
fix it.)

But... I'm rather surprised that you need this test. Are you sure that 
your array capitalsadvanced will *always* contain at least one Not A 
Number value? Unless you put one in yourself, NANs generally indicate 
that a mathematical error has occurred somewhere.




-- 
Steve

From s.shall at virginmedia.com  Wed Jul 19 12:55:34 2017
From: s.shall at virginmedia.com (Sydney Shall)
Date: Wed, 19 Jul 2017 18:55:34 +0200
Subject: [Tutor] unitest with random inputs
In-Reply-To: <20170719164216.GF3149@ando.pearwood.info>
References: <04d8aedd-0677-a6d1-efb3-864a4d467b58@virginmedia.com>
 <20170719164216.GF3149@ando.pearwood.info>
Message-ID: <e17f11db-984a-0904-29cf-e27f4bb1ded5@virginmedia.com>

On 19/07/2017 18:42, Steven D'Aprano wrote:
> On Wed, Jul 19, 2017 at 05:01:53PM +0200, Sydney Shall wrote:
> 
> [...]
>>   def test_zero_in_capitalsadvanced(self):
>>          self.assertIn(self.capitalsadvanced, 0.0)
>>
>> The error message is:
>>
>> Traceback (most recent call last):
> [...]
>> in assertIn
>>      if member not in container:
>> TypeError: argument of type 'float' is not iterable
> 
> You are trying to test whether capitalsadvanced is in 0.0. Reverse the
> arguments:
> 
>          self.assertIn(0.0, self.capitalsadvanced)
> 
> which will test whether 0.0 is in self.capitalsadvanced.
> 
> 
>> FAILED (failures=9, errors=1)
>>
>> The failures all arise from a 'nan'.
>> It is this problem that I am trying to resolve.
> 
> Well, since you don't show us what those failing tests are, we cannot
> possibly tell you how to fix them.
> 
> Start by showing us *one* failing test, and what the failure is.
> 
> 
Thank you Steve.

The remaining 'nan' problems are shown below.

runfile('/Users/sydney/Capital/Capital_with_productivity/Current_Versions/testPOCWP_V2.py', 
wdir='/Users/sydney/Capital/Capital_with_productivity/Current_Versions')
/Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:1582: 
RuntimeWarning: invalid value encountered in true_divide

/Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:1637: 
RuntimeWarning: invalid value encountered in true_divide
   constantcapitals is divided, element-wise by the array
/Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:1665: 
RuntimeWarning: invalid value encountered in true_divide
   capitalsadvanced.
/Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:1695: 
RuntimeWarning: invalid value encountered in true_divide
   The output is a numpy array of floats; and they are ratios of (Variable
/Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:1729: 
RuntimeWarning: invalid value encountered in true_divide
   The method returns is a numpy array of floats; the ratios of (Variable
/Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:1758: 
RuntimeWarning: invalid value encountered in true_divide
   The method returns a numpy array of floats, which are the ratios of
/Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:1787: 
RuntimeWarning: invalid value encountered in true_divide
   The method returns a numpy array of floats which are the individual
/Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:1816: 
RuntimeWarning: invalid value encountered in true_divide
   The method returns a numpy array of floats which are the ratios of (New
..............................................................................................................FF.F.FFF..FF...F......./Users/sydney/anaconda/lib/python3.6/unittest/case.py:1077: 
FutureWarning: elementwise comparison failed; returning scalar instead, 
but in the future will perform elementwise comparison
   if member not in container:
F............................................../Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:2311: 
RuntimeWarning: invalid value encountered in double_scalars
   values in UCC.
/Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:2256: 
RuntimeWarning: invalid value encountered in double_scalars

....................................................................

I have looked carefully at the lines indicated and they almost all 
involve 4 specific numpy.ndarrays. I suspect from the logic that they 
all results from the commonest array in the list.

The last error is different, but I belie that it is related.



-- 
Sydney

From s.shall at virginmedia.com  Wed Jul 19 13:09:22 2017
From: s.shall at virginmedia.com (Sydney Shall)
Date: Wed, 19 Jul 2017 19:09:22 +0200
Subject: [Tutor] unitest with random inputs
In-Reply-To: <20170719165648.GG3149@ando.pearwood.info>
References: <04d8aedd-0677-a6d1-efb3-864a4d467b58@virginmedia.com>
 <oknunr$9jq$1@blaine.gmane.org>
 <bd1e3118-e34c-e1ec-7795-7aaeaa0a015a@virginmedia.com>
 <20170719165648.GG3149@ando.pearwood.info>
Message-ID: <a445f02f-ac3d-6659-730b-a4eefd3668d1@virginmedia.com>

On 19/07/2017 18:56, Steven D'Aprano wrote:
> On Wed, Jul 19, 2017 at 06:08:57PM +0200, Sydney Shall wrote:
> 
>> 
> 
> (I haven't tested that code myself, so please try it, and if it doesn't
> work for some reason, let us know on the mailing list and somebody can
> fix it.)
> 
> But... I'm rather surprised that you need this test. Are you sure that
> your array capitalsadvanced will *always* contain at least one Not A
> Number value? Unless you put one in yourself, NANs generally indicate
> that a mathematical error has occurred somewhere.
> 

Steven,

Thanks again.

I started this precisely because I also thought and still think, that 
the origin of my problem is a mathematical error somewhere.

However, when I use predetermined input values, the errors are absent. 
They only appear when I use the random function. Although it should not 
be the case, I wondered whether the random function was feeding in a 
zero, because the errors seem to involve an invalid value after a 
true-divide according to some of the error reports earlier. So, my first 
step was to try and see if there are any zeros in the array that is used 
first. The tests say that the type and the length of the array is 
correct. But how do I test for a zero in a numpy.ndarray?


-- 
Sydney

From __peter__ at web.de  Wed Jul 19 14:04:24 2017
From: __peter__ at web.de (Peter Otten)
Date: Wed, 19 Jul 2017 20:04:24 +0200
Subject: [Tutor] unitest with random inputs
References: <04d8aedd-0677-a6d1-efb3-864a4d467b58@virginmedia.com>
 <oknunr$9jq$1@blaine.gmane.org>
 <bd1e3118-e34c-e1ec-7795-7aaeaa0a015a@virginmedia.com>
 <20170719165648.GG3149@ando.pearwood.info>
 <a445f02f-ac3d-6659-730b-a4eefd3668d1@virginmedia.com>
Message-ID: <oko6v3$5l1$1@blaine.gmane.org>

Sydney Shall wrote:

> On 19/07/2017 18:56, Steven D'Aprano wrote:
>> On Wed, Jul 19, 2017 at 06:08:57PM +0200, Sydney Shall wrote:
>> 
>>> 
>> 
>> (I haven't tested that code myself, so please try it, and if it doesn't
>> work for some reason, let us know on the mailing list and somebody can
>> fix it.)
>> 
>> But... I'm rather surprised that you need this test. Are you sure that
>> your array capitalsadvanced will *always* contain at least one Not A
>> Number value? Unless you put one in yourself, NANs generally indicate
>> that a mathematical error has occurred somewhere.
>> 
> 
> Steven,
> 
> Thanks again.
> 
> I started this precisely because I also thought and still think, that
> the origin of my problem is a mathematical error somewhere.
> 
> However, when I use predetermined input values, the errors are absent.
> They only appear when I use the random function. Although it should not
> be the case, I wondered whether the random function was feeding in a
> zero, because the errors seem to involve an invalid value after a
> true-divide according to some of the error reports earlier. So, my first
> step was to try and see if there are any zeros in the array that is used
> first. The tests say that the type and the length of the array is
> correct. But how do I test for a zero in a numpy.ndarray?

(a == 0).any()

But dividing by 0 should give you inf, not nan:

>>> import numpy
>>> a = numpy.arange(5)
>>> b = 1 / a
__main__:1: RuntimeWarning: divide by zero encountered in true_divide
>>> b
array([        inf,  1.        ,  0.5       ,  0.33333333,  0.25      ])

Can you show a bit more of the relevant code, a toy script that shows the 
problematic behaviour perhaps? That might reduce the need for speculation.


From mats at wichmann.us  Wed Jul 19 14:26:18 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Wed, 19 Jul 2017 12:26:18 -0600
Subject: [Tutor] unitest with random inputs
In-Reply-To: <e17f11db-984a-0904-29cf-e27f4bb1ded5@virginmedia.com>
References: <04d8aedd-0677-a6d1-efb3-864a4d467b58@virginmedia.com>
 <20170719164216.GF3149@ando.pearwood.info>
 <e17f11db-984a-0904-29cf-e27f4bb1ded5@virginmedia.com>
Message-ID: <00d936a2-c4bf-3120-3777-a82428d33a16@wichmann.us>

On 07/19/2017 10:55 AM, Sydney Shall wrote:
> On 19/07/2017 18:42, Steven D'Aprano wrote:
>> On Wed, Jul 19, 2017 at 05:01:53PM +0200, Sydney Shall wrote:
>>
>> [...]
>>>   def test_zero_in_capitalsadvanced(self):
>>>          self.assertIn(self.capitalsadvanced, 0.0)
>>>
>>> The error message is:
>>>
>>> Traceback (most recent call last):
>> [...]
>>> in assertIn
>>>      if member not in container:
>>> TypeError: argument of type 'float' is not iterable
>>
>> You are trying to test whether capitalsadvanced is in 0.0. Reverse the
>> arguments:
>>
>>          self.assertIn(0.0, self.capitalsadvanced)
>>
>> which will test whether 0.0 is in self.capitalsadvanced.
>>
>>
>>> FAILED (failures=9, errors=1)
>>>
>>> The failures all arise from a 'nan'.
>>> It is this problem that I am trying to resolve.
>>
>> Well, since you don't show us what those failing tests are, we cannot
>> possibly tell you how to fix them.
>>
>> Start by showing us *one* failing test, and what the failure is.
>>
>>
> Thank you Steve.
> 
> The remaining 'nan' problems are shown below.
> 
> runfile('/Users/sydney/Capital/Capital_with_productivity/Current_Versions/testPOCWP_V2.py',
> wdir='/Users/sydney/Capital/Capital_with_productivity/Current_Versions')
> /Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:1582:
> RuntimeWarning: invalid value encountered in true_divide


The thing to remember is that NaN is actually... _not_ a number,
literally.  If you like to think in terms of exceptions, then NaN is lan
exception - some thing caused a result which cannot be represented as a
number, and so this magical value is used to tell you.  Thus, no numeric
operations can be done on it.  This is not from Python... this is the
way it was defined in the IEEE standard (754 if memory serves), Python
just tries to implement the requirements of that standard as best it
can.  (turns out Python actually has two flavors: a quiet NaN, and a
signaling NaN).

sorry there wasn't much Python content in this message :)





From japhy at pearachute.com  Wed Jul 19 13:34:55 2017
From: japhy at pearachute.com (Japhy Bartlett)
Date: Wed, 19 Jul 2017 13:34:55 -0400
Subject: [Tutor] unittest difficulty
In-Reply-To: <d6e3a140-efad-6dc2-be10-7db9c3f35963@kcl.ac.uk>
References: <d6e3a140-efad-6dc2-be10-7db9c3f35963@kcl.ac.uk>
Message-ID: <CANTsVHJcFygo1NeBXQFi49CtYPcm_8BOu9XowJs4WKucWwd1kQ@mail.gmail.com>

Is `0.0` the troublesome float here?




On Wed, Jul 19, 2017 at 7:35 AM, Shall, Sydney <sydney.shall at kcl.ac.uk>
wrote:

> I am learning to use unittest.
>
> I have written a program that runs as it should.
> 247 tests give me a satisfactory answer.
>
> I have now added one more test and I get an error which I do not
> understand.
>
> The two relevant tests are:
>
>  def test_type_capitalsadvanced(self):
>         self.assertEqual(type(self.capitalsadvanced), numpy.ndarray)
>
>  def test_zero_in_capitalsadvanced(self):
>         self.assertIn(self.capitalsadvanced, 0.0)
>
> The error message is:
>
> Traceback (most recent call last):
>   File "/Users/sydney/Capital/Capital_with_productivity/Current_Versions/testPOCWP_V2.py",
> line 320, in test_zero_in_capitalsadvanced
>     self.assertIn(self.capitalsadvanced, 0.0)
>   File "/Users/sydney/anaconda/lib/python3.6/unittest/case.py", line
> 1077, in assertIn
>     if member not in container:
> TypeError: argument of type 'float' is not iterable
>
> Final output from the tests is :
>
> Ran 247 tests in 1.179s
>
> FAILED (failures=9, errors=1)
>
> The failures all arise from a 'nan'.
> It is this problem that I am trying to resolve.
>
> My problem is that the first test tells me correctly that the object
> capitalsadvanced is a numpy.ndarray. But the second test error message says
> it is a float.
>
> I should add that the program creates the initial data set by making use
> of the random function which is given a mean to work with. Thus each test
> run will be with different input data. But repeated tests show the same
> errors.
>
> Any guidance will be very welcome.
>
> Sydney
>
> _________
>
> Professor Sydney Shall
> Department of Haematology/Oncology
> Phone: +(0)2078489200
> E-Mail: sydney.shall
> [Correspondents outside the College should add @kcl.ac.uk]
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From badouglas at gmail.com  Wed Jul 19 16:48:17 2017
From: badouglas at gmail.com (bruce)
Date: Wed, 19 Jul 2017 16:48:17 -0400
Subject: [Tutor] centos 7 - new setup.. weird python!
Message-ID: <CAP16ngpbhQbCUS=M1e4ZLM_QeokRvW+B2CL39XbywB_owr-msA@mail.gmail.com>

Hi.

Testing setting up a new Cnntos7 instance.

I ran python -v from the cmdline...  and instantly got a bunch of the
following! Pretty sure this isn't correct.

Anyone able to give pointers as to what I've missed.

thanks

python -v
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# /usr/lib64/python2.7/site.pyc matches /usr/lib64/python2.7/site.py
import site # precompiled from /usr/lib64/python2.7/site.pyc
# /usr/lib64/python2.7/os.pyc matches /usr/lib64/python2.7/os.py
import os # precompiled from /usr/lib64/python2.7/os.pyc
.
.
.

From dbosah at buffalo.edu  Wed Jul 19 15:58:49 2017
From: dbosah at buffalo.edu (Daniel Bosah)
Date: Wed, 19 Jul 2017 15:58:49 -0400
Subject: [Tutor] Problems with pytz module
Message-ID: <CAFSTFyW1O-mWZkW54tUv_ao6KLB2w7zJsFRVbmMHDE_SZycpfw@mail.gmail.com>

I'm learning about OOP programming in Python.
This is my code from my online course.

import datetime
import pytz
class Account:
    """""""Simple account class with balance"""""""
    def __init__(self,name,balance):
        self.name = name
        self.balance = balance
        self.transaction_list = []
        print "Account created for " + self.name

    def deposit(self,amount):
        if amount > 0:
            self.balance += amount
            self.show_balance()

self.transaction_list.append((pytz.utc.localize(datetime.datetime.utcnow()),amount))
# appends traction details to list

    def withdrawl(self,amount):
         if 0 < amount <= self.balance:
                self.balance -= amount
         else:
            print "The account must be greater then zero and no more then
your account balance"
         self.show_balance()

    def show_balance(self):
        print "Balance is {}".format(self.balance)

    def show_transactions(self):
        for date, amount in self.transaction_list:
            if amount > 0:
                tran_type = "deposited"
            else:
                tran_type = "withdrawn"
                amount *= -1 # to show negative number
                print "{:6} {} on {} (local time was {})".format(amount,
tran_type, date, date.astimezone())

if __name__ == '__main__':
    tim = Account("Tim", 0)
    tim.show_balance()


    tim.deposit(1000)
    tim.show_balance()
    tim.withdrawl(500)
    tim.show_transactions()

    tim.show_balance()



Im using Ubuntu Linux. My problem is that I cannot get show_transactions to
print out on the console. I suspect that I cannot use pytz ( as I'm using
Python 2.7) . Im trying to get the date and time of the transaction (as
shown on this line -

print "{:6} {} on {} (local time was {})".format(amount, tran_type, date,
date.astimezone())

But it will. Is there a workaround for pytz, or another problem that I am
missing?

From zachary.ware+pytut at gmail.com  Wed Jul 19 16:58:10 2017
From: zachary.ware+pytut at gmail.com (Zachary Ware)
Date: Wed, 19 Jul 2017 15:58:10 -0500
Subject: [Tutor] centos 7 - new setup.. weird python!
In-Reply-To: <CAP16ngpbhQbCUS=M1e4ZLM_QeokRvW+B2CL39XbywB_owr-msA@mail.gmail.com>
References: <CAP16ngpbhQbCUS=M1e4ZLM_QeokRvW+B2CL39XbywB_owr-msA@mail.gmail.com>
Message-ID: <CAKJDb-OgW92TJBaW_k8f3bOd0FQGp4dpk0VFnf-H8oq8cYCHyw@mail.gmail.com>

On Wed, Jul 19, 2017 at 3:48 PM, bruce <badouglas at gmail.com> wrote:
> Hi.

Hi Bruce,

>
> Testing setting up a new Cnntos7 instance.
>
> I ran python -v from the cmdline...  and instantly got a bunch of the
> following! Pretty sure this isn't correct.
>
> Anyone able to give pointers as to what I've missed.
>
> thanks
>
> python -v
> # installing zipimport hook
> import zipimport # builtin
> # installed zipimport hook
> # /usr/lib64/python2.7/site.pyc matches /usr/lib64/python2.7/site.py
> import site # precompiled from /usr/lib64/python2.7/site.pyc
> # /usr/lib64/python2.7/os.pyc matches /usr/lib64/python2.7/os.py
> import os # precompiled from /usr/lib64/python2.7/os.pyc

This is correct: this is python's "verbose" mode, which prints out
some debugging information, like imports and module cleanup.  I think
you were looking for the `-V` or `--version` flag.

-- 
Zach

From mats at wichmann.us  Wed Jul 19 17:01:57 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Wed, 19 Jul 2017 15:01:57 -0600
Subject: [Tutor] centos 7 - new setup.. weird python!
In-Reply-To: <CAP16ngpbhQbCUS=M1e4ZLM_QeokRvW+B2CL39XbywB_owr-msA@mail.gmail.com>
References: <CAP16ngpbhQbCUS=M1e4ZLM_QeokRvW+B2CL39XbywB_owr-msA@mail.gmail.com>
Message-ID: <5bc8dac9-8d78-1ac8-edba-96ee84a106ab@wichmann.us>

On 07/19/2017 02:48 PM, bruce wrote:
> Hi.
> 
> Testing setting up a new Cnntos7 instance.
> 
> I ran python -v from the cmdline...  and instantly got a bunch of the
> following! Pretty sure this isn't correct.
> 
> Anyone able to give pointers as to what I've missed.

It is expected, actually. You perhaps intended a capital v.  The
lowercase one means this:

       -v     Print  a  message each time a module is initialized,
showing the
              place (filename or built-in module) from  which  it  is
loaded.
              When  given twice, print a message for each file that is
checked
              for when searching for a module.  Also provides
information  on
              module cleanup at exit.


so you asked it to tell you  what it was doing in extra detail, and it
did :)

> 
> thanks
> 
> python -v
> # installing zipimport hook
> import zipimport # builtin
> # installed zipimport hook
> # /usr/lib64/python2.7/site.pyc matches /usr/lib64/python2.7/site.py
> import site # precompiled from /usr/lib64/python2.7/site.pyc
> # /usr/lib64/python2.7/os.pyc matches /usr/lib64/python2.7/os.py
> import os # precompiled from /usr/lib64/python2.7/os.pyc
> .
> .
> .
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 


From __peter__ at web.de  Wed Jul 19 17:51:59 2017
From: __peter__ at web.de (Peter Otten)
Date: Wed, 19 Jul 2017 23:51:59 +0200
Subject: [Tutor] Problems with pytz module
References: <CAFSTFyW1O-mWZkW54tUv_ao6KLB2w7zJsFRVbmMHDE_SZycpfw@mail.gmail.com>
Message-ID: <okok9t$rch$1@blaine.gmane.org>

Daniel Bosah wrote:

> I'm learning about OOP programming in Python.
> This is my code from my online course.
> 
> import datetime
> import pytz
> class Account:
>     """""""Simple account class with balance"""""""

Why so many "s ? Use either one for single-line strings

"Simple account class with balance."

or three for multiline strings

"""Simple account class with balance.
   yadda yadda...
"""


>     def __init__(self,name,balance):
>         self.name = name
>         self.balance = balance
>         self.transaction_list = []
>         print "Account created for " + self.name
> 
>     def deposit(self,amount):
>         if amount > 0:
>             self.balance += amount
>             self.show_balance()
> 
> 
self.transaction_list.append((pytz.utc.localize(datetime.datetime.utcnow()),amount))
> # appends traction details to list

That's either an indentation error in your code or a cut-and-past mishap.

>     def withdrawl(self,amount):
>          if 0 < amount <= self.balance:
>                 self.balance -= amount
>          else:
>             print "The account must be greater then zero and no more then
> your account balance"
>          self.show_balance()

Looks like you don't add anything to the transaction_list for withdrawals.

>     def show_balance(self):
>         print "Balance is {}".format(self.balance)
> 
>     def show_transactions(self):
>         for date, amount in self.transaction_list:
>             if amount > 0:
>                 tran_type = "deposited"
>             else:
>                 tran_type = "withdrawn"
>                 amount *= -1 # to show negative number
>                 print "{:6} {} on {} (local time was {})".format(amount,
> tran_type, date, date.astimezone())

Do you want to print only when money is withdrawn?

> 
> if __name__ == '__main__':
>     tim = Account("Tim", 0)
>     tim.show_balance()
> 
> 
>     tim.deposit(1000)
>     tim.show_balance()
>     tim.withdrawl(500)
>     tim.show_transactions()
> 
>     tim.show_balance()
> 
> 
> 
> Im using Ubuntu Linux. My problem is that I cannot get show_transactions
> to print out on the console. I suspect that I cannot use pytz ( as I'm
> using Python 2.7) . Im trying to get the date and time of the transaction
> (as shown on this line -
> 
> print "{:6} {} on {} (local time was {})".format(amount, tran_type, date,
> date.astimezone())
> 
> But it will. Is there a workaround for pytz, or another problem that I am
> missing?

Read the error message and traceback carefully (and remember to provide it 
in your post). It usually has important clues that help you (or us) fix what 
went wrong.

Now I recommend that you forget about the Account class for the moment, fire 
up the interactive interpreter and play around with datetime and pytz 
a bit. Once you have working building blocks you can go back and easily 
apply the lessons you learned from your experiments to the original problem. 
Spoiler below:



























>>> import datetime
>>> import pytz
>>> t = pytz.utc.localize(datetime.datetime.utcnow())
>>> t
datetime.datetime(2017, 7, 19, 21, 34, 40, 117522, tzinfo=<UTC>)
>>> t.astimezone()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Required argument 'tz' (pos 1) not found
>>> t.astimezone(pytz.timezone("MET"))
datetime.datetime(2017, 7, 19, 23, 34, 40, 117522, tzinfo=<DstTzInfo 'MET' 
MEST+2:00:00 DST>)

See? To convert to a timezone you have to actually specify the timezone you 
want.



From __peter__ at web.de  Wed Jul 19 18:05:32 2017
From: __peter__ at web.de (Peter Otten)
Date: Thu, 20 Jul 2017 00:05:32 +0200
Subject: [Tutor] Problems with pytz module
References: <CAFSTFyW1O-mWZkW54tUv_ao6KLB2w7zJsFRVbmMHDE_SZycpfw@mail.gmail.com>
Message-ID: <okol39$m6a$1@blaine.gmane.org>

Daniel Bosah wrote:

> I'm learning about OOP programming in Python.
> This is my code from my online course.
> 
> import datetime
> import pytz
> class Account:
>     """""""Simple account class with balance"""""""

Why so many "s ? Use either one for single-line strings

"Simple account class with balance"

or three for multiline strings

"""Simple account class with balance.
   yadda yadda...
"""


>     def __init__(self,name,balance):
>         self.name = name
>         self.balance = balance
>         self.transaction_list = []
>         print "Account created for " + self.name
> 
>     def deposit(self,amount):
>         if amount > 0:
>             self.balance += amount
>             self.show_balance()
> 
> 
self.transaction_list.append((pytz.utc.localize(datetime.datetime.utcnow()),amount))
> # appends traction details to list

That's either an indentation error in your code or a cut-and-past mishap.

>     def withdrawl(self,amount):
>          if 0 < amount <= self.balance:
>                 self.balance -= amount
>          else:
>             print "The account must be greater then zero and no more then
> your account balance"
>          self.show_balance()

Nothing is added to the transaction_list for withdrawals.

>     def show_balance(self):
>         print "Balance is {}".format(self.balance)
> 
>     def show_transactions(self):
>         for date, amount in self.transaction_list:
>             if amount > 0:
>                 tran_type = "deposited"
>             else:
>                 tran_type = "withdrawn"
>                 amount *= -1 # to show negative number
>                 print "{:6} {} on {} (local time was {})".format(amount,
> tran_type, date, date.astimezone())

This prints only "withdrawn" transactions.

> 
> if __name__ == '__main__':
>     tim = Account("Tim", 0)
>     tim.show_balance()
> 
> 
>     tim.deposit(1000)
>     tim.show_balance()
>     tim.withdrawl(500)
>     tim.show_transactions()
> 
>     tim.show_balance()
> 
> 
> 
> Im using Ubuntu Linux. My problem is that I cannot get show_transactions
> to print out on the console. I suspect that I cannot use pytz ( as I'm
> using Python 2.7) . Im trying to get the date and time of the transaction
> (as shown on this line -
> 
> print "{:6} {} on {} (local time was {})".format(amount, tran_type, date,
> date.astimezone())
> 
> But it will. Is there a workaround for pytz, or another problem that I am
> missing?

First read the error message and the traceback carefully (and remember to 
always include it in your posts here). They usually contain clues that make 
it much easier for you (or us) to fix what went wrong.

Then I recommend that you forget about the Account class for the moment, 
fire up the interactive interpreter and play around with the datetime and 
pytz module a bit. Once you have that part working on its own you can take 
the building blocks and put them back into your Account class.
Spoiler below:















>>> import datetime
>>> import pytz
>>> t = pytz.utc.localize(datetime.datetime.utcnow())
>>> t
datetime.datetime(2017, 7, 19, 21, 34, 40, 117522, tzinfo=<UTC>)
>>> t.astimezone()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Required argument 'tz' (pos 1) not found
>>> t.astimezone(pytz.timezone("MET"))
datetime.datetime(2017, 7, 19, 23, 34, 40, 117522, tzinfo=<DstTzInfo 'MET' 
MEST+2:00:00 DST>)

See? To convert to a timezone you have to specify which timezone you 
actually want.


From alan.gauld at yahoo.co.uk  Wed Jul 19 18:52:01 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 19 Jul 2017 23:52:01 +0100
Subject: [Tutor] Problems with pytz module
In-Reply-To: <CAFSTFyW1O-mWZkW54tUv_ao6KLB2w7zJsFRVbmMHDE_SZycpfw@mail.gmail.com>
References: <CAFSTFyW1O-mWZkW54tUv_ao6KLB2w7zJsFRVbmMHDE_SZycpfw@mail.gmail.com>
Message-ID: <okonqc$krc$1@blaine.gmane.org>

On 19/07/17 20:58, Daniel Bosah wrote:

> class Account:
>     def deposit(self,amount):
>         if amount > 0:
>             self.balance += amount
>             self.show_balance()
> 
> self.transaction_list.append(....

>     def withdrawl(self,amount):
>          if 0 < amount <= self.balance:
>                 self.balance -= amount
>          else:
>             print "The account must be greater then zero and no more then
> your account balance"
>          self.show_balance()

Ignoring the indentation issue, you only write transactions for
deposits. nothing for withdrawals.

>     def show_transactions(self):
>         for date, amount in self.transaction_list:
>             if amount > 0:
>                 tran_type = "deposited"
>             else:
>                 tran_type = "withdrawn"
>                 amount *= -1 # to show negative number
>                 print "{:6} {} on {} (local time was {})".format(amount,

But here you only print for withdrawals but not for deposits.

So you try to print non existent transactions.

> Im using Ubuntu Linux. My problem is that I cannot get show_transactions to
> print out on the console.

Since there shouldn't be any that match that's not surprising.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From mats at wichmann.us  Wed Jul 19 19:40:00 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Wed, 19 Jul 2017 17:40:00 -0600
Subject: [Tutor] Problems with pytz module
In-Reply-To: <okonqc$krc$1@blaine.gmane.org>
References: <CAFSTFyW1O-mWZkW54tUv_ao6KLB2w7zJsFRVbmMHDE_SZycpfw@mail.gmail.com>
 <okonqc$krc$1@blaine.gmane.org>
Message-ID: <e26f1c4c-134d-459d-50fe-f6ee884b2034@wichmann.us>

> On 19/07/17 20:58, Daniel Bosah wrote:

don't see a lot of benefit to using pytz here... just my opinion.  the
question does give a chance to annotate the example with some thoughts,
though; take them for what they're worth.

import datetime
import pytz

class Account:
    """Simple account class with balance"""
    # 1. if you set up balance param with a default value, you can skip
    #    the argument if account is created with no balance
    #def __init__(self, name, balance):
    def __init__(self, name, balance=0):
        self.name = name
        self.balance = balance
        self.transaction_list = []
        # 2. seems to make sense to report initial balance
        #print "Account created for " + self.name
        print "Account created for " + self.name + ", initial balance" +
balance

    def deposit(self,amount):
        # 3. to avoid cascading indents, bail on "not applicable",
        #    rather than indenting a whole function behind "applicable"
        #if amount > 0:
        if amount <= 0:
            # 4. do you want to indicate this call was a problem somehow?
            return

        self.balance += amount
        # 5. it is not very interesting to just dump a balance.
        #    Either add indication it's a deposit/withdrawal and amount,
        #    or just omit, leaving caller to print balance if they want.
        #self.show_balance()
        # 6. the pytz part is just adding confusion. In the log, store the
        #    utc time.
        # 7. suggest put the simpler/more important value first in the
log entry

#self.transaction_list.append((pytz.utc.localize(datetime.datetime.utcnow()),
amount))
        # appends traction details to list
        self.transaction_list.append((amount, datetime.datetime.utcnow()))

    def withdrawl(self, amount):
        if 0 < amount <= self.balance:
            self.balance -= amount
        else:
            print "The account must be greater then zero and no more
then your account balance"
        #self.show_balance()
        # 8. record a transaction on withdraw as well. Make it negative
        #    as show_transactions method triggers on that.
        self.transaction_list.append((-amount, datetime.datetime.utcnow()))

    def show_balance(self):
        print "Balance is {}".format(self.balance)

    def show_transactions(self):
        # 9. Presumably translog print is rare, let's say what we're doing
        print "Transaction log:"
        # after note #7, unpack in other order
        #for date, amount in self.transaction_list:
        for amount, date in self.transaction_list:
            if amount > 0:
                tran_type = "deposited"
            else:
                tran_type = "withdrawn"
                amount *= -1 # to show negative number
            # 10. Assuming you wanted to print in either case, change indent
            #     print "{:6} {} on {} (local time was
{})".format(amount, tran_type, date, date.astimezone())
            print "{:6} {} on {} UTC".format(amount, tran_type, date)
            # can add timezone-relative display back in if you wish

if __name__ == '__main__':
    # after note #1, can leave out a zero initial balance
    #tim = Account("Tim", 0)
    tim = Account("Tim")
    tim.show_balance()


    tim.deposit(1000)
    tim.show_balance()
    tim.withdrawl(500)
    tim.show_transactions()

    tim.show_balance()


From dbosah at buffalo.edu  Thu Jul 20 13:41:11 2017
From: dbosah at buffalo.edu (Daniel Bosah)
Date: Thu, 20 Jul 2017 13:41:11 -0400
Subject: [Tutor] PYTZ Package not working.
Message-ID: <CAFSTFyU_v_z5X_1=s_V5z0KuaXtBnb7zWDmT_iYoPkJnX5U9PQ@mail.gmail.com>

I'm trying to get my function to work:

 def deposit(self,amount):
        if amount > 0:
            self.balance += amount
            self.show_balance()
            self.transaction_list.append((pytz.utc.localize(datetime.datetime.utcnow()),amount))
# appends traction details to list

    def show_transactions(self):
        for date, amount in self.transaction_list:
            if amount > 0:
                tran_type = "deposited"
            else:
                tran_type = "withdrawn"
                amount *= -1 # to show negative number
                print "{:6} {} on {} (local time was {})".format(amount,
tran_type, date, date.astimezone())


But it doens't show on the console at all. Theres no error message,
show_transactions just doesn't show up in the console, which is weird. I
think it may be the way I installed my package, but last time I checked,
it's installed in the right place.

From alan.gauld at yahoo.co.uk  Thu Jul 20 20:07:09 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 21 Jul 2017 01:07:09 +0100
Subject: [Tutor] PYTZ Package not working.
In-Reply-To: <CAFSTFyU_v_z5X_1=s_V5z0KuaXtBnb7zWDmT_iYoPkJnX5U9PQ@mail.gmail.com>
References: <CAFSTFyU_v_z5X_1=s_V5z0KuaXtBnb7zWDmT_iYoPkJnX5U9PQ@mail.gmail.com>
Message-ID: <okrgj7$a7t$1@blaine.gmane.org>

On 20/07/17 18:41, Daniel Bosah wrote:
> I'm trying to get my function to work:

Did you read any of the replies to your previous message?

You do not appear to have applied any of the suggestions.

>  def deposit(self,amount):
>         if amount > 0:
>             self.balance += amount
>             self.show_balance()
>             self.transaction_list.append((pytz.utc.localize(datetime.datetime.utcnow()),amount))
> # appends traction details to list
> 
>     def show_transactions(self):
>         for date, amount in self.transaction_list:
>             if amount > 0:
>                 tran_type = "deposited"
>             else:
>                 tran_type = "withdrawn"
>                 amount *= -1 # to show negative number
>                 print "{:6} {} on {} (local time was {})".format(amount,
> tran_type, date, date.astimezone())


But you are showing us less code...

-- 
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 arj.python at gmail.com  Sat Jul 22 07:20:19 2017
From: arj.python at gmail.com (Abdur-Rahmaan Janhangeer)
Date: Sat, 22 Jul 2017 15:20:19 +0400
Subject: [Tutor] Quick Pythonic Style Tips
In-Reply-To: <CADrxXXkZeQknyv6=uuf0S-9n9LrBNqyCVx2HE3+d9FyTuP464A@mail.gmail.com>
References: <CADrxXXmFS0iHWz2nr40MUaVoYqG_P3VHjm22ueCQ2Wm9-LxpvQ@mail.gmail.com>
 <CADrxXXkaxZ-bVBaDTo-4xVKF2+R6ZZrNHjzHqT7Y=xTJd-0=ag@mail.gmail.com>
 <CADrxXXk5iObs5JUOAu73HRQJUTAgd8EeP+pXiKqy+VrYk-_=7Q@mail.gmail.com>
 <CADrxXXnGysC0afCpDHYXnGyhsfTtYGYtr8JeU5A2FrieBZtM=g@mail.gmail.com>
 <CADrxXX=d9TYNq=2PHf40dYX9AELbpSLR12jPiO39=bGXA0SbHA@mail.gmail.com>
 <CADrxXXmg5U8-ZzOc4B+3bHjmdUZS225URDWaTm0QsMmpL6N0LQ@mail.gmail.com>
 <CADrxXX=1kWEq946HyUe-B8X9+sKGz10zp6QO8kJ7RzFuTunTdw@mail.gmail.com>
 <CADrxXXnNo2doX9BMnMYzFkGrLL4r1CgSmS2X74vTw8TUs6+Scw@mail.gmail.com>
 <CADrxXXmuRjBKrm7S1VtG9Z0+a-KEKBfXuskxxH1JZ1o6ryMCxw@mail.gmail.com>
 <CADrxXX=WcvOUq-Me_myFftN67=vQYRXn=4Ap9wtpzs9emc_FHg@mail.gmail.com>
 <CADrxXXkdN3Y_ugaaeTYpUWrzPW5PQ_iL79R=YtK-Rm4TPGBOEQ@mail.gmail.com>
 <CADrxXXngz2uvf_ETbmxoX62yMOrhfpaNy2Cr5j=EhPVbA+4D+g@mail.gmail.com>
 <CADrxXXkZeQknyv6=uuf0S-9n9LrBNqyCVx2HE3+d9FyTuP464A@mail.gmail.com>
Message-ID: <CADrxXX=MCSK=UBS_YcEF+Te3Zz-dc+5wBQ92YaD0XYzAWFU8NQ@mail.gmail.com>

Hi all,

As a user switching between some languages, it took sometimes before i
discovered that there was a styling guide in python (obviously from not so
kind users when asking on forums). as i did not learnt python as first
lang, i learnt only the syntax (no need to relearn concepts)

besides some tips here and there i heard of the PEP8 etc. nice very nice.

i'll outline some styling guide which striked me :

use CAPS to declare constant variables
use plurals for many : ex. names =[ ]
the 89 char limit ...

i'd like to know if there was a specific C++ or java style of doing things
which should be avoided ?

thanks in advance,

Abdur-Rahmaan Janhangeer,
Mauritius
abdurrahmaanjanhangeer.wordpress.com

From alan.gauld at yahoo.co.uk  Sat Jul 22 09:46:26 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 22 Jul 2017 14:46:26 +0100
Subject: [Tutor] Quick Pythonic Style Tips
In-Reply-To: <CADrxXX=MCSK=UBS_YcEF+Te3Zz-dc+5wBQ92YaD0XYzAWFU8NQ@mail.gmail.com>
References: <CADrxXXmFS0iHWz2nr40MUaVoYqG_P3VHjm22ueCQ2Wm9-LxpvQ@mail.gmail.com>
 <CADrxXXkaxZ-bVBaDTo-4xVKF2+R6ZZrNHjzHqT7Y=xTJd-0=ag@mail.gmail.com>
 <CADrxXXk5iObs5JUOAu73HRQJUTAgd8EeP+pXiKqy+VrYk-_=7Q@mail.gmail.com>
 <CADrxXXnGysC0afCpDHYXnGyhsfTtYGYtr8JeU5A2FrieBZtM=g@mail.gmail.com>
 <CADrxXX=d9TYNq=2PHf40dYX9AELbpSLR12jPiO39=bGXA0SbHA@mail.gmail.com>
 <CADrxXXmg5U8-ZzOc4B+3bHjmdUZS225URDWaTm0QsMmpL6N0LQ@mail.gmail.com>
 <CADrxXX=1kWEq946HyUe-B8X9+sKGz10zp6QO8kJ7RzFuTunTdw@mail.gmail.com>
 <CADrxXXnNo2doX9BMnMYzFkGrLL4r1CgSmS2X74vTw8TUs6+Scw@mail.gmail.com>
 <CADrxXXmuRjBKrm7S1VtG9Z0+a-KEKBfXuskxxH1JZ1o6ryMCxw@mail.gmail.com>
 <CADrxXX=WcvOUq-Me_myFftN67=vQYRXn=4Ap9wtpzs9emc_FHg@mail.gmail.com>
 <CADrxXXkdN3Y_ugaaeTYpUWrzPW5PQ_iL79R=YtK-Rm4TPGBOEQ@mail.gmail.com>
 <CADrxXXngz2uvf_ETbmxoX62yMOrhfpaNy2Cr5j=EhPVbA+4D+g@mail.gmail.com>
 <CADrxXXkZeQknyv6=uuf0S-9n9LrBNqyCVx2HE3+d9FyTuP464A@mail.gmail.com>
 <CADrxXX=MCSK=UBS_YcEF+Te3Zz-dc+5wBQ92YaD0XYzAWFU8NQ@mail.gmail.com>
Message-ID: <okvkvc$cal$1@blaine.gmane.org>

On 22/07/17 12:20, Abdur-Rahmaan Janhangeer wrote:

> As a user switching between some languages, it took sometimes before i
> discovered that there was a styling guide in python

There are style idioms in most languages although not always
written down as clearly as in PEP8. That having been said
they should be viewed as guides not rules. In addition there
are often local style guides that must be followed in
a particular company.

> i'd like to know if there was a specific C++ or java> style of doing things which should be avoided ?

Mostly it's not layout style things that should be avoided
but actual programming styles - such as using Java style
getXXX/setXXX type methods for attribute access. Or getting
overly hung-up on trying to make data "private".

Some people get excited about naming (xxx_yyy v xxxYyy v XxxYyy)
but in practice these things make very little difference in
comprehensibility of code, which is the most important
consideration. Much more important is clarity of intent
in naming (such as the plurals-for-collections rule you
mentioned, or not using types as names - eg. anInt - unless
it truly is a completely generic place-holder).

The exception to all of this is code submitted to the
standard library. It really should have PEP8 applied
fairly rigorously both for the sake of consistency and
because the library is often cited as a style template.

-- 
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  Sat Jul 22 10:57:36 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Sat, 22 Jul 2017 08:57:36 -0600
Subject: [Tutor] Quick Pythonic Style Tips
In-Reply-To: <okvkvc$cal$1@blaine.gmane.org>
References: <CADrxXXmFS0iHWz2nr40MUaVoYqG_P3VHjm22ueCQ2Wm9-LxpvQ@mail.gmail.com>
 <CADrxXXk5iObs5JUOAu73HRQJUTAgd8EeP+pXiKqy+VrYk-_=7Q@mail.gmail.com>
 <CADrxXXnGysC0afCpDHYXnGyhsfTtYGYtr8JeU5A2FrieBZtM=g@mail.gmail.com>
 <CADrxXX=d9TYNq=2PHf40dYX9AELbpSLR12jPiO39=bGXA0SbHA@mail.gmail.com>
 <CADrxXXmg5U8-ZzOc4B+3bHjmdUZS225URDWaTm0QsMmpL6N0LQ@mail.gmail.com>
 <CADrxXX=1kWEq946HyUe-B8X9+sKGz10zp6QO8kJ7RzFuTunTdw@mail.gmail.com>
 <CADrxXXnNo2doX9BMnMYzFkGrLL4r1CgSmS2X74vTw8TUs6+Scw@mail.gmail.com>
 <CADrxXXmuRjBKrm7S1VtG9Z0+a-KEKBfXuskxxH1JZ1o6ryMCxw@mail.gmail.com>
 <CADrxXX=WcvOUq-Me_myFftN67=vQYRXn=4Ap9wtpzs9emc_FHg@mail.gmail.com>
 <CADrxXXkdN3Y_ugaaeTYpUWrzPW5PQ_iL79R=YtK-Rm4TPGBOEQ@mail.gmail.com>
 <CADrxXXngz2uvf_ETbmxoX62yMOrhfpaNy2Cr5j=EhPVbA+4D+g@mail.gmail.com>
 <CADrxXXkZeQknyv6=uuf0S-9n9LrBNqyCVx2HE3+d9FyTuP464A@mail.gmail.com>
 <CADrxXX=MCSK=UBS_YcEF+Te3Zz-dc+5wBQ92YaD0XYzAWFU8NQ@mail.gmail.com>
 <okvkvc$cal$1@blaine.gmane.org>
Message-ID: <bfe5b37b-101a-378a-b7be-cec867dd8c39@wichmann.us>

On 07/22/2017 07:46 AM, Alan Gauld via Tutor wrote:
> On 22/07/17 12:20, Abdur-Rahmaan Janhangeer wrote:
> 
>> As a user switching between some languages, it took sometimes before i
>> discovered that there was a styling guide in python
> 
> There are style idioms in most languages although not always
> written down as clearly as in PEP8. That having been said
> they should be viewed as guides not rules. In addition there
> are often local style guides that must be followed in
> a particular company.
> 
>> i'd like to know if there was a specific C++ or java> style of doing things which should be avoided ?

I'd like to contibute a rather different sort of tidbit to what Alan
wrote: be really careful about using mutable data types in function
calls, as class variables, and just in general.  Here's a quick example
of a classic "trap":

# append value to list, if list omitted return a new list
def func(val, alist=[]):
    alist.append(val)
    print alist
    return alist

func(1)
func(2)
func(3)

pop quiz :)  what is the output?

C++ has default arguments as well, so the output might be surprising in
that context:

[1]
[1, 2]
[1, 2, 3]

Instead of you getting a new empty list each time 'func' is called
without a second argument, the default list is part of the function.
Python runs the function code when it comes across it, creating a
function object which is then used each time the function is called, so
this initially empty list is reused each time.

To move the instantiation of the list to run-time, you could recode like
this:

def func(val, alist=None):
    if not alist:
        alist = []
    alist.append(val)
    print alist
    return alist

func(1)
func(2)
func(3)


This is really a bit of "Python style" (using None as the default to act
as a flag to do something special) that may not be reflected in the code
format parts of style guides.



From dyoo at hashcollision.org  Sat Jul 22 17:59:26 2017
From: dyoo at hashcollision.org (Danny Yoo)
Date: Sat, 22 Jul 2017 14:59:26 -0700
Subject: [Tutor] Quick Pythonic Style Tips
In-Reply-To: <bfe5b37b-101a-378a-b7be-cec867dd8c39@wichmann.us>
References: <CADrxXXmFS0iHWz2nr40MUaVoYqG_P3VHjm22ueCQ2Wm9-LxpvQ@mail.gmail.com>
 <CADrxXXk5iObs5JUOAu73HRQJUTAgd8EeP+pXiKqy+VrYk-_=7Q@mail.gmail.com>
 <CADrxXXnGysC0afCpDHYXnGyhsfTtYGYtr8JeU5A2FrieBZtM=g@mail.gmail.com>
 <CADrxXX=d9TYNq=2PHf40dYX9AELbpSLR12jPiO39=bGXA0SbHA@mail.gmail.com>
 <CADrxXXmg5U8-ZzOc4B+3bHjmdUZS225URDWaTm0QsMmpL6N0LQ@mail.gmail.com>
 <CADrxXX=1kWEq946HyUe-B8X9+sKGz10zp6QO8kJ7RzFuTunTdw@mail.gmail.com>
 <CADrxXXnNo2doX9BMnMYzFkGrLL4r1CgSmS2X74vTw8TUs6+Scw@mail.gmail.com>
 <CADrxXXmuRjBKrm7S1VtG9Z0+a-KEKBfXuskxxH1JZ1o6ryMCxw@mail.gmail.com>
 <CADrxXX=WcvOUq-Me_myFftN67=vQYRXn=4Ap9wtpzs9emc_FHg@mail.gmail.com>
 <CADrxXXkdN3Y_ugaaeTYpUWrzPW5PQ_iL79R=YtK-Rm4TPGBOEQ@mail.gmail.com>
 <CADrxXXngz2uvf_ETbmxoX62yMOrhfpaNy2Cr5j=EhPVbA+4D+g@mail.gmail.com>
 <CADrxXXkZeQknyv6=uuf0S-9n9LrBNqyCVx2HE3+d9FyTuP464A@mail.gmail.com>
 <CADrxXX=MCSK=UBS_YcEF+Te3Zz-dc+5wBQ92YaD0XYzAWFU8NQ@mail.gmail.com>
 <okvkvc$cal$1@blaine.gmane.org>
 <bfe5b37b-101a-378a-b7be-cec867dd8c39@wichmann.us>
Message-ID: <CAGZAPF4x5QS4u_eyK+juSxAi+kzYbrxnvpWweSqZNz2_7PBBpg@mail.gmail.com>

> I'd like to contibute a rather different sort of tidbit to what Alan
> wrote: be really careful about using mutable data types in function
> calls, as class variables, and just in general.

By the way, there are some tools known as "linters" that can help
catch these kind of errors.  https://www.pylint.org/ is one of them,
and it is worth using.

From theodelgato-100 at yahoo.com  Sat Jul 22 15:00:23 2017
From: theodelgato-100 at yahoo.com (Theodore D)
Date: Sat, 22 Jul 2017 19:00:23 +0000 (UTC)
Subject: [Tutor] Python mentors for refugee learners are needed
References: <45082928.2747644.1500750023499.ref@mail.yahoo.com>
Message-ID: <45082928.2747644.1500750023499@mail.yahoo.com>


Dear Pythonistas,

We would like to inform you about project Match & Teach Me for Integration, an e-Learning platform to train refugee students in Greece, on computer programming. The pilot program starts this Wednesday, 26th of July, with an introduction to Python for beginners, and we are looking for a couple of middle/senior level Python developers to provide mentoring through web conference (in English) to 10 refugees 16-24 years old, for a couple of hours per week, for approximately 2 weeks.

So, if you can afford to spare them just a few hours of your time, please step forward and apply as a volunteer here. We are pretty sure that the gratitude those people will show you will be a precious reward.



Below, you will find a short description.

We deeply apologize if you found this message intrusive.


Thank you!





Match & Teach Me for Integration ? Description

?

The idea

Bridge the European digital skills gap by teaching refugees how to code, through an e-Learning platform with the use of their smartphones.

?

Summary

Match & Teach Me for Integration is a project of the recently registered NGO, REvive Greece. The project?s objectives are:

??????????? To fight the digital skills gap in Europe.

??????????? To help refugees integrate into the receiving European countries and get into employment.

Initially, through our e-Learning platform Match & Teach Me for Integration, the newcomers will take courses on computer programming, through their smartphones. Technologies to be taught include HTML, CSS, JS, Python, PHP, Java and MySQL.

If they successfully pass the courses, they ?ll have a chance to be employed in the private sector.


Our vision - Expected impact

??????????? It is estimated that currently there is a shortage of 400,000 software developers in Europe alone, with the projection this shortage to reach 800,000 until 2020. By teaching coding to the newcomers, we will manage, not only to integrate them into the receiving countries but also to boost their economies through the ?Brain Gain? effect.

??????????? Since Greece, as the main entrance to Europe for refugees from the Middle East, is the assembly point for those waiting up to 2 years for relocation to other European countries, it can become the place where the newcomers will learn a highly valued skill.

??????????? It is crucial that the refugees who will finish the coding courses will not be competing with the locals for a position into the out-of-balance job market (high demand / low supply). Hence, they will not be perceived from them as intruding rivals, especially in southern European countries like Greece, where there is increased unemployment.

??????????? The refugees who eventually become IT professionals will have a major role in the rebuilding of their countries if they ever return back.

??????????? Under our proposal, refugees, public, civil, and private sectors, they all win. That is why we truly believe that solution is sustainable and is expected to have a great impact.

?

Some technical

??????????? The coding courses are taught via the smartphones they already have.

??????????? We provide (free of charge, of course) a limited number of flexible Bluetooth keyboards.

??????????? With the support of the Greek Mobile Operators? Association, we will also provide to all students the SIM cards needed for access to 25 Gb of data/month for free.

??????????? The e-Learning platform is based on Moodle and the development is carried out by WIDE Services (the Official Moodle Partner in Greece) which ensures the technical expertise.

??????????? An example of how one can code through her smartphone can be found here (video): https://www.youtube.com/watch?v=uR4g0KkgqZw.

??????????? Regarding the IDE, for Python we suggest QPython3.

?

Distinction - Support

This initiative was among the finalists (was chosen among 1623 submissions) at the international competition ?Innovate for Refugees? which took place in Amman, Jordan last October and was organized, among others, by UNHCR and UNICEF (this attracted the attention of some charitable institutions and CSR programs).

As a result, our organization secured the support of the Greek Mobile Operators? Association and was selected for incubation at HIGGS, the NGO incubator which is funded by the Stavros Niarchos Foundation and provides apprehensive high-level training and support to established and upcoming NGOs.

From winonah1992 at gmail.com  Sat Jul 22 14:14:12 2017
From: winonah1992 at gmail.com (Winonah Ojanen)
Date: Sat, 22 Jul 2017 14:14:12 -0400
Subject: [Tutor] Python Help
Message-ID: <CAG8Q0obUTdJSNnwF8mbpcFKHSWH6YaL4Zakv7RJyva+rDKzcfQ@mail.gmail.com>

Hello,
I am an intern working with the Center for Computational Astrophysics
through the American Museum of Natural History as an astrophysics intern. I
am working with a galaxy simulation program called "illustris" which you
can find at illustris-project.org. I am working to download example scripts
from the website to work with merger trees and galaxy simulation through
using python with anaconda in jupiter notebook. However, I am having
trouble o the coding side with importing the example scripts through
jupiter notebook. original instructions are here:
http://www.illustris-project.org/data/docs/scripts/
I started by downloading the example scripts for the python version from
bitbucket. I have them download on my computer in a folder that is named
"illustris_python". I did the first commands through jupiter notebook and
they were successful :
$ mkdir Illustris-3
$ mkdir Illustris-3/groups_135
$ cd Illustris-3/groups_135/
I got a success message for creating the directory.
I then went to the link to download the illustris data I need:
$ wget -nd -nc -nv -e robots=off -l 1 -r -A hdf5 --content-disposition
--header="API-Key: d522db2e1b33e36d3b365cc9ac1c2c5d" "
http://www.illustris-project.org/api/Illustris-3/files/groupcat-135/?format=api
"
download successfully.
Then the next command is the have python important the example scripts
which i downloaded earlier, and named as "illustris_python":
$ python
>>> import illustris_python as il
>>>
The computer is giving me this error message:
import illustris_python as il
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-33-ff06d24b4811> in <module>()
----> 1 import illustris_python as il

ModuleNotFoundError: No module named 'illustris_python'

For some reason the computer is not recognizing this as a file on my
computer. The CCA folks says this is a coding problem and not an illustris
problem. any ideas to get me past this? I may also need help getting
farther into the download process.


Thank you,
Winonah Ojanen
Astrophysics Research Intern at the American Museum of Natural History
Education/ Ojibwe Language Undergraduate at the College of Saint Scholastica

From alan.gauld at yahoo.co.uk  Sat Jul 22 19:20:50 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 23 Jul 2017 00:20:50 +0100
Subject: [Tutor] Python Help
In-Reply-To: <CAG8Q0obUTdJSNnwF8mbpcFKHSWH6YaL4Zakv7RJyva+rDKzcfQ@mail.gmail.com>
References: <CAG8Q0obUTdJSNnwF8mbpcFKHSWH6YaL4Zakv7RJyva+rDKzcfQ@mail.gmail.com>
Message-ID: <ol0mkc$2ud$1@blaine.gmane.org>

On 22/07/17 19:14, Winonah Ojanen wrote:

> using python with anaconda in jupiter notebook. However, I am having

Usual caveat: The tutor list is targeted at the standard library
so any help for non standard library modules is best sought from
the library support fora. In this case that includes the SciPy forum
and any illustris one.

That having been said, I'll take a guess...

> $ mkdir Illustris-3
> $ mkdir Illustris-3/groups_135

Are these folders in your PYTHONPATH? If not Python will not find them.

> import illustris_python as il
> ---------------------------------------------------------------------------
> ModuleNotFoundError                       Traceback (most recent call last)


> For some reason the computer is not recognizing this as a file on my
> computer. The CCA folks says this is a coding problem and not an illustris
> problem. any ideas to get me past this? I may also need help getting
> farther into the download process.
You probably need to add the folders to PYTHONPATH environment
variable. How you do that depends on your shell. But any shell
tutorial will show you how. The format of PYTHONPATH is the same
as most other Unix PATHs - eg $PATH, $MANPATH, etc

The other thing to check is that there is not a pip compatible
installer which will put it in the right place for you... often
somewhere in site-packages.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From cs at zip.com.au  Sat Jul 22 21:34:59 2017
From: cs at zip.com.au (Cameron Simpson)
Date: Sun, 23 Jul 2017 11:34:59 +1000
Subject: [Tutor] Python Help
In-Reply-To: <ol0mkc$2ud$1@blaine.gmane.org>
References: <ol0mkc$2ud$1@blaine.gmane.org>
Message-ID: <20170723013459.GA76980@cskk.homeip.net>

On 23Jul2017 00:20, Alan Gauld <alan.gauld at yahoo.co.uk> wrote:
>On 22/07/17 19:14, Winonah Ojanen wrote:
>> using python with anaconda in jupiter notebook. However, I am having
>
>Usual caveat: The tutor list is targeted at the standard library
>so any help for non standard library modules is best sought from
>the library support fora. In this case that includes the SciPy forum
>and any illustris one.

Though arguably the OP's problem is an import issue, not really module 
specific.

>That having been said, I'll take a guess...
>> $ mkdir Illustris-3
>> $ mkdir Illustris-3/groups_135
>Are these folders in your PYTHONPATH? If not Python will not find them.
>
>> import illustris_python as il
>> ---------------------------------------------------------------------------
>> ModuleNotFoundError                       Traceback (most recent call last)

The OP cded into the new dir; I'd normally expect things to be found if the 
module was a local file/dir. However...

>> For some reason the computer is not recognizing this as a file on my
>> computer. The CCA folks says this is a coding problem and not an illustris
>> problem. any ideas to get me past this? I may also need help getting
>> farther into the download process.

I just ran the OP's download command:

  wget -nd -nc -nv -e robots=off -l 1 -r -A hdf5 --content-disposition --header="API-Key: d522db2e1b33e36d3b365cc9ac1c2c5d" "http://www.illustris-project.org/api/Illustris-3/files/groupcat-135/?format=api"

This doesn't seem to download any Python code at all. It does get a couple of 
HDF files, presumably with data to work with.

So the issue is initially that the module isn't present anywhere. Looking at 
the instructions cited <http://www.illustris-project.org/data/docs/scripts/>, 
they only cover fetching som data and working; they presume the software is 
already present. I don't immediately see actual software installation 
instructions, and it is not presented in PyPI.

Most like the OP will have to install the software directly from:

  https://bitbucket.org/illustris/illustris_python

This command:

  hg clone https://bitbucket.org/illustris/stris_pythonillustris_python

should produce an "illustris_python" in the current directory, and then her 
import command will find it.

However, there are other prerequisites. This pip command:

  pip install h5py numpy

seems to resolve them. The OP will need to use Python 2 because the module 
seems to rely on a relative import (for its "util.py" file).

Cheers,
Cameron Simpson <cs at zip.com.au>

From n6ghost at gmail.com  Sun Jul 23 02:26:59 2017
From: n6ghost at gmail.com (N6Ghost)
Date: Sat, 22 Jul 2017 23:26:59 -0700
Subject: [Tutor] new to python
Message-ID: <5bf8a9be-29d5-c045-bfe1-e1c01f7ca466@gmail.com>

C:\coderoot\python3\level1>python
Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:14:34) [MSC v.1900 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

/windows 10 x64

new to python, but not really new to programming.

going through the beginners docs, I am stuck on the file handling opening:


   my code so far:

f = open("C:\coderoot\python3\level1\inputfile.txt", 'r')
for line in file:
     for line in f:
         print(line.rstripe())
         f.close()

I want to try the different methods of opening files and reading them. 
and processing the data.  from there I will then start with writing to 
files.


any idea why that does not work?



From alan.gauld at yahoo.co.uk  Sun Jul 23 04:03:00 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 23 Jul 2017 09:03:00 +0100
Subject: [Tutor] new to python
In-Reply-To: <5bf8a9be-29d5-c045-bfe1-e1c01f7ca466@gmail.com>
References: <5bf8a9be-29d5-c045-bfe1-e1c01f7ca466@gmail.com>
Message-ID: <ol1l7e$3jm$1@blaine.gmane.org>

On 23/07/17 07:26, N6Ghost wrote:

> 
> f = open("C:\coderoot\python3\level1\inputfile.txt", 'r')
> for line in file:

Note that you have no variable called 'file'.
So this line doesn't make sense.

>      for line in f:
>          print(line.rstripe())

This bit will work if you omit the line above and
fix the indentation. (and remove the 'e' from strip()

>          f.close()

This should be outside the loop, you don't want
to close the file after every line.

Finally, there is another way to do this which
is considered 'better'/more Pythonic:

with open("C:\coderoot\python3\level1\inputfile.txt", 'r') as f:
     for line in f:
         print(line.strip())

Notice with this construct the closing of the file is
handled for you.

> any idea why that does not work?

When posting questions always include the full error text.
Although apparently cryptic it actually contains a lot of
useful detail which saves us from making guesses.


-- 
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 anish.tambe.lists at gmail.com  Sun Jul 23 04:06:35 2017
From: anish.tambe.lists at gmail.com (Anish Tambe)
Date: Sun, 23 Jul 2017 13:36:35 +0530
Subject: [Tutor] new to python
In-Reply-To: <CAMxoHv3OnAhk0eCHrBFxGuLikGTT2LSfbpa4-VygeEWc4NAzCQ@mail.gmail.com>
References: <5bf8a9be-29d5-c045-bfe1-e1c01f7ca466@gmail.com>
 <CAMxoHv3OnAhk0eCHrBFxGuLikGTT2LSfbpa4-VygeEWc4NAzCQ@mail.gmail.com>
Message-ID: <CAMxoHv1iR8M9otScWaUBsa4y_J-tPu0hqj-5+r75E=fAXS=gnQ@mail.gmail.com>

> for line in file:

This line is not required as the you have opened your file to 'f'.
'file' is a built-in class. Type -
help(file)
on the interpreter to know more about it.

>     for line in f:
>         print(line.rstripe())
>         f.close()

Are you sure that you need to close the file after reading each line?

>
> I want to try the different methods of opening files and reading them.
and processing the data.  from there I will then start with writing to
files.

Bonus : read about the 'with' keyword.

> any idea why that does not work?

When you say the code does not work, you should provide the exact error or
stacktrace that you see.

Thanks,
Anish

From __peter__ at web.de  Sun Jul 23 04:23:36 2017
From: __peter__ at web.de (Peter Otten)
Date: Sun, 23 Jul 2017 10:23:36 +0200
Subject: [Tutor] new to python
References: <5bf8a9be-29d5-c045-bfe1-e1c01f7ca466@gmail.com>
Message-ID: <ol1me5$doa$1@blaine.gmane.org>

N6Ghost wrote:

> C:\coderoot\python3\level1>python
> Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:14:34) [MSC v.1900 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> 
> /windows 10 x64
> 
> new to python, but not really new to programming.
> 
> going through the beginners docs, I am stuck on the file handling opening:
> 
> 
>    my code so far:
> 
> f = open("C:\coderoot\python3\level1\inputfile.txt", 'r')

While this one is OK using backslashes in a normal string will sooner or 
later produce erroneous paths:

>>> print("C:\test")
C:      est

Oops, \t is a TAB char, not a backslash followed by a 't'. Possible 
solutions are 

- always escape the backslash "C:\\test"
- use raw strings r"C:\test"
- use forward slashes for file paths: "C:/test" (yes, it works even on
  windows)

> for line in file:

It looks like file isn't defined anywhere.

>      for line in f:
>          print(line.rstripe())
>          f.close()

It looks like f.close() is indentend one level to deep -- the file will be 
closed on the second iteration of the inner loop. 

Indentation is important as Python uses it to represent the code structure.  
If your editor alows it ensure that it converts one hit of the TAB key into 
four spaces to avoid discrepancies between what you see and what you have.
 
> I want to try the different methods of opening files and reading them.
> and processing the data.  from there I will then start with writing to
> files.
> 
> 
> any idea why that does not work?

Since you can already program:

Read the traceback and error message carefully -- they prodvide valuable 
hints. 

If you cannot make sense of them please provide them along with the code 
that produced them; use cut-and-paste for both code and traceback.


From akleider at sonic.net  Sun Jul 23 11:16:26 2017
From: akleider at sonic.net (Alex Kleider)
Date: Sun, 23 Jul 2017 08:16:26 -0700
Subject: [Tutor] new to python
In-Reply-To: <CAMxoHv1iR8M9otScWaUBsa4y_J-tPu0hqj-5+r75E=fAXS=gnQ@mail.gmail.com>
References: <5bf8a9be-29d5-c045-bfe1-e1c01f7ca466@gmail.com>
 <CAMxoHv3OnAhk0eCHrBFxGuLikGTT2LSfbpa4-VygeEWc4NAzCQ@mail.gmail.com>
 <CAMxoHv1iR8M9otScWaUBsa4y_J-tPu0hqj-5+r75E=fAXS=gnQ@mail.gmail.com>
Message-ID: <4f6cc08cc72fc6457127367545efabcf@sonic.net>

On 2017-07-23 01:06, Anish Tambe wrote:
>> for line in file:
> 
> This line is not required as the you have opened your file to 'f'.
> 'file' is a built-in class. Type -
> help(file)
> on the interpreter to know more about it.

This appears to be true in python2x but not in python3:

alex at X301n3:~$ python3
Python 3.4.3 (default, Nov 17 2016, 01:11:57)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> help(file)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'file' is not defined
>>> exit()
alex at X301n3:~$ python
Python 2.7.6 (default, Oct 26 2016, 20:32:47)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> help(file)
Help on class file in module __builtin__:

class file(object)
  |  file(name[, mode[, buffering]]) -> file object
  |
...

Also puzzling is that the 'intro' to python2 declares itself to be 'on 
linux2' vs just 'on linux' in the case of python3.  (Something I'd not 
previously noticed.)




From mats at wichmann.us  Sun Jul 23 12:10:33 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Sun, 23 Jul 2017 10:10:33 -0600
Subject: [Tutor] new to python
In-Reply-To: <4f6cc08cc72fc6457127367545efabcf@sonic.net>
References: <5bf8a9be-29d5-c045-bfe1-e1c01f7ca466@gmail.com>
 <CAMxoHv3OnAhk0eCHrBFxGuLikGTT2LSfbpa4-VygeEWc4NAzCQ@mail.gmail.com>
 <CAMxoHv1iR8M9otScWaUBsa4y_J-tPu0hqj-5+r75E=fAXS=gnQ@mail.gmail.com>
 <4f6cc08cc72fc6457127367545efabcf@sonic.net>
Message-ID: <a311ace8-c8b1-5fe5-0f40-cbe593553aa1@wichmann.us>

On 07/23/2017 09:16 AM, Alex Kleider wrote:
> On 2017-07-23 01:06, Anish Tambe wrote:
>>> for line in file:
>>
>> This line is not required as the you have opened your file to 'f'.
>> 'file' is a built-in class. Type -
>> help(file)
>> on the interpreter to know more about it.
> 
> This appears to be true in python2x but not in python3:
> 
> alex at X301n3:~$ python3
> Python 3.4.3 (default, Nov 17 2016, 01:11:57)
> [GCC 4.8.4] on linux
> Type "help", "copyright", "credits" or "license" for more information.
>>>> help(file)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> NameError: name 'file' is not defined
>>>> exit()
> alex at X301n3:~$ python
> Python 2.7.6 (default, Oct 26 2016, 20:32:47)
> [GCC 4.8.4] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> help(file)
> Help on class file in module __builtin__:
> 
> class file(object)
>  |  file(name[, mode[, buffering]]) -> file object
>  |
> ...

It is nonetheless still true that Python provides context manager
support for file objects that behave the same way as described (that is,
when handle - called 'f' in the example above - goes out of scope, it is
closed for you).  Otherwise, the relevant documentation on file objects
is now in the IO discussion:

https://docs.python.org/3/library/io.html

> Also puzzling is that the 'intro' to python2 declares itself to be 'on
> linux2' vs just 'on linux' in the case of python3.  (Something I'd not
> previously noticed.)

That's just a cleanup of an old issue, Python3 dropped the "linux2"
thing (which was never a great idea, linux kernels are now 4.x after 2.x
lived for a very long time, Python never followed those changes nor did
it need to);

FWIW, the preferred method now to check if a host is linux is to do:

if sys.platform.startswith("linux"):

instead of checking explicitly for a string "linux", "linux2", etc.




From __peter__ at web.de  Sun Jul 23 12:56:59 2017
From: __peter__ at web.de (Peter Otten)
Date: Sun, 23 Jul 2017 18:56:59 +0200
Subject: [Tutor] Import Error.
References: <CAEa+n9y1W5jEVd2snjVekboqVb0zqjZVGWHbe1yyr9N2n+bzGQ@mail.gmail.com>
Message-ID: <ol2kgq$5bc$1@blaine.gmane.org>

Deepen Patel wrote:

> Hi,
> 
> I got error like Import error.
> 
> Traceback (most recent call last):
>   File "startnode.py", line 8, in <module>
>     from twisted.conch import manhole, manhole_ssh
>   File
> "/usr/local/lib/python2.7/dist-packages/twisted/conch/manhole_ssh.py",
> line 14, in <module>
>     from twisted.conch.ssh import factory, session
>   File
> "/usr/local/lib/python2.7/dist-packages/twisted/conch/ssh/factory.py",
> line 18, in <module>
>     from twisted.conch.ssh import (_kex, transport, userauth, connection)
>   File
> "/usr/local/lib/python2.7/dist-packages/twisted/conch/ssh/transport.py",
> line 22, in <module>
>     from cryptography.exceptions import UnsupportedAlgorithm
> ImportError: No module named cryptography.exceptions
> 
> Currently, I am using virtual environments and in virtual environment this
> code not run properly.
> previously, I am running code without virtual environments. it works
> proper.
> 
> Await your reply.
> 
> Regards,
> Deepen Patel.

If I understand

https://github.com/twisted/twisted/blob/trunk/INSTALL.rst

and

http://twistedmatrix.com/documents/current/installation/howto/optional.html

correctly you have to install with

$ pip install twisted[conch]


From deepenpatel.lintel at gmail.com  Sun Jul 23 12:24:09 2017
From: deepenpatel.lintel at gmail.com (Deepen Patel)
Date: Sun, 23 Jul 2017 21:54:09 +0530
Subject: [Tutor] Import Error.
Message-ID: <CAEa+n9y1W5jEVd2snjVekboqVb0zqjZVGWHbe1yyr9N2n+bzGQ@mail.gmail.com>

Hi,

I got error like Import error.

Traceback (most recent call last):
  File "startnode.py", line 8, in <module>
    from twisted.conch import manhole, manhole_ssh
  File
"/usr/local/lib/python2.7/dist-packages/twisted/conch/manhole_ssh.py", line
14, in <module>
    from twisted.conch.ssh import factory, session
  File
"/usr/local/lib/python2.7/dist-packages/twisted/conch/ssh/factory.py", line
18, in <module>
    from twisted.conch.ssh import (_kex, transport, userauth, connection)
  File
"/usr/local/lib/python2.7/dist-packages/twisted/conch/ssh/transport.py",
line 22, in <module>
    from cryptography.exceptions import UnsupportedAlgorithm
ImportError: No module named cryptography.exceptions

Currently, I am using virtual environments and in virtual environment this
code not run properly.
previously, I am running code without virtual environments. it works proper.

Await your reply.

Regards,
Deepen Patel.

From alex.gaynor at gmail.com  Sun Jul 23 12:27:20 2017
From: alex.gaynor at gmail.com (Alex Gaynor)
Date: Sun, 23 Jul 2017 12:27:20 -0400
Subject: [Tutor] [Cryptography-dev] Import Error.
In-Reply-To: <CAEa+n9y1W5jEVd2snjVekboqVb0zqjZVGWHbe1yyr9N2n+bzGQ@mail.gmail.com>
References: <CAEa+n9y1W5jEVd2snjVekboqVb0zqjZVGWHbe1yyr9N2n+bzGQ@mail.gmail.com>
Message-ID: <CAFRnB2W7YfPrx+4HHkMvXcrnrRmKmXHy1fP2a_r0N3wwd=se+w@mail.gmail.com>

Hi Deepen,

Without any more information, it looks like you didn't install cryptography
into your virtualenv. How did you install twisted?

Alex

On Sun, Jul 23, 2017 at 12:24 PM, Deepen Patel <deepenpatel.lintel at gmail.com
> wrote:

> Hi,
>
> I got error like Import error.
>
> Traceback (most recent call last):
>   File "startnode.py", line 8, in <module>
>     from twisted.conch import manhole, manhole_ssh
>   File "/usr/local/lib/python2.7/dist-packages/twisted/conch/manhole_ssh.py",
> line 14, in <module>
>     from twisted.conch.ssh import factory, session
>   File "/usr/local/lib/python2.7/dist-packages/twisted/conch/ssh/factory.py",
> line 18, in <module>
>     from twisted.conch.ssh import (_kex, transport, userauth, connection)
>   File "/usr/local/lib/python2.7/dist-packages/twisted/conch/ssh/transport.py",
> line 22, in <module>
>     from cryptography.exceptions import UnsupportedAlgorithm
> ImportError: No module named cryptography.exceptions
>
> Currently, I am using virtual environments and in virtual environment this
> code not run properly.
> previously, I am running code without virtual environments. it works
> proper.
>
> Await your reply.
>
> Regards,
> Deepen Patel.
>
> _______________________________________________
> Cryptography-dev mailing list
> Cryptography-dev at python.org
> https://mail.python.org/mailman/listinfo/cryptography-dev
>
>


-- 
"I disapprove of what you say, but I will defend to the death your right to
say it." -- Evelyn Beatrice Hall (summarizing Voltaire)
"The people's good is the highest law." -- Cicero
GPG Key fingerprint: D1B3 ADC0 E023 8CA6

From arj.python at gmail.com  Sun Jul 23 11:02:09 2017
From: arj.python at gmail.com (Abdur-Rahmaan Janhangeer)
Date: Sun, 23 Jul 2017 19:02:09 +0400
Subject: [Tutor] Quick Pythonic Style Tips
In-Reply-To: <CAGZAPF4x5QS4u_eyK+juSxAi+kzYbrxnvpWweSqZNz2_7PBBpg@mail.gmail.com>
References: <CADrxXXmFS0iHWz2nr40MUaVoYqG_P3VHjm22ueCQ2Wm9-LxpvQ@mail.gmail.com>
 <CADrxXXk5iObs5JUOAu73HRQJUTAgd8EeP+pXiKqy+VrYk-_=7Q@mail.gmail.com>
 <CADrxXXnGysC0afCpDHYXnGyhsfTtYGYtr8JeU5A2FrieBZtM=g@mail.gmail.com>
 <CADrxXX=d9TYNq=2PHf40dYX9AELbpSLR12jPiO39=bGXA0SbHA@mail.gmail.com>
 <CADrxXXmg5U8-ZzOc4B+3bHjmdUZS225URDWaTm0QsMmpL6N0LQ@mail.gmail.com>
 <CADrxXX=1kWEq946HyUe-B8X9+sKGz10zp6QO8kJ7RzFuTunTdw@mail.gmail.com>
 <CADrxXXnNo2doX9BMnMYzFkGrLL4r1CgSmS2X74vTw8TUs6+Scw@mail.gmail.com>
 <CADrxXXmuRjBKrm7S1VtG9Z0+a-KEKBfXuskxxH1JZ1o6ryMCxw@mail.gmail.com>
 <CADrxXX=WcvOUq-Me_myFftN67=vQYRXn=4Ap9wtpzs9emc_FHg@mail.gmail.com>
 <CADrxXXkdN3Y_ugaaeTYpUWrzPW5PQ_iL79R=YtK-Rm4TPGBOEQ@mail.gmail.com>
 <CADrxXXngz2uvf_ETbmxoX62yMOrhfpaNy2Cr5j=EhPVbA+4D+g@mail.gmail.com>
 <CADrxXXkZeQknyv6=uuf0S-9n9LrBNqyCVx2HE3+d9FyTuP464A@mail.gmail.com>
 <CADrxXX=MCSK=UBS_YcEF+Te3Zz-dc+5wBQ92YaD0XYzAWFU8NQ@mail.gmail.com>
 <okvkvc$cal$1@blaine.gmane.org>
 <bfe5b37b-101a-378a-b7be-cec867dd8c39@wichmann.us>
 <CAGZAPF4x5QS4u_eyK+juSxAi+kzYbrxnvpWweSqZNz2_7PBBpg@mail.gmail.com>
Message-ID: <CADrxXX=saz8fbVDDg0Yhb4rXf9Lr6-aARVQuA03CKo=1QFfWpg@mail.gmail.com>

Thanks everybody, i wanted to get some pythonic ideas.

yes forgot that

assert(... is liked by some strongly typed programmers

anInt -> did not not some people liked tha

data encapsulation might be depressing to some migrating coders

ah pylint yes, great checker ! *some guys thought of inventing it*

Else more styling tips if any and whenever, appreciated !

Abdur-Rahmaan Janhangeer,
Mauritius
abdurrahmaanjanhangeer.wordpress.com

On 23 Jul 2017 01:59, "Danny Yoo" <dyoo at hashcollision.org> wrote:

> > I'd like to contibute a rather different sort of tidbit to what Alan
> > wrote: be really careful about using mutable data types in function
> > calls, as class variables, and just in general.
>
> By the way, there are some tools known as "linters" that can help
> catch these kind of errors.  https://www.pylint.org/ is one of them,
> and it is worth using.
> _______________________________________________
> 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  Sun Jul 23 11:18:56 2017
From: arj.python at gmail.com (Abdur-Rahmaan Janhangeer)
Date: Sun, 23 Jul 2017 19:18:56 +0400
Subject: [Tutor] Best OpenCV tutorials
In-Reply-To: <CADrxXXmp5LFGoUQ7ChNUYPsC2RWzmOdfHv6SCDTfNVKWLx2QQQ@mail.gmail.com>
References: <CADrxXXkPDHz+eDBCdAS4gTLc2M4A9V4J-+uL2vozqRdM3kZL4w@mail.gmail.com>
 <CADrxXX=jqUH6RQ2sSVAqO87pgP3rYbChTU9UyHOVTZdtNct13Q@mail.gmail.com>
 <CADrxXXmWJ6MKLySJD1A7H8rj=wXct8gOG4-UDcFPSj5fRwDWfg@mail.gmail.com>
 <CADrxXXk9SdkxOaFxVHVaXm-1Af5H7HJ-4ggAomEjxss2UivKZw@mail.gmail.com>
 <CADrxXXmp5LFGoUQ7ChNUYPsC2RWzmOdfHv6SCDTfNVKWLx2QQQ@mail.gmail.com>
Message-ID: <CADrxXXnzJ4ydEzsJ2w=u+ygQ6THqBLmzKic+=VKvczc2PnjeeA@mail.gmail.com>

The last python issue i'd like to resolve is the OpenCV issue

I just want some nice opencv tutorials apart from the official docs

also, some nice algos if any apart from Haar Cascades with examples.

P.s. This is a 3rd party lib, so, some links is fine !

Abdur-Rahmaan Janhangeer,
Mauritius
abdurrahmaanjanhangeer.wordpress.com

From alan.gauld at yahoo.co.uk  Sun Jul 23 16:45:45 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 23 Jul 2017 21:45:45 +0100
Subject: [Tutor] Fwd: Re:  Python Help
In-Reply-To: <CAG8Q0obG=QJn1wje+Qe-3MMsnSmfdvpkov8UWpEnyKO4rNwK2w@mail.gmail.com>
References: <CAG8Q0obG=QJn1wje+Qe-3MMsnSmfdvpkov8UWpEnyKO4rNwK2w@mail.gmail.com>
Message-ID: <4b8f68d5-2cf0-e6d9-19b6-9118acbdf4d4@yahoo.co.uk>


Forwarding to list,
please use ReplyAll or ReplyList when responding to the list.


-------- Forwarded Message --------

I also tried the correct command for the mac ox s in terminal shell,
running:

Jims-MacBook-Pro-2:~ Jim$
PYTHONPATH="/Users/Jim/Documents/illustris_python:$PYTHONPATH

> export PYTHONPATH


no error messages there but it is still not finding the module through
python.

Winonah


On Sun, Jul 23, 2017 at 1:34 PM, Winonah Ojanen <winonah1992 at gmail.com
<mailto:winonah1992 at gmail.com>> wrote:

    I did use the pip command and am attempting to add the files to my
    python path. I used
     import sys
    sys.path.append("/Users/Jim/Documents/illustris_python")

    and that worked. I even checked to make sure the files were there 


    import sys
    print (sys.path)

    ['', '/Users/Jim/anaconda/lib/python36.zip',
    '/Users/Jim/anaconda/lib/python3.6',
    '/Users/Jim/anaconda/lib/python3.6/lib-dynload',
    '/Users/Jim/anaconda/lib/python3.6/site-packages',
    '/Users/Jim/anaconda/lib/python3.6/site-packages/Sphinx-1.5.6-py3.6.egg',
    '/Users/Jim/anaconda/lib/python3.6/site-packages/aeosa',
    '/Users/Jim/anaconda/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg',
    '/Users/Jim/anaconda/lib/python3.6/site-packages/IPython/extensions',
    '/Users/Jim/.ipython', 'Users/Jim/Documents/illustris_python']

    the file is clearly there but when i try to do import
    illustris_python as il it still can't find the module.


Note that only shows the folder is in the path.

What does an 'ls' listing reveal as to the contents of the folder?
Is there a file called illustris_python.py? or maybe illustris_python.pyc?



    I also figured that I need to manually export to python path so i tried:
    export PYTHONPATH=$PYTHONPATH:/Users/Jim/Documents/illustris_python/
      File "<ipython-input-14-30d153a77da5>", line 1
        export PYTHONPATH=$PYTHONPATH:/Users/Jim/Documents/illustris_python/
                        ^
    SyntaxError: invalid syntax

    I got invalid syntax... using a mac os x

    I tried typing in terminal open .bash_profile and telling it to
    export the python path in there like some others recommended but in
    terminal it is giving me an error message for that... it must not be
    the right command for the shell.

    Winonah

    On Sat, Jul 22, 2017 at 9:34 PM, Cameron Simpson <cs at zip.com.au
    <mailto:cs at zip.com.au>> wrote:

        On 23Jul2017 00:20, Alan Gauld <alan.gauld at yahoo.co.uk
        <mailto:alan.gauld at yahoo.co.uk>> wrote:

            On 22/07/17 19:14, Winonah Ojanen wrote:

                using python with anaconda in jupiter notebook. However,
                I am having


            Usual caveat: The tutor list is targeted at the standard library
            so any help for non standard library modules is best sought from
            the library support fora. In this case that includes the
            SciPy forum
            and any illustris one.


        Though arguably the OP's problem is an import issue, not really
        module specific.

            That having been said, I'll take a guess...

                $ mkdir Illustris-3
                $ mkdir Illustris-3/groups_135

            Are these folders in your PYTHONPATH? If not Python will not
            find them.

                import illustris_python as il
                ---------------------------------------------------------------------------
                ModuleNotFoundError                       Traceback
                (most recent call last)


        The OP cded into the new dir; I'd normally expect things to be
        found if the module was a local file/dir. However...

                For some reason the computer is not recognizing this as
                a file on my
                computer. The CCA folks says this is a coding problem
                and not an illustris
                problem. any ideas to get me past this? I may also need
                help getting
                farther into the download process.


        I just ran the OP's download command:

         wget -nd -nc -nv -e robots=off -l 1 -r -A hdf5
        --content-disposition --header="API-Key:
        d522db2e1b33e36d3b365cc9ac1c2c5d"
        "http://www.illustris-project.org/api/Illustris-3/files/groupcat-135/?format=api
        <http://www.illustris-project.org/api/Illustris-3/files/groupcat-135/?format=api>"

        This doesn't seem to download any Python code at all. It does
        get a couple of HDF files, presumably with data to work with.

        So the issue is initially that the module isn't present
        anywhere. Looking at the instructions cited
        <http://www.illustris-project.org/data/docs/scripts/
        <http://www.illustris-project.org/data/docs/scripts/>>, they
        only cover fetching som data and working; they presume the
        software is already present. I don't immediately see actual
        software installation instructions, and it is not presented in PyPI.

        Most like the OP will have to install the software directly from:

         https://bitbucket.org/illustris/illustris_python
        <https://bitbucket.org/illustris/illustris_python>

        This command:

         hg clone
        https://bitbucket.org/illustris/stris_pythonillustris_python
        <https://bitbucket.org/illustris/stris_pythonillustris_python>

        should produce an "illustris_python" in the current directory,
        and then her import command will find it.

        However, there are other prerequisites. This pip command:

         pip install h5py numpy

        seems to resolve them. The OP will need to use Python 2 because
        the module seems to rely on a relative import (for its "util.py"
        file).

        Cheers,
        Cameron Simpson <cs at zip.com.au <mailto:cs at zip.com.au>>

        _______________________________________________
        Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
        To unsubscribe or change subscription options:
        https://mail.python.org/mailman/listinfo/tutor
        <https://mail.python.org/mailman/listinfo/tutor>




From alan.gauld at yahoo.co.uk  Sun Jul 23 16:42:26 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 23 Jul 2017 21:42:26 +0100
Subject: [Tutor] Fwd: Re:  Python Help
In-Reply-To: <CAG8Q0obSDcmQ9_in-a5C2G2N56eJ3JaApothLqXqE2z5mOF+Hg@mail.gmail.com>
References: <CAG8Q0obSDcmQ9_in-a5C2G2N56eJ3JaApothLqXqE2z5mOF+Hg@mail.gmail.com>
Message-ID: <f4a163ee-9750-b91c-30b2-7a0f3b54508c@yahoo.co.uk>

Forwarding to list



-------- Forwarded Message --------

I did use the pip command and am attempting to add the files to my
python path. I used
 import sys
sys.path.append("/Users/Jim/Documents/illustris_python")

and that worked. I even checked to make sure the files were there 


import sys
print (sys.path)

['', '/Users/Jim/anaconda/lib/python36.zip',
'/Users/Jim/anaconda/lib/python3.6',
'/Users/Jim/anaconda/lib/python3.6/lib-dynload',
'/Users/Jim/anaconda/lib/python3.6/site-packages',
'/Users/Jim/anaconda/lib/python3.6/site-packages/Sphinx-1.5.6-py3.6.egg',
'/Users/Jim/anaconda/lib/python3.6/site-packages/aeosa',
'/Users/Jim/anaconda/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg',
'/Users/Jim/anaconda/lib/python3.6/site-packages/IPython/extensions',
'/Users/Jim/.ipython', 'Users/Jim/Documents/illustris_python']

the file is clearly there but when i try to do import illustris_python
as il it still can't find the module. 

I also figured that I need to manually export to python path so i tried:
export PYTHONPATH=$PYTHONPATH:/Users/Jim/Documents/illustris_python/
  File "<ipython-input-14-30d153a77da5>", line 1
    export PYTHONPATH=$PYTHONPATH:/Users/Jim/Documents/illustris_python/
                    ^
SyntaxError: invalid syntax

I got invalid syntax... using a mac os x

I tried typing in terminal open .bash_profile and telling it to export
the python path in there like some others recommended but in terminal it
is giving me an error message for that... it must not be the right
command for the shell.

Winonah

On Sat, Jul 22, 2017 at 9:34 PM, Cameron Simpson <cs at zip.com.au
<mailto:cs at zip.com.au>> wrote:

    On 23Jul2017 00:20, Alan Gauld <alan.gauld at yahoo.co.uk
    <mailto:alan.gauld at yahoo.co.uk>> wrote:

        On 22/07/17 19:14, Winonah Ojanen wrote:

            using python with anaconda in jupiter notebook. However, I
            am having


        Usual caveat: The tutor list is targeted at the standard library
        so any help for non standard library modules is best sought from
        the library support fora. In this case that includes the SciPy forum
        and any illustris one.


    Though arguably the OP's problem is an import issue, not really
    module specific.

        That having been said, I'll take a guess...

            $ mkdir Illustris-3
            $ mkdir Illustris-3/groups_135

        Are these folders in your PYTHONPATH? If not Python will not
        find them.

            import illustris_python as il
            ---------------------------------------------------------------------------
            ModuleNotFoundError                       Traceback (most
            recent call last)


    The OP cded into the new dir; I'd normally expect things to be found
    if the module was a local file/dir. However...

            For some reason the computer is not recognizing this as a
            file on my
            computer. The CCA folks says this is a coding problem and
            not an illustris
            problem. any ideas to get me past this? I may also need help
            getting
            farther into the download process.


    I just ran the OP's download command:

     wget -nd -nc -nv -e robots=off -l 1 -r -A hdf5
    --content-disposition --header="API-Key:
    d522db2e1b33e36d3b365cc9ac1c2c5d"
    "http://www.illustris-project.org/api/Illustris-3/files/groupcat-135/?format=api
    <http://www.illustris-project.org/api/Illustris-3/files/groupcat-135/?format=api>"

    This doesn't seem to download any Python code at all. It does get a
    couple of HDF files, presumably with data to work with.

    So the issue is initially that the module isn't present anywhere.
    Looking at the instructions cited
    <http://www.illustris-project.org/data/docs/scripts/
    <http://www.illustris-project.org/data/docs/scripts/>>, they only
    cover fetching som data and working; they presume the software is
    already present. I don't immediately see actual software
    installation instructions, and it is not presented in PyPI.

    Most like the OP will have to install the software directly from:

     https://bitbucket.org/illustris/illustris_python
    <https://bitbucket.org/illustris/illustris_python>

    This command:

     hg clone
    https://bitbucket.org/illustris/stris_pythonillustris_python
    <https://bitbucket.org/illustris/stris_pythonillustris_python>

    should produce an "illustris_python" in the current directory, and
    then her import command will find it.

    However, there are other prerequisites. This pip command:

     pip install h5py numpy

    seems to resolve them. The OP will need to use Python 2 because the
    module seems to rely on a relative import (for its "util.py" file).

    Cheers,
    Cameron Simpson <cs at zip.com.au <mailto:cs at zip.com.au>>

    _______________________________________________
    Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
    To unsubscribe or change subscription options:
    https://mail.python.org/mailman/listinfo/tutor
    <https://mail.python.org/mailman/listinfo/tutor>



From brandonanderson at me.com  Sun Jul 23 19:19:41 2017
From: brandonanderson at me.com (Brandon Anderson)
Date: Sun, 23 Jul 2017 16:19:41 -0700
Subject: [Tutor] Python3 Help
Message-ID: <7B8D0BE1-006B-458A-9BE6-5BBC9F75D5F5@me.com>

Hello!

1. 	I have Python3 installed on my 2017 MacBook Pro. I know that it is successfully installed because, when I enter ?Python3? into my terminal,
	I get the following message:
	
	Python 3.6.2 (v3.6.2:5fd33b5926, Jul 16 2017, 20:11:06) 
	[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
	Type "help", "copyright", "credits" or "license" for more information.

2.  I?m trying to locate the directory path to where Python3 is located on my system, but when I enter 
	the following command:
	$ type -a python3
	
	I get:
	-bash: $: command not found  

	My understanding is that the command should have provided me with the path to Python3 is located on my system.

3.  How do I determine why I?m getting the ?error? command, instead of the directory location of Python3.
    I need the location in order to setup my Text Editor to execute Python3 commands.

Thank you in advance.

Brandon Anderson
(510) 468-0154
brandonanderson at icloud.com

From mysecretrobotfactory at gmail.com  Sun Jul 23 16:24:49 2017
From: mysecretrobotfactory at gmail.com (Michael C)
Date: Sun, 23 Jul 2017 13:24:49 -0700
Subject: [Tutor] class newbie
Message-ID: <CANyKM1hxQSp6nErS5eJ=np6vEn6=WtmjV6Mc4BSdq1K2Qg4Ekg@mail.gmail.com>

class mahschool:
    def print():
        print('Say something')


a = mahschool()

a.print()



With this, I get this error:

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    a.print()
TypeError: print() takes 0 positional arguments but 1 was given


What did I do wrong?

Thanks!

From mysecretrobotfactory at gmail.com  Sun Jul 23 16:42:56 2017
From: mysecretrobotfactory at gmail.com (Michael C)
Date: Sun, 23 Jul 2017 13:42:56 -0700
Subject: [Tutor] class newbie
In-Reply-To: <CANyKM1hxQSp6nErS5eJ=np6vEn6=WtmjV6Mc4BSdq1K2Qg4Ekg@mail.gmail.com>
References: <CANyKM1hxQSp6nErS5eJ=np6vEn6=WtmjV6Mc4BSdq1K2Qg4Ekg@mail.gmail.com>
Message-ID: <CANyKM1jGFwGNTaZ6u_5ucRH8domF+zjDmz1qka42h=TnyDN08w@mail.gmail.com>

never mind, I forgot to put 'self' in the method definition!

class mahschool:
    def print(self):
        print('Say something')


a = mahschool()

a.print()


On Sun, Jul 23, 2017 at 1:24 PM, Michael C <mysecretrobotfactory at gmail.com>
wrote:

> class mahschool:
>     def print():
>         print('Say something')
>
>
> a = mahschool()
>
> a.print()
>
>
>
> With this, I get this error:
>
> Traceback (most recent call last):
>   File "test.py", line 8, in <module>
>     a.print()
> TypeError: print() takes 0 positional arguments but 1 was given
>
>
> What did I do wrong?
>
> Thanks!
>

From dyoo at hashcollision.org  Sun Jul 23 20:35:20 2017
From: dyoo at hashcollision.org (Danny Yoo)
Date: Sun, 23 Jul 2017 17:35:20 -0700
Subject: [Tutor] class newbie
In-Reply-To: <CANyKM1hxQSp6nErS5eJ=np6vEn6=WtmjV6Mc4BSdq1K2Qg4Ekg@mail.gmail.com>
References: <CANyKM1hxQSp6nErS5eJ=np6vEn6=WtmjV6Mc4BSdq1K2Qg4Ekg@mail.gmail.com>
Message-ID: <CAGZAPF4QUYj39dRsA27PFyr-hbcs36MKqebUyF92fF2kYi5_5A@mail.gmail.com>

On Sun, Jul 23, 2017 at 1:24 PM, Michael C
<mysecretrobotfactory at gmail.com> wrote:
> class mahschool:
>     def print():
>         print('Say something')


By the way, you've chosen a name for your method that's spelled the
same as the name of the built-in "print" function.  I'd recommend you
choose a different name than "print" in your method name, just to
avoid any potential confusion.  This isn't going to solve the
immediate problem that you encountered and solved: you figured out
that methods need to have a self argument.  But you probably still
want to rename to avoid the name collision.


Good luck!

From mats at wichmann.us  Sun Jul 23 20:37:53 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Sun, 23 Jul 2017 18:37:53 -0600
Subject: [Tutor] class newbie
In-Reply-To: <CANyKM1jGFwGNTaZ6u_5ucRH8domF+zjDmz1qka42h=TnyDN08w@mail.gmail.com>
References: <CANyKM1hxQSp6nErS5eJ=np6vEn6=WtmjV6Mc4BSdq1K2Qg4Ekg@mail.gmail.com>
 <CANyKM1jGFwGNTaZ6u_5ucRH8domF+zjDmz1qka42h=TnyDN08w@mail.gmail.com>
Message-ID: <d416043c-d59b-0c5e-6e82-f4ab75695b2c@wichmann.us>

On 07/23/2017 02:42 PM, Michael C wrote:
> never mind, I forgot to put 'self' in the method definition!

class mahschool:
    def print(self):
        print('Say something')


a = mahschool()

a.print()

Indeed.  The error message was clear on this - but not in a way that's
always instructive until you're used to it :)

"TypeError: print() takes 0 positional arguments but 1 was given"

A method is called "silently" (you didn't pass it yourself as an
argument when you called print()) with the instance, so you need to
declare such a parameter in the method definition.

And to give myself an excuse for preaching: it's usually not a great
idea to reuse the name of a built-in function.

From dyoo at hashcollision.org  Sun Jul 23 20:44:37 2017
From: dyoo at hashcollision.org (Danny Yoo)
Date: Sun, 23 Jul 2017 17:44:37 -0700
Subject: [Tutor] Python3 Help
In-Reply-To: <7B8D0BE1-006B-458A-9BE6-5BBC9F75D5F5@me.com>
References: <7B8D0BE1-006B-458A-9BE6-5BBC9F75D5F5@me.com>
Message-ID: <CAGZAPF7e=L7k+qFksVs2kirHcq0E40Td0CmO7mTb_2gY1MGw1A@mail.gmail.com>

> 2.  I?m trying to locate the directory path to where Python3 is located on my system, but when I enter
>         the following command:
>         $ type -a python3
>
>         I get:
>         -bash: $: command not found


Ah.  Do not include the leading "$" in the command that you're typing.
I'm assuming that you're reading some instruction that says something
like this:

-------

Type the following into your command prompt:

    $ type -a python3

--------

If you are reading such an instruction, don't literally type the
dollar sign.  "$" is a convention that's used to indicate to you to
type the rest of the line into your command prompt.  It's because, by
default, the command shell will use "$" as its primary prompt to tell
the user that it is ready to accept a new command.
(https://superuser.com/questions/57575/what-is-the-origin-of-the-unix-dollar-prompt)

From steve at pearwood.info  Sun Jul 23 20:50:10 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 24 Jul 2017 10:50:10 +1000
Subject: [Tutor] Import Error.
In-Reply-To: <CAEa+n9y1W5jEVd2snjVekboqVb0zqjZVGWHbe1yyr9N2n+bzGQ@mail.gmail.com>
References: <CAEa+n9y1W5jEVd2snjVekboqVb0zqjZVGWHbe1yyr9N2n+bzGQ@mail.gmail.com>
Message-ID: <20170724005009.GM3149@ando.pearwood.info>

On Sun, Jul 23, 2017 at 09:54:09PM +0530, Deepen Patel wrote:

> ImportError: No module named cryptography.exceptions
> 
> Currently, I am using virtual environments and in virtual environment this
> code not run properly.
> previously, I am running code without virtual environments. it works proper.

You need to install the cryptography package into your virtual 
environment. The virtual environment will not see packages installed 
elsewhere.


-- 
Steve

From alan.gauld at yahoo.co.uk  Sun Jul 23 20:58:43 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 24 Jul 2017 01:58:43 +0100
Subject: [Tutor] Python3 Help
In-Reply-To: <7B8D0BE1-006B-458A-9BE6-5BBC9F75D5F5@me.com>
References: <7B8D0BE1-006B-458A-9BE6-5BBC9F75D5F5@me.com>
Message-ID: <ol3gns$1gm$1@blaine.gmane.org>

On 24/07/17 00:19, Brandon Anderson wrote:

> 2.  I?m trying to locate the directory path to where Python3 is located on my system, but when I enter 
> 	the following command:
> 	$ type -a python3

You could also try

$ which python3

> 	-bash: $: command not found  

The $ is the OS prompt you are not supposed to type it in.

> 3.  How do I determine why I?m getting the ?error? command, instead of the directory location of Python3.

The error means that there a mistake in your input.
In this case you included the $ in your input.

Note that this is an OS error and nothing to do
with python itself.

-- 
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 mysecretrobotfactory at gmail.com  Sun Jul 23 20:38:06 2017
From: mysecretrobotfactory at gmail.com (Michael C)
Date: Sun, 23 Jul 2017 17:38:06 -0700
Subject: [Tutor] class newbie
In-Reply-To: <CAGZAPF4QUYj39dRsA27PFyr-hbcs36MKqebUyF92fF2kYi5_5A@mail.gmail.com>
References: <CANyKM1hxQSp6nErS5eJ=np6vEn6=WtmjV6Mc4BSdq1K2Qg4Ekg@mail.gmail.com>
 <CAGZAPF4QUYj39dRsA27PFyr-hbcs36MKqebUyF92fF2kYi5_5A@mail.gmail.com>
Message-ID: <CANyKM1gFkyVwady2VbGFoDxS+jcWDp+tPYA5BpXy-t7BitsBJw@mail.gmail.com>

thanks!

On Sun, Jul 23, 2017 at 5:35 PM, Danny Yoo <dyoo at hashcollision.org> wrote:

> On Sun, Jul 23, 2017 at 1:24 PM, Michael C
> <mysecretrobotfactory at gmail.com> wrote:
> > class mahschool:
> >     def print():
> >         print('Say something')
>
>
> By the way, you've chosen a name for your method that's spelled the
> same as the name of the built-in "print" function.  I'd recommend you
> choose a different name than "print" in your method name, just to
> avoid any potential confusion.  This isn't going to solve the
> immediate problem that you encountered and solved: you figured out
> that methods need to have a self argument.  But you probably still
> want to rename to avoid the name collision.
>
>
> Good luck!
>

From steve at pearwood.info  Sun Jul 23 21:09:37 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 24 Jul 2017 11:09:37 +1000
Subject: [Tutor] Quick Pythonic Style Tips
In-Reply-To: <CADrxXX=saz8fbVDDg0Yhb4rXf9Lr6-aARVQuA03CKo=1QFfWpg@mail.gmail.com>
References: <CADrxXXmuRjBKrm7S1VtG9Z0+a-KEKBfXuskxxH1JZ1o6ryMCxw@mail.gmail.com>
 <CADrxXX=WcvOUq-Me_myFftN67=vQYRXn=4Ap9wtpzs9emc_FHg@mail.gmail.com>
 <CADrxXXkdN3Y_ugaaeTYpUWrzPW5PQ_iL79R=YtK-Rm4TPGBOEQ@mail.gmail.com>
 <CADrxXXngz2uvf_ETbmxoX62yMOrhfpaNy2Cr5j=EhPVbA+4D+g@mail.gmail.com>
 <CADrxXXkZeQknyv6=uuf0S-9n9LrBNqyCVx2HE3+d9FyTuP464A@mail.gmail.com>
 <CADrxXX=MCSK=UBS_YcEF+Te3Zz-dc+5wBQ92YaD0XYzAWFU8NQ@mail.gmail.com>
 <okvkvc$cal$1@blaine.gmane.org>
 <bfe5b37b-101a-378a-b7be-cec867dd8c39@wichmann.us>
 <CAGZAPF4x5QS4u_eyK+juSxAi+kzYbrxnvpWweSqZNz2_7PBBpg@mail.gmail.com>
 <CADrxXX=saz8fbVDDg0Yhb4rXf9Lr6-aARVQuA03CKo=1QFfWpg@mail.gmail.com>
Message-ID: <20170724010936.GN3149@ando.pearwood.info>

On Sun, Jul 23, 2017 at 07:02:09PM +0400, Abdur-Rahmaan Janhangeer wrote:

> assert(... is liked by some strongly typed programmers

Not just strongly-typed programmers:

http://import-that.dreamwidth.org/676.html


> data encapsulation might be depressing to some migrating coders

"Data encapsulation" does not mean "data hiding". Python has excellent 
data encapsulation:

- packages encapsulate modules together;

- modules encapsulate classes, functions and variables together;

- classes encapsulate object state and behaviour together.


Compared to languages like C++ and Java, Python's data HIDING is weak. 
Python has no private, public, protected, etc.

But even in the strictest languages like C++ and Java, there is usually 
some way to "defeat" the compiler and get access to private data and 
break data hiding. For instance, in C++ you can often do something like

#define private public

and in Java you can use reflection. The creator of Python, Guido van 
Rossum, understands that sometimes there *are* good uses for breaking 
data hiding (usually for testing and debugging). Because Python is an 
interpreter where most features are done at runtime rather than compile 
time, implementing data hiding in Python would hurt performance, and 
there would be some way to break it anyway.

So why bother?

Instead, Python is "for consenting adults". Data hiding is very simple: 
the developer flags objects they want to keep private with a leading 
underscore:

_private

and that tells you that this is private and you shouldn't touch it. If 
you decide to ignore this and touch it anyway, then:

- either you have a good reason, and that's okay;

- or you are a "consenting adult", and if your code blows up, 
  well, that's your own fault and don't complain to us.



-- 
Steve

From cs at zip.com.au  Sun Jul 23 19:22:02 2017
From: cs at zip.com.au (Cameron Simpson)
Date: Mon, 24 Jul 2017 09:22:02 +1000
Subject: [Tutor] Quick Pythonic Style Tips
In-Reply-To: <CADrxXX=saz8fbVDDg0Yhb4rXf9Lr6-aARVQuA03CKo=1QFfWpg@mail.gmail.com>
References: <CADrxXX=saz8fbVDDg0Yhb4rXf9Lr6-aARVQuA03CKo=1QFfWpg@mail.gmail.com>
Message-ID: <20170723232202.GA19130@cskk.homeip.net>

On 23Jul2017 19:02, Abdur-Rahmaan Janhangeer <arj.python at gmail.com> wrote:
>ah pylint yes, great checker ! *some guys thought of inventing it*

Yes, very handy. Greate for checking for simple logic errors too (variable used 
but never bound, missing imports, etc).

Just for folks' interest, I have a shell script called "lint" which I use which 
encapsulates my personal lint practices. Great for a final check before 
committing code.  I append it for anyone else to use or adapt.

Interactively I've got a personal shell function called "lint" which, if no 
files are specificly named, runs that script against whatever files are 
currently modified in my working code repo.  So one can just say "lint" at the 
shell prompt to get a report on one's work in progress.

Script appended below.

Cheers,
Cameron Simpson <cs at zip.com.au>

#!/bin/sh
#
# Lint the named files.
#   - Cameron Simpson <cs at zip.com.au> 22apr2017
#

set -ue

trace=
[ -t 2 ] && trace=set-x

cmd=$0
usage="Usage: $cmd filenames..."

[ $# -gt 0 ] || { echo "$cmd: missing filenames" >&2; echo "$usage" >&2; exit 2; }

xit=0

for lintfile
do
  case "$lintfile" in
    *.json)
      $trace json-pprint <"$lintfile" 2>&1 >/dev/null || xit=1
      ;;
    *.go)
      $trace go tool vet -all -shadowstrict "$lintfile" || xit=1
      ;;
    *.php)
      { $trace php -l "$lintfile" \
        && $trace phpcs --standard=PSR2 --report=emacs "$lintfile"
      } || xit=1
      ;;
    *.py)
      { $trace python3 -m py_compile "$lintfile" \
        && $trace pyflakes-2.7 "$lintfile" \
        && $trace pep8 --ignore=E111,E114,E126,E201,E202,E265,E266,E301,E302,E501,E731,W503 "$lintfile" \
        && $trace pylint "$lintfile"
      } || xit=1
      ;;
    *)echo "$cmd: no lint for $lintfile"
      ;;
  esac
done

exit $xit

From cs at zip.com.au  Sun Jul 23 19:11:58 2017
From: cs at zip.com.au (Cameron Simpson)
Date: Mon, 24 Jul 2017 09:11:58 +1000
Subject: [Tutor] Python help
In-Reply-To: <CAG8Q0obG=QJn1wje+Qe-3MMsnSmfdvpkov8UWpEnyKO4rNwK2w@mail.gmail.com>
References: <CAG8Q0obG=QJn1wje+Qe-3MMsnSmfdvpkov8UWpEnyKO4rNwK2w@mail.gmail.com>
Message-ID: <20170723231158.GA8656@cskk.homeip.net>

On 23Jul2017 13:40, Winonah Ojanen <winonah1992 at gmail.com> wrote:
>I also tried the correct command for the mac ox s in terminal shell,
>running:
>
>Jims-MacBook-Pro-2:~ Jim$
>PYTHONPATH="/Users/Jim/Documents/illustris_python:$PYTHONPATH
>> export PYTHONPATH
[...]
>> I did use the pip command and am attempting to add the files to my python
>> path. I used
>>  import sys
>> sys.path.append("/Users/Jim/Documents/illustris_python")

Please always reply-all or reply-to-list.

The python path is a list of places to look for modules. By adding 
'....../illustris_python' you're implying you want the module to be at 
'....../illustris_python/illustris_python'.

See if using '/Users/Jim/Documents' finds the module. Then move it to a better 
(more targeted) directory and use that directory's name :-)

Cheers,
Cameron Simpson <cs at zip.com.au>

From arj.python at gmail.com  Sun Jul 23 23:58:36 2017
From: arj.python at gmail.com (Abdur-Rahmaan Janhangeer)
Date: Mon, 24 Jul 2017 07:58:36 +0400
Subject: [Tutor] Quick Pythonic Style Tips
In-Reply-To: <20170724010936.GN3149@ando.pearwood.info>
References: <CADrxXXmuRjBKrm7S1VtG9Z0+a-KEKBfXuskxxH1JZ1o6ryMCxw@mail.gmail.com>
 <CADrxXX=WcvOUq-Me_myFftN67=vQYRXn=4Ap9wtpzs9emc_FHg@mail.gmail.com>
 <CADrxXXkdN3Y_ugaaeTYpUWrzPW5PQ_iL79R=YtK-Rm4TPGBOEQ@mail.gmail.com>
 <CADrxXXngz2uvf_ETbmxoX62yMOrhfpaNy2Cr5j=EhPVbA+4D+g@mail.gmail.com>
 <CADrxXXkZeQknyv6=uuf0S-9n9LrBNqyCVx2HE3+d9FyTuP464A@mail.gmail.com>
 <CADrxXX=MCSK=UBS_YcEF+Te3Zz-dc+5wBQ92YaD0XYzAWFU8NQ@mail.gmail.com>
 <okvkvc$cal$1@blaine.gmane.org>
 <bfe5b37b-101a-378a-b7be-cec867dd8c39@wichmann.us>
 <CAGZAPF4x5QS4u_eyK+juSxAi+kzYbrxnvpWweSqZNz2_7PBBpg@mail.gmail.com>
 <CADrxXX=saz8fbVDDg0Yhb4rXf9Lr6-aARVQuA03CKo=1QFfWpg@mail.gmail.com>
 <20170724010936.GN3149@ando.pearwood.info>
Message-ID: <CADrxXX=S2sZSTH89p+S_Df5RLtXMm13fSZckjhLM_uG-TTU7ig@mail.gmail.com>

nice, just wanted some "styling" guide rather than technical guides

you know doing things the python style rather than the python way

Abdur-Rahmaan Janhangeer,
Mauritius
abdurrahmaanjanhangeer.wordpress.com

On 24 Jul 2017 05:09, "Steven D'Aprano" <steve at pearwood.info> wrote:

> On Sun, Jul 23, 2017 at 07:02:09PM +0400, Abdur-Rahmaan Janhangeer wrote:
>
> > assert(... is liked by some strongly typed programmers
>
> Not just strongly-typed programmers:
>
> http://import-that.dreamwidth.org/676.html
>
>
> > data encapsulation might be depressing to some migrating coders
>
> "Data encapsulation" does not mean "data hiding". Python has excellent
> data encapsulation:
>
> - packages encapsulate modules together;
>
> - modules encapsulate classes, functions and variables together;
>
> - classes encapsulate object state and behaviour together.
>
>
> Compared to languages like C++ and Java, Python's data HIDING is weak.
> Python has no private, public, protected, etc.
>
> But even in the strictest languages like C++ and Java, there is usually
> some way to "defeat" the compiler and get access to private data and
> break data hiding. For instance, in C++ you can often do something like
>
> #define private public
>
> and in Java you can use reflection. The creator of Python, Guido van
> Rossum, understands that sometimes there *are* good uses for breaking
> data hiding (usually for testing and debugging). Because Python is an
> interpreter where most features are done at runtime rather than compile
> time, implementing data hiding in Python would hurt performance, and
> there would be some way to break it anyway.
>
> So why bother?
>
> Instead, Python is "for consenting adults". Data hiding is very simple:
> the developer flags objects they want to keep private with a leading
> underscore:
>
> _private
>
> and that tells you that this is private and you shouldn't touch it. If
> you decide to ignore this and touch it anyway, then:
>
> - either you have a good reason, and that's okay;
>
> - or you are a "consenting adult", and if your code blows up,
>   well, that's your own fault and don't complain to us.
>
>
>
> --
> Steve
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From brandonanderson at me.com  Mon Jul 24 02:40:21 2017
From: brandonanderson at me.com (Brandon Anderson)
Date: Sun, 23 Jul 2017 23:40:21 -0700
Subject: [Tutor] Python3 Help
In-Reply-To: <CAGZAPF7e=L7k+qFksVs2kirHcq0E40Td0CmO7mTb_2gY1MGw1A@mail.gmail.com>
References: <7B8D0BE1-006B-458A-9BE6-5BBC9F75D5F5@me.com>
 <CAGZAPF7e=L7k+qFksVs2kirHcq0E40Td0CmO7mTb_2gY1MGw1A@mail.gmail.com>
Message-ID: <B5AB77EA-B369-406C-8F2D-C4873CD68247@me.com>

Success!

Thank you, Danny!

Mission accomplished.

-Brandon

Sent from my iPhone

On Jul 23, 2017, at 5:44 PM, Danny Yoo <dyoo at hashcollision.org> wrote:

>> 2.  I?m trying to locate the directory path to where Python3 is located on my system, but when I enter
>>        the following command:
>>        $ type -a python3
>> 
>>        I get:
>>        -bash: $: command not found
> 
> 
> Ah.  Do not include the leading "$" in the command that you're typing.
> I'm assuming that you're reading some instruction that says something
> like this:
> 
> -------
> 
> Type the following into your command prompt:
> 
>    $ type -a python3
> 
> --------
> 
> If you are reading such an instruction, don't literally type the
> dollar sign.  "$" is a convention that's used to indicate to you to
> type the rest of the line into your command prompt.  It's because, by
> default, the command shell will use "$" as its primary prompt to tell
> the user that it is ready to accept a new command.
> (https://superuser.com/questions/57575/what-is-the-origin-of-the-unix-dollar-prompt)

From alan.gauld at yahoo.co.uk  Mon Jul 24 04:27:18 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 24 Jul 2017 09:27:18 +0100
Subject: [Tutor] Python3 Help
In-Reply-To: <ol3gns$1gm$1@blaine.gmane.org>
References: <7B8D0BE1-006B-458A-9BE6-5BBC9F75D5F5@me.com>
 <ol3gns$1gm$1@blaine.gmane.org>
Message-ID: <ol4b10$j0f$1@blaine.gmane.org>

On 24/07/17 01:58, Alan Gauld via Tutor wrote:

> $ which python3
> 
>> 	-bash: $: command not found  
> 
> The $ is the OS prompt you are not supposed to type it in.

While on the subject you might also see something like

# <some command>

Which can mean one of two things
1) It's a comment and you should not type it in
2) It's a root level command and you should su to root
   before running it. (# was the default Unix prompt
   for super users)

The latter usage is dying out and usually replaced with

$ sudo <some command>

Which means that as an ordinary user ($) you type sudo
before the command. sudo should then prompt for your
user password before carrying out the command.

But the older # prompt style is still around in some
onlne tutorials.

-- 
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 badouglas at gmail.com  Mon Jul 24 10:33:25 2017
From: badouglas at gmail.com (bruce)
Date: Mon, 24 Jul 2017 10:33:25 -0400
Subject: [Tutor] basic decorator question
Message-ID: <CAP16ngq88xZUk9JUVV-9ouCSG-Xu6ioMwUZa-BdPgxpvOXY1jg@mail.gmail.com>

Hi.

I've seen sites discuss decorators, as functions that "wrap" and
return functions.

But, I'm sooo confuzed! My real question though, can a decorator have
multiple internal functions? All the examples I've seen so far have a
single internal function.

And, if a decorator can have multiple internal functions, how would
the calling sequence work?

But as a start, if you have pointers to any really "basic" step by
step sites/examples I can look at, I'd appreciate it. I suspect I'm
getting flumoxed by something simple.

thanks

From mats at wichmann.us  Mon Jul 24 11:49:03 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Mon, 24 Jul 2017 09:49:03 -0600
Subject: [Tutor] basic decorator question
In-Reply-To: <CAP16ngq88xZUk9JUVV-9ouCSG-Xu6ioMwUZa-BdPgxpvOXY1jg@mail.gmail.com>
References: <CAP16ngq88xZUk9JUVV-9ouCSG-Xu6ioMwUZa-BdPgxpvOXY1jg@mail.gmail.com>
Message-ID: <a6639edf-2487-6f8c-07a8-40a83218d248@wichmann.us>

On 07/24/2017 08:33 AM, bruce wrote:
> Hi.
> 
> I've seen sites discuss decorators, as functions that "wrap" and
> return functions.
> 
> But, I'm sooo confuzed! My real question though, can a decorator have
> multiple internal functions? All the examples I've seen so far have a
> single internal function.
> 
> And, if a decorator can have multiple internal functions, how would
> the calling sequence work?
> 
> But as a start, if you have pointers to any really "basic" step by
> step sites/examples I can look at, I'd appreciate it. I suspect I'm
> getting flumoxed by something simple.

wrap and return are not two distinct things, they're part of the same
process...  the general concept is that a decorator changes the result
of a function without modifying the function itself by returning a new
function object which does some other stuff in addition to running the
code of the original function object.

This is a really simple wrapper:

def my_decorator(some_function):
    def wrapper():
        print("Stuff happening before some_function() is called.")
        some_function()
        print("Stuff after some_function() is called.")
    return wrapper

If you have an unwrapped function:

def foo():
    print "This is the unwrapped function"

You can show this in action like this:

foo()
bar = my_decorator(foo)
bar()

function names are just handles to the function object, so the middle
line of those three is passing the original function object referred to
by foo to my_decorator, whose inner function returns a function object
which is runs some code before and after the original function.  If the
undecorated fuction does not need to be referred to, the previous often
gets written as:

foo = my_decorator(foo)
foo()

Now to add Python's magical decorator syntax:

@my_decorator
def bar():
    print "This is another unwrapped function"

bar()

So all the @my_decorator bit does is provide shorthand for the syntax

bar = my_decorator(bar)

Wasn't ultra-clear on your original question; if you wanted the
"happening before" and "happening after" to call out to other functions
instead of doing a print, you can. Is that what you mean by multiple
internal functions?

Does this clarify at all?

Do hunt some, there are some really good tutorials on decorators.


From steve at pearwood.info  Mon Jul 24 12:01:30 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 25 Jul 2017 02:01:30 +1000
Subject: [Tutor] basic decorator question
In-Reply-To: <CAP16ngq88xZUk9JUVV-9ouCSG-Xu6ioMwUZa-BdPgxpvOXY1jg@mail.gmail.com>
References: <CAP16ngq88xZUk9JUVV-9ouCSG-Xu6ioMwUZa-BdPgxpvOXY1jg@mail.gmail.com>
Message-ID: <20170724160129.GP3149@ando.pearwood.info>

Hi Bruce,

On Mon, Jul 24, 2017 at 10:33:25AM -0400, bruce wrote:
> Hi.
> 
> I've seen sites discuss decorators, as functions that "wrap" and
> return functions.
> 
> But, I'm sooo confuzed! My real question though, can a decorator have
> multiple internal functions? All the examples I've seen so far have a
> single internal function.

Yes, a decorator can have multiple internal functions. A decorator is 
just a function, and it can contain anything a function contains. What 
makes it specifically a decorator is what you use it for.

Let's step back and cover a basic: nested functions.

def function(x):
    def add_one():
        return x + 1
    def times_two():
        return x*2
    return (add_one(), times_two())

function(10)


Can you predict what the result of that will be? I hope you can predict 
that it will return (11, 20). Can you see why?

That sort of nested function isn't very interesting, and you won't see 
much code doing that. But it demonstrates that a function can contain 
multiple inner functions. Now let's look at something that is often 
called a *factory function* -- a function which creates and returns a 
new function.

def factory(a):
    def inner(x):
        return a + x
    return inner  # No parentheses!

add_one = factory(1)  # create a new function & assign it to add_one
add_two = factory(2)

add_one(100)  # returns 101
add_two(100)  # returns 102

How this works isn't important (the technical term is "a closure") but 
the important factor is this: factory() creates a new function, and 
returns it. That function can then be used like any other function 
created with "def".

Functions can not only *return* functions as their return result, but 
they can take functions as arguments. We say that "functions are first 
class values" -- in Python, functions are just another kind of data, 
like ints, floats, strings, lists, dicts and more. The most common 
examples of passing a function as input to another function include:

- builtin functions map() and reduce();

- the key argument to sorted() and list.sort();

- GUI libraries that take callback functions;

- and of course, decorators.


So let's start to create our first decorator. A decorator takes a 
function as argument, "decorates" it in some way (usually by adding some 
sort of extra functionality), and then returns the decorated function. 
Here's a simple example: a decorator that makes the other function print 
a message.

def decorate(func):
    def inner(arg):
        print('received argument %r' % arg)
        return func(arg)
    return inner

Now let's set up a couple of functions:

def add_five(x):
    return x+5

def add_ten(x):
    return x+10

And decorate them:

add_five = decorate(add_five)
add_ten = decorate(add_ten)


Try predicting what 

result = add_five(100)

will print, and what the result will be. Likewise for:

result = add_ten(50)

Try running the code and see if you are correct.


The way I decorated the functions above is a little bit clumsy, so 
Python has a special syntax to make it easier: the "@decorate" syntax.

@decorate
def times_three(x):
    return x*3


result = times_three(5)


Can you predict what that will do?


There's more to decorators than that, but hopefully that will 
demonstrate some of the basic concepts. Feel free to ask any more 
questions on the mailing list, and we will answer if we can.


-- 
Steve

From __peter__ at web.de  Mon Jul 24 12:13:34 2017
From: __peter__ at web.de (Peter Otten)
Date: Mon, 24 Jul 2017 18:13:34 +0200
Subject: [Tutor] basic decorator question
References: <CAP16ngq88xZUk9JUVV-9ouCSG-Xu6ioMwUZa-BdPgxpvOXY1jg@mail.gmail.com>
Message-ID: <ol56b8$886$1@blaine.gmane.org>

bruce wrote:

> Hi.
> 
> I've seen sites discuss decorators, as functions that "wrap" and
> return functions.
> 
> But, I'm sooo confuzed! My real question though, can a decorator have
> multiple internal functions? All the examples I've seen so far have a
> single internal function.
> 
> And, if a decorator can have multiple internal functions, how would
> the calling sequence work?
> 
> But as a start, if you have pointers to any really "basic" step by
> step sites/examples I can look at, I'd appreciate it. I suspect I'm
> getting flumoxed by something simple.

Here's a completely useless decorator to drive home the point that

@deco
def f(...):
    ...

is only a fancy way to write

def f(...):
   ...
f = deco(f)


>>> def fortytwo(func):
...     print("I don't care about your function")
...     return 42
... 
>>> @fortytwo
... def f():
...     print("this is important")
... 
I don't care about your function
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> f
42



From alan.gauld at alan-g.me.uk  Mon Jul 24 13:52:09 2017
From: alan.gauld at alan-g.me.uk (Alan Gauld)
Date: Mon, 24 Jul 2017 18:52:09 +0100
Subject: [Tutor] Fwd: Re: basic decorator question
In-Reply-To: <4d377f20-d934-4eab-06ea-700f8781dbd9@yahoo.co.uk>
References: <4d377f20-d934-4eab-06ea-700f8781dbd9@yahoo.co.uk>
Message-ID: <2e72f2b6-f612-8e59-aa4b-40805759efa8@alan-g.me.uk>

Bah, Forgot to ReplyAll...



-------- Forwarded Message --------

On 24/07/17 15:33, bruce wrote:

> But, I'm sooo confuzed! My real question though, can a decorator have
> multiple internal functions? 

Yes and classes too if you want. A decorator is just a
standard function in all respects. The only thing that makes
it a decorator is that it takes a function as input and returns
a function as a result (ie it observes the decorator protocol).
Internally it can do anything that is legal in any function,
including creating as many inner functions and data structures
and classes as it wants.

> And, if a decorator can have multiple internal functions, how would
> the calling sequence work?

The calling sequence is just like any other code, it starts
at the top and follows the program control logic until it
either hits a return statement of falls off the bottom
(implicitly returning None). Note that the inner functions
do not need to be part of the returned function, they could
just be there to create some fixed value that is then stored
and used in the returned function.

eg:

def f(g):
 def h(): return 42
 myValue = h()
 def z():
   return myValue
 return z

f() is a decorator that takes a function g. It uses an
internal function h() to calculate a value. It then creates
a second inner function z() which returns that value.
Finally the decorator returns z. Notice that neither g()
nor h() are used in the returned function z().

You would use it like so:

def aFunc():
   return 666

always42 = f(aFunc)
print( always42() )

OR

@f
def aFunc() :return 666

print(aFunc())   # --> prints 42 !

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 boriscobizaro8 at gmail.com  Mon Jul 24 13:41:41 2017
From: boriscobizaro8 at gmail.com (Borisco Bizaro)
Date: Mon, 24 Jul 2017 10:41:41 -0700
Subject: [Tutor] Tutor Digest, Vol 161, Issue 36
In-Reply-To: <mailman.10.1500912003.10016.tutor@python.org>
References: <mailman.10.1500912003.10016.tutor@python.org>
Message-ID: <CAKE=nh7LdruDczR=M961AbOhvSE_R6jA24n2_Vwshq-R7Vwfog@mail.gmail.com>

Please what is the best way to study python programming well.
On Jul 24, 2017 17:00, <tutor-request at python.org> wrote:

> Send Tutor mailing list submissions to
>         tutor at python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>         https://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>         tutor-request at python.org
>
> You can reach the person managing the list at
>         tutor-owner at python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
> Today's Topics:
>
>    1. Re: Python3 Help (Alan Gauld)
>    2. basic decorator question (bruce)
>    3. Re: basic decorator question (Mats Wichmann)
>
>
> ---------- Forwarded message ----------
> From: Alan Gauld <alan.gauld at yahoo.co.uk>
> To: tutor at python.org
> Cc:
> Bcc:
> Date: Mon, 24 Jul 2017 09:27:18 +0100
> Subject: Re: [Tutor] Python3 Help
> On 24/07/17 01:58, Alan Gauld via Tutor wrote:
>
> > $ which python3
> >
> >>      -bash: $: command not found
> >
> > The $ is the OS prompt you are not supposed to type it in.
>
> While on the subject you might also see something like
>
> # <some command>
>
> Which can mean one of two things
> 1) It's a comment and you should not type it in
> 2) It's a root level command and you should su to root
>    before running it. (# was the default Unix prompt
>    for super users)
>
> The latter usage is dying out and usually replaced with
>
> $ sudo <some command>
>
> Which means that as an ordinary user ($) you type sudo
> before the command. sudo should then prompt for your
> user password before carrying out the command.
>
> But the older # prompt style is still around in some
> onlne tutorials.
>
> --
> 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
>
>
>
>
>
> ---------- Forwarded message ----------
> From: bruce <badouglas at gmail.com>
> To: Python Tutor Mailing List <tutor at python.org>
> Cc:
> Bcc:
> Date: Mon, 24 Jul 2017 10:33:25 -0400
> Subject: [Tutor] basic decorator question
> Hi.
>
> I've seen sites discuss decorators, as functions that "wrap" and
> return functions.
>
> But, I'm sooo confuzed! My real question though, can a decorator have
> multiple internal functions? All the examples I've seen so far have a
> single internal function.
>
> And, if a decorator can have multiple internal functions, how would
> the calling sequence work?
>
> But as a start, if you have pointers to any really "basic" step by
> step sites/examples I can look at, I'd appreciate it. I suspect I'm
> getting flumoxed by something simple.
>
> thanks
>
>
>
> ---------- Forwarded message ----------
> From: Mats Wichmann <mats at wichmann.us>
> To: bruce <badouglas at gmail.com>, Python Tutor Mailing List <
> tutor at python.org>
> Cc:
> Bcc:
> Date: Mon, 24 Jul 2017 09:49:03 -0600
> Subject: Re: [Tutor] basic decorator question
> On 07/24/2017 08:33 AM, bruce wrote:
> > Hi.
> >
> > I've seen sites discuss decorators, as functions that "wrap" and
> > return functions.
> >
> > But, I'm sooo confuzed! My real question though, can a decorator have
> > multiple internal functions? All the examples I've seen so far have a
> > single internal function.
> >
> > And, if a decorator can have multiple internal functions, how would
> > the calling sequence work?
> >
> > But as a start, if you have pointers to any really "basic" step by
> > step sites/examples I can look at, I'd appreciate it. I suspect I'm
> > getting flumoxed by something simple.
>
> wrap and return are not two distinct things, they're part of the same
> process...  the general concept is that a decorator changes the result
> of a function without modifying the function itself by returning a new
> function object which does some other stuff in addition to running the
> code of the original function object.
>
> This is a really simple wrapper:
>
> def my_decorator(some_function):
>     def wrapper():
>         print("Stuff happening before some_function() is called.")
>         some_function()
>         print("Stuff after some_function() is called.")
>     return wrapper
>
> If you have an unwrapped function:
>
> def foo():
>     print "This is the unwrapped function"
>
> You can show this in action like this:
>
> foo()
> bar = my_decorator(foo)
> bar()
>
> function names are just handles to the function object, so the middle
> line of those three is passing the original function object referred to
> by foo to my_decorator, whose inner function returns a function object
> which is runs some code before and after the original function.  If the
> undecorated fuction does not need to be referred to, the previous often
> gets written as:
>
> foo = my_decorator(foo)
> foo()
>
> Now to add Python's magical decorator syntax:
>
> @my_decorator
> def bar():
>     print "This is another unwrapped function"
>
> bar()
>
> So all the @my_decorator bit does is provide shorthand for the syntax
>
> bar = my_decorator(bar)
>
> Wasn't ultra-clear on your original question; if you wanted the
> "happening before" and "happening after" to call out to other functions
> instead of doing a print, you can. Is that what you mean by multiple
> internal functions?
>
> Does this clarify at all?
>
> Do hunt some, there are some really good tutorials on decorators.
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> https://mail.python.org/mailman/listinfo/tutor
>
>

From n6ghost at gmail.com  Mon Jul 24 18:32:40 2017
From: n6ghost at gmail.com (N6Ghost)
Date: Mon, 24 Jul 2017 15:32:40 -0700
Subject: [Tutor] new to python
In-Reply-To: <ol1l7e$3jm$1@blaine.gmane.org>
References: <5bf8a9be-29d5-c045-bfe1-e1c01f7ca466@gmail.com>
 <ol1l7e$3jm$1@blaine.gmane.org>
Message-ID: <00334dcd-e911-8c54-cb32-3ade1722c302@gmail.com>



On 7/23/2017 1:03 AM, Alan Gauld via Tutor wrote:
> On 23/07/17 07:26, N6Ghost wrote:
>
>> f = open("C:\coderoot\python3\level1\inputfile.txt", 'r')
>> for line in file:
> Note that you have no variable called 'file'.
> So this line doesn't make sense.
>
>>       for line in f:
>>           print(line.rstripe())
> This bit will work if you omit the line above and
> fix the indentation. (and remove the 'e' from strip()
>
>>           f.close()
> This should be outside the loop, you don't want
> to close the file after every line.
>
> Finally, there is another way to do this which
> is considered 'better'/more Pythonic:
>
> with open("C:\coderoot\python3\level1\inputfile.txt", 'r') as f:
>       for line in f:
>           print(line.strip())
>
> Notice with this construct the closing of the file is
> handled for you.
>
>> any idea why that does not work?
> When posting questions always include the full error text.
> Although apparently cryptic it actually contains a lot of
> useful detail which saves us from making guesses.
>

update code:
f = open("C:\coderoot\python3\level1\inputfile.txt", 'r')
for line in f:
     for line in f:
         print(line.rstripe())

         f.close()


C:\coderoot\python3\level1>python secondscript.py
Traceback (most recent call last):
   File "secondscript.py", line 5, in <module>
     print(line.rstripe())
AttributeError: 'str' object has no attribute 'rstripe'





From mats at wichmann.us  Mon Jul 24 19:33:15 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Mon, 24 Jul 2017 17:33:15 -0600
Subject: [Tutor] new to python
In-Reply-To: <00334dcd-e911-8c54-cb32-3ade1722c302@gmail.com>
References: <5bf8a9be-29d5-c045-bfe1-e1c01f7ca466@gmail.com>
 <ol1l7e$3jm$1@blaine.gmane.org>
 <00334dcd-e911-8c54-cb32-3ade1722c302@gmail.com>
Message-ID: <feb180ed-7a6e-cdc4-1e14-19f0a1097702@wichmann.us>

On 07/24/2017 04:32 PM, N6Ghost wrote:

> update code:
> f = open("C:\coderoot\python3\level1\inputfile.txt", 'r')
> for line in f:
>     for line in f:
>         print(line.rstripe())
> 
>         f.close()
> 
> 
> C:\coderoot\python3\level1>python secondscript.py
> Traceback (most recent call last):
>   File "secondscript.py", line 5, in <module>
>     print(line.rstripe())
> AttributeError: 'str' object has no attribute 'rstripe'

You presumably meant 'rstrip' (strip from right) rather than 'rstripe'.
With errors like this, look in the documentation to see the available
methods:

https://docs.python.org/3/library/stdtypes.html#string-methods

From n6ghost at gmail.com  Mon Jul 24 23:58:23 2017
From: n6ghost at gmail.com (N6Ghost)
Date: Mon, 24 Jul 2017 20:58:23 -0700
Subject: [Tutor] new to python
In-Reply-To: <ol1l7e$3jm$1@blaine.gmane.org>
References: <5bf8a9be-29d5-c045-bfe1-e1c01f7ca466@gmail.com>
 <ol1l7e$3jm$1@blaine.gmane.org>
Message-ID: <a2fd26ce-7f1c-c64b-dce5-a6832d695223@gmail.com>



On 7/23/2017 1:03 AM, Alan Gauld via Tutor wrote:
> On 23/07/17 07:26, N6Ghost wrote:
>
>> f = open("C:\coderoot\python3\level1\inputfile.txt", 'r')
>> for line in file:
> Note that you have no variable called 'file'.
> So this line doesn't make sense.
>
>>       for line in f:
>>           print(line.rstripe())
> This bit will work if you omit the line above and
> fix the indentation. (and remove the 'e' from strip()
>
>>           f.close()
> This should be outside the loop, you don't want
> to close the file after every line.
>
> Finally, there is another way to do this which
> is considered 'better'/more Pythonic:
>
> with open("C:\coderoot\python3\level1\inputfile.txt", 'r') as f:
>       for line in f:
>           print(line.strip())
>
> Notice with this construct the closing of the file is
> handled for you.
>
>> any idea why that does not work?
> When posting questions always include the full error text.
> Although apparently cryptic it actually contains a lot of
> useful detail which saves us from making guesses.
>


this code works
f = open("C:/coderoot/python3/level1/inputfile.txt", 'r')
for line in f:
     for line in f:
         #print(line.rstrip())
         print(line)

f.close()f = open("C:/coderoot/python3/level1/inputfile.txt", 'r')
for line in f:
     for line in f:
         #print(line.rstrip())
         print(line)

f.close()

the out put skips the first line of the inputfile and puts a blank line 
inbetween

inputfile is:
tom
jerry
make
windows
linux

-N6Ghost


From alan.gauld at yahoo.co.uk  Tue Jul 25 03:31:39 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 25 Jul 2017 08:31:39 +0100
Subject: [Tutor] Study Python was: Re: Tutor Digest, Vol 161, Issue 36
In-Reply-To: <CAKE=nh7LdruDczR=M961AbOhvSE_R6jA24n2_Vwshq-R7Vwfog@mail.gmail.com>
References: <mailman.10.1500912003.10016.tutor@python.org>
 <CAKE=nh7LdruDczR=M961AbOhvSE_R6jA24n2_Vwshq-R7Vwfog@mail.gmail.com>
Message-ID: <ol6s4l$a28$1@blaine.gmane.org>

On 24/07/17 18:41, Borisco Bizaro wrote:
> Please what is the best way to study python programming well.

One important skill is to read and follow instructions.
For example...

> On Jul 24, 2017 17:00, <tutor-request at python.org> wrote:
> 
>> Send Tutor mailing list submissions to
>>         tutor at python.org
>>
...
>>
>> When replying, please edit your Subject line so it is more specific
>> than "Re: Contents of Tutor digest..."

Also, do not  resend the entire digest - we have already
seen the messages and some members pay by the byte for
internet access.

As for learning Python there are videos on Youtube, multiple online
tutorials at every level and literally dozens of books. It all
depends on your personal learning style and your previous
programming experience.

I'd suggest you start with a few YouTube videos to get a feel
for things then dive into an online tutorial. The important thing
is to write code. Not just what the tutorials show you but take
that as a starter and modify it. See if the changes do what
you expected, if not figure out why not.

If you get stuck as questions here. Always tell us your Python
version and OS, post the problem code (cut n paste) and the full
error message if any.


-- 
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 andreengels at gmail.com  Tue Jul 25 03:41:05 2017
From: andreengels at gmail.com (Andre Engels)
Date: Tue, 25 Jul 2017 09:41:05 +0200
Subject: [Tutor] new to python
In-Reply-To: <a2fd26ce-7f1c-c64b-dce5-a6832d695223@gmail.com>
References: <5bf8a9be-29d5-c045-bfe1-e1c01f7ca466@gmail.com>
 <ol1l7e$3jm$1@blaine.gmane.org>
 <a2fd26ce-7f1c-c64b-dce5-a6832d695223@gmail.com>
Message-ID: <CAGzCZ0r_rKQD6dUnUHpLKYYXHwspTE1Wfc5kL0zOb3RtZ4kKow@mail.gmail.com>

The problem here is that you have doubled the "for line in f:" line.
Given that you say you know some programming, I'll just cut to the
technical name of the problem you are having: You are changing the
value of a loop variable (by starting an inner loop with the same loop
variable) inside a loop. Doing that in Python leads to behaviour that
is hard to understand and almost never what you intended.


On Tue, Jul 25, 2017 at 5:58 AM, N6Ghost <n6ghost at gmail.com> wrote:
>
>
> On 7/23/2017 1:03 AM, Alan Gauld via Tutor wrote:
>>
>> On 23/07/17 07:26, N6Ghost wrote:
>>
>>> f = open("C:\coderoot\python3\level1\inputfile.txt", 'r')
>>> for line in file:
>>
>> Note that you have no variable called 'file'.
>> So this line doesn't make sense.
>>
>>>       for line in f:
>>>           print(line.rstripe())
>>
>> This bit will work if you omit the line above and
>> fix the indentation. (and remove the 'e' from strip()
>>
>>>           f.close()
>>
>> This should be outside the loop, you don't want
>> to close the file after every line.
>>
>> Finally, there is another way to do this which
>> is considered 'better'/more Pythonic:
>>
>> with open("C:\coderoot\python3\level1\inputfile.txt", 'r') as f:
>>       for line in f:
>>           print(line.strip())
>>
>> Notice with this construct the closing of the file is
>> handled for you.
>>
>>> any idea why that does not work?
>>
>> When posting questions always include the full error text.
>> Although apparently cryptic it actually contains a lot of
>> useful detail which saves us from making guesses.
>>
>
>
> this code works
> f = open("C:/coderoot/python3/level1/inputfile.txt", 'r')
> for line in f:
>     for line in f:
>         #print(line.rstrip())
>         print(line)
>
> f.close()f = open("C:/coderoot/python3/level1/inputfile.txt", 'r')
> for line in f:
>     for line in f:
>         #print(line.rstrip())
>         print(line)
>
> f.close()
>
> the out put skips the first line of the inputfile and puts a blank line
> inbetween
>
> inputfile is:
> tom
> jerry
> make
> windows
> linux
>
> -N6Ghost
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



-- 
Andr? Engels, andreengels at gmail.com

From alan.gauld at yahoo.co.uk  Tue Jul 25 03:43:46 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 25 Jul 2017 08:43:46 +0100
Subject: [Tutor] new to python
In-Reply-To: <a2fd26ce-7f1c-c64b-dce5-a6832d695223@gmail.com>
References: <5bf8a9be-29d5-c045-bfe1-e1c01f7ca466@gmail.com>
 <ol1l7e$3jm$1@blaine.gmane.org>
 <a2fd26ce-7f1c-c64b-dce5-a6832d695223@gmail.com>
Message-ID: <ol6src$gir$1@blaine.gmane.org>

On 25/07/17 04:58, N6Ghost wrote:

> this code works

> f = open("C:/coderoot/python3/level1/inputfile.txt", 'r')
> for line in f:
>      for line in f:
>          #print(line.rstrip())
>          print(line)
> 
> f.close()

> the out put skips the first line of the inputfile and puts a blank line 
> inbetween


I'm not sure why you have two for loops? Why did you do that?
Can you explain your thinking there?

Remove one of the for... lines.

Your code does this:

> f = open("C:/coderoot/python3/level1/inputfile.txt", 'r')

open the file and assign it to 'f'

> for line in f:

get the first line from f and assign it to 'line'

>      for line in f: print(line)

get the next line from f and assign it to 'line'
This overwrites the value from the first for loop above.
The line is then printed.

The second loop then repeats for all of the remaining
lines in the file. At the end of the second for loop
control returns to the top for loop. But, since the file
is now empty, the top loop never gets any more values
from f, so it terminates.

The blank lines are caused by the fact that the lines
in the file end in a newline character and print() adds
a newline of its own. Either reinstate your rstrip()
call or stop print() adding a newline with

print(line, end='')

I'm also not sure why you posted two copies of
your code? I assume you only use one since otherwise
you would have told us that you got two lots of output?

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 n6ghost at gmail.com  Wed Jul 26 16:53:07 2017
From: n6ghost at gmail.com (N6Ghost)
Date: Wed, 26 Jul 2017 13:53:07 -0700
Subject: [Tutor] new to python
In-Reply-To: <ol6src$gir$1@blaine.gmane.org>
References: <5bf8a9be-29d5-c045-bfe1-e1c01f7ca466@gmail.com>
 <ol1l7e$3jm$1@blaine.gmane.org>
 <a2fd26ce-7f1c-c64b-dce5-a6832d695223@gmail.com>
 <ol6src$gir$1@blaine.gmane.org>
Message-ID: <41c4d217-c637-333b-ff1e-f0a2e79a1004@gmail.com>



On 7/25/2017 12:43 AM, Alan Gauld via Tutor wrote:
> On 25/07/17 04:58, N6Ghost wrote:
>
>> this code works
>> f = open("C:/coderoot/python3/level1/inputfile.txt", 'r')
>> for line in f:
>>       for line in f:
>>           #print(line.rstrip())
>>           print(line)
>>
>> f.close()
>> the out put skips the first line of the inputfile and puts a blank line
>> inbetween
>
> I'm not sure why you have two for loops? Why did you do that?
> Can you explain your thinking there?
>
> Remove one of the for... lines.
>
> Your code does this:
>
>> f = open("C:/coderoot/python3/level1/inputfile.txt", 'r')
> open the file and assign it to 'f'
>
>> for line in f:
> get the first line from f and assign it to 'line'
>
>>       for line in f: print(line)
> get the next line from f and assign it to 'line'
> This overwrites the value from the first for loop above.
> The line is then printed.
>
> The second loop then repeats for all of the remaining
> lines in the file. At the end of the second for loop
> control returns to the top for loop. But, since the file
> is now empty, the top loop never gets any more values
> from f, so it terminates.
>
> The blank lines are caused by the fact that the lines
> in the file end in a newline character and print() adds
> a newline of its own. Either reinstate your rstrip()
> call or stop print() adding a newline with
>
> print(line, end='')
>
> I'm also not sure why you posted two copies of
> your code? I assume you only use one since otherwise
> you would have told us that you got two lots of output?
>
> HTH

final working code for this method:
# open meth 1
f = open("C:/coderoot/python3/level1/inputfile.txt", 'r')
for line in f:
         #print(line.rstrip())
         print(line.strip())
         j = line
         #print ("****below new var used****")
         #print (j)

f.close()


thanks for the replys, not sure why i had the second for loop. removing 
that remove some of the oddball behavioral issues.

next going to look into using the with....



From tmrsg11 at gmail.com  Wed Jul 26 14:40:17 2017
From: tmrsg11 at gmail.com (C W)
Date: Wed, 26 Jul 2017 14:40:17 -0400
Subject: [Tutor] What's the difference between sort(aList) and aList.sorted()
Message-ID: <CAE2FW2nA8yq_bVLs8N+KQkkxoRokoCcHPJdfZ2tdE+J2ycNdVw@mail.gmail.com>

Dear Python experts,

I suppose I have the following Python code:

aList = [3, 5, 2, 4]

sorted(aList)
> [2, 3, 4, 5]

aList.sort()

aList
> [2, 3, 4, 5]

My understanding of each is:
1) function(variable) is manipulating a vector, I can do bList =
sorted(aList)
2) object.method() is permanently changing it, I don't even need to assign
it in #1.

Why is there both? They do the same thing. Is if I unknowingly hit the
keyboard with the aList.sort(), then the "damage" is permanent.

Thank you!

From joel.goldstick at gmail.com  Wed Jul 26 18:37:11 2017
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Wed, 26 Jul 2017 18:37:11 -0400
Subject: [Tutor] What's the difference between sort(aList) and
 aList.sorted()
In-Reply-To: <CAE2FW2nA8yq_bVLs8N+KQkkxoRokoCcHPJdfZ2tdE+J2ycNdVw@mail.gmail.com>
References: <CAE2FW2nA8yq_bVLs8N+KQkkxoRokoCcHPJdfZ2tdE+J2ycNdVw@mail.gmail.com>
Message-ID: <CAPM-O+y-agE038Ek_sA-nHXuxrd5EfWY3GDFTzX8xchQPiT7ig@mail.gmail.com>

On Wed, Jul 26, 2017 at 2:40 PM, C W <tmrsg11 at gmail.com> wrote:

> Dear Python experts,
>
> I suppose I have the following Python code:
>
> aList = [3, 5, 2, 4]
>
> sorted(aList)
> > [2, 3, 4, 5]
>
> aList.sort()
>
> aList
> > [2, 3, 4, 5]
>
> My understanding of each is:
> 1) function(variable) is manipulating a vector, I can do bList =
> sorted(aList)
> 2) object.method() is permanently changing it, I don't even need to assign
> it in #1.
>
> Why is there both? They do the same thing. Is if I unknowingly hit the
> keyboard with the aList.sort(), then the "damage" is permanent.
>
> Thank you!
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

I haven't looked it up recently, but one sorts in place (object.method) i
think, and the other  (a function) returns a new sorted list

-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays

From alan.gauld at yahoo.co.uk  Wed Jul 26 19:36:16 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 27 Jul 2017 00:36:16 +0100
Subject: [Tutor] What's the difference between sort(aList) and
 aList.sorted()
In-Reply-To: <CAE2FW2nA8yq_bVLs8N+KQkkxoRokoCcHPJdfZ2tdE+J2ycNdVw@mail.gmail.com>
References: <CAE2FW2nA8yq_bVLs8N+KQkkxoRokoCcHPJdfZ2tdE+J2ycNdVw@mail.gmail.com>
Message-ID: <olb91a$lck$1@blaine.gmane.org>

On 26/07/17 19:40, C W wrote:

> My understanding of each is:
> 1) function(variable) is manipulating a vector, I can do bList =
> sorted(aList)
> 2) object.method() is permanently changing it, I don't even need to assign
> it in #1.
> 
> Why is there both? They do the same thing.

As you have just shown they do very different things.
One sorts the list in place the other returns a sorted
copy of the list.

Sometimes you want one, sometimes the other.


-- 
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  Wed Jul 26 20:21:11 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 27 Jul 2017 10:21:11 +1000
Subject: [Tutor] What's the difference between sort(aList) and
 aList.sorted()
In-Reply-To: <CAE2FW2nA8yq_bVLs8N+KQkkxoRokoCcHPJdfZ2tdE+J2ycNdVw@mail.gmail.com>
References: <CAE2FW2nA8yq_bVLs8N+KQkkxoRokoCcHPJdfZ2tdE+J2ycNdVw@mail.gmail.com>
Message-ID: <20170727002111.GX3149@ando.pearwood.info>

On Wed, Jul 26, 2017 at 02:40:17PM -0400, C W wrote:

> sorted(aList)
> > [2, 3, 4, 5]

sorted() makes a copy of whatever you give it, as a list, and sorts the 
copy. It doesn't have to be a list to start with:

py> sorted("alphabet")
['a', 'a', 'b', 'e', 'h', 'l', 'p', 't']


> aList.sort()
> aList
> > [2, 3, 4, 5]

The sort() method only works on actual lists, and it sorts the list in 
place, just as list.reverse() reverses the list, list.append() appends a 
value to the list, list.insert() inserts a value into the list, etc.

> Why is there both? They do the same thing. Is if I unknowingly hit the
> keyboard with the aList.sort(), then the "damage" is permanent.

They don't do the same thing. sorted() makes a copy of the argument 
first, list.sort() does not.

We have both because sometimes one is useful and other times the other 
is useful. Originally, and for many years, Python only had list.sort(), 
and if you wanted to sort a copy you had to write:

blist = list(alist)
blist.sort()

which is always a minimum of two lines and not very convenient. So it 
was eventually decided to add sorted().



-- 
Steve

From steve at pearwood.info  Wed Jul 26 22:16:08 2017
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 27 Jul 2017 12:16:08 +1000
Subject: [Tutor] What's the difference between sort(aList) and
 aList.sorted()
In-Reply-To: <CAE2FW2mvKAjCg_1kSiv=cEdMXgc-k-YH-JqwBKWh+0ssfu=kkQ@mail.gmail.com>
References: <CAE2FW2nA8yq_bVLs8N+KQkkxoRokoCcHPJdfZ2tdE+J2ycNdVw@mail.gmail.com>
 <20170727002111.GX3149@ando.pearwood.info>
 <CAE2FW2mvKAjCg_1kSiv=cEdMXgc-k-YH-JqwBKWh+0ssfu=kkQ@mail.gmail.com>
Message-ID: <20170727021608.GA3149@ando.pearwood.info>

On Wed, Jul 26, 2017 at 10:03:59PM -0400, C W wrote:
> Thank you very much, all!
> 
> One other question: how do you look up a method?

Any of these will work:

help(list.sort)

help([].sort)

alist = [1, 2, 3, 99]
help(alist.sort)




-- 
Steve

From robertvstepp at gmail.com  Wed Jul 26 22:22:59 2017
From: robertvstepp at gmail.com (boB Stepp)
Date: Wed, 26 Jul 2017 21:22:59 -0500
Subject: [Tutor] basic decorator question
In-Reply-To: <20170724160129.GP3149@ando.pearwood.info>
References: <CAP16ngq88xZUk9JUVV-9ouCSG-Xu6ioMwUZa-BdPgxpvOXY1jg@mail.gmail.com>
 <20170724160129.GP3149@ando.pearwood.info>
Message-ID: <CANDiX9J0SyO4+_4UwNFBjqS1a-8O4CTj6brV9VF0CchQf255WA@mail.gmail.com>

On Mon, Jul 24, 2017 at 11:01 AM, Steven D'Aprano <steve at pearwood.info> wrote:

>
> There's more to decorators than that, but hopefully that will
> demonstrate some of the basic concepts. Feel free to ask any more
> questions on the mailing list, and we will answer if we can.
>

I hope I can ask questions, too!  ~(:>))

I am having a recurring problem with Python:  I can work out the
mechanics of how various Python constructs work, such as decorators,
but then I find myself scratching my head as to why would I want to
use them.  The idea of replacing a function with its decorated version
sounds cool, but what types of problems would I want to use this
approach on?

One thing that bothers me, is that once I decorate the function, I no
longer have access to the original, un-decorated function.  But on the
other hand, if I had a decorator which I wanted to apply to multiple
functions, then I would be DRY-er by taking this approach -- I would
need only one decorator function and could then use it decorate as
many other functions as it made sense to do so.

So some guidance, please, on what types of problems this approach is useful for?

TIA!

-- 
boB

From tmrsg11 at gmail.com  Wed Jul 26 22:03:59 2017
From: tmrsg11 at gmail.com (C W)
Date: Wed, 26 Jul 2017 22:03:59 -0400
Subject: [Tutor] What's the difference between sort(aList) and
 aList.sorted()
In-Reply-To: <20170727002111.GX3149@ando.pearwood.info>
References: <CAE2FW2nA8yq_bVLs8N+KQkkxoRokoCcHPJdfZ2tdE+J2ycNdVw@mail.gmail.com>
 <20170727002111.GX3149@ando.pearwood.info>
Message-ID: <CAE2FW2mvKAjCg_1kSiv=cEdMXgc-k-YH-JqwBKWh+0ssfu=kkQ@mail.gmail.com>

Thank you very much, all!

One other question: how do you look up a method?

>help(sort)
Traceback (most recent call last):

  File "<ipython-input-1-1dcda44a1b89>", line 1, in <module>
    help(sort)

NameError: name 'sort' is not defined


Back to function vs method, I came from R:

aList = sort(aList)

There was never aList.sort(), I was fine with it for years. I suppose
sort(aList) is more of a data science thing.

Thanks to all!


On Wed, Jul 26, 2017 at 8:21 PM, Steven D'Aprano <steve at pearwood.info>
wrote:

> On Wed, Jul 26, 2017 at 02:40:17PM -0400, C W wrote:
>
> > sorted(aList)
> > > [2, 3, 4, 5]
>
> sorted() makes a copy of whatever you give it, as a list, and sorts the
> copy. It doesn't have to be a list to start with:
>
> py> sorted("alphabet")
> ['a', 'a', 'b', 'e', 'h', 'l', 'p', 't']
>
>
> > aList.sort()
> > aList
> > > [2, 3, 4, 5]
>
> The sort() method only works on actual lists, and it sorts the list in
> place, just as list.reverse() reverses the list, list.append() appends a
> value to the list, list.insert() inserts a value into the list, etc.
>
> > Why is there both? They do the same thing. Is if I unknowingly hit the
> > keyboard with the aList.sort(), then the "damage" is permanent.
>
> They don't do the same thing. sorted() makes a copy of the argument
> first, list.sort() does not.
>
> We have both because sometimes one is useful and other times the other
> is useful. Originally, and for many years, Python only had list.sort(),
> and if you wanted to sort a copy you had to write:
>
> blist = list(alist)
> blist.sort()
>
> which is always a minimum of two lines and not very convenient. So it
> was eventually decided to add sorted().
>
>
>
> --
> Steve
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From tmrsg11 at gmail.com  Wed Jul 26 22:22:45 2017
From: tmrsg11 at gmail.com (C W)
Date: Wed, 26 Jul 2017 22:22:45 -0400
Subject: [Tutor] What's the difference between sort(aList) and
 aList.sorted()
In-Reply-To: <20170727021608.GA3149@ando.pearwood.info>
References: <CAE2FW2nA8yq_bVLs8N+KQkkxoRokoCcHPJdfZ2tdE+J2ycNdVw@mail.gmail.com>
 <20170727002111.GX3149@ando.pearwood.info>
 <CAE2FW2mvKAjCg_1kSiv=cEdMXgc-k-YH-JqwBKWh+0ssfu=kkQ@mail.gmail.com>
 <20170727021608.GA3149@ando.pearwood.info>
Message-ID: <CAE2FW2ndsYgP3DOy9vRYyUpTqBGm_feFy_BVpTRv69Ej1D+vow@mail.gmail.com>

Thank you very much, Steve!

I think I got it. To get help() on a method, you have to somehow invoke an
object first.

In your example, even an empty vector [] will do.

Thanks!

On Wed, Jul 26, 2017 at 10:16 PM, Steven D'Aprano <steve at pearwood.info>
wrote:

> On Wed, Jul 26, 2017 at 10:03:59PM -0400, C W wrote:
> > Thank you very much, all!
> >
> > One other question: how do you look up a method?
>
> Any of these will work:
>
> help(list.sort)
>
> help([].sort)
>
> alist = [1, 2, 3, 99]
> help(alist.sort)
>
>
>
>
> --
> Steve
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From alan.gauld at yahoo.co.uk  Thu Jul 27 02:25:00 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 27 Jul 2017 07:25:00 +0100
Subject: [Tutor] basic decorator question
In-Reply-To: <CANDiX9J0SyO4+_4UwNFBjqS1a-8O4CTj6brV9VF0CchQf255WA@mail.gmail.com>
References: <CAP16ngq88xZUk9JUVV-9ouCSG-Xu6ioMwUZa-BdPgxpvOXY1jg@mail.gmail.com>
 <20170724160129.GP3149@ando.pearwood.info>
 <CANDiX9J0SyO4+_4UwNFBjqS1a-8O4CTj6brV9VF0CchQf255WA@mail.gmail.com>
Message-ID: <olc0vm$tjv$1@blaine.gmane.org>

On 27/07/17 03:22, boB Stepp wrote:

> use them.  The idea of replacing a function with its decorated version
> sounds cool, but what types of problems would I want to use this
> approach on?

I'm sure others will have their own take on this but personally I view
them as primarily for building frameworks. For example in the standard
Python pantheon we use decorators to create properties and classmethods.

Web frameworks like Django use decorators extensively.

They are a way of embedding user code into our framework code without
the user having to know anything about how the framework does its magic.

And that is why I try not to use decorators for day to day code -
because they hide how the code works. Its similar with metaclasses,
they are immensely powerful but should be used sparingly because they
obfuscate how the code is working. And that, IMHO, is a bad thing.

So if you have some functionality that you want to wrap around a
set of functions in a standard way while at the same time not impinging
on the core logic of those functions then use a decorator. If you are
not sure why you are using them don't use them, just write an explicit
wrapper instead.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Thu Jul 27 02:28:43 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 27 Jul 2017 07:28:43 +0100
Subject: [Tutor] What's the difference between sort(aList) and
 aList.sorted()
In-Reply-To: <CAE2FW2ndsYgP3DOy9vRYyUpTqBGm_feFy_BVpTRv69Ej1D+vow@mail.gmail.com>
References: <CAE2FW2nA8yq_bVLs8N+KQkkxoRokoCcHPJdfZ2tdE+J2ycNdVw@mail.gmail.com>
 <20170727002111.GX3149@ando.pearwood.info>
 <CAE2FW2mvKAjCg_1kSiv=cEdMXgc-k-YH-JqwBKWh+0ssfu=kkQ@mail.gmail.com>
 <20170727021608.GA3149@ando.pearwood.info>
 <CAE2FW2ndsYgP3DOy9vRYyUpTqBGm_feFy_BVpTRv69Ej1D+vow@mail.gmail.com>
Message-ID: <olc16l$tjv$2@blaine.gmane.org>

On 27/07/17 03:22, C W wrote:
> Thank you very much, Steve!
> 
> I think I got it. To get help() on a method, you have to somehow invoke an
> object first.

Or just use the class. In Steven's examples he included list.sort.
'list' is the class name for a list.

-- 
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 davidtorres7888 at gmail.com  Fri Jul 28 16:10:53 2017
From: davidtorres7888 at gmail.com (David Torres)
Date: Fri, 28 Jul 2017 15:10:53 -0500
Subject: [Tutor] Installing NUMPY
Message-ID: <CA+ZCVFDsgLnX0Rbi6VJpjjzM_0FMyMdTdjOra9XXVTHqHqLerg@mail.gmail.com>

Hello,
I am having trouble executing a scripty that imports numpy. I have a
feeling its because I had an old version of Numpy when I was using python
2.7. I am now using Pyhton 3X and I am getting the following error when I
execute the program:::


ImportError:
Importing the multiarray numpy extension module failed.  Most
likely you are trying to import a failed build of numpy.
If you're working with a numpy git repo, try `git clean -xdf` (removes all
files not under version control).  Otherwise reinstall numpy.

Original error was: DLL load failed: The specified procedure could not be
found.



Please let me know if we can email each other or call. I would appreciate
your help, I am very desperate! Thanks
David A. Torres
GitHub : https://github.com/dav1dt0rres
-Man lives like a robot: mechanically efficient, but with no awareness.
Department of Computer Science



Department of Mathematics
Department of Economics

From boriscobizaro8 at gmail.com  Sun Jul 30 14:50:22 2017
From: boriscobizaro8 at gmail.com (Borisco Bizaro)
Date: Sun, 30 Jul 2017 11:50:22 -0700
Subject: [Tutor] Tutor Digest, Vol 161, Issue 41
In-Reply-To: <mailman.12.1501344003.18701.tutor@python.org>
References: <mailman.12.1501344003.18701.tutor@python.org>
Message-ID: <CAKE=nh6a15eGEZGAUztT4pYrFbJuk1YOpy9EGzmdi=GOa7EBVg@mail.gmail.com>

Please I have been ask to write python code that ask user to enter a price
continuetly until key press to and give the total amount of price I have
enter using while loop I don't know how to go about it,please help me
On Jul 29, 2017 17:00, <tutor-request at python.org> wrote:

> Send Tutor mailing list submissions to
>         tutor at python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>         https://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>         tutor-request at python.org
>
> You can reach the person managing the list at
>         tutor-owner at python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
> Today's Topics:
>
>    1. Installing NUMPY (David Torres)
>
>
> ---------- Forwarded message ----------
> From: David Torres <davidtorres7888 at gmail.com>
> To: tutor at python.org
> Cc:
> Bcc:
> Date: Fri, 28 Jul 2017 15:10:53 -0500
> Subject: [Tutor] Installing NUMPY
> Hello,
> I am having trouble executing a scripty that imports numpy. I have a
> feeling its because I had an old version of Numpy when I was using python
> 2.7. I am now using Pyhton 3X and I am getting the following error when I
> execute the program:::
>
>
> ImportError:
> Importing the multiarray numpy extension module failed.  Most
> likely you are trying to import a failed build of numpy.
> If you're working with a numpy git repo, try `git clean -xdf` (removes all
> files not under version control).  Otherwise reinstall numpy.
>
> Original error was: DLL load failed: The specified procedure could not be
> found.
>
>
>
> Please let me know if we can email each other or call. I would appreciate
> your help, I am very desperate! Thanks
> David A. Torres
> GitHub : https://github.com/dav1dt0rres
> -Man lives like a robot: mechanically efficient, but with no awareness.
> Department of Computer Science
>
>
>
> Department of Mathematics
> Department of Economics
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> https://mail.python.org/mailman/listinfo/tutor
>
>

From alan.gauld at yahoo.co.uk  Sun Jul 30 18:40:57 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 30 Jul 2017 23:40:57 +0100
Subject: [Tutor] Tutor Digest, Vol 161, Issue 41
In-Reply-To: <CAKE=nh6a15eGEZGAUztT4pYrFbJuk1YOpy9EGzmdi=GOa7EBVg@mail.gmail.com>
References: <mailman.12.1501344003.18701.tutor@python.org>
 <CAKE=nh6a15eGEZGAUztT4pYrFbJuk1YOpy9EGzmdi=GOa7EBVg@mail.gmail.com>
Message-ID: <olln9i$9bq$1@blaine.gmane.org>

On 30/07/17 19:50, Borisco Bizaro wrote:
> Please I have been ask to write python code that ask user to enter a price
> continuetly until key press to and give the total amount of price I have
> enter using while loop I don't know how to go about it

First of all, please do not send the whole digest to the list
 - some people pay by the byte and we've all seen it already.

Second, we solve programming challenges by breaking them down
into small parts and solving each part.

Third we don't do homework for you, but we can point you
in the right direction.

So, looking at your problem...

> ...write python code that ask user to enter a price

Do you know how to do that bit? get the usr to enter
a price and store (or print) the value?

> continuetly until key press

We'll come back to this.

> to and give the total amount of price

Do you know how to get the total of a list of prices?
For exanmple if I say

prices = [12, 13.00, 24.50. 17. 5.30]

Can you print the total of prices?

> enter using while loop

This ties in with the earlier requirement:

> enter using while loop
> continuously until key press

Lets assume the "keypress" is 0.
Do you know how to write a while loop that terminates
when an input value is 0?

Let us know the answers and we can point you
a little further towards solving the problem.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From boriscobizaro8 at gmail.com  Sun Jul 30 18:36:07 2017
From: boriscobizaro8 at gmail.com (Borisco Bizaro)
Date: Sun, 30 Jul 2017 15:36:07 -0700
Subject: [Tutor] Tutor Digest, Vol 161, Issue 33
In-Reply-To: <mailman.75.1500854764.3036.tutor@python.org>
References: <mailman.75.1500854764.3036.tutor@python.org>
Message-ID: <CAKE=nh6WRLbEOZ7AbwGEfN-ud8N+tTT_=7Jv7HVdxzxgEnpv_Q@mail.gmail.com>

Please I have been ask to write python code that ask user to enter a price
continuetly until key press to and give the total amount of price I have
enter using while loop I don't know how to go about it,please help me
This is what I have done,
untitled
a=1
b=2
while a<b:
  input ("enter another price :")
print"\n\n press 0 key to stop"
On Jul 24, 2017 01:06, <tutor-request at python.org> wrote:

> Send Tutor mailing list submissions to
>         tutor at python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>         https://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>         tutor-request at python.org
>
> You can reach the person managing the list at
>         tutor-owner at python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
> Today's Topics:
>
>    1. Fwd: Re:  Python Help (Alan Gauld)
>    2. Fwd: Re:  Python Help (Alan Gauld)
>    3. Python3 Help (Brandon Anderson)
>    4. class newbie (Michael C)
>
>
> ---------- Forwarded message ----------
> From: Alan Gauld <alan.gauld at yahoo.co.uk>
> To: tutor <tutor at python.org>
> Cc:
> Bcc:
> Date: Sun, 23 Jul 2017 21:45:45 +0100
> Subject: [Tutor] Fwd: Re: Python Help
>
> Forwarding to list,
> please use ReplyAll or ReplyList when responding to the list.
>
>
> -------- Forwarded Message --------
>
> I also tried the correct command for the mac ox s in terminal shell,
> running:
>
> Jims-MacBook-Pro-2:~ Jim$
> PYTHONPATH="/Users/Jim/Documents/illustris_python:$PYTHONPATH
>
> > export PYTHONPATH
>
>
> no error messages there but it is still not finding the module through
> python.
>
> Winonah
>
>
> On Sun, Jul 23, 2017 at 1:34 PM, Winonah Ojanen <winonah1992 at gmail.com
> <mailto:winonah1992 at gmail.com>> wrote:
>
>     I did use the pip command and am attempting to add the files to my
>     python path. I used
>      import sys
>     sys.path.append("/Users/Jim/Documents/illustris_python")
>
>     and that worked. I even checked to make sure the files were there
>
>
>     import sys
>     print (sys.path)
>
>     ['', '/Users/Jim/anaconda/lib/python36.zip',
>     '/Users/Jim/anaconda/lib/python3.6',
>     '/Users/Jim/anaconda/lib/python3.6/lib-dynload',
>     '/Users/Jim/anaconda/lib/python3.6/site-packages',
>     '/Users/Jim/anaconda/lib/python3.6/site-packages/
> Sphinx-1.5.6-py3.6.egg',
>     '/Users/Jim/anaconda/lib/python3.6/site-packages/aeosa',
>     '/Users/Jim/anaconda/lib/python3.6/site-packages/
> setuptools-27.2.0-py3.6.egg',
>     '/Users/Jim/anaconda/lib/python3.6/site-packages/IPython/extensions',
>     '/Users/Jim/.ipython', 'Users/Jim/Documents/illustris_python']
>
>     the file is clearly there but when i try to do import
>     illustris_python as il it still can't find the module.
>
>
> Note that only shows the folder is in the path.
>
> What does an 'ls' listing reveal as to the contents of the folder?
> Is there a file called illustris_python.py? or maybe illustris_python.pyc?
>
>
>
>     I also figured that I need to manually export to python path so i
> tried:
>     export PYTHONPATH=$PYTHONPATH:/Users/Jim/Documents/illustris_python/
>       File "<ipython-input-14-30d153a77da5>", line 1
>         export PYTHONPATH=$PYTHONPATH:/Users/Jim/Documents/illustris_
> python/
>                         ^
>     SyntaxError: invalid syntax
>
>     I got invalid syntax... using a mac os x
>
>     I tried typing in terminal open .bash_profile and telling it to
>     export the python path in there like some others recommended but in
>     terminal it is giving me an error message for that... it must not be
>     the right command for the shell.
>
>     Winonah
>
>     On Sat, Jul 22, 2017 at 9:34 PM, Cameron Simpson <cs at zip.com.au
>     <mailto:cs at zip.com.au>> wrote:
>
>         On 23Jul2017 00:20, Alan Gauld <alan.gauld at yahoo.co.uk
>         <mailto:alan.gauld at yahoo.co.uk>> wrote:
>
>             On 22/07/17 19:14, Winonah Ojanen wrote:
>
>                 using python with anaconda in jupiter notebook. However,
>                 I am having
>
>
>             Usual caveat: The tutor list is targeted at the standard
> library
>             so any help for non standard library modules is best sought
> from
>             the library support fora. In this case that includes the
>             SciPy forum
>             and any illustris one.
>
>
>         Though arguably the OP's problem is an import issue, not really
>         module specific.
>
>             That having been said, I'll take a guess...
>
>                 $ mkdir Illustris-3
>                 $ mkdir Illustris-3/groups_135
>
>             Are these folders in your PYTHONPATH? If not Python will not
>             find them.
>
>                 import illustris_python as il
>                 ------------------------------
> ---------------------------------------------
>                 ModuleNotFoundError                       Traceback
>                 (most recent call last)
>
>
>         The OP cded into the new dir; I'd normally expect things to be
>         found if the module was a local file/dir. However...
>
>                 For some reason the computer is not recognizing this as
>                 a file on my
>                 computer. The CCA folks says this is a coding problem
>                 and not an illustris
>                 problem. any ideas to get me past this? I may also need
>                 help getting
>                 farther into the download process.
>
>
>         I just ran the OP's download command:
>
>          wget -nd -nc -nv -e robots=off -l 1 -r -A hdf5
>         --content-disposition --header="API-Key:
>         d522db2e1b33e36d3b365cc9ac1c2c5d"
>         "http://www.illustris-project.org/api/Illustris-3/files/
> groupcat-135/?format=api
>         <http://www.illustris-project.org/api/Illustris-3/files/
> groupcat-135/?format=api>"
>
>         This doesn't seem to download any Python code at all. It does
>         get a couple of HDF files, presumably with data to work with.
>
>         So the issue is initially that the module isn't present
>         anywhere. Looking at the instructions cited
>         <http://www.illustris-project.org/data/docs/scripts/
>         <http://www.illustris-project.org/data/docs/scripts/>>, they
>         only cover fetching som data and working; they presume the
>         software is already present. I don't immediately see actual
>         software installation instructions, and it is not presented in
> PyPI.
>
>         Most like the OP will have to install the software directly from:
>
>          https://bitbucket.org/illustris/illustris_python
>         <https://bitbucket.org/illustris/illustris_python>
>
>         This command:
>
>          hg clone
>         https://bitbucket.org/illustris/stris_pythonillustris_python
>         <https://bitbucket.org/illustris/stris_pythonillustris_python>
>
>         should produce an "illustris_python" in the current directory,
>         and then her import command will find it.
>
>         However, there are other prerequisites. This pip command:
>
>          pip install h5py numpy
>
>         seems to resolve them. The OP will need to use Python 2 because
>         the module seems to rely on a relative import (for its "util.py"
>         file).
>
>         Cheers,
>         Cameron Simpson <cs at zip.com.au <mailto:cs at zip.com.au>>
>
>         _______________________________________________
>         Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
>         To unsubscribe or change subscription options:
>         https://mail.python.org/mailman/listinfo/tutor
>         <https://mail.python.org/mailman/listinfo/tutor>
>
>
>
>
>
>
> ---------- Forwarded message ----------
> From: Alan Gauld <alan.gauld at yahoo.co.uk>
> To: tutor <tutor at python.org>
> Cc:
> Bcc:
> Date: Sun, 23 Jul 2017 21:42:26 +0100
> Subject: [Tutor] Fwd: Re: Python Help
> Forwarding to list
>
>
>
> -------- Forwarded Message --------
>
> I did use the pip command and am attempting to add the files to my
> python path. I used
>  import sys
> sys.path.append("/Users/Jim/Documents/illustris_python")
>
> and that worked. I even checked to make sure the files were there
>
>
> import sys
> print (sys.path)
>
> ['', '/Users/Jim/anaconda/lib/python36.zip',
> '/Users/Jim/anaconda/lib/python3.6',
> '/Users/Jim/anaconda/lib/python3.6/lib-dynload',
> '/Users/Jim/anaconda/lib/python3.6/site-packages',
> '/Users/Jim/anaconda/lib/python3.6/site-packages/Sphinx-1.5.6-py3.6.egg',
> '/Users/Jim/anaconda/lib/python3.6/site-packages/aeosa',
> '/Users/Jim/anaconda/lib/python3.6/site-packages/
> setuptools-27.2.0-py3.6.egg',
> '/Users/Jim/anaconda/lib/python3.6/site-packages/IPython/extensions',
> '/Users/Jim/.ipython', 'Users/Jim/Documents/illustris_python']
>
> the file is clearly there but when i try to do import illustris_python
> as il it still can't find the module.
>
> I also figured that I need to manually export to python path so i tried:
> export PYTHONPATH=$PYTHONPATH:/Users/Jim/Documents/illustris_python/
>   File "<ipython-input-14-30d153a77da5>", line 1
>     export PYTHONPATH=$PYTHONPATH:/Users/Jim/Documents/illustris_python/
>                     ^
> SyntaxError: invalid syntax
>
> I got invalid syntax... using a mac os x
>
> I tried typing in terminal open .bash_profile and telling it to export
> the python path in there like some others recommended but in terminal it
> is giving me an error message for that... it must not be the right
> command for the shell.
>
> Winonah
>
> On Sat, Jul 22, 2017 at 9:34 PM, Cameron Simpson <cs at zip.com.au
> <mailto:cs at zip.com.au>> wrote:
>
>     On 23Jul2017 00:20, Alan Gauld <alan.gauld at yahoo.co.uk
>     <mailto:alan.gauld at yahoo.co.uk>> wrote:
>
>         On 22/07/17 19:14, Winonah Ojanen wrote:
>
>             using python with anaconda in jupiter notebook. However, I
>             am having
>
>
>         Usual caveat: The tutor list is targeted at the standard library
>         so any help for non standard library modules is best sought from
>         the library support fora. In this case that includes the SciPy
> forum
>         and any illustris one.
>
>
>     Though arguably the OP's problem is an import issue, not really
>     module specific.
>
>         That having been said, I'll take a guess...
>
>             $ mkdir Illustris-3
>             $ mkdir Illustris-3/groups_135
>
>         Are these folders in your PYTHONPATH? If not Python will not
>         find them.
>
>             import illustris_python as il
>             ------------------------------------------------------------
> ---------------
>             ModuleNotFoundError                       Traceback (most
>             recent call last)
>
>
>     The OP cded into the new dir; I'd normally expect things to be found
>     if the module was a local file/dir. However...
>
>             For some reason the computer is not recognizing this as a
>             file on my
>             computer. The CCA folks says this is a coding problem and
>             not an illustris
>             problem. any ideas to get me past this? I may also need help
>             getting
>             farther into the download process.
>
>
>     I just ran the OP's download command:
>
>      wget -nd -nc -nv -e robots=off -l 1 -r -A hdf5
>     --content-disposition --header="API-Key:
>     d522db2e1b33e36d3b365cc9ac1c2c5d"
>     "http://www.illustris-project.org/api/Illustris-3/files/
> groupcat-135/?format=api
>     <http://www.illustris-project.org/api/Illustris-3/files/
> groupcat-135/?format=api>"
>
>     This doesn't seem to download any Python code at all. It does get a
>     couple of HDF files, presumably with data to work with.
>
>     So the issue is initially that the module isn't present anywhere.
>     Looking at the instructions cited
>     <http://www.illustris-project.org/data/docs/scripts/
>     <http://www.illustris-project.org/data/docs/scripts/>>, they only
>     cover fetching som data and working; they presume the software is
>     already present. I don't immediately see actual software
>     installation instructions, and it is not presented in PyPI.
>
>     Most like the OP will have to install the software directly from:
>
>      https://bitbucket.org/illustris/illustris_python
>     <https://bitbucket.org/illustris/illustris_python>
>
>     This command:
>
>      hg clone
>     https://bitbucket.org/illustris/stris_pythonillustris_python
>     <https://bitbucket.org/illustris/stris_pythonillustris_python>
>
>     should produce an "illustris_python" in the current directory, and
>     then her import command will find it.
>
>     However, there are other prerequisites. This pip command:
>
>      pip install h5py numpy
>
>     seems to resolve them. The OP will need to use Python 2 because the
>     module seems to rely on a relative import (for its "util.py" file).
>
>     Cheers,
>     Cameron Simpson <cs at zip.com.au <mailto:cs at zip.com.au>>
>
>     _______________________________________________
>     Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
>     To unsubscribe or change subscription options:
>     https://mail.python.org/mailman/listinfo/tutor
>     <https://mail.python.org/mailman/listinfo/tutor>
>
>
>
>
>
> ---------- Forwarded message ----------
> From: Brandon Anderson <brandonanderson at me.com>
> To: tutor at python.org
> Cc:
> Bcc:
> Date: Sun, 23 Jul 2017 16:19:41 -0700
> Subject: [Tutor] Python3 Help
> Hello!
>
> 1.      I have Python3 installed on my 2017 MacBook Pro. I know that it is
> successfully installed because, when I enter ?Python3? into my terminal,
>         I get the following message:
>
>         Python 3.6.2 (v3.6.2:5fd33b5926, Jul 16 2017, 20:11:06)
>         [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
>         Type "help", "copyright", "credits" or "license" for more
> information.
>
> 2.  I?m trying to locate the directory path to where Python3 is located on
> my system, but when I enter
>         the following command:
>         $ type -a python3
>
>         I get:
>         -bash: $: command not found
>
>         My understanding is that the command should have provided me with
> the path to Python3 is located on my system.
>
> 3.  How do I determine why I?m getting the ?error? command, instead of the
> directory location of Python3.
>     I need the location in order to setup my Text Editor to execute
> Python3 commands.
>
> Thank you in advance.
>
> Brandon Anderson
> (510) 468-0154
> brandonanderson at icloud.com
>
>
> ---------- Forwarded message ----------
> From: Michael C <mysecretrobotfactory at gmail.com>
> To: python tutor <tutor at python.org>
> Cc:
> Bcc:
> Date: Sun, 23 Jul 2017 13:24:49 -0700
> Subject: [Tutor] class newbie
> class mahschool:
>     def print():
>         print('Say something')
>
>
> a = mahschool()
>
> a.print()
>
>
>
> With this, I get this error:
>
> Traceback (most recent call last):
>   File "test.py", line 8, in <module>
>     a.print()
> TypeError: print() takes 0 positional arguments but 1 was given
>
>
> What did I do wrong?
>
> Thanks!
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> https://mail.python.org/mailman/listinfo/tutor
>
>

From alan.gauld at yahoo.co.uk  Sun Jul 30 19:05:39 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 31 Jul 2017 00:05:39 +0100
Subject: [Tutor] While loop homework: was Re: Tutor Digest, Vol 161, Issue 33
In-Reply-To: <CAKE=nh6WRLbEOZ7AbwGEfN-ud8N+tTT_=7Jv7HVdxzxgEnpv_Q@mail.gmail.com>
References: <mailman.75.1500854764.3036.tutor@python.org>
 <CAKE=nh6WRLbEOZ7AbwGEfN-ud8N+tTT_=7Jv7HVdxzxgEnpv_Q@mail.gmail.com>
Message-ID: <ollont$23o$1@blaine.gmane.org>

On 30/07/17 23:36, Borisco Bizaro wrote:

> a=1
> b=2
> while a<b:
>   input ("enter another price :")

Do 'a' or 'b' ever change?
Does 'a<b' ever become false?
Does the while loop ever stop?

Do you store the value of the input() function anywhere?

> print"\n\n press 0 key to stop"

Does the user ever get the chance to enter a value?
If they were, Where is the value stored and is the
value ever used?

>> When replying, please edit your Subject line so it is more specific
>> than "Re: Contents of Tutor digest..."

Please follow the instructions as requested.
It helps find answers in the archives.


-- 
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 gsconyer at yahoo.com  Sun Jul 30 18:22:58 2017
From: gsconyer at yahoo.com (George Sconyers)
Date: Sun, 30 Jul 2017 22:22:58 +0000 (UTC)
Subject: [Tutor] Recommended Python Compiler
References: <1285690201.2134862.1501453378125.ref@mail.yahoo.com>
Message-ID: <1285690201.2134862.1501453378125@mail.yahoo.com>

Hello all. I am getting started with Python and looking for a recommended compiler for an Ubuntu environment. I've been using gedit but don't get the benefit of auto-indentation and color coding of key words. It is laziness for sure but as the programs get longer I am increasingly OK with being lazy. Wpuld also like something that facilitates debuggig and stepping through code. Thoughts?
ThanksGeorge


Sent from Yahoo Mail for iPhone

From dyoo at hashcollision.org  Sun Jul 30 19:48:46 2017
From: dyoo at hashcollision.org (Danny Yoo)
Date: Sun, 30 Jul 2017 16:48:46 -0700
Subject: [Tutor] Recommended Python Compiler
In-Reply-To: <1285690201.2134862.1501453378125@mail.yahoo.com>
References: <1285690201.2134862.1501453378125.ref@mail.yahoo.com>
 <1285690201.2134862.1501453378125@mail.yahoo.com>
Message-ID: <CAGZAPF7VVVRV5AY8t_c52hJbfhF1VhMLqtkZdQCA877mGDhHnA@mail.gmail.com>

On Sun, Jul 30, 2017 at 3:22 PM, George Sconyers via Tutor
<tutor at python.org> wrote:
> Hello all. I am getting started with Python and looking for a recommended compiler for an Ubuntu environment. I've been using gedit but don't get the benefit of auto-indentation and color coding of key words. It is laziness for sure but as the programs get longer I am increasingly OK with being lazy. Wpuld also like something that facilitates debuggig and stepping through code. Thoughts?


Hi George,

What you're asking for is an Integrated Development Environment (IDE),
not a compiler, which is an entirely different thing.


* An IDE is the program that you actively interact with to edit your
programs, explore relationships, do debugging, and run programs.

* A compiler is much more limited in scope: it's the tool used to
process your programs to be run.  It's not usually an interactive tool
though.


It's very often the case that an IDE will, behind the scenes,
integrate with a language compiler since the IDE will want to make it
easy for its users to run programs.


I've lately heard good things about PyCharm.  I have to admit that I
have not used it, though.  The PyCharm folks have a few video
tutorials: https://www.youtube.com/playlist?list=PLQ176FUIyIUZ1mwB-uImQE-gmkwzjNLjP
to show what their tool looks like.


For more recommendations and advice, you can take a look at the Wiki:

    https://wiki.python.org/moin/IntegratedDevelopmentEnvironments


Good luck!

From alan.gauld at yahoo.co.uk  Sun Jul 30 20:09:20 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 31 Jul 2017 01:09:20 +0100
Subject: [Tutor] Recommended Python Compiler
In-Reply-To: <1285690201.2134862.1501453378125@mail.yahoo.com>
References: <1285690201.2134862.1501453378125.ref@mail.yahoo.com>
 <1285690201.2134862.1501453378125@mail.yahoo.com>
Message-ID: <ollsfa$n7q$1@blaine.gmane.org>

On 30/07/17 23:22, George Sconyers via Tutor wrote:
> ...looking for a recommended compiler for an Ubuntu environment. 

In programming precision is everything.

You are not in fact looking for a compiler, you are
looking for a development environment or IDE.

A compiler takes source code and produces executable
machine code. C-Python does not have such a thing
(it uses an interpreter to translate the code at runtime)
although you an get one for the Java based Jython.
But that's not really what you are asking for...

> ...using gedit but don't get the benefit of auto-indentation > and color coding of key words.

These are feature of the editor (usually a component of an IDE)
- and gedit can do the syntax colouring, I'm not sure about the
auto-indent... But rather than use gedit I suggest you use
IDLE which is a simple but useful Python IDE built in Python.

> ...something that facilitates debuggig and stepping through code. 

IDLE does all of the above.

You can get it via the Ubuntu software manager or Synaptic or apt-get...
Make sure you get the right version for your Python version

There are many other IDEs for Python, right up to professional tools
like Eclipse and Netbeans but IDLE is a good starting point. And
there are lots of YouTube videos to get you started.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From mats at wichmann.us  Sun Jul 30 21:31:00 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Sun, 30 Jul 2017 19:31:00 -0600
Subject: [Tutor] Recommended Python Compiler
In-Reply-To: <ollsfa$n7q$1@blaine.gmane.org>
References: <1285690201.2134862.1501453378125.ref@mail.yahoo.com>
 <1285690201.2134862.1501453378125@mail.yahoo.com>
 <ollsfa$n7q$1@blaine.gmane.org>
Message-ID: <2699BAAD-C396-4547-80D5-7350B9232218@wichmann.us>

since this all opinions :), I don't think idle is worth bothering with. for editor that can do ide like things, consider atom (free, get a bunch of plugins) or sublime text (not free). for a full ide, pycharm is great (community edition free). for a lightweight ide to get started, i liked thonny when i trialed it at somebody's request, but do look at that wiki page, tons of choices there.

On July 30, 2017 6:09:20 PM MDT, Alan Gauld via Tutor <tutor at python.org> wrote:
>On 30/07/17 23:22, George Sconyers via Tutor wrote:
>> ...looking for a recommended compiler for an Ubuntu environment. 
>
>In programming precision is everything.
>
>You are not in fact looking for a compiler, you are
>looking for a development environment or IDE.
>
>A compiler takes source code and produces executable
>machine code. C-Python does not have such a thing
>(it uses an interpreter to translate the code at runtime)
>although you an get one for the Java based Jython.
>But that's not really what you are asking for...
>
>> ...using gedit but don't get the benefit of auto-indentation > and
>color coding of key words.
>
>These are feature of the editor (usually a component of an IDE)
>- and gedit can do the syntax colouring, I'm not sure about the
>auto-indent... But rather than use gedit I suggest you use
>IDLE which is a simple but useful Python IDE built in Python.
>
>> ...something that facilitates debuggig and stepping through code. 
>
>IDLE does all of the above.
>
>You can get it via the Ubuntu software manager or Synaptic or
>apt-get...
>Make sure you get the right version for your Python version
>
>There are many other IDEs for Python, right up to professional tools
>like Eclipse and Netbeans but IDLE is a good starting point. And
>there are lots of YouTube videos to get you started.
>
>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

-- 
Sent from my Android device with K-9 Mail. Please excuse my brevity.

From ben+python at benfinney.id.au  Sun Jul 30 22:24:32 2017
From: ben+python at benfinney.id.au (Ben Finney)
Date: Mon, 31 Jul 2017 12:24:32 +1000
Subject: [Tutor] Recommended Python Compiler
References: <1285690201.2134862.1501453378125.ref@mail.yahoo.com>
 <1285690201.2134862.1501453378125@mail.yahoo.com>
Message-ID: <85ini92vj3.fsf@benfinney.id.au>

George Sconyers via Tutor <tutor at python.org> writes:

> Hello all. I am getting started with Python and looking for a
> recommended compiler for an Ubuntu environment.

Python comes with a compiler: it is the ?python? command, which compiles
your program code ?foo.py? to a bytecode file, typically ?foo.pyc?.

You might be looking for a different compiler, maybe one which compiles
not to Python byte code but instead to CPU machine code. There isn't
such a thing; running your compiled Python code typically requires a
Python interpreter.

(Yes, Python is both compiled *and* interpreted, in separate steps.
Those steps are typically done automatically behind the scenes, but they
are separate.)

You can find programs which will take your compiled bytecode, along with
a Python interpreter, and bundle them into a single executable file. Is
that what you're asking for?

-- 
 \         ?Truth would quickly cease to become stranger than fiction, |
  `\                     once we got as used to it.? ?Henry L. Mencken |
_o__)                                                                  |
Ben Finney


From stefan_ml at behnel.de  Mon Jul 31 05:18:28 2017
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Mon, 31 Jul 2017 11:18:28 +0200
Subject: [Tutor] Recommended Python Compiler
In-Reply-To: <85ini92vj3.fsf@benfinney.id.au>
References: <1285690201.2134862.1501453378125.ref@mail.yahoo.com>
 <1285690201.2134862.1501453378125@mail.yahoo.com>
 <85ini92vj3.fsf@benfinney.id.au>
Message-ID: <olmsku$obb$1@blaine.gmane.org>

Ben Finney schrieb am 31.07.2017 um 04:24:
> You might be looking for a different compiler, maybe one which compiles
> not to Python byte code but instead to CPU machine code. There isn't
> such a thing;

The Python wiki lists several compilers for Python, although with varying
levels of language compliance and/or code compatibility*:

https://wiki.python.org/moin/PythonImplementations#Compilers

The most widely used static Python compiler is probably still Cython.

Stefan
(Cython core developer)


PS*: being compliant with the Python language does not necessarily mean it
can successfully run your existing code, as that also requires access to
third-party dependencies etc. Not all tools (aim to) provide that.

PPS: it seems that wiki list needs an update as a) many of the links did
not survive the termination of and migration away from Google Code and b)
some of the projects should now better be marked as abandoned.


From arj.python at gmail.com  Sun Jul 30 22:39:02 2017
From: arj.python at gmail.com (Abdur-Rahmaan Janhangeer)
Date: Mon, 31 Jul 2017 06:39:02 +0400
Subject: [Tutor] Recommended Python Compiler
In-Reply-To: <1285690201.2134862.1501453378125@mail.yahoo.com>
References: <1285690201.2134862.1501453378125.ref@mail.yahoo.com>
 <1285690201.2134862.1501453378125@mail.yahoo.com>
Message-ID: <CADrxXXk=bXjwF30Df5aDiRTugXnzaVhFQN=RLEZy6HBWT_PxDw@mail.gmail.com>

can i recommend you wing ide personal edition?

a breeze.

p.s. an ide cares about helping you coping with errors, syntax highlighting
and ironing out some corners here and there

a compiler (for a moment) just make things work for you

Abdur-Rahmaan Janhangeer,
Mauritius
abdurrahmaanjanhangeer.wordpress.com

On 31 Jul 2017 3:10 am, "George Sconyers via Tutor" <tutor at python.org>
wrote:

> Hello all. I am getting started with Python and looking for a recommended
> compiler for an Ubuntu environment. I've been using gedit but don't get the
> benefit of auto-indentation and color coding of key words. It is laziness
> for sure but as the programs get longer I am increasingly OK with being
> lazy. Wpuld also like something that facilitates debuggig and stepping
> through code. Thoughts?
> ThanksGeorge
>
>
> Sent from Yahoo Mail for iPhone
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From wolfgang.maier at biologie.uni-freiburg.de  Mon Jul 31 08:45:20 2017
From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier)
Date: Mon, 31 Jul 2017 14:45:20 +0200
Subject: [Tutor] Recommended Python Compiler
In-Reply-To: <2699BAAD-C396-4547-80D5-7350B9232218@wichmann.us>
References: <1285690201.2134862.1501453378125.ref@mail.yahoo.com>
 <1285690201.2134862.1501453378125@mail.yahoo.com>
 <ollsfa$n7q$1@blaine.gmane.org>
 <2699BAAD-C396-4547-80D5-7350B9232218@wichmann.us>
Message-ID: <oln8op$tr2$1@blaine.gmane.org>

On 07/31/2017 03:31 AM, Mats Wichmann wrote:
> since this all opinions :), I don't think idle is worth bothering with. for editor that can do ide like things, consider atom (free, get a bunch of plugins) or sublime text (not free). for a full ide, pycharm is great (community edition free). for a lightweight ide to get started, i liked thonny when i trialed it at somebody's request, but do look at that wiki page, tons of choices there.

As you're saying, it is all about opinion here so let me defend IDLE 
here. There may be more powerful IDEs than IDLE, but it takes you a long 
way (far beyond beginner/scripting level) and, of interest if you are 
ever writing Python code on a Windows machine, typically comes installed 
together with the Python interpreter there, so you will find it on many 
machines (even ones you are not allowed to install other software on).

Best,
Wolfgang


From kwpolska at gmail.com  Mon Jul 31 08:53:30 2017
From: kwpolska at gmail.com (Chris Warrick)
Date: Mon, 31 Jul 2017 14:53:30 +0200
Subject: [Tutor] Recommended Python Compiler
In-Reply-To: <oln8op$tr2$1@blaine.gmane.org>
References: <1285690201.2134862.1501453378125.ref@mail.yahoo.com>
 <1285690201.2134862.1501453378125@mail.yahoo.com>
 <ollsfa$n7q$1@blaine.gmane.org>
 <2699BAAD-C396-4547-80D5-7350B9232218@wichmann.us>
 <oln8op$tr2$1@blaine.gmane.org>
Message-ID: <CAMw+j7J-VK8w-O8tmYtkZDMrQc9a5pYDRNRZ608aH-Cv0S1uJg@mail.gmail.com>

On 31 July 2017 at 14:45, Wolfgang Maier
<wolfgang.maier at biologie.uni-freiburg.de> wrote:
> On 07/31/2017 03:31 AM, Mats Wichmann wrote:
>>
>> since this all opinions :), I don't think idle is worth bothering with.
>> for editor that can do ide like things, consider atom (free, get a bunch of
>> plugins) or sublime text (not free). for a full ide, pycharm is great
>> (community edition free). for a lightweight ide to get started, i liked
>> thonny when i trialed it at somebody's request, but do look at that wiki
>> page, tons of choices there.
>
>
> As you're saying, it is all about opinion here so let me defend IDLE here.
> There may be more powerful IDEs than IDLE, but it takes you a long way (far
> beyond beginner/scripting level) and, of interest if you are ever writing
> Python code on a Windows machine, typically comes installed together with
> the Python interpreter there, so you will find it on many machines (even
> ones you are not allowed to install other software on).

IDLE is one step up from Notepad. Which makes it a pretty terrible
editor. It even lacks line numbers, which is an elementary feature,
and a necessity for debugging (tracebacks!)

On the other hand, some of the better editors (eg. Visual Studio Code)
provide .zip packages that do not require installation and can even
run off a USB stick.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16

From wolfgang.maier at biologie.uni-freiburg.de  Mon Jul 31 09:22:01 2017
From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier)
Date: Mon, 31 Jul 2017 15:22:01 +0200
Subject: [Tutor] Recommended Python Compiler
In-Reply-To: <CAMw+j7J-VK8w-O8tmYtkZDMrQc9a5pYDRNRZ608aH-Cv0S1uJg@mail.gmail.com>
References: <1285690201.2134862.1501453378125.ref@mail.yahoo.com>
 <1285690201.2134862.1501453378125@mail.yahoo.com>
 <ollsfa$n7q$1@blaine.gmane.org>
 <2699BAAD-C396-4547-80D5-7350B9232218@wichmann.us>
 <oln8op$tr2$1@blaine.gmane.org>
 <CAMw+j7J-VK8w-O8tmYtkZDMrQc9a5pYDRNRZ608aH-Cv0S1uJg@mail.gmail.com>
Message-ID: <olnatk$jdg$1@blaine.gmane.org>

On 07/31/2017 02:53 PM, Chris Warrick wrote:
> On 31 July 2017 at 14:45, Wolfgang Maier
> <wolfgang.maier at biologie.uni-freiburg.de> wrote:
>> On 07/31/2017 03:31 AM, Mats Wichmann wrote:
>>>
>>> since this all opinions :), I don't think idle is worth bothering with.
>>> for editor that can do ide like things, consider atom (free, get a bunch of
>>> plugins) or sublime text (not free). for a full ide, pycharm is great
>>> (community edition free). for a lightweight ide to get started, i liked
>>> thonny when i trialed it at somebody's request, but do look at that wiki
>>> page, tons of choices there.
>>
>>
>> As you're saying, it is all about opinion here so let me defend IDLE here.
>> There may be more powerful IDEs than IDLE, but it takes you a long way (far
>> beyond beginner/scripting level) and, of interest if you are ever writing
>> Python code on a Windows machine, typically comes installed together with
>> the Python interpreter there, so you will find it on many machines (even
>> ones you are not allowed to install other software on).
> 
> IDLE is one step up from Notepad. Which makes it a pretty terrible
> editor. It even lacks line numbers, which is an elementary feature,
> and a necessity for debugging (tracebacks!)
> 

- Displays current line number in lower right corner
- Has a goto line number option
- Lets you right-click line numbers ,emtioned in tracebacks, then jump 
right there

Have no intention to start a but-whatever-ide-is-better-debate


From badouglas at gmail.com  Mon Jul 31 11:39:46 2017
From: badouglas at gmail.com (bruce)
Date: Mon, 31 Jul 2017 11:39:46 -0400
Subject: [Tutor] pythonic ascii decoding!
Message-ID: <CAP16ngqmSRJfFPUNQmmyebSA88qmRrZBebmAdRJiJ1aHAvLVTw@mail.gmail.com>

Hi guys.

Testing getting data from a number of different US based/targeted
websites. So the input data source for the most part, will be "ascii".
I'm getting a few "weird" chars every now and then asn as fas as I can
tell, they should be utf-8.

However, the following hasn;t always worked:
    s=str(s).decode('utf-8').strip()

So, is there a quick/dirty approach I can use to simply strip out the
"non-ascii" chars. I know, this might not be the "best/pythonic" way,
and that it might result in loss of some data/chars, but I can live
with it for now.

thoughts/comments ??

thanks

From mats at wichmann.us  Mon Jul 31 11:56:22 2017
From: mats at wichmann.us (Mats Wichmann)
Date: Mon, 31 Jul 2017 09:56:22 -0600
Subject: [Tutor] pythonic ascii decoding!
In-Reply-To: <CAP16ngqmSRJfFPUNQmmyebSA88qmRrZBebmAdRJiJ1aHAvLVTw@mail.gmail.com>
References: <CAP16ngqmSRJfFPUNQmmyebSA88qmRrZBebmAdRJiJ1aHAvLVTw@mail.gmail.com>
Message-ID: <6c635d01-3f7e-81bd-f367-0edf1b49f548@wichmann.us>

On 07/31/2017 09:39 AM, bruce wrote:
> Hi guys.
> 
> Testing getting data from a number of different US based/targeted
> websites. So the input data source for the most part, will be "ascii".
> I'm getting a few "weird" chars every now and then asn as fas as I can
> tell, they should be utf-8.
> 
> However, the following hasn;t always worked:
>     s=str(s).decode('utf-8').strip()
> 
> So, is there a quick/dirty approach I can use to simply strip out the
> "non-ascii" chars. I know, this might not be the "best/pythonic" way,
> and that it might result in loss of some data/chars, but I can live
> with it for now.
> 
> thoughts/comments ??

It's easy enough to toss chars if you don't care what's being tossed,
which sounds like your case, something like:

''.join(i for i in s if ord(i) < 128)


but there's actually lots to think about here (I'm sure others will jump in)

- Python2 strings default to ascii, Python3 to unicode, there may be
some excitement with the use of ord() depending on how the string is
passed around
- websites will tell you their encoding, which you could and probably
should make use of
- web scraping with Python is a pretty well developed field, perhaps you
might want to use one of the existing projects? (https://scrapy.org/ is
pretty famous, certainly not the only one)

From arj.python at gmail.com  Mon Jul 31 09:27:19 2017
From: arj.python at gmail.com (Abdur-Rahmaan Janhangeer)
Date: Mon, 31 Jul 2017 17:27:19 +0400
Subject: [Tutor] Recommended Python Compiler
In-Reply-To: <1285690201.2134862.1501453378125@mail.yahoo.com>
References: <1285690201.2134862.1501453378125.ref@mail.yahoo.com>
 <1285690201.2134862.1501453378125@mail.yahoo.com>
Message-ID: <CADrxXXmT6PHo_K+Gey_fLig0O5gUbCJHp73HKUknRGkpfHhpmw@mail.gmail.com>

I may say that i was turned off by idle initially, never used it at all
until i landed on another pc to teach someone.

it changed my opinion on it, as it was not as horrible as expected. it was
nice enough not to overwhelm a beginner. it could open and run files
(and nice, at least a python editor made using the python language itself)

however of course, popular ides have done a far better job, but if you are
really screwed, it is ok and ... a normal beginner won't realise the
difference

else,
this is the first tutor thread i feel came on the brink of explosion

and may i suggest something, if someone is a beginner and will use
scientific packages often, better go on with spyder.

look you might say i won't need other packages but just for matplotlib, how
many sci modules you need?, as you follow awesome tutorials, one pulls in
the other. so, don't forget spyder even if py3.6 puts you off

cheers,

Abdur-Rahmaan Janhangeer,
Mauritius
abdurrahmaanjanhangeer.wordpress.com

On 31 Jul 2017 03:10, "George Sconyers via Tutor" <tutor at python.org> wrote:

> Hello all. I am getting started with Python and looking for a recommended
> compiler for an Ubuntu environment. I've been using gedit but don't get the
> benefit of auto-indentation and color coding of key words. It is laziness
> for sure but as the programs get longer I am increasingly OK with being
> lazy. Wpuld also like something that facilitates debuggig and stepping
> through code. Thoughts?
> ThanksGeorge
>
>
> Sent from Yahoo Mail for iPhone
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From jeffvanderdoes at gmail.com  Mon Jul 31 11:53:28 2017
From: jeffvanderdoes at gmail.com (Jeff VanderDoes)
Date: Mon, 31 Jul 2017 09:53:28 -0600
Subject: [Tutor] Quick question on dirsync a python pkg
Message-ID: <CAFSq=otewE28gudHn8EMdN1QoMrdc73r7e=eHbEUmdNgLZu9Sw@mail.gmail.com>

Hi,

Just curious if anyone can give me an explanation of when using the pkg
dirsync 2.2.2 what the difference is between --update and --sync option.
Maybe my brain is just a bit slow this morning.

Thanks!
Jeff

From mcgrath_ch at hotmail.com  Mon Jul 31 01:31:40 2017
From: mcgrath_ch at hotmail.com (Christopher McGrath)
Date: Mon, 31 Jul 2017 05:31:40 +0000
Subject: [Tutor] Python isn't working with Apache (Windows)
Message-ID: <BN6PR2201MB1121B3B0DA34DAE0117E5F7BFDB20@BN6PR2201MB1121.namprd22.prod.outlook.com>

I am trying to run a simple python web script in a browser with apache. I have apache installed and running perfectly. I installed Ruby and Perl using instructions from here and worked perfect. http://editrocket.com/articles/python_apache_windows.html

I did have to change my ?shebang lines? for PERL and RUBY like these:
#!Q:\LifeForce\perl\perl\bin\perl.exe
#!Q:\LifeForce\Ruby24-x64\bin\ruby.exe
As you can see, I didn?t install them on C: drive. They worked.

I had Python 3.6 installed before and tried to test with these
#!Q:\LifeForce\Python36-32\Scripts\pip3.exe
#!Q:\LifeForce\Python36-32\Scripts\pip.exe
#!Q:\LifeForce\Python36-32\Scripts\pip2.6.exe
All the pip files in the Script directory.
I also tried with #!Q:\LifeForce\Python36-32\python.exe. This one works worked from Window Command, but didn?t work from web browser like PERL and RUBY.
I tried downgrading to Python 2.7 and installed directly at C: drive and tested with
#!C:\Python27\python.exe
#!C:\Python27\Scripts\pip2.7.exe
#!C:\Python27\Scripts\pip2.exe
#!C:\Python27\Scripts\pip.exe
Nothing worked. I don?t have any idea anymore. Please help!
This is the simple code:
print ("Content-type: text/html")
print (" ")
print ("<html><head>")
print ("")
print ("</head><body>")
print ("Hello Python.")
print ("</body></html>")

I am trying to run directly from Apache htdoc dir. Not from cgi dir. I think something is wrong with the shebang line.
This is the error output in the web browser:
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator at postmaster at localhost to inform them of the time this error occurred, and the actions you performed just before this error.
More information about this error may be available in the server error log.
Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.
This is what is shown in Apache?s error log:
[Mon Jul 31 01:06:54.266478 2017] [cgi:error] [pid 5156:tid 1688] [client 98.5.128.152:51723] malformed header from script 'test.py': Bad header:
[Mon Jul 31 01:06:54.270479 2017] [authz_core:error] [pid 5156:tid 1688] [client 98.5.128.152:51723] AH01630: client denied by server configuration: C:/Apache24








Christopher McGrath

[http://aawisdom.com/Top_of_main_files/BizCard-Front-hotmailSignature.jpg]
[http://aawisdom.com/Top_of_main_files/image001.gif]
www.aawisdom.com<http://www.aawisdom.com> (716) 240-7786

From george at fischhof.hu  Mon Jul 31 16:34:48 2017
From: george at fischhof.hu (George Fischhof)
Date: Mon, 31 Jul 2017 22:34:48 +0200
Subject: [Tutor] Python isn't working with Apache (Windows)
In-Reply-To: <BN6PR2201MB1121B3B0DA34DAE0117E5F7BFDB20@BN6PR2201MB1121.namprd22.prod.outlook.com>
References: <BN6PR2201MB1121B3B0DA34DAE0117E5F7BFDB20@BN6PR2201MB1121.namprd22.prod.outlook.com>
Message-ID: <CAFwcP0j0493npTt_dm=8MQ5eRr4BSzzbUjLkuL7xeE2AyZE9TQ@mail.gmail.com>

2017-07-31 7:31 GMT+02:00 Christopher McGrath <mcgrath_ch at hotmail.com>:

> I am trying to run a simple python web script in a browser with apache. I
> have apache installed and running perfectly. I installed Ruby and Perl
> using instructions from here and worked perfect. http://editrocket.com/
> articles/python_apache_windows.html
>
> I did have to change my ?shebang lines? for PERL and RUBY like these:
> #!Q:\LifeForce\perl\perl\bin\perl.exe
> #!Q:\LifeForce\Ruby24-x64\bin\ruby.exe
> As you can see, I didn?t install them on C: drive. They worked.
>
> I had Python 3.6 installed before and tried to test with these
> #!Q:\LifeForce\Python36-32\Scripts\pip3.exe
> #!Q:\LifeForce\Python36-32\Scripts\pip.exe
> #!Q:\LifeForce\Python36-32\Scripts\pip2.6.exe
> All the pip files in the Script directory.
> I also tried with #!Q:\LifeForce\Python36-32\python.exe. This one works
> worked from Window Command, but didn?t work from web browser like PERL and
> RUBY.
> I tried downgrading to Python 2.7 and installed directly at C: drive and
> tested with
> #!C:\Python27\python.exe
> #!C:\Python27\Scripts\pip2.7.exe
> #!C:\Python27\Scripts\pip2.exe
> #!C:\Python27\Scripts\pip.exe
> Nothing worked. I don?t have any idea anymore. Please help!
> This is the simple code:
> print ("Content-type: text/html")
> print (" ")
> print ("<html><head>")
> print ("")
> print ("</head><body>")
> print ("Hello Python.")
> print ("</body></html>")
>
> I am trying to run directly from Apache htdoc dir. Not from cgi dir. I
> think something is wrong with the shebang line.
> This is the error output in the web browser:
> Internal Server Error
> The server encountered an internal error or misconfiguration and was
> unable to complete your request.
> Please contact the server administrator at postmaster at localhost to inform
> them of the time this error occurred, and the actions you performed just
> before this error.
> More information about this error may be available in the server error log.
> Additionally, a 500 Internal Server Error error was encountered while
> trying to use an ErrorDocument to handle the request.
> This is what is shown in Apache?s error log:
> [Mon Jul 31 01:06:54.266478 2017] [cgi:error] [pid 5156:tid 1688] [client
> 98.5.128.152:51723] malformed header from script 'test.py': Bad header:
> [Mon Jul 31 01:06:54.270479 2017] [authz_core:error] [pid 5156:tid 1688]
> [client 98.5.128.152:51723] AH01630: client denied by server
> configuration: C:/Apache24
>
>
>
>
>
> Christopher McGrath
>
> [http://aawisdom.com/Top_of_main_files/BizCard-Front-hotmailSignature.jpg]
> [http://aawisdom.com/Top_of_main_files/image001.gif]
> www.aawisdom.com<http://www.aawisdom.com> (716) 240-7786
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


Hi Christopher,

unfortunately I do not know much about your problem but I think it can be
useful to read about WSGI and WSGI web services, servers:

https://en.wikipedia.org/wiki/Web_Server_Gateway_Interface

https://www.python.org/dev/peps/pep-0333/

https://wiki.python.org/moin/WebFrameworks

https://www.fullstackpython.com/wsgi-servers.html


According to these articles I chose Flask for application server (it has a
built-in development webserver as well) and Waitress for webserver.
Maybe you can give them a try ;-)

BR
George

From george at fischhof.hu  Mon Jul 31 16:46:26 2017
From: george at fischhof.hu (George Fischhof)
Date: Mon, 31 Jul 2017 22:46:26 +0200
Subject: [Tutor] Python isn't working with Apache (Windows)
In-Reply-To: <BN6PR2201MB11218091167FB4973B7EE83CFDB20@BN6PR2201MB1121.namprd22.prod.outlook.com>
References: <BN6PR2201MB1121B3B0DA34DAE0117E5F7BFDB20@BN6PR2201MB1121.namprd22.prod.outlook.com>
 <CAFwcP0j0493npTt_dm=8MQ5eRr4BSzzbUjLkuL7xeE2AyZE9TQ@mail.gmail.com>
 <BN6PR2201MB11218091167FB4973B7EE83CFDB20@BN6PR2201MB1121.namprd22.prod.outlook.com>
Message-ID: <CAFwcP0j50=xcM23=UahkwiAJYbU-MVseyeeKR5ZQB=3xdrJ=Ow@mail.gmail.com>

2017-07-31 22:37 GMT+02:00 Christopher McGrath <mcgrath_ch at hotmail.com>:

> Someone told me the problem is within the second line of the code.
>
>
> print ("Content-type: text/html")
> print (" ")
> print ("<html><head>")
> print ("")
> print ("</head><body>")
> print ("Hello Python.")
> print ("</body></html>")
>
>
> There should be no space. I copied and pasted that code from somewhere and
> somehow that space has some hidden char that python didn't like...
>
>
> The one "who" does not like that space is not the Python, but the CGI
standard.
https://en.wikipedia.org/wiki/Common_Gateway_Interface

citation:

print "Content-type: text/plain\n\n";

end citation


there is blank line after content-type.


But when you use a framework, you do not have to care with cgi ;-)


BR

George


>
> *Christopher McGrath*
>
>
>
> *www.aawisdom.com <http://www.aawisdom.com> (716) 240-7786*
>
>
>
> ------------------------------
> *From:* georgefischhof at gmail.com <georgefischhof at gmail.com> on behalf of
> George Fischhof <george at fischhof.hu>
> *Sent:* Monday, July 31, 2017 8:34 PM
> *To:* Christopher McGrath
> *Cc:* tutor at python.org
> *Subject:* Re: [Tutor] Python isn't working with Apache (Windows)
>
>
>
> 2017-07-31 7:31 GMT+02:00 Christopher McGrath <mcgrath_ch at hotmail.com>:
>
>> I am trying to run a simple python web script in a browser with apache. I
>> have apache installed and running perfectly. I installed Ruby and Perl
>> using instructions from here and worked perfect.
>> http://editrocket.com/articles/python_apache_windows.html
>>
>> I did have to change my ?shebang lines? for PERL and RUBY like these:
>> #!Q:\LifeForce\perl\perl\bin\perl.exe
>> #!Q:\LifeForce\Ruby24-x64\bin\ruby.exe
>> As you can see, I didn?t install them on C: drive. They worked.
>>
>> I had Python 3.6 installed before and tried to test with these
>> #!Q:\LifeForce\Python36-32\Scripts\pip3.exe
>> #!Q:\LifeForce\Python36-32\Scripts\pip.exe
>> #!Q:\LifeForce\Python36-32\Scripts\pip2.6.exe
>> All the pip files in the Script directory.
>> I also tried with #!Q:\LifeForce\Python36-32\python.exe. This one works
>> worked from Window Command, but didn?t work from web browser like PERL and
>> RUBY.
>> I tried downgrading to Python 2.7 and installed directly at C: drive and
>> tested with
>> #!C:\Python27\python.exe
>> #!C:\Python27\Scripts\pip2.7.exe
>> #!C:\Python27\Scripts\pip2.exe
>> #!C:\Python27\Scripts\pip.exe
>> Nothing worked. I don?t have any idea anymore. Please help!
>> This is the simple code:
>> print ("Content-type: text/html")
>> print (" ")
>> print ("<html><head>")
>> print ("")
>> print ("</head><body>")
>> print ("Hello Python.")
>> print ("</body></html>")
>>
>> I am trying to run directly from Apache htdoc dir. Not from cgi dir. I
>> think something is wrong with the shebang line.
>> This is the error output in the web browser:
>> Internal Server Error
>> The server encountered an internal error or misconfiguration and was
>> unable to complete your request.
>> Please contact the server administrator at postmaster at localhost to
>> inform them of the time this error occurred, and the actions you performed
>> just before this error.
>> More information about this error may be available in the server error
>> log.
>> Additionally, a 500 Internal Server Error error was encountered while
>> trying to use an ErrorDocument to handle the request.
>> This is what is shown in Apache?s error log:
>> [Mon Jul 31 01:06:54.266478 2017] [cgi:error] [pid 5156:tid 1688] [client
>> 98.5.128.152:51723] malformed header from script 'test.py': Bad header:
>> [Mon Jul 31 01:06:54.270479 2017] [authz_core:error] [pid 5156:tid 1688]
>> [client 98.5.128.152:51723] AH01630: client denied by server
>> configuration: C:/Apache24
>>
>>
>>
>>
>>
>> Christopher McGrath
>>
>> [http://aawisdom.com/Top_of_main_files/BizCard-Front-hotmailSignature.jpg
>> ]
>> [http://aawisdom.com/Top_of_main_files/image001.gif]
>> www.aawisdom.com<http://www.aawisdom.com> (716) 240-7786
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
>
> Hi Christopher,
>
> unfortunately I do not know much about your problem but I think it can be
> useful to read about WSGI and WSGI web services, servers:
>
> https://en.wikipedia.org/wiki/Web_Server_Gateway_Interface
>
> https://www.python.org/dev/peps/pep-0333/
>
> https://wiki.python.org/moin/WebFrameworks
>
> https://www.fullstackpython.com/wsgi-servers.html
>
>
> According to these articles I chose Flask for application server (it has a
> built-in development webserver as well) and Waitress for webserver.
> Maybe you can give them a try ;-)
>
> BR
> George
>

From alan.gauld at yahoo.co.uk  Mon Jul 31 18:18:15 2017
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 31 Jul 2017 23:18:15 +0100
Subject: [Tutor] Recommended Python Compiler
In-Reply-To: <oln8op$tr2$1@blaine.gmane.org>
References: <1285690201.2134862.1501453378125.ref@mail.yahoo.com>
 <1285690201.2134862.1501453378125@mail.yahoo.com>
 <ollsfa$n7q$1@blaine.gmane.org>
 <2699BAAD-C396-4547-80D5-7350B9232218@wichmann.us>
 <oln8op$tr2$1@blaine.gmane.org>
Message-ID: <oloab1$20r$1@blaine.gmane.org>

On 31/07/17 13:45, Wolfgang Maier wrote:

> here. There may be more powerful IDEs than IDLE, but it takes you a long 
> way (far beyond beginner/scripting level) 

And IdleX is a vastly superior, drop-in replacement, superset
of IDLE. The extra features, for those interested, are described
here:

http://idlex.sourceforge.net/features.html

It fixes most of the things people don't like about IDLE, except
for its appearance!

-- 
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 eryksun at gmail.com  Mon Jul 31 19:13:51 2017
From: eryksun at gmail.com (eryk sun)
Date: Mon, 31 Jul 2017 23:13:51 +0000
Subject: [Tutor] pythonic ascii decoding!
In-Reply-To: <CAP16ngqmSRJfFPUNQmmyebSA88qmRrZBebmAdRJiJ1aHAvLVTw@mail.gmail.com>
References: <CAP16ngqmSRJfFPUNQmmyebSA88qmRrZBebmAdRJiJ1aHAvLVTw@mail.gmail.com>
Message-ID: <CACL+1avbLn_=X0p48YY08i_4UA4F7QNhxST4rxLfnuUmriR6XQ@mail.gmail.com>

On Mon, Jul 31, 2017 at 3:39 PM, bruce <badouglas at gmail.com> wrote:
>
> So, is there a quick/dirty approach I can use to simply strip out the
> "non-ascii" chars. I know, this might not be the "best/pythonic" way,
> and that it might result in loss of some data/chars, but I can live
> with it for now.

Ignore or replace the non-ASCII characters. For example:

    >>> print 's\xffp\xffa\xffm'.decode('ascii', 'ignore')
    spam
    >>> print 's\xffp\xffa\xffm'.decode('ascii', 'replace')
    s?p?a?m