From robertvstepp at gmail.com  Wed May  1 00:48:05 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Tue, 30 Apr 2013 17:48:05 -0500
Subject: [Tutor] New book: Data Structures and Algorithms in Python.
	Opinions?
Message-ID: <CANDiX9Jew4P2pQ-YcAQ2zX=FirLw087+WsuWNvxFHX5v72jrLA@mail.gmail.com>

The following textbook was just released yesterday on Amazon:

Data Structures and Algorithms in Python

Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
March 2013, ?2013

I was wondering if anyone was familiar with the earlier "market
leading" textbooks in C++ and Java with essentially the same title and
can tell me if I have made a good purchase or not. This is a topic I
need to look into at some point and, if nothing else, it is another
Python-based book!

Cheers!
boB

From eliswilson at hushmail.com  Wed May  1 00:57:47 2013
From: eliswilson at hushmail.com (eliswilson at hushmail.com)
Date: Tue, 30 Apr 2013 18:57:47 -0400
Subject: [Tutor] Biggest Fake Conference in Computer Science
Message-ID: <20130430225747.BEFE3A6E45@smtp.hushmail.com>

Biggest Fake Conference in Computer Science

We are researchers from different parts of the world and conducted a study on the world?s biggest 
bogus computer science conference WORLDCOMP  http://sites.google.com/site/worlddump1 
organized by Prof. Hamid Arabnia from University of Georgia, USA.


We submitted a fake paper to WORLDCOMP 2011 and again (the same paper with a modified title) to 
WORLDCOMP 2012. This paper had numerous fundamental mistakes. Sample statements from that 
paper include: 

(1). Binary logic is fuzzy logic and vice versa
(2). Pascal developed fuzzy logic
(3). Object oriented languages do not exhibit any polymorphism or inheritance
(4). TCP and IP are synonyms and are part of OSI model 
(5). Distributed systems deal with only one computer
(6). Laptop is an example for a super computer
(7). Operating system is an example for computer hardware


Also, our paper did not express any conceptual meaning.  However, it was accepted both the times 
without any modifications (and without any reviews) and we were invited to submit the final paper 
and a payment of $500+ fee to present the paper. We decided to use the fee for better purposes than 
making Prof. Hamid Arabnia richer. After that, we received few reminders from WORLDCOMP to pay 
the fee but we never responded. This fake paper is different from the two fake papers already published 
(see https://sites.google.com/site/worlddump4 for details) in WORLDCOMP.


We MUST say that you should look at the above website if you have any thoughts of participating in
WORLDCOMP.  DBLP and other indexing agencies have stopped indexing WORLDCOMP?s proceedings 
since 2011 due to its fakeness. See http://www.informatik.uni-trier.de/~ley/db/conf/icai/index.html for
of one of the conferences of WORLDCOMP and notice that there is no listing after 2010. See Section 2 of
http://sites.google.com/site/dumpconf for comments from well-known researchers about 
WORLDCOMP. 


The status of your WORLDCOMP papers can be changed from scientific to other (i.e., junk or 
non-technical) at any time. Better not to have a paper than having it in WORLDCOMP and spoil the 
resume and peace of mind forever!


Our study revealed that WORLDCOMP is money making business, using University of Georgia mask, for 
Prof. Hamid Arabnia. He is throwing out a small chunk of that money (around 20 dollars per paper 
published in WORLDCOMP?s proceedings) to his puppet (Mr. Ashu Solo or A.M.G. Solo) who publicizes 
WORLDCOMP and also defends it at various forums, using fake/anonymous names. The puppet uses 
fake names and defames other conferences to divert traffic to WORLDCOMP. He also makes anonymous 
phone calls and threatens the critiques of WORLDCOMP (See Item 7 of Section 5 of above website). That 
is, the puppet does all his best to get a maximum number of papers published at WORLDCOMP to get 
more money into his (and Prof. Hamid Arabnia?s) pockets. Prof. Hamid Arabnia makes a lot of tricks. For 
example, he appeared in a newspaper to fool the public, claiming him a victim of cyber-attack (see Item 
8 in Section 5 of above website).


Monte Carlo Resort (the venue of WORLDCOMP for more than 10 years, until 2012) has refused to 
provide the venue for WORLDCOMP?13 because of the fears of their image being tarnished due to 
WORLDCOMP?s fraudulent activities. That is why WORLDCOMP?13 is taking place at a different resort. 
WORLDCOMP will not be held after 2013. 


The draft paper submission deadline is over but still there are no committee members, no reviewers, 
and there is no conference Chairman. The only contact details available on WORLDCOMP?s website is 
just an email address! 

We ask Prof. Hamid Arabnia to publish all reviews for all the papers (after blocking identifiable details) 
since 2000 conference. Reveal the names and affiliations of all the reviewers (for each year) and how 
many papers each reviewer had reviewed on average. We also ask him to look at the Open Challenge 
(Section 6) at https://sites.google.com/site/moneycomp1 and respond if he has any professional values.


Sorry for posting to multiple lists. Spreading the word is the only way to stop this bogus conference. 
Please forward this message to other mailing lists and people. 


We are shocked with Prof. Hamid Arabnia and his puppet?s activities at
http://worldcomp-fake-bogus.blogspot.com   Search Google using the keyword worldcomp fake for 
additional links.


From robertvstepp at gmail.com  Wed May  1 04:12:07 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Tue, 30 Apr 2013 21:12:07 -0500
Subject: [Tutor] Continuation of long lines of string characters
Message-ID: <CANDiX9J=PcHGGfFrJn0FAcX6bGW4bNQ2Um4NfKrREecTE4T_cQ@mail.gmail.com>

I have been looking through PEP 8--Style Guide for Python Code. It
recommends a maximum line length of 79 characters. What is the
preferred way to continue on another line or lines really long print
functions of string literals (Python 3)? The only thing that
immediately occurs to me is to break up the string literal into
multiple parts separated by + and break after the + . This seems to
use Python's built-in line continuation of anything between parens. Is
this the preferred way to do this?

Thanks!
boB

From brianjamesarb at gmail.com  Wed May  1 04:28:07 2013
From: brianjamesarb at gmail.com (brian arb)
Date: Tue, 30 Apr 2013 22:28:07 -0400
Subject: [Tutor] Continuation of long lines of string characters
In-Reply-To: <CANDiX9J=PcHGGfFrJn0FAcX6bGW4bNQ2Um4NfKrREecTE4T_cQ@mail.gmail.com>
References: <CANDiX9J=PcHGGfFrJn0FAcX6bGW4bNQ2Um4NfKrREecTE4T_cQ@mail.gmail.com>
Message-ID: <CABYizFLCqbBDeJZ9w+mzNNQpL660PXxJhMhbRYZKw5nLs8Ubpg@mail.gmail.com>

I really like breaking my long strings like...

Take this...
my_very_long_string = "I have been looking through PEP 8--Style Guide for
Python Code. It recommends a maximum line length of 79 characters. What is
the preferred way to continue on another line or lines really long print
functions of string literals (Python 3)? The only thing that immediately
occurs to me is to break up the string literal into multiple parts
separated by + and break after the + . This seems to use Python's built-in
line continuation of anything between parens. Is this the preferred way to
do this?"

And rewrite it like this...
my_very_long_string = ('I have been looking through PEP 8--Style Guide for
Python Code.'
                       'It recommends a maximum line length of 79
characters. What is the'
                       'preferred way to continue on another line or lines
really long print'
                       'functions of string literals (Python 3)? The only
thing that'
                       'immediately occurs to me is to break up the string
literal into'
                       'multiple parts separated by + and break after the +
. This seems to'
                       'use Python\'s built-in line continuation of
anything between parens. Is'
                       'this the preferred way to do this?')

On Tue, Apr 30, 2013 at 10:12 PM, boB Stepp <robertvstepp at gmail.com> wrote:

> I have been looking through PEP 8--Style Guide for Python Code. It
> recommends a maximum line length of 79 characters. What is the
> preferred way to continue on another line or lines really long print
> functions of string literals (Python 3)? The only thing that
> immediately occurs to me is to break up the string literal into
> multiple parts separated by + and break after the + . This seems to
> use Python's built-in line continuation of anything between parens. Is
> this the preferred way to do this?
>
> Thanks!
> boB
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130430/ff7d8c7e/attachment-0001.html>

From steve at pearwood.info  Wed May  1 04:32:47 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 01 May 2013 12:32:47 +1000
Subject: [Tutor] Continuation of long lines of string characters
In-Reply-To: <CANDiX9J=PcHGGfFrJn0FAcX6bGW4bNQ2Um4NfKrREecTE4T_cQ@mail.gmail.com>
References: <CANDiX9J=PcHGGfFrJn0FAcX6bGW4bNQ2Um4NfKrREecTE4T_cQ@mail.gmail.com>
Message-ID: <51807ECF.8000408@pearwood.info>

On 01/05/13 12:12, boB Stepp wrote:
> I have been looking through PEP 8--Style Guide for Python Code. It
> recommends a maximum line length of 79 characters. What is the
> preferred way to continue on another line or lines really long print
> functions of string literals (Python 3)? The only thing that
> immediately occurs to me is to break up the string literal into
> multiple parts separated by + and break after the + . This seems to
> use Python's built-in line continuation of anything between parens. Is
> this the preferred way to do this?

Use Python's implicit string concatenation:

some_message = ("This is a really long line "
                 "of text that Python automatically "
                 "joins into a single string.")


The advantage of implicit concatenation is that it is guaranteed to
happen at compile-time, while the + operator may or may not occur until
run-time, depending on the version of Python.



-- 
Steven

From robertvstepp at gmail.com  Wed May  1 04:34:02 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Tue, 30 Apr 2013 21:34:02 -0500
Subject: [Tutor] Continuation of long lines of string characters
In-Reply-To: <CABYizFLCqbBDeJZ9w+mzNNQpL660PXxJhMhbRYZKw5nLs8Ubpg@mail.gmail.com>
References: <CANDiX9J=PcHGGfFrJn0FAcX6bGW4bNQ2Um4NfKrREecTE4T_cQ@mail.gmail.com>
	<CABYizFLCqbBDeJZ9w+mzNNQpL660PXxJhMhbRYZKw5nLs8Ubpg@mail.gmail.com>
Message-ID: <CANDiX9K7azf1mGe0V6qJKsPZhQkS+sVKJjk=uof_6pqRF6mQDg@mail.gmail.com>

I was just now playing around in the interpreter trying
print('Hello''world!') thinking I would get a syntax error, only to
discover the kernel of what you show below...

On Tue, Apr 30, 2013 at 9:28 PM, brian arb <brianjamesarb at gmail.com> wrote:
> I really like breaking my long strings like...
>
> And rewrite it like this...
> my_very_long_string = ('I have been looking through PEP 8--Style Guide for
> Python Code.'
>                        'It recommends a maximum line length of 79
> characters. What is the'
>                        'preferred way to continue on another line or lines
> really long print'
>                        'functions of string literals (Python 3)? The only
> thing that'
>                        'immediately occurs to me is to break up the string
> literal into'
>                        'multiple parts separated by + and break after the +
> . This seems to'
>                        'use Python\'s built-in line continuation of anything
> between parens. Is'
>                        'this the preferred way to do this?')
>
Thanks!
boB

From amckenzie4 at gmail.com  Thu May  2 19:16:54 2013
From: amckenzie4 at gmail.com (Andy McKenzie)
Date: Thu, 2 May 2013 13:16:54 -0400
Subject: [Tutor] Multiple search and replace?
Message-ID: <CAJttDkq3C2E3-CDGrz-hYerfr1Xprmu+d6FuN4F0r_rwpCq2Ug@mail.gmail.com>

Hey folks,

  I'm trying to figure out how to do something, and it feels like it should
be possible, but I can't figure out how.  What I want is to define four
expressions, like so:

(\sNorth\s|\sN\s)(\sSouth\s|\sS\s)(\sEast\s|\sE\s)(\sWest\s|\sW\s)

And then run a replace such that the groups are replaced, in order, with "N
", "S ", "E ", or "W " (capital letters, no spaces before).

It's easy enough to use re.sub to replace ONE of those, and I could just do
that four times, but is there a way to do all at once?  It looks from some
things I've seen like it should be, but I can't figure out how.

Thanks,
  Andy McKenzie
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130502/29c3d22d/attachment.html>

From __peter__ at web.de  Thu May  2 19:42:30 2013
From: __peter__ at web.de (Peter Otten)
Date: Thu, 02 May 2013 19:42:30 +0200
Subject: [Tutor] Multiple search and replace?
References: <CAJttDkq3C2E3-CDGrz-hYerfr1Xprmu+d6FuN4F0r_rwpCq2Ug@mail.gmail.com>
Message-ID: <klu8hp$t8u$1@ger.gmane.org>

Andy McKenzie wrote:

> Hey folks,
> 
>   I'm trying to figure out how to do something, and it feels like it
>   should
> be possible, but I can't figure out how.  What I want is to define four
> expressions, like so:
> 
> (\sNorth\s|\sN\s)(\sSouth\s|\sS\s)(\sEast\s|\sE\s)(\sWest\s|\sW\s)
> 
> And then run a replace such that the groups are replaced, in order, with
> "N ", "S ", "E ", or "W " (capital letters, no spaces before).
> 
> It's easy enough to use re.sub to replace ONE of those, and I could just
> do
> that four times, but is there a way to do all at once?  It looks from some
> things I've seen like it should be, but I can't figure out how.

re.sub() accepts a function where you can do anything you like:

>>> r = re.compile(r"\b(red|yellow|blue)\b")
>>> def sub(match):
...     s = match.group(1)
...     return {"red": "pink", "yellow": "monsters"}.get(s, "starts to cry")
... 
>>> r.sub(sub, "Who's afraid of red yellow and blue?")
"Who's afraid of pink monsters and starts to cry?"

>>> re.compile(r"\b(north|south|east|west)\b").sub(lambda m: m.group(1)[:1],
... "north by northwest, south of southpark")
'n by northwest, s of southpark'



From karthik.sharma at gmail.com  Fri May  3 00:13:34 2013
From: karthik.sharma at gmail.com (Karthik Sharma)
Date: Fri, 3 May 2013 10:13:34 +1200
Subject: [Tutor] query from sqlalchemy returns AttributeError: 'NoneType'
	object
Message-ID: <CAJQZjgM8+XrLC7P1CHDEkcDu5rqL14oiJQbC5RZUorOTwUeMjA@mail.gmail.com>

    from pox.core import core
    import pox.openflow.libopenflow_01 as of
    import re
    import datetime

    from sqlalchemy import create_engine, ForeignKey
    from sqlalchemy import Column, Date, Integer, String
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import relationship, backref
    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker
    from sqlalchemy.sql.expression import exists

    log = core.getLogger()

    engine = create_engine('sqlite:///nwtopology.db', echo=False)
    Base = declarative_base()
    Session = sessionmaker(bind=engine)
    session = Session()

    ########################################################################
    class SourcetoPort(Base):
        """"""
        __tablename__ = 'source_to_port'
        id = Column(Integer, primary_key=True)
        port_no        = Column(Integer)
        src_address    = Column(String,index=True)


#----------------------------------------------------------------------
        def __init__(self, src_address,port_no):
            """"""
            self.src_address = src_address
    self.port_no     = port_no

    ########################################################################

    #create tables
    Base.metadata.create_all(engine)

    class Tutorial (object):
      def __init__ (self, connection):
        self.connection = connection
        connection.addListeners(self)
        # Use this table to keep track of which ethernet address is on
        # which switch port (keys are MACs, values are ports).
        self.mac_to_port = {}
        self.matrix={}

        #This will keep track of the traffic matrix.
        #matrix[i][j]=number of times a packet from i went to j

      def send_packet (self, buffer_id, raw_data, out_port, in_port):
        #print "calling send_packet"
        #Sends a packet out of the specified switch port.
        msg = of.ofp_packet_out()
        msg.in_port = in_port
        msg.data = raw_data
        # Add an action to send to the specified port
        action = of.ofp_action_output(port = out_port)
        msg.actions.append(action)
        # Send message to switch
        self.connection.send(msg)

      def act_like_hub (self, packet, packet_in):
        #flood packet on all ports
        self.send_packet(packet_in.buffer_id, packet_in.data,
                         of.OFPP_FLOOD, packet_in.in_port)

      def act_like_switch (self, packet, packet_in):
        """
        Implement switch-like behavior.
        """
        # Learn the port for the source MAC
        #print "RECIEVED FROM PORT ",packet_in.in_port , "SOURCE
",packet.src
        # create a Session
        #Session = sessionmaker(bind=engine)
        #session = Session()
        self.mac_to_port[packet.src]=packet_in.in_port
        #if self.mac_to_port.get(packet.dst)!=None:
        #print "count for
dst",session.query(SourcetoPort).filter_by(src_address=str(packet.dst)).count(),str(packet.dst)
        #if
session.query(SourcetoPort).filter_by(src_address=str(packet.dst)).count():
        if session.query(exists().where(SourcetoPort.src_address ==
str(packet.dst))).scalar() is not None:
             #send this packet
       print "got info from the database"
       q_res =
session.query(SourcetoPort).filter_by(src_address=str(packet.dst)).one()
       self.send_packet(packet_in.buffer_id, packet_in.data,q_res.port_no,
packet_in.in_port)
               #create a flow modification message
             msg = of.ofp_flow_mod()
             #set the fields to match from the incoming packet
       msg.match = of.ofp_match.from_packet(packet)
               #send the rule to the switch so that it does not query the
controller again.
               msg.actions.append(of.ofp_action_output(port=q_res.port_no))
               #push the rule
               self.connection.send(msg)
        else:
               #flood this packet out as we don't know about this node.
               print "flooding the first packet"
               self.send_packet(packet_in.buffer_id, packet_in.data,
                           of.OFPP_FLOOD, packet_in.in_port)
       #self.matrix[(packet.src,packet.dst)]+=1
       entry = SourcetoPort(src_address=str(packet.src) ,
port_no=packet_in.in_port)
               #add the record to the session object
               session.add(entry)
               #add the record to the session object
               session.commit()

      def _handle_PacketIn (self, event):
        """
        Handles packet in messages from the switch.
        """
        packet = event.parsed # This is the parsed packet data.
        if not packet.parsed:
          log.warning("Ignoring incomplete packet")
          return
        packet_in = event.ofp # The actual ofp_packet_in message.

        #self.act_like_hub(packet, packet_in)
        self.act_like_switch(packet, packet_in)

    def launch ():
      """
      Starts the component
      """
      def start_switch (event):
        log.debug("Controlling %s" % (event.connection,))
        Tutorial(event.connection)
      core.openflow.addListenerByName("ConnectionUp", start_switch)



When I run the above code I get the following error:



The problem that I am facing is for some reason if I use

    if session.query(exists().where(SourcetoPort.src_address ==
str(packet.dst))).scalar() is not None:

    in place of count query.

    #if
session.query(SourcetoPort).filter_by(src_address=str(packet.dst)).count():

The querying from the database

    q_res =
session.query(SourcetoPort).filter_by(src_address=str(packet.dst)).first()
    self.send_packet(packet_in.buffer_id, packet_in.data,q_res.port_no,
packet_in.in_port)

is giving the following error:

    DEBUG:core:POX 0.1.0 (betta) going up...
    DEBUG:core:Running on CPython (2.7.3/Aug 1 2012 05:14:39)
    DEBUG:core:Platform is
Linux-3.5.0-23-generic-x86_64-with-Ubuntu-12.04-precise
    INFO:core:POX 0.1.0 (betta) is up.
    DEBUG:openflow.of_01:Listening on 0.0.0.0:6633
    INFO:openflow.of_01:[00-00-00-00-00-02 1] connected
    DEBUG:tutorial:Controlling [00-00-00-00-00-02 1]
    got info from the database
    ERROR:core:Exception while handling Connection!PacketIn...
    Traceback (most recent call last):
      File "/home/karthik/pox/pox/lib/revent/revent.py", line 234, in
raiseEventNoErrors
        return self.raiseEvent(event, *args, **kw)
      File "/home/karthik/pox/pox/lib/revent/revent.py", line 281, in
raiseEvent
        rv = event._invoke(handler, *args, **kw)
      File "/home/karthik/pox/pox/lib/revent/revent.py", line 159, in
_invoke
        return handler(self, *args, **kw)
      File "/home/karthik/pox/tutorial.py", line 118, in _handle_PacketIn
        self.act_like_switch(packet, packet_in)
      File "/home/karthik/pox/tutorial.py", line 86, in act_like_switch
        self.send_packet(packet_in.buffer_id, packet_in.data,q_res.port_no,
packet_in.in_port)
    AttributeError: 'NoneType' object has no attribute 'port_no'
    got info from the database
    ERROR:core:Exception while handling Connection!PacketIn...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130503/3e34facf/attachment-0001.html>

From paradox at pobox.com  Fri May  3 04:17:12 2013
From: paradox at pobox.com (Paradox)
Date: Fri, 03 May 2013 10:17:12 +0800
Subject: [Tutor] query from sqlalchemy returns AttributeError:
 'NoneType' object :p:
In-Reply-To: <CAJQZjgM8+XrLC7P1CHDEkcDu5rqL14oiJQbC5RZUorOTwUeMjA@mail.gmail.com>
References: <CAJQZjgM8+XrLC7P1CHDEkcDu5rqL14oiJQbC5RZUorOTwUeMjA@mail.gmail.com>
Message-ID: <51831E28.50600@pobox.com>


On 05/03/2013 06:13 AM, Karthik Sharma wrote:
>
>     from sqlalchemy import create_engine, ForeignKey
>     from sqlalchemy import Column, Date, Integer, String
>
This list is mostly for standard library questions (though there may be 
some that can help here too).  Did you know there is an sqlalchemy 
google group (

This list is really for standard library questions (though there may be some that can help here too).  Did you know there is an sqlalchemy google group?  The site is here: http://groups.google.com/group/sqlalchemy?hl=en.  Michael Bayer frequently answers questions there too, though there are lots of knowledgeable people on that list that can handle simpler problems.

thomas


From jollynony at gmail.com  Fri May  3 08:10:24 2013
From: jollynony at gmail.com (Nonso Ibenegbu)
Date: Fri, 3 May 2013 07:10:24 +0100
Subject: [Tutor] Why do I not get the same results for these two functions
 when I pass 7 as an argument?
Message-ID: <CAA2qq3e1CLNXdSApvQrxvr2JiBD9vHbq3ch33AzpZnj1Efn86g@mail.gmail.com>

Hello everyone,
Wonder if someone can help me understand why these two codes do not give
the same results for what looks essentially the same ("?") code. The
argument passed is
7.

def rental_car_cost(days):
    payment = days * 40
    if days >= 7:
        return payment - 50
    elif days >= 3 < 7:
        return payment - 20
    else:
        return payment

and...

def rental_car_cost(days):
    payment = days * 40
    if days >= 3 < 7:
        return payment - 20
    elif days >= 7:
        return payment - 50
    else:
        return payment
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130503/6f811027/attachment.html>

From breamoreboy at yahoo.co.uk  Fri May  3 09:07:46 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Fri, 03 May 2013 08:07:46 +0100
Subject: [Tutor] Why do I not get the same results for these two
 functions when I pass 7 as an argument?
In-Reply-To: <CAA2qq3e1CLNXdSApvQrxvr2JiBD9vHbq3ch33AzpZnj1Efn86g@mail.gmail.com>
References: <CAA2qq3e1CLNXdSApvQrxvr2JiBD9vHbq3ch33AzpZnj1Efn86g@mail.gmail.com>
Message-ID: <klvno1$s16$1@ger.gmane.org>

On 03/05/2013 07:10, Nonso Ibenegbu wrote:
> Hello everyone,
> Wonder if someone can help me understand why these two codes do not give
> the same results for what looks essentially the same ("?") code. The
> argument passed is
> 7.
>
> def rental_car_cost(days):
>      payment = days * 40
>      if days >= 7:
>          return payment - 50
>      elif days >= 3 < 7:
>          return payment - 20
>      else:
>          return payment
>
> and...
>
> def rental_car_cost(days):
>      payment = days * 40
>      if days >= 3 < 7:
>          return payment - 20
>      elif days >= 7:
>          return payment - 50
>      else:
>          return payment
>

Python comparisons are chained.  days >= 3 < 7 is saying "days is 
greater or equal to 3 and 3 is less than 7".  You need 3 <= days < 7.

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From alan.gauld at btinternet.com  Fri May  3 11:13:40 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 03 May 2013 10:13:40 +0100
Subject: [Tutor] query from sqlalchemy returns AttributeError:
	'NoneType' object
In-Reply-To: <CAJQZjgM8+XrLC7P1CHDEkcDu5rqL14oiJQbC5RZUorOTwUeMjA@mail.gmail.com>
References: <CAJQZjgM8+XrLC7P1CHDEkcDu5rqL14oiJQbC5RZUorOTwUeMjA@mail.gmail.com>
Message-ID: <klvv40$69q$1@ger.gmane.org>

On 02/05/13 23:13, Karthik Sharma wrote:

This doesn't have much to do with learning Python and a lot to do with 
SqlAlchemy so you'd be better off asking on a SqlAlchemy forum I suspect.

However, some basic debugging investigation first may help your cause.
For example...

>      Traceback (most recent call last):
...
>        File "/home/karthik/pox/tutorial.py", line 118, in _handle_PacketIn
>          self.act_like_switch(packet, packet_in)
>        File "/home/karthik/pox/tutorial.py", line 86, in act_like_switch
>          self.send_packet(packet_in.buffer_id,
> packet_in.data,q_res.port_no, packet_in.in_port)
>      AttributeError: 'NoneType' object has no attribute 'port_no'

Have you checked to see what q_res is supposed to be?
And where it comes from? And why it's apparently a NoneType?

Some print statements might be in order?

That will help anyone who can help you to so do.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From askar.kengesbayev at etrade.com  Fri May  3 16:48:36 2013
From: askar.kengesbayev at etrade.com (Kengesbayev, Askar)
Date: Fri, 3 May 2013 14:48:36 +0000
Subject: [Tutor] Why do I not get the same results for these two
 functions when I pass 7 as an argument?
In-Reply-To: <CAA2qq3e1CLNXdSApvQrxvr2JiBD9vHbq3ch33AzpZnj1Efn86g@mail.gmail.com>
References: <CAA2qq3e1CLNXdSApvQrxvr2JiBD9vHbq3ch33AzpZnj1Efn86g@mail.gmail.com>
Message-ID: <6FAD14604B087B438F6FF64D9875A40C68E80149@atl1ex10mbx4.corp.etradegrp.com>


You need to change the condition statement:

  if days >= 3 < 7:  to  this    if days >= 3 and days < 7:

When it goes through the function it sees this statement days >= 3 as true and execute - payment -20.

Askar

From: Nonso Ibenegbu [mailto:jollynony at gmail.com]
Sent: Friday, May 03, 2013 2:10 AM
To: Tutor at python.org
Subject: [Tutor] Why do I not get the same results for these two functions when I pass 7 as an argument?

Hello everyone,
Wonder if someone can help me understand why these two codes do not give the same results for what looks essentially the same ("?") code. The argument passed is
7.

def rental_car_cost(days):
    payment = days * 40
    if days >= 7:
        return payment - 50
    elif days >= 3 < 7:
        return payment - 20
    else:
        return payment

and...

def rental_car_cost(days):
    payment = days * 40
    if days >= 3 < 7:
        return payment - 20
    elif days >= 7:
        return payment - 50
    else:
        return payment
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130503/1f0211e6/attachment.html>

From jollynony at gmail.com  Fri May  3 18:51:31 2013
From: jollynony at gmail.com (Nonso Ibenegbu)
Date: Fri, 3 May 2013 17:51:31 +0100
Subject: [Tutor] Why do I not get the same results for these two
 functions when I pass 7 as an argument?
In-Reply-To: <klvno1$s16$1@ger.gmane.org>
References: <CAA2qq3e1CLNXdSApvQrxvr2JiBD9vHbq3ch33AzpZnj1Efn86g@mail.gmail.com>
	<klvno1$s16$1@ger.gmane.org>
Message-ID: <CAA2qq3fr49_3PUCvPoMA5W4r+3AJRWL6Ue9EOgzdyA7WZKPcOg@mail.gmail.com>

Great! Many thanks for the help offered. The background of the problem is
that if I book a certain service for 1 or 2 days I pay $40 per day, if I
book 3,  4, 5 or 6 days I get $20 off but if I book above 7 days I get $50
off.

The first function does the job!

The second function breaks down when the argument is 7 or above.

Yet the only difference is that the condition "if days >= 7:" comes first
in the first function but comes second (as "elif days >= 7:") in the second
code.

I think essentially that the difference lies in the fact that the
conditions were swapped. But how are they different?


On Fri, May 3, 2013 at 8:07 AM, Mark Lawrence <breamoreboy at yahoo.co.uk>wrote:

> On 03/05/2013 07:10, Nonso Ibenegbu wrote:
>
>> Hello everyone,
>> Wonder if someone can help me understand why these two codes do not give
>> the same results for what looks essentially the same ("?") code. The
>> argument passed is
>> 7.
>>
>> def rental_car_cost(days):
>>      payment = days * 40
>>      if days >= 7:
>>          return payment - 50
>>      elif days >= 3 < 7:
>>          return payment - 20
>>      else:
>>          return payment
>>
>> and...
>>
>> def rental_car_cost(days):
>>      payment = days * 40
>>      if days >= 3 < 7:
>>          return payment - 20
>>      elif days >= 7:
>>          return payment - 50
>>      else:
>>          return payment
>>
>>
> Python comparisons are chained.  days >= 3 < 7 is saying "days is greater
> or equal to 3 and 3 is less than 7".  You need 3 <= days < 7.
>
> --
> If you're using GoogleCrap? please read this http://wiki.python.org/moin/*
> *GoogleGroupsPython <http://wiki.python.org/moin/GoogleGroupsPython>.
>
> Mark Lawrence
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130503/a9f74e74/attachment.html>

From alan.gauld at btinternet.com  Fri May  3 20:10:55 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 03 May 2013 19:10:55 +0100
Subject: [Tutor] Why do I not get the same results for these two
 functions when I pass 7 as an argument?
In-Reply-To: <CAA2qq3fr49_3PUCvPoMA5W4r+3AJRWL6Ue9EOgzdyA7WZKPcOg@mail.gmail.com>
References: <CAA2qq3e1CLNXdSApvQrxvr2JiBD9vHbq3ch33AzpZnj1Efn86g@mail.gmail.com>
	<klvno1$s16$1@ger.gmane.org>
	<CAA2qq3fr49_3PUCvPoMA5W4r+3AJRWL6Ue9EOgzdyA7WZKPcOg@mail.gmail.com>
Message-ID: <km0uja$9cm$1@ger.gmane.org>

On 03/05/13 17:51, Nonso Ibenegbu wrote:

> The second function breaks down when the argument is 7 or above.
>
> Yet the only difference is that the condition "if days >= 7:" comes
> first in the first function but comes second (as "elif days >= 7:") in
> the second code.

Yes but that's because the other expression is nonsense (to python).

You cannot write

if days >= 3 < 7:

It doesn't make any sense.

What you mean is

if days >=3 and days < 7

If you fix that then the two functions will have similar logic.

In Python 9unlike most languages) you can abbreviate that but not the 
way you did it.
You need to use

if 3 <= days < 7:

Note that the variable is in the middle and the test for 3
is now reversed (3<=days). If in doubt use the double test
combined by 'and' as above.



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From dyoo at hashcollision.org  Fri May  3 20:13:57 2013
From: dyoo at hashcollision.org (Danny Yoo)
Date: Fri, 3 May 2013 12:13:57 -0600
Subject: [Tutor] Why do I not get the same results for these two
 functions when I pass 7 as an argument?
In-Reply-To: <CAA2qq3e1CLNXdSApvQrxvr2JiBD9vHbq3ch33AzpZnj1Efn86g@mail.gmail.com>
References: <CAA2qq3e1CLNXdSApvQrxvr2JiBD9vHbq3ch33AzpZnj1Efn86g@mail.gmail.com>
Message-ID: <CAGZAPF579igr1Gz3qYJgGvQOR=pO_=+N==Vf_L5gSAT+9UTZTw@mail.gmail.com>

>     elif days >= 3 < 7:

This condition here, as well as:


>     if days >= 3 < 7:


this condition here, looks very suspicious.  Can you say what you
trying to express here?

From Robert.Treder at morganstanley.com  Fri May  3 22:48:40 2013
From: Robert.Treder at morganstanley.com (Treder, Robert)
Date: Fri, 3 May 2013 16:48:40 -0400
Subject: [Tutor] creating a corpus from a csv file
Message-ID: <E84A3AA0F1F20E41953E8486223DD65057F533AAD3@NYWEXMBX2130.msad.ms.com>

Hi, 
 
I'm very new to python and am trying to figure out how to make a corpus from a text file. I have a csv file (actually pipe '|' delimited) where each row corresponds to a different text document. Each row contains a communication note. Other columns correspond to categories of types of communications. I am able to read the csv file and print the notes column as follows: 
 
import csv
with open('notes.txt', 'rb') as infile:
    reader = csv.reader(infile, delimiter = '|')
    i = 0
    for row in reader:
    if i <= 25: print row[8]
    i = i+1

I would like to convert this to a categorized corpus with some of the other columns corresponding to the categories. All of the columns are text (i.e., strings). I have looked for documentation on how to use csv.reader with PlaintextCorpusReader but have been unsuccessful in finding a  example similar to what I want to do. Can someone please help?  
 
Thanks, 
Bob


--------------------------------------------------------------------------------

NOTICE: Morgan Stanley is not acting as a municipal advisor and the opinions or views contained herein are not intended to be, and do not constitute, advice within the meaning of Section 975 of the Dodd-Frank Wall Street Reform and Consumer Protection Act. If you have received this communication in error, please destroy all electronic and paper copies and notify the sender immediately. Mistransmission is not intended to waive confidentiality or privilege. Morgan Stanley reserves the right, to the extent permitted under applicable law, to monitor electronic communications. This message is subject to terms available at the following link: http://www.morganstanley.com/disclaimers. If you cannot access these links, please notify us by reply message and we will send the contents to you. By messaging with Morgan Stanley you consent to the foregoing.

From alan.gauld at btinternet.com  Sat May  4 00:05:32 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 03 May 2013 23:05:32 +0100
Subject: [Tutor] creating a corpus from a csv file
In-Reply-To: <E84A3AA0F1F20E41953E8486223DD65057F533AAD3@NYWEXMBX2130.msad.ms.com>
References: <E84A3AA0F1F20E41953E8486223DD65057F533AAD3@NYWEXMBX2130.msad.ms.com>
Message-ID: <km1cb8$ist$1@ger.gmane.org>

On 03/05/13 21:48, Treder, Robert wrote:

> I'm very new to python and am trying to figure out how to
 > make a corpus from a text file.

Hi, I for one have no idea what a corpus is or looks like
so you will need to help us out a little before we can help you.

> I have a csv file (actually pipe '|' delimited) where each
> row corresponds to a different text document.

> Each row contains a communication note.
 > Other columns correspond to categories of types of communications.

> I am able to read the csv file and print the notes column as follows:
>
> import csv
> with open('notes.txt', 'rb') as infile:
>      reader = csv.reader(infile, delimiter = '|')
>      i = 0
>      for row in reader:
>      if i <= 25: print row[8]
>      i = i+1

You don't need to manually manage 'i'.

you could do this instead:

with open('notes.txt', 'rb') as infile:
      reader = csv.reader(infile, delimiter = '|')
      for count, row in enumerate(reader):
          if count <= 25: print row[8]  # I assume indented?
          else: break                   # save time if its a big file

> I would like to convert this to a categorized corpus with
 > some of the other columns corresponding to the categories.

You might be able to use a dictionary but for now
I'm still not clear what you mean. Can you show us
some sample input and output data?

 > documentation on how to use csv.reader with PlaintextCorpusReader

never heard of the latter - is it an external module?

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From davea at davea.name  Sat May  4 02:34:28 2013
From: davea at davea.name (Dave Angel)
Date: Fri, 03 May 2013 20:34:28 -0400
Subject: [Tutor] Why do I not get the same results for these two
 functions when I pass 7 as an argument?
In-Reply-To: <CAA2qq3fr49_3PUCvPoMA5W4r+3AJRWL6Ue9EOgzdyA7WZKPcOg@mail.gmail.com>
References: <CAA2qq3e1CLNXdSApvQrxvr2JiBD9vHbq3ch33AzpZnj1Efn86g@mail.gmail.com>
	<klvno1$s16$1@ger.gmane.org>
	<CAA2qq3fr49_3PUCvPoMA5W4r+3AJRWL6Ue9EOgzdyA7WZKPcOg@mail.gmail.com>
Message-ID: <51845794.7020604@davea.name>

On 05/03/2013 12:51 PM, Nonso Ibenegbu wrote:
> Great! Many thanks for the help offered. The background of the problem is
> that if I book a certain service for 1 or 2 days I pay $40 per day, if I
> book 3,  4, 5 or 6 days I get $20 off but if I book above 7 days I get $50
> off.
>
> The first function does the job!

By accident only.
The elif on the first one doesn't compare days to 7 at all.  So it's 
simply equivalent to:

     elif days >= 3:

If you can't understand that, then comparing the two functions is useless.


-- 
DaveA

From cybervigilante at gmail.com  Sat May  4 06:13:02 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Fri, 3 May 2013 21:13:02 -0700
Subject: [Tutor] changing char list to int list isn't working
Message-ID: <CALRAYNV+2suCqjJnvYPkCmrxpskXDudugCLt_EfHaQxxqvvcWw@mail.gmail.com>

I'm turning an integer into a string so I can make a list of separate
chars, then turn those chars back into individual ints, but the
resulting list still looks like string chars when I print it. What am
I doing wrong?


listOfNumChars = list(str(intNum))
for num in listOfNumChars:
    num = int(num)

print(listOfNumChars)

# result of 455 entered is ['4', '5', '5']

--
Jim Mooney

?For anything that matters, the timing is never quite right, the
resources are always a little short, and the people who affect the
outcome are always ambivalent.?

From eryksun at gmail.com  Sat May  4 07:03:38 2013
From: eryksun at gmail.com (eryksun)
Date: Sat, 4 May 2013 01:03:38 -0400
Subject: [Tutor] changing char list to int list isn't working
In-Reply-To: <CALRAYNV+2suCqjJnvYPkCmrxpskXDudugCLt_EfHaQxxqvvcWw@mail.gmail.com>
References: <CALRAYNV+2suCqjJnvYPkCmrxpskXDudugCLt_EfHaQxxqvvcWw@mail.gmail.com>
Message-ID: <CACL+1aty499HkwFd68cYpFM41L8f8jvspRBtzqLKRT8=97hdjg@mail.gmail.com>

On Sat, May 4, 2013 at 12:13 AM, Jim Mooney <cybervigilante at gmail.com> wrote:
> I'm turning an integer into a string so I can make a list of separate
> chars, then turn those chars back into individual ints, but the
> resulting list still looks like string chars when I print it. What am
> I doing wrong?
>
> listOfNumChars = list(str(intNum))
> for num in listOfNumChars:
>     num = int(num)
>
> print(listOfNumChars)
>
> # result of 455 entered is ['4', '5', '5']

The body of your for loop only rebinds the loop variable. It's not
appending to a new list or modifying listOfNumChars. As to the latter
list, it's redundant since a string is iterable.

The following snippet creates the list [4, 5, 5]:

    num = 455

    numlist = []
    for c in str(num):
        numlist.append(int(c))

or using a list comprehension:

    numlist = [int(c) for c in str(num)]

or using map:

    numlist = list(map(int, str(num)))

iterators
http://docs.python.org/3/library/stdtypes.html#typeiter

built-in functions
http://docs.python.org/3/library/functions.html#iter
http://docs.python.org/3/library/functions.html#map

for statement
http://docs.python.org/3/reference/compound_stmts.html#the-for-statement

comprehensions
http://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries

From steve at pearwood.info  Sat May  4 07:49:25 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 04 May 2013 15:49:25 +1000
Subject: [Tutor] changing char list to int list isn't working
In-Reply-To: <CALRAYNV+2suCqjJnvYPkCmrxpskXDudugCLt_EfHaQxxqvvcWw@mail.gmail.com>
References: <CALRAYNV+2suCqjJnvYPkCmrxpskXDudugCLt_EfHaQxxqvvcWw@mail.gmail.com>
Message-ID: <5184A165.6070703@pearwood.info>

On 04/05/13 14:13, Jim Mooney wrote:
> I'm turning an integer into a string so I can make a list of separate
> chars, then turn those chars back into individual ints, but the
> resulting list still looks like string chars when I print it. What am
> I doing wrong?
>
> listOfNumChars = list(str(intNum))

This creates a list of characters.


> for num in listOfNumChars:
>      num = int(num)

This walks over the list, setting the variable "num" to each character in turn, then inside the loop you set the variable "num" to the converted char->int. But num isn't linked to the list in any way -- num has no memory that the value it got came from a list. Reassigning num inside the loop doesn't touch the list in any way, so naturally the list doesn't change.


> print(listOfNumChars)
>
> # result of 455 entered is ['4', '5', '5']


To split a number into digits, the shortest way is to use a list comprehension:


digits = [int(c) for c in str(num)]


We can expand that list comp into a for-loop:


digits = []
for c in str(num):
     digits.append(int(c))



Notice that there is no need to convert the string into a list. You can iterate over the characters of a string just fine.

If you prefer to create a list, then modify it in place, we can do this:


digits = list(str(num))
for position, char in enumerate(digits):
     digits[position] = int(char)



Here we use enumerate() to iterate over pairs of (position, value) instead of just value:

py> list("abcd")
['a', 'b', 'c', 'd']
py> list(enumerate("abcd"))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]



Here's another way, using map:


digits = map(int, str(num))  # Python 2.x only

digits = list(map(int, str(num)))  # Python 3.x or better



Why the difference between Python 2.x and 3.x? In 2.x, map is "eager", it runs all the way through the string as soon as you call it, returning a list. In 3.x, map is "lazy", and only generates values when and as needed. By wrapping the map generator in a call to list, that forces it to run all the way through the string.



-- 
Steven

From alan.gauld at btinternet.com  Sat May  4 10:17:29 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 04 May 2013 09:17:29 +0100
Subject: [Tutor] changing char list to int list isn't working
In-Reply-To: <CALRAYNV+2suCqjJnvYPkCmrxpskXDudugCLt_EfHaQxxqvvcWw@mail.gmail.com>
References: <CALRAYNV+2suCqjJnvYPkCmrxpskXDudugCLt_EfHaQxxqvvcWw@mail.gmail.com>
Message-ID: <km2g6k$i8o$1@ger.gmane.org>

On 04/05/13 05:13, Jim Mooney wrote:
> I'm turning an integer into a string so I can make a list of separate
> chars, then turn those chars back into individual ints,

You don't actually need to convert to chars, you could
use divmod to do it directly on the numbers:

 >>> digits = []
 >>> root = 455
 >>> while root > 0:
...     root, n = divmod(root,10)
...     digits.insert(0,n)
...
 >>> digits
[4, 5, 5]

But I suspect the str() method is slightly faster...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From __peter__ at web.de  Sat May  4 10:29:57 2013
From: __peter__ at web.de (Peter Otten)
Date: Sat, 04 May 2013 10:29:57 +0200
Subject: [Tutor] creating a corpus from a csv file
References: <E84A3AA0F1F20E41953E8486223DD65057F533AAD3@NYWEXMBX2130.msad.ms.com>
Message-ID: <km2gtu$o7a$1@ger.gmane.org>

Treder, Robert wrote:

> I'm very new to python and am trying to figure out how to make a corpus
> from a text file. I have a csv file (actually pipe '|' delimited) where
> each row corresponds to a different text document. Each row contains a
> communication note. Other columns correspond to categories of types of
> communications. I am able to read the csv file and print the notes column
> as follows:
>  
> import csv
> with open('notes.txt', 'rb') as infile:
>     reader = csv.reader(infile, delimiter = '|')
>     i = 0
>     for row in reader:
>     if i <= 25: print row[8]
>     i = i+1
> 
> I would like to convert this to a categorized corpus with some of the
> other columns corresponding to the categories. All of the columns are text
> (i.e., strings). I have looked for documentation on how to use csv.reader
> with PlaintextCorpusReader but have been unsuccessful in finding a 
> example similar to what I want to do. Can someone please help?

This mailing list is for learning Python. For problems with a specific 
library you should use the general python list 

<http://mail.python.org/mailman/listinfo/python-list>

or a forum dedicated to that library

<http://groups.google.com/group/nltk-users>

If you ask on a general forum you should give some context -- the name of 
the library would be the bare minimum.

The following comes with no warranties as I'm not an nltk user:

import csv
from nltk.corpus.reader.plaintext import CategorizedPlaintextCorpusReader
from itertools import islice, chain

LIMIT_SIZE = 25 # set to None if not debugging

def pairs(filename):
    """Generate (filename, list_of_categories) pairs from a csv file
    """
    with open(filename, "rb") as infile:
        rows = islice(csv.reader(infile, delimiter="|"), LIMIT_SIZE)
        for row in rows:
            # assume that columns 10 and above contain categories
            yield row[8], row[9:]

if __name__ == "__main__":
    import random
    FILENAME = "notes.txt"

    # assume that every filename occurs only once in the file
    file_to_categories = dict(pairs(FILENAME))

    files = list(file_to_categories)

    all_categories = 
set(chain.from_iterable(file_to_categories.itervalues()))

    reader = CategorizedPlaintextCorpusReader(".", files, 
cat_map=file_to_categories)

    # print words for a random category
    category = random.choice(list(all_categories))
    print "words for category {}:".format(category)
    print sorted(set(reader.words(categories=category)))




From kartiksundarajan at gmail.com  Sat May  4 15:04:23 2013
From: kartiksundarajan at gmail.com (kartik sundarajan)
Date: Sat, 4 May 2013 18:34:23 +0530
Subject: [Tutor] Python internals
Message-ID: <CAJ2_K2-GzwPEvE_SRGNO0VkC=0Z17EOnKGX8TmQZYxuZoYtbSA@mail.gmail.com>

Hi,

I am trying to learn how Python stores variables in memory. For ex:

my_var = 'test'

def func():
    pass

when I type dir() I get

['__builtins__', '__doc__', '__name__', '__package__', 'func', 'help',
'my_var']

are these variables stored in a dict and on calling dir() all the keys are
returned?
Or is it stored in a list or a heap?

Can anyone suggest if there some document I can read to help me understand
the Python internals work ?

Cheers
Kartik
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130504/9839edb6/attachment.html>

From steve at pearwood.info  Sat May  4 15:32:27 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 04 May 2013 23:32:27 +1000
Subject: [Tutor] Python internals
In-Reply-To: <CAJ2_K2-GzwPEvE_SRGNO0VkC=0Z17EOnKGX8TmQZYxuZoYtbSA@mail.gmail.com>
References: <CAJ2_K2-GzwPEvE_SRGNO0VkC=0Z17EOnKGX8TmQZYxuZoYtbSA@mail.gmail.com>
Message-ID: <51850DEB.4060504@pearwood.info>

On 04/05/13 23:04, kartik sundarajan wrote:
> Hi,
>
> I am trying to learn how Python stores variables in memory. For ex:
>
> my_var = 'test'
>
> def func():
>      pass
>
> when I type dir() I get
>
> ['__builtins__', '__doc__', '__name__', '__package__', 'func', 'help',
> 'my_var']
>
> are these variables stored in a dict and on calling dir() all the keys are
> returned?
> Or is it stored in a list or a heap?

Python objects are dynamically allocated in the heap.

Python "variables" are not variables in the C or Pascal sense, they are name bindings. When you do this:

my_var = 'test'


Python does the following:

- create a string object 'test'

- create a string object, 'my_var'

- use 'my_var' as a key in the current namespace, with value 'test'.



Creating a function is a little more complicated, but the simplified version goes like this:

- create a string object 'func'

- compile the body of the function into a code object

- create a new function object named 'func' from the code object

- use 'func' as a key in the current namespace, with the function object as the value.



When you call dir(), by default it looks at the current namespace. The "dunder" names shown (Double leading and trailing UNDERscore) have special meaning to Python; the others are objects you have added.


The documentation for dir says:


py> help(dir)

Help on built-in function dir in module __builtin__:

dir(...)
     dir([object]) -> list of strings

     If called without an argument, return the names in the current scope.
     Else, return an alphabetized list of names comprising (some of) the attributes
     of the given object, and of attributes reachable from it.
     If the object supplies a method named __dir__, it will be used; otherwise
     the default dir() logic is used and returns:
       for a module object: the module's attributes.
       for a class object:  its attributes, and recursively the attributes
         of its bases.
       for any other object: its attributes, its class's attributes, and
         recursively the attributes of its class's base classes.



> Can anyone suggest if there some document I can read to help me understand
> the Python internals work ?

The Python docs are a good place to start.

http://docs.python.org/3/index.html


Especially:

http://docs.python.org/3/reference/datamodel.html

http://docs.python.org/3/reference/executionmodel.html



-- 
Steven

From msirenef at lightbird.net  Sun May  5 01:35:53 2013
From: msirenef at lightbird.net (Mitya Sirenef)
Date: Sat, 04 May 2013 19:35:53 -0400
Subject: [Tutor] changing char list to int list isn't working
In-Reply-To: <CALRAYNV+2suCqjJnvYPkCmrxpskXDudugCLt_EfHaQxxqvvcWw@mail.gmail.com>
References: <CALRAYNV+2suCqjJnvYPkCmrxpskXDudugCLt_EfHaQxxqvvcWw@mail.gmail.com>
Message-ID: <51859B59.5070408@lightbird.net>

On 05/04/2013 12:13 AM, Jim Mooney wrote:
> for num in listOfNumChars:
 >     num = int(num)


It seems like people learning Python run into this very often.

I think the reason is that in most simple cases, it's easier and more
intuitive to think that the name IS the object:

x = 1
y = 2
print x + y

Even though I know it's not a precise description, when I see this code,
I think of it as "x is 1, y is 2, print x plus y". And you do get
expected result, which reinforces this intuition.

Of course, a more precise way to think is:

  name 'x' is assigned to object with value=1
  name 'y' is assigned to object with value=2
  sum values that currently have assigned names of 'x' and 'y'

Therefore, what you are really doing is:

for each object in listOfNumChars:
     assign name 'num' to object (this is done automatically by the loop)
     assign name 'num' to int(value that has currently assigned name 'num')


  -m



-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Oaths are the fossils of piety.  George Santayana


From ewing.rj at gmail.com  Sun May  5 05:27:05 2013
From: ewing.rj at gmail.com (RJ Ewing)
Date: Sat, 4 May 2013 20:27:05 -0700
Subject: [Tutor] urllib2 and tests
Message-ID: <CAOSSsV3hG6=q0MdvZnHJKrhJ0=5P=i0zvpzNpHL4+myXSAAmvA@mail.gmail.com>

When I run the following test.py, I get the following error:

RROR: test_fetch_file (__main__.TestFileFetcher)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_filefetcher.py", line 12, in test_fetch_file
    fetched_file = filefetcher.fetch_file(URL)
  File "/Users/rjewing/Documents/Work/filefetcher.py", line 7, in fetch_file
    return urllib2.urlopen(url).read()
  File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py",
line 126, in urlopen
    return _opener.open(url, data, timeout)
  File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py",
line 392, in open
    protocol = req.get_type()
AttributeError: 'TestFileFetcher' object has no attribute 'get_type'

----------------------------------------------------------------------

Test.py:

class TestFileFetcher(unittest.TestCase):

    def test_fetch_file(URL):
        phrase = 'position = support-intern'

        fetched_file = filefetcher.fetch_file(URL)
        unittest.assertIsNone(fetched_file,
                              'The file was not fetched correctly')

        text = filefetcher.add_phrase(fetched_file)
        unittest.assertNotIn(phrase, text, 'The phrase is not in the file')


fetch_file():

def fetch_file(url):
    print 'Fetching file from %s' % url
    return urllib2.urlopen(url).read()


If I run the fetch_file function outside of the test, it works fine. Any
ideas?
Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130504/998aff5c/attachment.html>

From steve at pearwood.info  Sun May  5 06:08:15 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 05 May 2013 14:08:15 +1000
Subject: [Tutor] urllib2 and tests
In-Reply-To: <CAOSSsV3hG6=q0MdvZnHJKrhJ0=5P=i0zvpzNpHL4+myXSAAmvA@mail.gmail.com>
References: <CAOSSsV3hG6=q0MdvZnHJKrhJ0=5P=i0zvpzNpHL4+myXSAAmvA@mail.gmail.com>
Message-ID: <5185DB2F.40207@pearwood.info>

On 05/05/13 13:27, RJ Ewing wrote:
> When I run the following test.py, I get the following error:
[...]
> If I run the fetch_file function outside of the test, it works fine. Any
> ideas?

The code you are actually running, and the code you say you are running below, are different. Your error message refers to a file test_filefetcher.py, not the Test.py you show us. As given, Test.py cannot possibly work, since it doesn't define "filefetcher". I can only guess that this is meant to be the module you are trying to test, but since you don't show us what is in that module, I can only guess what it contains.


More comments below:


> RROR: test_fetch_file (__main__.TestFileFetcher)
> ----------------------------------------------------------------------
> Traceback (most recent call last):
>    File "test_filefetcher.py", line 12, in test_fetch_file
>      fetched_file = filefetcher.fetch_file(URL)

What's filefetcher? I'm guessing its the module you are testing, which is consistent with the next line showing the file name filefetcher.py:


>    File "/Users/rjewing/Documents/Work/filefetcher.py", line 7, in fetch_file
>      return urllib2.urlopen(url).read()
>    File
> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py",
> line 126, in urlopen
>      return _opener.open(url, data, timeout)
>    File
> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py",
> line 392, in open
>      protocol = req.get_type()
> AttributeError: 'TestFileFetcher' object has no attribute 'get_type'


Somehow, your test suite, the TestFileFetcher object, is being passed down into the urllib2 library. I can only guess that somehow url is not an actual URL. I suggest you add a line:

print(url, type(url))

just before the failing line, and see what it prints.


> ----------------------------------------------------------------------
>
> Test.py:

This cannot be the actual test suite you are running, since it cannot run as shown. It doesn't import unittest or the module to be tested.


> class TestFileFetcher(unittest.TestCase):
>
>      def test_fetch_file(URL):
>          phrase = 'position = support-intern'
>
>          fetched_file = filefetcher.fetch_file(URL)

And here's your error! Just as I thought, URL is not what you think it is, it is the TestFileFetcher instance.

Unittest cases do not take arguments. Since they are methods, they are always defined with a single argument, conventionally called "self", representing the instance that the method is called on. So normally you would define a method like this:

     def test_fetch_file(self, url):

which then takes a single *implicit* argument "self", provided by Python, plus a second *explicit* argument, "url". But because this is a test method, the unittest framework does not expect to pass an argument to the method, so you have to write it like this:

     def test_fetch_file(self):

and get the url some other way.

One common way would be to define an attribute on the test, and store the URL in that:

class TestFileFetcher(unittest.TestCase):
     URL = "some_url_goes_here"  # FIX THIS

     def test_fetch_file(self):
         phrase = 'position = support-intern'
         fetched_file = filefetcher.fetch_file(self.URL)
         ...



>          unittest.assertIsNone(fetched_file,
>                                'The file was not fetched correctly')

This part of the test seems to be wrong to me. It says:

"compare the value of fetched_file to None; if it is None, the test passes; if it is some other value, the test fails with error message 'The file was not fetched correctly'"

But then you immediately go on to use fetched_file:

>          text = filefetcher.add_phrase(fetched_file)

but if the above assertIsNone test passed, then fetched_file is None so this is equivalent to:

         text = filefetcher.add_phrase(None)


which surely isn't right?


>          unittest.assertNotIn(phrase, text, 'The phrase is not in the file')

This test also appears backwards. You're testing:

"check whether phrase is NOT in text; if it is NOT in, then the test passes; otherwise, if it IS in, then fail with an error message 'The phrase is not in the file'"

which is clearly wrong. The message should be:

'The phrase is in the file'


since your test is checking that it isn't in.



-- 
Steven

From ewing.rj at gmail.com  Sun May  5 06:43:09 2013
From: ewing.rj at gmail.com (RJ Ewing)
Date: Sat, 4 May 2013 21:43:09 -0700
Subject: [Tutor] urllib2 and tests
In-Reply-To: <5185DB2F.40207@pearwood.info>
References: <CAOSSsV3hG6=q0MdvZnHJKrhJ0=5P=i0zvpzNpHL4+myXSAAmvA@mail.gmail.com>
	<5185DB2F.40207@pearwood.info>
Message-ID: <CAOSSsV1WO6uDc0zjrjxawRs0yqLgSpyUdCAMLyZsmD7EUG8-8Q@mail.gmail.com>

Thank you, I figured out what the problem was. I was passing in url into
the test_file_fetch function instead of self. URL was a global. I did get
the asserts mixed up. They were the opposite of what I wanted. Sorry I
didn't include the whole test.py file for reference.

Thanks again


On Sat, May 4, 2013 at 9:08 PM, Steven D'Aprano <steve at pearwood.info> wrote:

> On 05/05/13 13:27, RJ Ewing wrote:
>
>> When I run the following test.py, I get the following error:
>>
> [...]
>
>  If I run the fetch_file function outside of the test, it works fine. Any
>> ideas?
>>
>
> The code you are actually running, and the code you say you are running
> below, are different. Your error message refers to a file
> test_filefetcher.py, not the Test.py you show us. As given, Test.py cannot
> possibly work, since it doesn't define "filefetcher". I can only guess that
> this is meant to be the module you are trying to test, but since you don't
> show us what is in that module, I can only guess what it contains.
>
>
> More comments below:
>
>
>
>  RROR: test_fetch_file (__main__.TestFileFetcher)
>> ------------------------------**------------------------------**
>> ----------
>> Traceback (most recent call last):
>>    File "test_filefetcher.py", line 12, in test_fetch_file
>>      fetched_file = filefetcher.fetch_file(URL)
>>
>
> What's filefetcher? I'm guessing its the module you are testing, which is
> consistent with the next line showing the file name filefetcher.py:
>
>
>
>     File "/Users/rjewing/Documents/**Work/filefetcher.py", line 7, in
>> fetch_file
>>      return urllib2.urlopen(url).read()
>>    File
>> "/Library/Frameworks/Python.**framework/Versions/2.7/lib/**
>> python2.7/urllib2.py",
>> line 126, in urlopen
>>      return _opener.open(url, data, timeout)
>>    File
>> "/Library/Frameworks/Python.**framework/Versions/2.7/lib/**
>> python2.7/urllib2.py",
>> line 392, in open
>>      protocol = req.get_type()
>> AttributeError: 'TestFileFetcher' object has no attribute 'get_type'
>>
>
>
> Somehow, your test suite, the TestFileFetcher object, is being passed down
> into the urllib2 library. I can only guess that somehow url is not an
> actual URL. I suggest you add a line:
>
> print(url, type(url))
>
> just before the failing line, and see what it prints.
>
>
>  ------------------------------**------------------------------**
>> ----------
>>
>> Test.py:
>>
>
> This cannot be the actual test suite you are running, since it cannot run
> as shown. It doesn't import unittest or the module to be tested.
>
>
>
>  class TestFileFetcher(unittest.**TestCase):
>>
>>      def test_fetch_file(URL):
>>          phrase = 'position = support-intern'
>>
>>          fetched_file = filefetcher.fetch_file(URL)
>>
>
> And here's your error! Just as I thought, URL is not what you think it is,
> it is the TestFileFetcher instance.
>
> Unittest cases do not take arguments. Since they are methods, they are
> always defined with a single argument, conventionally called "self",
> representing the instance that the method is called on. So normally you
> would define a method like this:
>
>     def test_fetch_file(self, url):
>
> which then takes a single *implicit* argument "self", provided by Python,
> plus a second *explicit* argument, "url". But because this is a test
> method, the unittest framework does not expect to pass an argument to the
> method, so you have to write it like this:
>
>     def test_fetch_file(self):
>
> and get the url some other way.
>
> One common way would be to define an attribute on the test, and store the
> URL in that:
>
> class TestFileFetcher(unittest.**TestCase):
>     URL = "some_url_goes_here"  # FIX THIS
>
>     def test_fetch_file(self):
>
>         phrase = 'position = support-intern'
>         fetched_file = filefetcher.fetch_file(self.**URL)
>         ...
>
>
>
>
>           unittest.assertIsNone(fetched_**file,
>>                                'The file was not fetched correctly')
>>
>
> This part of the test seems to be wrong to me. It says:
>
> "compare the value of fetched_file to None; if it is None, the test
> passes; if it is some other value, the test fails with error message 'The
> file was not fetched correctly'"
>
> But then you immediately go on to use fetched_file:
>
>           text = filefetcher.add_phrase(**fetched_file)
>>
>
> but if the above assertIsNone test passed, then fetched_file is None so
> this is equivalent to:
>
>         text = filefetcher.add_phrase(None)
>
>
> which surely isn't right?
>
>
>
>           unittest.assertNotIn(phrase, text, 'The phrase is not in the
>> file')
>>
>
> This test also appears backwards. You're testing:
>
> "check whether phrase is NOT in text; if it is NOT in, then the test
> passes; otherwise, if it IS in, then fail with an error message 'The phrase
> is not in the file'"
>
> which is clearly wrong. The message should be:
>
> 'The phrase is in the file'
>
>
> since your test is checking that it isn't in.
>
>
>
> --
> Steven
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130504/dd33b3ad/attachment.html>

From ajin25 at gmail.com  Sun May  5 10:00:08 2013
From: ajin25 at gmail.com (Ajin Abraham)
Date: Sun, 5 May 2013 13:30:08 +0530
Subject: [Tutor] Raw string form variable
Message-ID: <CAKHNSoxuKpMMTQjnhZs=KQ5LnCtHbd_Ho0X6syVCMJRvUsxmmg@mail.gmail.com>

Please refer this paste: http://bpaste.net/show/vsTXLEjwTLrWjjnfmmKn/
and suggest me the possible solutions.
Regards,
Ajin Abraham

From __peter__ at web.de  Sun May  5 10:34:49 2013
From: __peter__ at web.de (Peter Otten)
Date: Sun, 05 May 2013 10:34:49 +0200
Subject: [Tutor] Raw string form variable
References: <CAKHNSoxuKpMMTQjnhZs=KQ5LnCtHbd_Ho0X6syVCMJRvUsxmmg@mail.gmail.com>
Message-ID: <km55iu$quq$1@ger.gmane.org>

Ajin Abraham wrote:

> Please refer this paste: http://bpaste.net/show/vsTXLEjwTLrWjjnfmmKn/
> and suggest me the possible solutions.
> Regards,

Quoting the paste:

> i am executing these in Python 2.7 interpreter
> >>>import os
> >>> os.path.join(r'C:\win\apple.exe')
> #will returns me = 'C:\\win\\apple.exe'

os.path.join() is pointless if you have only one component. It is meant to 
*join* a directory with a basename, or multiple directory names etc.

The double backslashes are an artifact of the display mechanism built into 
the interactive interpreter that does the escaping on the fly. It is caused 
by an implicit call to the repr() function. Compare:

>>> path = r"c:\win\apple.exe"
>>> path
'c:\\win\\apple.exe'
>>> print repr(path)
'c:\\win\\apple.exe'
>>> print path
c:\win\apple.exe

> >>> path='c:\win\apple.exe'
> #here for example i assign the path. but in my case value is assigned to 
my variable after a file read operation.
> >>> path
> 'c:\\win\x07pple.exe'
> # i know '\a' is encountered here.

Certain combinations of the backslash have a special meaning, but only in 
Python source code. \n stands for newline, \t for the tab and \a for alarm 
(beep), and \\ for the backslash.

> #but i need it as 'C:\\win\\apple.exe'
> How can i convert the content of a variable to a raw string.
> 
> help me out
> 
> this is a solution but it didn't worked out: 
http://code.activestate.com/recipes/65211/

You are asking for the solution of a non-problem. Backslashes are only 
treated specially in string literals in Python source code. If you are 
reading filenames from a file


with open("mypaths.txt") as f:
    for line in f:
        path = line.strip()
        print path

The filenames will be taken as is. The only problem you may run into is 
filenames with non-ascii characters. If the encoding used in the file 
differs from that of the file system you should use

import codecs
encoding = ... # "UTF-8" or "ISO-8850-1" or whatever
with codecs.open("mypaths.txt, encoding=encoding) as f:
    ...
    


From steve at pearwood.info  Sun May  5 11:03:07 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 05 May 2013 19:03:07 +1000
Subject: [Tutor] Raw string form variable
In-Reply-To: <CAKHNSoxuKpMMTQjnhZs=KQ5LnCtHbd_Ho0X6syVCMJRvUsxmmg@mail.gmail.com>
References: <CAKHNSoxuKpMMTQjnhZs=KQ5LnCtHbd_Ho0X6syVCMJRvUsxmmg@mail.gmail.com>
Message-ID: <5186204B.5070100@pearwood.info>

On 05/05/13 18:00, Ajin Abraham wrote:
> Please refer this paste: http://bpaste.net/show/vsTXLEjwTLrWjjnfmmKn/
> and suggest me the possible solutions.

There is no need for a paste bin for this. In six months time, when other people are searching the mail archives looking for answers, the paste bin will be expired and gone and your post will be pointless. We are here to help everybody, including people who come in the future and read over existing posts.

Your question says:


[quote]

i am executing these in Python 2.7 interpreter

>>>import os
>>> os.path.join(r'C:\win\apple.exe')
#will returns me = 'C:\\win\\apple.exe'

>>> path='c:\win\apple.exe'
#here for example i assign the path. but in my case value is assigned to my variable after a file read operation.

>>> path
'c:\\win\x07pple.exe'
# i know '\a' is encountered here.
#but i need it as 'C:\\win\\apple.exe'

How can i convert the content of a variable to a raw string.

help me out

this is a solution but it didn't worked out: http://code.activestate.com/recipes/65211/
[end quote]


which is short enough that a paste bin is unnecessary.


Firstly, you say:

os.path.join(r'C:\win\apple.exe')


but that's a waste of time, because you're not joining anything. You only have one path. Normally you would join two or more path components:

py> os.path.join("a/b/c", "d/e", "f")
'a/b/c/d/e/f'


os.path.join will work with a single path component, but it doesn't really do anything so there is no point.

In this case, you will see that raw strings are not a different kind of string, they are just a different syntax for creating string literals. So we have:

py> a = r'C:\win\apple.exe'  # Use raw string syntax
py> b = 'C:\\win\\apple.exe'  # Use normal string syntax, with escaped backslashes
py> print a, b, a == b
C:\win\apple.exe C:\win\apple.exe True



When you do this:

path = 'c:\win\apple.exe'


you are not using a raw string, so backslashes have special meaning. Backslash-w has no special meaning and is left as given, but backslash-a means the ASCII BEL character.

If you read path from a file, then backslashes are just backslashes, and nothing special happens. It is only when you type a literal string in Python source code that backslashes are special.

For example:

py> literal = '\a'  # String literal, backslashes are special
py> variable = chr(92) + 'a'  # backslash-a
py> (literal, variable, literal == variable)
('\x07', '\\a', False)


The thing that you may not have understood is that backslash escapes are not part of the string, they are part of the syntax, like the quote delimiters. When you type:

s = "abc"

the string s has THREE characters, a b c, and not five characters quote a b c quote. The quotes are only there to tell Python that you want it to create a string. The same with backslashes: they are there only to tell Python to add a special character:

s = "abc\n"

means to create the FOUR character string, a b c newline, not seven characters quote a b c backslash n quote.

This "magic" only happens when Python reads string constants in source code, not whenever it sees a string. So if you have a config file containing the string "c:\win\apple.exe", and you read from the file and assign to the variable path, then path will contain:

c colon backslash w i n backslash a p p l e dot e x e


which is exactly what you need. You DON'T need:

c colon backslash backslash w i n backslash backslash a p p l e dot e x e


although I suppose Windows may be able to cope with the unneeded, extra backslashes.


Another alternative is to just use forward slashes, since Windows can cope with them fine:

path = "c:/win/apple.exe"



-- 
Steven

From staffordbaines at yahoo.com  Sun May  5 13:49:28 2013
From: staffordbaines at yahoo.com (Stafford Baines)
Date: Sun, 5 May 2013 12:49:28 +0100
Subject: [Tutor] Using graphics
Message-ID: <AD4141DE-6129-4E6B-BBA8-1FA688E43456@yahoo.com>

I have just finished Python Programming by Michael Dawson. A wonderful book with downloadable examples. However, after many hours of frustrating attempts I can't get the graphics to work.

I get error messages such as 'no module called python.image' 

I have made sure that the folder 
Livewires iis in the same folder as the program (Falling Pizzas say, but it won't
work with any of the included graphics games)

The book is written using python 3.1 and I am using python 3.3, could this be a problem?

Any advice would be very much appreciated as I do wish to use graphics facilities.

Thanking any one who can help in advance.

Stafford?

Sent from my iPhone

From davea at davea.name  Sun May  5 14:18:51 2013
From: davea at davea.name (Dave Angel)
Date: Sun, 05 May 2013 08:18:51 -0400
Subject: [Tutor] Using graphics
In-Reply-To: <AD4141DE-6129-4E6B-BBA8-1FA688E43456@yahoo.com>
References: <AD4141DE-6129-4E6B-BBA8-1FA688E43456@yahoo.com>
Message-ID: <51864E2B.3080806@davea.name>

On 05/05/2013 07:49 AM, Stafford Baines wrote:
> I have just finished Python Programming by Michael Dawson. A wonderful book with downloadable examples. However, after many hours of frustrating attempts I can't get the graphics to work.
>
> I get error messages such as 'no module called python.image'

Error messages are lots more specific than that. You generally should 
include a full traceback, and the matching source code.  In this case, 
presumably you had something like:
    import python.image

in your source code.  No idea why anyone might want to make a package 
called python, but image is the normal name for the optional importable 
module PIL.  (Python Imaging Library)

However, the book probably has instructions for how to get it, and it 
may not be using PIL at all.  If not, then much of the following is wrong.

What version of Python are you running, and what OS?  PIL is available 
prebuilt for Python up to 2.7, in some Windows environments, but 
anywhere else you'll probably have to build it yourself.

>
> I have made sure that the folder
> Livewires iis in the same folder as the program (Falling Pizzas say, but it won't
> work with any of the included graphics games)
>
> The book is written using python 3.1 and I am using python 3.3, could this be a problem?

Probably not.
>
> Any advice would be very much appreciated as I do wish to use graphics facilities.
>
> Thanking any one who can help in advance.
>

For non-standard packages, always start by searching on pypi:

https://pypi.python.org/pypi/PIL
   which leads you to:
http://www.pythonware.com/products/pil/


-- 
DaveA

From cybervigilante at gmail.com  Sun May  5 18:56:22 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sun, 5 May 2013 09:56:22 -0700
Subject: [Tutor] stumped by what looks like recursive list comprehension
Message-ID: <CALRAYNWey4w8i=rpq0Gwx0MTG_Q+NZdeU+3kwUv8vTwJ9ZcHrQ@mail.gmail.com>

I looked up "list comprehension" after the last explanation and it's
really cool. But the example below stumps me. I understand the second
part, "primes =" but the first part, "noprimes =" baffles me since it
swaps i and j back and forth in what looks like a circle ;')  Also,
the other examples I looked at had a function of 'x' before the 'for,'
and 'x' after, so they were easy to follow. But this example has 'j'
as a function of 'i,' then 'i,' as a function of 'j' and has me dizzy.

Could someone show this in normal, indented 'for' loops so I can see
what 'for' goes where and how it works. I figure if I figure this one
one I'll really comprehend list comprehension.

# find nonprimes up to 50, then filter out what's left as primes

noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
primes = [x for x in range(2, 50) if x not in noprimes]

--
Jim Mooney

?For anything that matters, the timing is never quite right, the
resources are always a little short, and the people who affect the
outcome are always ambivalent.?

From steve at pearwood.info  Sun May  5 19:21:01 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 06 May 2013 03:21:01 +1000
Subject: [Tutor] stumped by what looks like recursive list comprehension
In-Reply-To: <CALRAYNWey4w8i=rpq0Gwx0MTG_Q+NZdeU+3kwUv8vTwJ9ZcHrQ@mail.gmail.com>
References: <CALRAYNWey4w8i=rpq0Gwx0MTG_Q+NZdeU+3kwUv8vTwJ9ZcHrQ@mail.gmail.com>
Message-ID: <518694FD.1020400@pearwood.info>

On 06/05/13 02:56, Jim Mooney wrote:
> I looked up "list comprehension" after the last explanation and it's
> really cool. But the example below stumps me. I understand the second
> part, "primes =" but the first part, "noprimes =" baffles me since it
> swaps i and j back and forth in what looks like a circle ;')  Also,
> the other examples I looked at had a function of 'x' before the 'for,'
> and 'x' after, so they were easy to follow. But this example has 'j'
> as a function of 'i,' then 'i,' as a function of 'j' and has me dizzy.
>
> Could someone show this in normal, indented 'for' loops so I can see
> what 'for' goes where and how it works. I figure if I figure this one
> one I'll really comprehend list comprehension.
>
> # find nonprimes up to 50, then filter out what's left as primes
>
> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
> primes = [x for x in range(2, 50) if x not in noprimes]


The most important difference between a list comprehensions and it's equivalent for-loop is that the "body" of the loop (a single expression in the list comp case) is moved to the front of the list comp. So to convert the list comp back to a for-loop, move the initial expression just before the very first "for" to the very bottom of the loop(s). Everything else remains in the same order, just indented as needed.

So the noprimes list comprehension acts like this:


# noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
noprimes = []
for i in range(2, 8):
     for j in range(i*2, 50, i):
         noprimes.append(j)


The primes list comprehension acts like this:


# primes = [x for x in range(2, 50) if x not in noprimes]
primes = []
for x in range(2, 50):
     if x not in noprimes:
         primes.append(x)



-- 
Steven

From zachary.ware+pytut at gmail.com  Sun May  5 19:23:52 2013
From: zachary.ware+pytut at gmail.com (Zachary Ware)
Date: Sun, 5 May 2013 12:23:52 -0500
Subject: [Tutor] stumped by what looks like recursive list comprehension
In-Reply-To: <CALRAYNWey4w8i=rpq0Gwx0MTG_Q+NZdeU+3kwUv8vTwJ9ZcHrQ@mail.gmail.com>
References: <CALRAYNWey4w8i=rpq0Gwx0MTG_Q+NZdeU+3kwUv8vTwJ9ZcHrQ@mail.gmail.com>
Message-ID: <CAKJDb-Ms7QY4s6sjphKn30aifauTA3hYpd=OvHot7z4dJ_fAKg@mail.gmail.com>

On Sun, May 5, 2013 at 11:56 AM, Jim Mooney <cybervigilante at gmail.com>
wrote:
> I looked up "list comprehension" after the last explanation and it's
> really cool. But the example below stumps me. I understand the second
> part, "primes =" but the first part, "noprimes =" baffles me since it
> swaps i and j back and forth in what looks like a circle ;')  Also,
> the other examples I looked at had a function of 'x' before the 'for,'
> and 'x' after, so they were easy to follow. But this example has 'j'
> as a function of 'i,' then 'i,' as a function of 'j' and has me dizzy.
>
> Could someone show this in normal, indented 'for' loops so I can see
> what 'for' goes where and how it works. I figure if I figure this one
> one I'll really comprehend list comprehension.
>
> # find nonprimes up to 50, then filter out what's left as primes
>
> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
> primes = [x for x in range(2, 50) if x not in noprimes]

The standard expansion of a list comprehension is as follows:

noprimes = [] # start with an empty list

for i in range(2,8):            # add a colon, a newline, and another
indention
    for j in range(i*2, 50, i): # level just before each 'for' and 'if'
        noprimes.append(j)    # everything before the first 'for' goes in
an
                              # append call on the empty list

primes = []

for x in range(2, 50):
    if x not in noprimes:
        primes.append(x)


Hope this helps,

Zach Ware


>
> --
> Jim Mooney
>
> ?For anything that matters, the timing is never quite right, the
> resources are always a little short, and the people who affect the
> outcome are always ambivalent.?
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130505/17a908e7/attachment.html>

From robertvstepp at gmail.com  Sun May  5 20:17:12 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 5 May 2013 13:17:12 -0500
Subject: [Tutor] Using graphics
In-Reply-To: <AD4141DE-6129-4E6B-BBA8-1FA688E43456@yahoo.com>
References: <AD4141DE-6129-4E6B-BBA8-1FA688E43456@yahoo.com>
Message-ID: <CANDiX9+kSpQnFV5UYg1otv1OWcN_JMYkDSQCjF2mEK6jBxo=0Q@mail.gmail.com>

On Sun, May 5, 2013 at 6:49 AM, Stafford Baines
<staffordbaines at yahoo.com> wrote:
> I have just finished Python Programming by Michael Dawson. A wonderful book with downloadable examples. However, after many hours of frustrating attempts I can't get the graphics to work.
>

I own this book, too, but I am not actively working in it yet. My copy
is the third edition.

> I get error messages such as 'no module called python.image'
>
> I have made sure that the folder
> Livewires iis in the same folder as the program (Falling Pizzas say, but it won't
> work with any of the included graphics games)
>

On page 323 of my edition it says:

"You need to install both pygame and livewires before you can run the
programs presented in this chapter. Fortunately, versions of both are
on the companion website (www.courseptr.com/downloads) in the Software
folder. Just follow the installation instructions that accompany the
packages."

You mention that you installed livewires, but did not mention
installing pygame. Could this be your problem? Also, the author notes
that the livewires package that he provides on HIS site is a modified
version of livewires. If you went to the official LiveWires website to
download and install livewires, then it is possible it might not work
with the programs in the book. The author mentions this as a "Trap" on
the same page.

> The book is written using python 3.1 and I am using python 3.3, could this be a problem?
>

I doubt that your exact version of Python 3.x is a problem as long as
you have at least 3.1.

> Any advice would be very much appreciated as I do wish to use graphics facilities.
>

Another trap is mentioned on page 324:

"Just as with a program that uses Tkinter to create a new window, you
shouldn't run a livewires program from IDLE..."

The only other thing that I can think of is that you may not be
importing all of the needed modules. Check your code with the author's
carefully to see that you have done so.

HTH,
boB

From robertvstepp at gmail.com  Mon May  6 02:17:18 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 5 May 2013 19:17:18 -0500
Subject: [Tutor] Clear screen questions
Message-ID: <CANDiX9+Q_2E6fRO-fwYqwNDW-PTHzgGQwQ4tVSh9carGvktrtQ@mail.gmail.com>

I have been playing around with my own version of a guess the number
game that I wrote before looking at how the kids' book (which I am
reviewing for my kids) did it. For some reason my children are
fascinated by this game and keep asking me for improvements. The
latest one was to implement an automatic clearing of the screen if the
user wishes to play again. So I got my handy-dandy pocket reference
out and added to the existing code at the appropriate places:

import os
...
os.system('cls')

The kids were pleased, but I wasn't. Yes, this works on Windows/DOS,
but nowhere else. So how to make this OS-independent? Googling has not
yielded a truly cross-platform solution. Currently, I have temporized
with:

os.system('cls' if os.name=='nt' else 'clear')

which I think will work for Windows/UNIX. I am not certain it would
work with DOS, since NT came after DOS, but who has DOS these days?

So my main question is there a truly clean, cross-platform solution to
the clear screen dilemma? If my online searching is accurate, then the
answer appears to be no, unless one wants to print many blank lines.

A second question is that one person had as the answer to use:

os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] )

I don't understand this syntax. The writer said that if one
understands what this is doing, then the method is more generally
useful. Would someone explain how this works? And hopefully it will
become apparent to me how this is more generally useful?

Finally, a minor, secondary question: I was curious how my clear
screen code would run in the IDLE Python shell window, since I know
there is currently no way to clear its screen (other than the blank
line approach). Of course it did not clear the screen, but it did do
something unexpected that I would like to understand. Upon hitting the
clear screen code the active window switched from the Python shell
window to the Python edit window. Why is this so?

As always thanks!
boB

From steve at pearwood.info  Mon May  6 02:54:15 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 06 May 2013 10:54:15 +1000
Subject: [Tutor] Clear screen questions
In-Reply-To: <CANDiX9+Q_2E6fRO-fwYqwNDW-PTHzgGQwQ4tVSh9carGvktrtQ@mail.gmail.com>
References: <CANDiX9+Q_2E6fRO-fwYqwNDW-PTHzgGQwQ4tVSh9carGvktrtQ@mail.gmail.com>
Message-ID: <5186FF37.6040802@pearwood.info>

On 06/05/13 10:17, boB Stepp wrote:
> I have been playing around with my own version of a guess the number
> game that I wrote before looking at how the kids' book (which I am
> reviewing for my kids) did it. For some reason my children are
> fascinated by this game and keep asking me for improvements. The
> latest one was to implement an automatic clearing of the screen if the
> user wishes to play again. So I got my handy-dandy pocket reference
> out and added to the existing code at the appropriate places:
>
> import os
> ...
> os.system('cls')
>
> The kids were pleased, but I wasn't. Yes, this works on Windows/DOS,
> but nowhere else. So how to make this OS-independent? Googling has not
> yielded a truly cross-platform solution. Currently, I have temporized
> with:
>
> os.system('cls' if os.name=='nt' else 'clear')
>
> which I think will work for Windows/UNIX. I am not certain it would
> work with DOS, since NT came after DOS, but who has DOS these days?

Certainly not Python. DOS is not supported. I think Windows 2000 is the oldest version still supported.

But even on Windows that will not work, if you are running under IDLE. And unfortunately there is no official way to tell if you are running under IDLE, or any other IDE for that matter.


> So my main question is there a truly clean, cross-platform solution to
> the clear screen dilemma? If my online searching is accurate, then the
> answer appears to be no, unless one wants to print many blank lines.

Your googling is accurate. There is no clean, cross-platform solution, not even for the "main three" (Linux/Unix, Windows, Mac), let alone minority and legacy platforms, other implementations, etc.


> A second question is that one person had as the answer to use:
>
> os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] )
>
> I don't understand this syntax. The writer said that if one
> understands what this is doing, then the method is more generally
> useful. Would someone explain how this works? And hopefully it will
> become apparent to me how this is more generally useful?


You start with a call to os.system. What's the argument to os.system? Well, *eventually* is has to become a single string, but it can be an expression that evaluates to a string. What is this expression? It starts with a list of two strings:

['clear', 'cls']


which is then indexed by the result of another expression, os.name == 'nt'. Under Windows, this evaluates to True, otherwise to False:

['clear', 'cls'][True]  # under Windows
['clear', 'cls'][False]  # everything else


A little known fact: True evaluates as equal to 1, and False as equal to 0. (This is mostly for historical reasons, but it's also useful.) So the above ends up as:

['clear', 'cls'][True]  # under Windows
=> 'cls'

['clear', 'cls'][False]  # everything else
=> 'clear'


and finally os.system gets to run a single string.



> Finally, a minor, secondary question: I was curious how my clear
> screen code would run in the IDLE Python shell window, since I know
> there is currently no way to clear its screen (other than the blank
> line approach). Of course it did not clear the screen, but it did do
> something unexpected that I would like to understand. Upon hitting the
> clear screen code the active window switched from the Python shell
> window to the Python edit window. Why is this so?

Magic. IDLE bug. Who knows? It doesn't do that for me, but I've only tested it interactively with one version on Linux.



-- 
Steven

From davea at davea.name  Mon May  6 03:13:36 2013
From: davea at davea.name (Dave Angel)
Date: Sun, 05 May 2013 21:13:36 -0400
Subject: [Tutor] Using graphics
In-Reply-To: <51864E2B.3080806@davea.name>
References: <AD4141DE-6129-4E6B-BBA8-1FA688E43456@yahoo.com>
	<51864E2B.3080806@davea.name>
Message-ID: <518703C0.40908@davea.name>

Please reply to the list, not to an individual, unless the response is 
personal, or something like a thank-you.  Also, please put your response 
*after* whatever you're quoting, and use the feature in your mail that 
uses the carets to mark quoted portions.

On 05/05/2013 09:17 AM, Stafford Baines wrote:> Thank you for your very 
prompt reply. As suggested I include complete error
 > message. The paths quoted
 > In the error message look very circuitous. I don't know why this 
should be
 > as all the files I have put into
 > One folder C:\Python33 which includes livewires which in it's turn 
contains
 > games.py and the other modules called. Can you spot any obvous mistakes?
 >
 > Stafford
 >
 > Traceback (most recent call last):
 >    File 
"C:\CGSB\Python\py3e_source\chapter11\new_graphics_window.py", line
 > 4, in <module>
 >      from livewires import games
 >    File "C:\Python33\livewires\games.py", line 57, in <module>
 >      import pygame, pygame.image, pygame.mixer, pygame.font, 
pygame.transform
 > ImportError: No module named 'pygame.image'

I expect that livewires thinks it can import pygame, and that you 
haven't installed that yet.  Didn't the book tell you what dependencies 
to install?

-- 
DaveA


-- 
DaveA

From robertvstepp at gmail.com  Mon May  6 04:10:01 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 5 May 2013 21:10:01 -0500
Subject: [Tutor] Clear screen questions
In-Reply-To: <5186FF37.6040802@pearwood.info>
References: <CANDiX9+Q_2E6fRO-fwYqwNDW-PTHzgGQwQ4tVSh9carGvktrtQ@mail.gmail.com>
	<5186FF37.6040802@pearwood.info>
Message-ID: <CANDiX9KNh6cSnVT5Tec_hLeLz07543prDchC0WmQaMjwC9XQdg@mail.gmail.com>

On Sun, May 5, 2013 at 7:54 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On 06/05/13 10:17, boB Stepp wrote:
>>
[...]
>
> But even on Windows that will not work, if you are running under IDLE. And
> unfortunately there is no official way to tell if you are running under
> IDLE, or any other IDE for that matter.
>

I was not expecting it to work under any IDE. With IDLE I was just
curious if it would generate some sort of error or other unexpected
behavior. But you make a good point: If possible my code should run
properly even under an IDE if it is possible to cover that scenario.

>
>> So my main question is there a truly clean, cross-platform solution to
>> the clear screen dilemma? If my online searching is accurate, then the
>> answer appears to be no, unless one wants to print many blank lines.
>
>
> Your googling is accurate. There is no clean, cross-platform solution, not
> even for the "main three" (Linux/Unix, Windows, Mac), let alone minority and
> legacy platforms, other implementations, etc.
>

So it appears that the only way to cover the various possibilities is
to query for the platform being used and then apply the correct
statement for that platform. And it still would not work for the point
noted above. Could be a lot of effort for little gain!

>
>> A second question is that one person had as the answer to use:
>>
>> os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] )
>>
>> I don't understand this syntax. The writer said that if one
>> understands what this is doing, then the method is more generally
>> useful. Would someone explain how this works? And hopefully it will
>> become apparent to me how this is more generally useful?
>
>
>
> You start with a call to os.system. What's the argument to os.system? Well,
> *eventually* is has to become a single string, but it can be an expression
> that evaluates to a string. What is this expression? It starts with a list
> of two strings:
>
> ['clear', 'cls']
>
>
> which is then indexed by the result of another expression, os.name == 'nt'.
> Under Windows, this evaluates to True, otherwise to False:
>
> ['clear', 'cls'][True]  # under Windows
> ['clear', 'cls'][False]  # everything else
>
>
> A little known fact: True evaluates as equal to 1, and False as equal to 0.
> (This is mostly for historical reasons, but it's also useful.) So the above
> ends up as:
>
> ['clear', 'cls'][True]  # under Windows
> => 'cls'
>
> ['clear', 'cls'][False]  # everything else
> => 'clear'
>
>
> and finally os.system gets to run a single string.
>
Thanks for the very clear explanation! I was not thinking in list
terms when I saw the first pair of brackets, so it did not occur to me
to see the second set of brackets as indexing.

boB

From brian.van.den.broek at gmail.com  Mon May  6 04:37:24 2013
From: brian.van.den.broek at gmail.com (Brian van den Broek)
Date: Sun, 5 May 2013 22:37:24 -0400
Subject: [Tutor] Clear screen questions
In-Reply-To: <CANDiX9KNh6cSnVT5Tec_hLeLz07543prDchC0WmQaMjwC9XQdg@mail.gmail.com>
References: <CANDiX9+Q_2E6fRO-fwYqwNDW-PTHzgGQwQ4tVSh9carGvktrtQ@mail.gmail.com>
	<5186FF37.6040802@pearwood.info>
	<CANDiX9KNh6cSnVT5Tec_hLeLz07543prDchC0WmQaMjwC9XQdg@mail.gmail.com>
Message-ID: <CAF6DajLfz_xrUoCXgfJJ5gmWaPGkOe9EAgKjRPxD3ib0L7mW3g@mail.gmail.com>

On 5 May 2013 22:10, boB Stepp <robertvstepp at gmail.com> wrote:

> On Sun, May 5, 2013 at 7:54 PM, Steven D'Aprano <steve at pearwood.info>
> wrote:
>

<snip>


> >
> >> So my main question is there a truly clean, cross-platform solution to
> >> the clear screen dilemma? If my online searching is accurate, then the
> >> answer appears to be no, unless one wants to print many blank lines.
> >
> >
> > Your googling is accurate. There is no clean, cross-platform solution,
> not
> > even for the "main three" (Linux/Unix, Windows, Mac), let alone minority
> and
> > legacy platforms, other implementations, etc.
> >
>
>

> So it appears that the only way to cover the various possibilities is
> to query for the platform being used and then apply the correct
> statement for that platform. And it still would not work for the point
> noted above. Could be a lot of effort for little gain!
>
>

Try:

def pragmatic_as_if_clear():
    print '\n' * 100

which isn't too far off of what clear does in bash.


> >
> >> A second question is that one person had as the answer to use:
> >>
> >> os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] )
> >>
> >> I don't understand this syntax. The writer said that if one
> >> understands what this is doing, then the method is more generally
> >> useful. Would someone explain how this works? And hopefully it will
> >> become apparent to me how this is more generally useful?
>
>
<snip>


> terms when I saw the first pair of brackets, so it did not occur to me
> to see the second set of brackets as indexing.
>
> boB
>
>

Steven explained it. I'd point out that wiser snake charmers than I
discouraged me (some on this list) from using it from the position that it
was too clever. I've done so from time to time anyway; there is a momentary
jolt when reading the code months later.

HTH,

Brian vdB
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130505/59c206b7/attachment-0001.html>

From steve at pearwood.info  Mon May  6 05:12:34 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 06 May 2013 13:12:34 +1000
Subject: [Tutor] Clear screen questions
In-Reply-To: <CAF6DajLfz_xrUoCXgfJJ5gmWaPGkOe9EAgKjRPxD3ib0L7mW3g@mail.gmail.com>
References: <CANDiX9+Q_2E6fRO-fwYqwNDW-PTHzgGQwQ4tVSh9carGvktrtQ@mail.gmail.com>
	<5186FF37.6040802@pearwood.info>
	<CANDiX9KNh6cSnVT5Tec_hLeLz07543prDchC0WmQaMjwC9XQdg@mail.gmail.com>
	<CAF6DajLfz_xrUoCXgfJJ5gmWaPGkOe9EAgKjRPxD3ib0L7mW3g@mail.gmail.com>
Message-ID: <51871FA2.1000306@pearwood.info>

On 06/05/13 12:37, Brian van den Broek wrote:
> On 5 May 2013 22:10, boB Stepp <robertvstepp at gmail.com> wrote:
>
>> On Sun, May 5, 2013 at 7:54 PM, Steven D'Aprano <steve at pearwood.info>
>> wrote:
>>
>
> <snip>
>
>
>>>
>>>> So my main question is there a truly clean, cross-platform solution to
>>>> the clear screen dilemma? If my online searching is accurate, then the
>>>> answer appears to be no, unless one wants to print many blank lines.
>>>
>>>
>>> Your googling is accurate. There is no clean, cross-platform solution,
>> not
>>> even for the "main three" (Linux/Unix, Windows, Mac), let alone minority
>> and
>>> legacy platforms, other implementations, etc.
>>>
>>
>>
>
>> So it appears that the only way to cover the various possibilities is
>> to query for the platform being used and then apply the correct
>> statement for that platform. And it still would not work for the point
>> noted above. Could be a lot of effort for little gain!
>>
>>
>
> Try:
>
> def pragmatic_as_if_clear():
>      print '\n' * 100
>
> which isn't too far off of what clear does in bash.


Not in the version of bash I am using in an xterm window. (To be precise, Konsole under KDE 3.)

If I start a bash session, and then do something "large" like print a file listing, the prompt ends up right at the bottom of the screen. If I then call clear, the visible area of the screen is cleared, the prompt ends up at the top of the screen, but if I scroll back using the scroll bar, I can see the previous output immediately before the clear command, without 100 blank lines separating them.




>>>> A second question is that one person had as the answer to use:
>>>>
>>>> os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] )
>>>>
>>>> I don't understand this syntax. The writer said that if one
>>>> understands what this is doing, then the method is more generally
>>>> useful. Would someone explain how this works? And hopefully it will
>>>> become apparent to me how this is more generally useful?
>>
>>
> <snip>
>
>
>> terms when I saw the first pair of brackets, so it did not occur to me
>> to see the second set of brackets as indexing.
>>
>> boB
>>
>>
>
> Steven explained it. I'd point out that wiser snake charmers than I
> discouraged me (some on this list) from using it from the position that it
> was too clever. I've done so from time to time anyway; there is a momentary
> jolt when reading the code months later.

I don't know who they were, I certainly hope they didn't include me.

The list[index] trick shown above is clever, but it shouldn't be too clever. It used to be one of the standard ways of getting a one-line ternary expression in Python. Of course, these days we have proper ternary operator `value if flag else other`, but it's still a perfectly reasonable thing to do, no weirder and much more concise than something like this:

commands = {'windows': 'clr', 'other': 'clear'}
if os.name == 'nt':
     system = 'windows'
else:
     system = 'other'
os.system(commands[system])





-- 
Steven

From brian.van.den.broek at gmail.com  Mon May  6 05:29:06 2013
From: brian.van.den.broek at gmail.com (Brian van den Broek)
Date: Sun, 5 May 2013 23:29:06 -0400
Subject: [Tutor] Clear screen questions
In-Reply-To: <51871FA2.1000306@pearwood.info>
References: <CANDiX9+Q_2E6fRO-fwYqwNDW-PTHzgGQwQ4tVSh9carGvktrtQ@mail.gmail.com>
	<5186FF37.6040802@pearwood.info>
	<CANDiX9KNh6cSnVT5Tec_hLeLz07543prDchC0WmQaMjwC9XQdg@mail.gmail.com>
	<CAF6DajLfz_xrUoCXgfJJ5gmWaPGkOe9EAgKjRPxD3ib0L7mW3g@mail.gmail.com>
	<51871FA2.1000306@pearwood.info>
Message-ID: <CAF6DajJxM4jwfWxpH2OMeQYv9VoABsqeeEr=BMhQUMx2pVj4gA@mail.gmail.com>

On 5 May 2013 23:12, Steven D'Aprano <steve at pearwood.info> wrote:
>
> On 06/05/13 12:37, Brian van den Broek wrote:

<snip>

>> Try:
>>
>> def pragmatic_as_if_clear():
>>      print '\n' * 100
>>
>> which isn't too far off of what clear does in bash.
>
> Not in the version of bash I am using in an xterm window. (To be precise,
> Konsole under KDE 3.)
>
> If I start a bash session, and then do something "large" like print a file
> listing, the prompt ends up right at the bottom of the screen. If I then
> call clear, the visible area of the screen is cleared, the prompt ends up at
> the top of the screen, but if I scroll back using the scroll bar, I can see
> the previous output immediately before the clear command, without 100 blank
> lines separating them.


terminator 0.93 under openbox 3.5 appears to fill a terminal window
height with blank lines. That isn't a hard coded value as above, but
that's why I put in the weasel words. Since those words are there,
I'll press them into service to cover the further inaccuracy you point
out :-)


>>>>> A second question is that one person had as the answer to use:
>>>>>
>>>>> os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] )
>>>>>
>>>>> I don't understand this syntax. The writer said that if one
>>>>> understands what this is doing, then the method is more generally
>>>>> useful. Would someone explain how this works? And hopefully it will
>>>>> become apparent to me how this is more generally useful?
>>>
>> <snip>
>>
>>> terms when I saw the first pair of brackets, so it did not occur to me
>>> to see the second set of brackets as indexing.
>>>
>>> boB
>>>
>>>
>>
>> Steven explained it. I'd point out that wiser snake charmers than I
>> discouraged me (some on this list) from using it from the position that
>> it
>> was too clever. I've done so from time to time anyway; there is a
>> momentary
>> jolt when reading the code months later.
>
>
> I don't know who they were, I certainly hope they didn't include me.

Not so far as I recollect, but it is nearing a decade ago, now. I'll
leave my fuzzy memories where they are. FWIW, as indicated, that's a
bit of advice I didn't always follow.

Best,

Brian vdB

From cybervigilante at gmail.com  Mon May  6 06:24:30 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sun, 5 May 2013 21:24:30 -0700
Subject: [Tutor] exit message
Message-ID: <CALRAYNXvPB4D3heFG0FQBJF4GZK4p0s3PbftMNN-WDNUp7+X6w@mail.gmail.com>

I've noticed that if you exit() a program you always get a traceback message:
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    exit('what now?')
  File "C:\Python33\lib\site.py", line 380, in __call__
    raise SystemExit(code)

What if you just want to exit for some normal reason and don't want
the message? Or is a program always supposed to end in some normal way
without an exit. Or is there a different, more graceful way to end a
program when you want?

--
Jim Mooney

?For anything that matters, the timing is never quite right, the resources
are always a little short, and the people who affect the outcome are always
ambivalent.?

From amitsaha.in at gmail.com  Mon May  6 06:27:14 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Mon, 6 May 2013 14:27:14 +1000
Subject: [Tutor] exit message
In-Reply-To: <CALRAYNXvPB4D3heFG0FQBJF4GZK4p0s3PbftMNN-WDNUp7+X6w@mail.gmail.com>
References: <CALRAYNXvPB4D3heFG0FQBJF4GZK4p0s3PbftMNN-WDNUp7+X6w@mail.gmail.com>
Message-ID: <CANODV3kpX145gXswXutr67f6Rqx_X6R1ZVFce_pXO4K5TBCz5g@mail.gmail.com>

On Mon, May 6, 2013 at 2:24 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> I've noticed that if you exit() a program you always get a traceback message:
> Traceback (most recent call last):
>   File "<pyshell#1>", line 1, in <module>
>     exit('what now?')
>   File "C:\Python33\lib\site.py", line 380, in __call__
>     raise SystemExit(code)
>
> What if you just want to exit for some normal reason and don't want
> the message? Or is a program always supposed to end in some normal way
> without an exit. Or is there a different, more graceful way to end a
> program when you want?

Something like this?

>> import sys
>>> while 1:
...     sys.exit('Exiting from Infinite Loop')
...
Exiting from Infinite Loop

-Amit.

--
http://echorand.me

From cybervigilante at gmail.com  Mon May  6 06:56:58 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sun, 5 May 2013 21:56:58 -0700
Subject: [Tutor] exit message
In-Reply-To: <CANODV3kpX145gXswXutr67f6Rqx_X6R1ZVFce_pXO4K5TBCz5g@mail.gmail.com>
References: <CALRAYNXvPB4D3heFG0FQBJF4GZK4p0s3PbftMNN-WDNUp7+X6w@mail.gmail.com>
	<CANODV3kpX145gXswXutr67f6Rqx_X6R1ZVFce_pXO4K5TBCz5g@mail.gmail.com>
Message-ID: <CALRAYNXHPRyqwUw=mOQAuL0-kS9AaMkun8s+VYFCLqQO4KRLEA@mail.gmail.com>

> Something like this?
>
>>> import sys
>>>> while 1:
> ...     sys.exit('Exiting from Infinite Loop')
> ...
> Exiting from Infinite Loop

I still get a traceback message from the console. I just want a clean
exit without that. I have a feeling I'm thinking about something the
wrong way ;')

Traceback (most recent call last):
  File "c:\Python33\Progs\fileActions.py", line 17, in <module>
builtins.SystemExit: you messed up too many times

Jim

From amitsaha.in at gmail.com  Mon May  6 07:04:29 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Mon, 6 May 2013 15:04:29 +1000
Subject: [Tutor] exit message
In-Reply-To: <CALRAYNXHPRyqwUw=mOQAuL0-kS9AaMkun8s+VYFCLqQO4KRLEA@mail.gmail.com>
References: <CALRAYNXvPB4D3heFG0FQBJF4GZK4p0s3PbftMNN-WDNUp7+X6w@mail.gmail.com>
	<CANODV3kpX145gXswXutr67f6Rqx_X6R1ZVFce_pXO4K5TBCz5g@mail.gmail.com>
	<CALRAYNXHPRyqwUw=mOQAuL0-kS9AaMkun8s+VYFCLqQO4KRLEA@mail.gmail.com>
Message-ID: <CANODV3mvtOY81O7VoHVT0ANKg01Fgnmvs=tf_VSn-dQ6xK8BCA@mail.gmail.com>

On Mon, May 6, 2013 at 2:56 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
>> Something like this?
>>
>>>> import sys
>>>>> while 1:
>> ...     sys.exit('Exiting from Infinite Loop')
>> ...
>> Exiting from Infinite Loop
>
> I still get a traceback message from the console. I just want a clean
> exit without that. I have a feeling I'm thinking about something the
> wrong way ;')
>
> Traceback (most recent call last):
>   File "c:\Python33\Progs\fileActions.py", line 17, in <module>
> builtins.SystemExit: you messed up too many times

Strange. Can you share some relevant code that can be executed?



--
http://echorand.me

From zachary.ware+pytut at gmail.com  Mon May  6 07:12:31 2013
From: zachary.ware+pytut at gmail.com (Zachary Ware)
Date: Mon, 6 May 2013 00:12:31 -0500
Subject: [Tutor] exit message
In-Reply-To: <CALRAYNXvPB4D3heFG0FQBJF4GZK4p0s3PbftMNN-WDNUp7+X6w@mail.gmail.com>
References: <CALRAYNXvPB4D3heFG0FQBJF4GZK4p0s3PbftMNN-WDNUp7+X6w@mail.gmail.com>
Message-ID: <CAKJDb-P06YCb=3pkA6-hvTwj5F_5rE-JVUhRLc4bc75-QGMi0Q@mail.gmail.com>

On Sun, May 5, 2013 at 11:24 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
>
> I've noticed that if you exit() a program you always get a traceback message:
> Traceback (most recent call last):
>   File "<pyshell#1>", line 1, in <module>
>     exit('what now?')
>   File "C:\Python33\lib\site.py", line 380, in __call__
>     raise SystemExit(code)
>
> What if you just want to exit for some normal reason and don't want
> the message? Or is a program always supposed to end in some normal way
> without an exit. Or is there a different, more graceful way to end a
> program when you want?

I believe that traceback is a bug in IDLE, which I think has been
fixed for the next release (or is being chased, one of the two).  If
you're not using IDLE, it's another bug that should be tracked down
:).  More generally, though, you can't count on 'exit()' being
available.  exit() is made available by the 'site' module (as you can
see in the traceback), but if Python is run with the -S option, 'site'
won't be imported and 'exit()' won't be available.

Instead, you can do what exit() actually does, which is to raise the
SystemExit exception with the code to be returned to the shell.  For
instance (and be warned that I'm typing this from a Linux box, so it's
untested, but you should be able to reproduce this :)):

C:\py> type example.py
# example.py
print('Hello')

raise SystemExit(13)

print('Goodbye')

C:\py> py -3.3 example.py
Hello

C:\py> echo %ERRORLEVEL%
13

You can also import sys and use sys.exit() for the same effect.

If you don't care about the exit code, you can just "drop off" the end
of the script.  If you don't end with an unhandled exception, your
exit code will be 0, otherwise it will (probably) be 1.  For example:

# example2.py

def main(arg=None):
    print('This is a main function.  It's not special, you still have
to call it.')
    if arg:
        return
    raise ValueError('If you had supplied an argument, you wouldn't
get this message')

if __name__ == '__main__':
    import sys
    if len(sys.argv) > 1:
        main(sys.argv[1])
    else:
        main()


Hope this helps,

Zach Ware

From eryksun at gmail.com  Mon May  6 09:12:22 2013
From: eryksun at gmail.com (eryksun)
Date: Mon, 6 May 2013 03:12:22 -0400
Subject: [Tutor] Clear screen questions
In-Reply-To: <5186FF37.6040802@pearwood.info>
References: <CANDiX9+Q_2E6fRO-fwYqwNDW-PTHzgGQwQ4tVSh9carGvktrtQ@mail.gmail.com>
	<5186FF37.6040802@pearwood.info>
Message-ID: <CACL+1auTbighY-50_tpqFEHkREPGgDcpTHDcNxRQ7w3gVRo57w@mail.gmail.com>

On Sun, May 5, 2013 at 8:54 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On 06/05/13 10:17, boB Stepp wrote:
>>
>> import os
>> ...
>> os.system('cls')

If you want to try your hand at using curses, it lets you clear the
screen and a whole lot more. Christoph Gohlke has a Windows extension
available based on the PDCurses library:

http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses

Here are some curses demos:

http://hg.python.org/cpython/file/026ee0057e2d/Demo/curses

As to clearing the console screen on NT, using the cmd shell's
internal "cls" command is the only easy way I know. The hard way is
using the Win32 console API. Microsoft has demo code here:

http://msdn.microsoft.com/en-us/library/ms682022

Writings spaces to the entire buffer like that is very different from
the way "clear" works. "clear" queries the terminfo database for the
current terminal to get the control sequence used to clear the screen.
In an xterm the following sequences work (note: \E is an escape
character, and [ is the control sequence introducer, or CSI):

    echo -n -e '\E[1;1H'  # move the cursor to the top corner, at
position (1, 1)
    echo -n -e '\E[2J'  # clear the whole screen

Of course you can combine these, and even append a message:

    echo -n -e '\E[1;1H\E[2JSpam!\nSpam!!\nSpam!!1\n'

See the following page for a detailed list of control codes:

http://www.xfree86.org/current/ctlseqs.html

>> Finally, a minor, secondary question: I was curious how my clear
>> screen code would run in the IDLE Python shell window, since I know
>> there is currently no way to clear its screen (other than the blank
>> line approach). Of course it did not clear the screen, but it did do
>> something unexpected that I would like to understand. Upon hitting the
>> clear screen code the active window switched from the Python shell
>> window to the Python edit window. Why is this so?
>
> Magic. IDLE bug. Who knows? It doesn't do that for me, but I've only tested
> it interactively with one version on Linux.

On NT, the IDLE development environment runs via pythonw.exe, which
has no attached console. Thus when system() starts cmd.exe, there's no
console window to inherit from the parent process and a new one has to
be created, and subsequently destroyed when cmd exits. After the
console window was destroyed it's possible that the edit window got
raised to the top instead of the shell window.  To avoid this you can
instead use subprocess.Popen. This lets you start a console process
with a hidden window:

http://docs.python.org/2/library/subprocess#windows-popen-helpers

Also, for pythonw.exe the streams stdin, stdout, and stderr are all
None. As far as I know all of Python's built-in standard I/O functions
such as print() and input() just silently return in this case. But
IDLE is different. Like many other IDEs and GUI shells, it fakes
stdin, stdout, and stderr with proxies. These are connected to its
PyShell and also the subprocess that it uses to actually run your
code. While this is convenient for development and most debugging,
make sure to test your code directly from the OS under 'normal'
conditions.

From eryksun at gmail.com  Mon May  6 09:21:29 2013
From: eryksun at gmail.com (eryksun)
Date: Mon, 6 May 2013 03:21:29 -0400
Subject: [Tutor] exit message
In-Reply-To: <CAKJDb-P06YCb=3pkA6-hvTwj5F_5rE-JVUhRLc4bc75-QGMi0Q@mail.gmail.com>
References: <CALRAYNXvPB4D3heFG0FQBJF4GZK4p0s3PbftMNN-WDNUp7+X6w@mail.gmail.com>
	<CAKJDb-P06YCb=3pkA6-hvTwj5F_5rE-JVUhRLc4bc75-QGMi0Q@mail.gmail.com>
Message-ID: <CACL+1as_Mqxu+csZAnQ3kqgGbB9bpVB3mbvmE=1BKUptm7Ne8w@mail.gmail.com>

On Mon, May 6, 2013 at 1:12 AM, Zachary Ware
<zachary.ware+pytut at gmail.com> wrote:
> If you don't care about the exit code, you can just "drop off" the end
> of the script.  If you don't end with an unhandled exception, your
> exit code will be 0, otherwise it will (probably) be 1.

You can also exit with a message and an exit code set to 1:

    >>> raise SystemExit('Red Alert!')
    Red Alert!

    C:\>echo %errorlevel%
    1

From cybervigilante at gmail.com  Mon May  6 09:47:08 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Mon, 6 May 2013 00:47:08 -0700
Subject: [Tutor] Tutor Digest, Vol 111, Issue 11
In-Reply-To: <mailman.7644.1367817179.3113.tutor@python.org>
References: <mailman.7644.1367817179.3113.tutor@python.org>
Message-ID: <CALRAYNU1AWhsQE2r2tcRWZcmiGHZAh1cJO+vS6no9W8fR6AzyA@mail.gmail.com>

> I believe that traceback is a bug in IDLE, which I think has been
> fixed for the next release (or is being chased, one of the two).

Ah, that clears it up. I've been using IDLE and Wing. Both have the
traceback so I guess Wing uses some IDLE code. But I tried it in the
command shell, which I haven't used in a while, and no traceback. So
that's solved. A production program wouldn't be using the IDLE
interpreter or Wing editor so there won't be a traceback littering the
screen.

Jim

From alan.gauld at btinternet.com  Mon May  6 10:42:22 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 06 May 2013 09:42:22 +0100
Subject: [Tutor] Clear screen questions
In-Reply-To: <CANDiX9+Q_2E6fRO-fwYqwNDW-PTHzgGQwQ4tVSh9carGvktrtQ@mail.gmail.com>
References: <CANDiX9+Q_2E6fRO-fwYqwNDW-PTHzgGQwQ4tVSh9carGvktrtQ@mail.gmail.com>
Message-ID: <km7qd9$i7v$1@ger.gmane.org>

On 06/05/13 01:17, boB Stepp wrote:

> os.system('cls' if os.name=='nt' else 'clear')
>
> So my main question is there a truly clean, cross-platform solution to
> the clear screen dilemma? If my online searching is accurate, then the
> answer appears to be no, unless one wants to print many blank lines.

Note that the issue is not strictly an OS issue but a terminal issue. 
Unix hides the terminal problems by using the terminfo database to 
standardize screen handling. Windows doesn't. So even CLS does not work 
for every kind of terminal you get on Windows. And the other solutions 
won't necessarily work on VMS or MVS or OS/390 etc.

You can usually clear the screen with an escape code but the code is 
terminal dependent. On DOS it usually uses the ANSI driver which may or 
may not be loaded. In an xterm it depends on whether you are using the 
VTx00 or the Tektronic emulation.

In other words it's much more complex than you would superficially 
expect and that's the reason cross platform languages like Python 
struggle to provide a solution.

Fred Lundh had a terminal module that tries to make common operations 
platform independent, but I'm not sure if its still supported. I don't 
know of anything that works within an IDE, for good reason - you don't 
want to clear the potentially useful debugging data that's on the
screen...

> something unexpected that I would like to understand. Upon hitting the
> clear screen code the active window switched from the Python shell
> window to the Python edit window. Why is this so?

No idea but worth asking on the IDLE list - its fairly active and they 
would probably be interested.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From alan.gauld at btinternet.com  Mon May  6 10:48:46 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 06 May 2013 09:48:46 +0100
Subject: [Tutor] Tutor Digest, Vol 111, Issue 11
In-Reply-To: <CALRAYNU1AWhsQE2r2tcRWZcmiGHZAh1cJO+vS6no9W8fR6AzyA@mail.gmail.com>
References: <mailman.7644.1367817179.3113.tutor@python.org>
	<CALRAYNU1AWhsQE2r2tcRWZcmiGHZAh1cJO+vS6no9W8fR6AzyA@mail.gmail.com>
Message-ID: <km7qp9$kt5$2@ger.gmane.org>

On 06/05/13 08:47, Jim Mooney wrote:

> Ah, that clears it up. I've been using IDLE and Wing. Both have the
> traceback so I guess Wing uses some IDLE code.

Not necessarily, it's a design decision in any IDE. Some designers opt 
to catch and display any exceptions, others try to emulate the normal OS 
response.

Both approaches have their supporters.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From alan.gauld at btinternet.com  Mon May  6 10:46:48 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 06 May 2013 09:46:48 +0100
Subject: [Tutor] exit message
In-Reply-To: <CALRAYNXvPB4D3heFG0FQBJF4GZK4p0s3PbftMNN-WDNUp7+X6w@mail.gmail.com>
References: <CALRAYNXvPB4D3heFG0FQBJF4GZK4p0s3PbftMNN-WDNUp7+X6w@mail.gmail.com>
Message-ID: <km7qlj$kt5$1@ger.gmane.org>

On 06/05/13 05:24, Jim Mooney wrote:
> I've noticed that if you exit() a program you always get a traceback message:
> Traceback (most recent call last):
>    File "<pyshell#1>", line 1, in <module>
>      exit('what now?')
>    File "C:\Python33\lib\site.py", line 380, in __call__
>      raise SystemExit(code)

Only within IDLE. You should remember that IDLE is a development tool 
and not intended for running finished programs. As such, it includes 
lots of useful extra "features" that help the developer, like catching 
exceptions and printing error messages. This is true for Ctrl-C 
keypresses as well as exit. It means you stay in IDLE rather than 
exiting the tool.

If you run your code from the OS instead of from IDLE it will do what 
you expect.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From steve at pearwood.info  Mon May  6 11:05:12 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 6 May 2013 19:05:12 +1000
Subject: [Tutor] exit message
In-Reply-To: <CALRAYNXvPB4D3heFG0FQBJF4GZK4p0s3PbftMNN-WDNUp7+X6w@mail.gmail.com>
References: <CALRAYNXvPB4D3heFG0FQBJF4GZK4p0s3PbftMNN-WDNUp7+X6w@mail.gmail.com>
Message-ID: <20130506090512.GA5145@ando>

On Sun, May 05, 2013 at 09:24:30PM -0700, Jim Mooney wrote:
> I've noticed that if you exit() a program you always get a traceback message:

Which exit are you talking about? There is sys.exit, and there is also 
the interactive exit() function defined by the site module for 
interactive use.



> Traceback (most recent call last):
>   File "<pyshell#1>", line 1, in <module>
>     exit('what now?')
>   File "C:\Python33\lib\site.py", line 380, in __call__
>     raise SystemExit(code)
> 
> What if you just want to exit for some normal reason and don't want
> the message? Or is a program always supposed to end in some normal way
> without an exit. Or is there a different, more graceful way to end a
> program when you want?

The normal way to exit a program is to just "fall out the bottom" when 
you reach the end. Once all loops are ended, and you reach the end of 
code, Python just neatly exits with no error.

Another alternative is to call sys.exit(), either with no argument, or 
an argument of 0. The convention for command-line tools is that an exit 
value of 0 means "no problem, the application ended normally". If you 
pass any other value, Python will generate a non-zero exit code for you.

A third way is to call down fire from the heavens and bring about the 
apocolypse for your program by calling os._exit(), which literally kills 
the application dead without giving it a chance to clean up after 
itself, close files, etc. Don't use this unless you know what you're 
doing. It also takes a status code argument like sys.exit.

Last but not least, if you raise SystemExit (or for that matter any 
exception) which is not caught by a try...except block, Python will exit 
your program with a non-zero exit code.

As always, IDLE may play silly tricks. You should not run programs "for 
real" under IDLE, but only while you are actively writing code, testing, 
etc. That's why IDLE is called an Interactive Development Environment -- 
if you're not interactively developing, don't use it.

(Actually, I am a great believer in not using IDLE for anything. If your 
application acts weird, is that because it has a bug, or because IDLE is 
doing something "clever"? I much prefer a text editor and a terminal 
window. But then I'm spoilt because I use Linux, where the standard 
environment is practically an IDE on its own.)


-- 
Steven

From alan.gauld at btinternet.com  Mon May  6 15:42:05 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 06 May 2013 14:42:05 +0100
Subject: [Tutor] Clear screen questions
In-Reply-To: <km7qd9$i7v$1@ger.gmane.org>
References: <CANDiX9+Q_2E6fRO-fwYqwNDW-PTHzgGQwQ4tVSh9carGvktrtQ@mail.gmail.com>
	<km7qd9$i7v$1@ger.gmane.org>
Message-ID: <km8bv9$9r0$1@ger.gmane.org>

On 06/05/13 09:42, Alan Gauld wrote:

> Fred Lundh had a terminal module that tries to make common operations
> platform independent, but I'm not sure if its still supported.

It was called console...

I had a quick peek and the last supported version appears to be for 2.6.
And it only claims support up to Win2000, XP is 'expected' to work.
So I doubt if it's a valid candidate now.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From drobinow at gmail.com  Mon May  6 17:13:18 2013
From: drobinow at gmail.com (David Robinow)
Date: Mon, 6 May 2013 11:13:18 -0400
Subject: [Tutor] Text Editors and Linux (was Re:  exit message)
Message-ID: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>

On Mon, May 6, 2013 at 5:05 AM, Steven D'Aprano <steve at pearwood.info> wrote:

> (Actually, I am a great believer in not using IDLE for anything. If your
> application acts weird, is that because it has a bug, or because IDLE is
> doing something "clever"? I much prefer a text editor and a terminal
> window. But then I'm spoilt because I use Linux, where the standard
> environment is practically an IDE on its own.)
>
> I certainly agree about IDLE and prefer a text editor myself. I don't use
Linux much and haven't noticed the "practically an IDE" part. Could you
expound?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130506/7cb2cd5b/attachment.html>

From alan.gauld at btinternet.com  Mon May  6 19:00:48 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 06 May 2013 18:00:48 +0100
Subject: [Tutor] Text Editors and Linux (was Re:  exit message)
In-Reply-To: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
References: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
Message-ID: <km8njr$f15$1@ger.gmane.org>

On 06/05/13 16:13, David Robinow wrote:

> I certainly agree about IDLE and prefer a text editor myself. I don't
> use Linux much and haven't noticed the "practically an IDE" part. Could
> you expound?

Unix is a software engineers OS. It comes with dozens of tools and they 
are nearly all integrated. So for example the text search tool grep can 
output its results in the same format as the compiler outputs errors. 
This allows text editors to implement features like "goto next error" 
and "goto next grep line" using common code. And many different editors 
use that same standard format.

Other tools analyze test coverage, profile execution, monitor system 
calls, analyze core dumps etc. Similarly the Unix debuggers tend to have 
common mechanisms which make them easy to integrate with editors.
The tags tools allow the OS to build a database of function definitions 
so that an editor can jump from a function reference to a function 
definition with ease.

Other OS features like command pipelines, a plethora of scripting 
languages, and a gazillion text processing commands all mean Unix can do 
most of the tricks modern IDEs do in other platforms.

The things that are less easy to reproduce tend to be things like
command completion, tooltip help and project creation/maintenance. There 
are tools to help with those but not as slick as an IDE.

Those are some of my favourite "Unix as an IDE" features, I'm sure there 
are others I've missed.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From ajin25 at gmail.com  Mon May  6 19:05:57 2013
From: ajin25 at gmail.com (Ajin Abraham)
Date: Mon, 6 May 2013 22:35:57 +0530
Subject: [Tutor] POST MULTI PART DATA WITH PYTHON
Message-ID: <CAKHNSow6VRax=1fe+qvSErGigzGmnMWNn9Kvy-mPiJJwspowOA@mail.gmail.com>

Hi,
   I was working on a python project that requires to upload an image
using httplib. Here i need to POST a MULTI PART DATA with Python using
inbuilt libraries. I know there are better libraries like requests and
poster. but i need to do it with httplib itself.

I will attach a screenshot==> http://s1.postimg.org/qjjhy445q/file.jpg

So here i think there is some problem with my code that the
'Content-Length is different and i am getting a 404 not found
response. i placed the file "screenshot.png" together with my python
source file.

Here is my source code==>http://bpaste.net/show/V2xbtcBSpYsNbwGPCmFM/

Please tell me what's wrong in my code. and please don't suggest me
other libraries.

Regards,
Ajin Abraham

From ajin25 at gmail.com  Mon May  6 20:54:02 2013
From: ajin25 at gmail.com (Ajin Abraham)
Date: Tue, 7 May 2013 00:24:02 +0530
Subject: [Tutor] POST MULTI PART DATA WITH PYTHON
In-Reply-To: <CAKHNSow6VRax=1fe+qvSErGigzGmnMWNn9Kvy-mPiJJwspowOA@mail.gmail.com>
References: <CAKHNSow6VRax=1fe+qvSErGigzGmnMWNn9Kvy-mPiJJwspowOA@mail.gmail.com>
Message-ID: <CAKHNSoxZ9Rw6HThrRObaFH+myeHhzeTu-vahYwUQivFEJaAdvg@mail.gmail.com>

    Actually i figured out the content length problem and
modified the source a bit.
http://bpaste.net/raw/lax7e7qMLY3bKM69su9k/
but still there is 404 not found problem My requirement is this.
"With httplib, i need to upload a file (png) with python at
:http://xboz.5gbfree.com/screenshot/upload.php
Regards,
Ajin Abraham

Information Security Enthusiast.
www.ajinabraham.com | www.defconkerala.org
www.keralacyberforce.in | +91-9633325997


On Mon, May 6, 2013 at 10:35 PM, Ajin Abraham <ajin25 at gmail.com> wrote:
> Hi,
>    I was working on a python project that requires to upload an image
> using httplib. Here i need to POST a MULTI PART DATA with Python using
> inbuilt libraries. I know there are better libraries like requests and
> poster. but i need to do it with httplib itself.
>
> I will attach a screenshot==> http://s1.postimg.org/qjjhy445q/file.jpg
>
> So here i think there is some problem with my code that the
> 'Content-Length is different and i am getting a 404 not found
> response. i placed the file "screenshot.png" together with my python
> source file.
>
> Here is my source code==>http://bpaste.net/show/V2xbtcBSpYsNbwGPCmFM/
>
> Please tell me what's wrong in my code. and please don't suggest me
> other libraries.
>
> Regards,
> Ajin Abraham

From drobinow at gmail.com  Mon May  6 21:54:02 2013
From: drobinow at gmail.com (David Robinow)
Date: Mon, 6 May 2013 15:54:02 -0400
Subject: [Tutor] Text Editors and Linux (was Re: exit message)
In-Reply-To: <km8njr$f15$1@ger.gmane.org>
References: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
	<km8njr$f15$1@ger.gmane.org>
Message-ID: <CAF3Xjby=Q940w6EP4=8MFusU4ry2HeUac0bJci1jrQztu1YNWw@mail.gmail.com>

On Mon, May 6, 2013 at 1:00 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> On 06/05/13 16:13, David Robinow wrote:
>
>  I certainly agree about IDLE and prefer a text editor myself. I don't
>> use Linux much and haven't noticed the "practically an IDE" part. Could
>> you expound?
>>
>
> Unix is a software engineers OS. It comes with dozens of tools and they
> are nearly all integrated. So for example the text search tool grep can
> output its results in the same format as the compiler outputs errors. This
> allows text editors to implement features like "goto next error" and "goto
> next grep line" using common code. And many different editors use that same
> standard format.
>
> Other tools analyze test coverage, profile execution, monitor system
> calls, analyze core dumps etc. Similarly the Unix debuggers tend to have
> common mechanisms which make them easy to integrate with editors.
> The tags tools allow the OS to build a database of function definitions so
> that an editor can jump from a function reference to a function definition
> with ease.
>
> Other OS features like command pipelines, a plethora of scripting
> languages, and a gazillion text processing commands all mean Unix can do
> most of the tricks modern IDEs do in other platforms.
>
> The things that are less easy to reproduce tend to be things like
> command completion, tooltip help and project creation/maintenance. There
> are tools to help with those but not as slick as an IDE.
>
> Those are some of my favourite "Unix as an IDE" features, I'm sure there
> are others I've missed.
>
You haven't gone into enough detail for me to tell whether I'm missing
anything. I'm not understanding what you're saying about grep although I've
used next-error with C code in emacs.
 I never thought tags were worth the trouble although the tools are
available on Windows.
 I should mention that I've been cheating since I use cygwin so I have
access to most of the "Unix" text tools on Windows.
 I've never heard of a scripting language that's not available on Windows.
This is all really off-topic for this list so I'll quit now.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130506/1a19fcf2/attachment-0001.html>

From oscar.j.benjamin at gmail.com  Mon May  6 22:52:05 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Mon, 6 May 2013 21:52:05 +0100
Subject: [Tutor] Text Editors and Linux (was Re: exit message)
In-Reply-To: <CAF3Xjby=Q940w6EP4=8MFusU4ry2HeUac0bJci1jrQztu1YNWw@mail.gmail.com>
References: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
	<km8njr$f15$1@ger.gmane.org>
	<CAF3Xjby=Q940w6EP4=8MFusU4ry2HeUac0bJci1jrQztu1YNWw@mail.gmail.com>
Message-ID: <CAHVvXxQYm+JwGW9noiiZLz3q2eUaNGozdgLCZz-CUr6SrG6cew@mail.gmail.com>

On 6 May 2013 20:54, David Robinow <drobinow at gmail.com> wrote:
> On Mon, May 6, 2013 at 1:00 PM, Alan Gauld <alan.gauld at btinternet.com>
> wrote:
>>
>> Those are some of my favourite "Unix as an IDE" features, I'm sure there
>> are others I've missed.
>
> You haven't gone into enough detail for me to tell whether I'm missing
> anything. I'm not understanding what you're saying about grep although I've
> used next-error with C code in emacs.

The grep thing is just one of many examples of how the plethora of
initially mundane seeming programs that every Unix ships with can be
surprisingly powerful when used in combination.

>  I never thought tags were worth the trouble although the tools are
> available on Windows.
>  I should mention that I've been cheating since I use cygwin so I have
> access to most of the "Unix" text tools on Windows.

I won't use Windows without installing some form of bash (usually
git-bash rather than cygwin) and ideally a better graphical terminal
(e.g. console2). Without that, the basic problem is the absolutely
terrible terminal that ships with Windows. I think that alone would be
reason enough to use an IDE for everything.

>  I've never heard of a scripting language that's not available on Windows.

It depends what you mean by available. I expect Unix systems to come
with bash, perl, python, and many more out of the box. Each of these
things can be installed on Windows, just as you can install Windows
versions of grep, awk, sed, vi ... The difference is that Unix just
always has these things without needing to do something as ridiculous
as cygwin.


Oscar

From ramit.prasad at jpmorgan.com  Mon May  6 23:03:20 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Mon, 6 May 2013 21:03:20 +0000
Subject: [Tutor] POST MULTI PART DATA WITH PYTHON
In-Reply-To: <CAKHNSoxZ9Rw6HThrRObaFH+myeHhzeTu-vahYwUQivFEJaAdvg@mail.gmail.com>
References: <CAKHNSow6VRax=1fe+qvSErGigzGmnMWNn9Kvy-mPiJJwspowOA@mail.gmail.com>
	<CAKHNSoxZ9Rw6HThrRObaFH+myeHhzeTu-vahYwUQivFEJaAdvg@mail.gmail.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF4741839AEA3@SCACMX008.exchad.jpmchase.net>

Please post your comments after quoted text (either bottom posting or in-line) not before (top posting). I have fixed the order below.

> On Mon, May 6, 2013 at 10:35 PM, Ajin Abraham <ajin25 at gmail.com> wrote:
> > Hi,
> >    I was working on a python project that requires to upload an image
> > using httplib. Here i need to POST a MULTI PART DATA with Python using
> > inbuilt libraries. I know there are better libraries like requests and
> > poster. but i need to do it with httplib itself.
> >
> > I will attach a screenshot==> http://s1.postimg.org/qjjhy445q/file.jpg
> >
> > So here i think there is some problem with my code that the
> > 'Content-Length is different and i am getting a 404 not found
> > response. i placed the file "screenshot.png" together with my python
> > source file.
> >
> > Here is my source code==>http://bpaste.net/show/V2xbtcBSpYsNbwGPCmFM/
> >
> > Please tell me what's wrong in my code. and please don't suggest me
> > other libraries.
> >

Ajin Abraham wrote:
>     Actually i figured out the content length problem and
> modified the source a bit.
> http://bpaste.net/raw/lax7e7qMLY3bKM69su9k/
> but still there is 404 not found problem My requirement is this.
> "With httplib, i need to upload a file (png) with python at
> :http://xboz.5gbfree.com/screenshot/upload.php
> Regards,
> Ajin Abraham
> 
> Information Security Enthusiast.
> www.ajinabraham.com | www.defconkerala.org
> www.keralacyberforce.in | +91-9633325997

Your code is small enough, that you should just paste it directly
rather than putting it on a website. That will help others searching
this list too.

What is the 404 error text? You may need to create an error handler so 
Python will pass the response back rather than throwing an exception.

I have only used urllib2 (standard library) and I have not done
multi-part form data. The general technique below should work, although
I used it on an XML file rather than a picture.

class BetterHTTPErrorProcessor(urllib2.BaseHandler):
    def http_error_404(self, request, response, code, msg, hdrs):
        '''Do not throw exception but instead return response because response text will eventually
        have a useful message for WHY this was received.
        '''
        return response

def foo():
    opener = urllib2.build_opener( BetterHTTPErrorProcessor, urllib2.HTTPHandler( debuglevel=debug ) )
    request = urllib2.Request(url, data=xml, headers={'Content-Type':'text/xml; charset=utf-8', 'Content-Length':len(xml) } )
    response = opener.open( request )

You should notice that I did not turn the content length into a string. 
I have no idea if that matters or not.


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

From alan.gauld at btinternet.com  Mon May  6 23:27:22 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 06 May 2013 22:27:22 +0100
Subject: [Tutor] Text Editors and Linux (was Re: exit message)
In-Reply-To: <CAF3Xjby=Q940w6EP4=8MFusU4ry2HeUac0bJci1jrQztu1YNWw@mail.gmail.com>
References: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
	<km8njr$f15$1@ger.gmane.org>
	<CAF3Xjby=Q940w6EP4=8MFusU4ry2HeUac0bJci1jrQztu1YNWw@mail.gmail.com>
Message-ID: <km977m$ooj$1@ger.gmane.org>

On 06/05/13 20:54, David Robinow wrote:

> You haven't gone into enough detail for me to tell whether I'm missing
> anything. I'm not understanding what you're saying about grep although
> I've used next-error with C code in emacs.

You can run grep from within an editor and then step through each 
occurence of the search within the editor just as you'd do for errors. 
This becomes powerful when dealing with many files and you want to 
seamlessly step from one file to the next. Most IDEs will do this within 
  the context of a "project" but it comes for free in Unix.

>   I never thought tags were worth the trouble

Tags are great on large projects. I once worked on a project where we 
bought the core software from an external company and it came with 
10,000 C files and little or no documentation. We had to understand it 
by reading our way through it (grep for main() and start from there)
By running tags on the source we could jump from any point in the code 
to the definition of a function regardless of which of the 10,000 files 
it was located in. That is a huge timesaver! Again an IDE will do the 
same trick but tags are standard in Unix.


>   I should mention that I've been cheating since I use cygwin so I have
> access to most of the "Unix" text tools on Windows.

Absolutely! And I never install Windows for my own use without adding 
cygwin. (And before Cygwin appeared it was the MKS Toolkit - which cost 
real $$$!) But if it's not my PC that's often not an option. And in 
server farms they get nervous about installing anything that's not 
absolutely required. In Unix I get it all for free.

>   I've never heard of a scripting language that's not available on Windows.

Available as in installable, yes (although that's a fairly recent thing 
- often via cygwin!). But Unix has them by default. You have to put a 
lot of work into making Windows look like Unix...

> This is all really off-topic for this list so I'll quit now.

Only slightly. Beginning programmers often wonder about the best tools 
and why pro programmers often use different tools to the ones they pick 
as beginners.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From steve at pearwood.info  Tue May  7 06:35:12 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 7 May 2013 14:35:12 +1000
Subject: [Tutor] Text Editors and Linux (was Re: exit message)
In-Reply-To: <CAHVvXxQYm+JwGW9noiiZLz3q2eUaNGozdgLCZz-CUr6SrG6cew@mail.gmail.com>
References: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
	<km8njr$f15$1@ger.gmane.org>
	<CAF3Xjby=Q940w6EP4=8MFusU4ry2HeUac0bJci1jrQztu1YNWw@mail.gmail.com>
	<CAHVvXxQYm+JwGW9noiiZLz3q2eUaNGozdgLCZz-CUr6SrG6cew@mail.gmail.com>
Message-ID: <20130507043511.GB5145@ando>

On Mon, May 06, 2013 at 09:52:05PM +0100, Oscar Benjamin wrote:

> >  I've never heard of a scripting language that's not available on Windows.
> 
> It depends what you mean by available. I expect Unix systems to come
> with bash, perl, python, and many more out of the box. Each of these
> things can be installed on Windows, just as you can install Windows
> versions of grep, awk, sed, vi ... The difference is that Unix just
> always has these things without needing to do something as ridiculous
> as cygwin.

Not only that, but Cygwin often introduces little quirks or outright 
bugs that make it a not-quite first-class development environment.


-- 
Steven


From steve at pearwood.info  Tue May  7 06:50:19 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 7 May 2013 14:50:19 +1000
Subject: [Tutor] Text Editors and Linux (was Re:  exit message)
In-Reply-To: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
References: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
Message-ID: <20130507045019.GC5145@ando>

On Mon, May 06, 2013 at 11:13:18AM -0400, David Robinow wrote:
> On Mon, May 6, 2013 at 5:05 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> 
> > (Actually, I am a great believer in not using IDLE for anything. If your
> > application acts weird, is that because it has a bug, or because IDLE is
> > doing something "clever"? I much prefer a text editor and a terminal
> > window. But then I'm spoilt because I use Linux, where the standard
> > environment is practically an IDE on its own.)
>
> I certainly agree about IDLE and prefer a text editor myself. I don't use
> Linux much and haven't noticed the "practically an IDE" part. Could you
> expound?


http://blog.sanctum.geek.nz/series/unix-as-ide/


My preferred development environment is:

* kate text editor (although I'm trying out geany and so far I like what 
I see);

* a decent console app that supports multiple tabs;

* a browser for googling stuff;

* and optionally, a file manager window, preferably Konqueror (but KDE 3 
only), but I don't even usually bother with that.

I tend to have at least one console tab open for running shell commands 
like grep, version control, etc; another tab open for running my app; at 
least one tab open for a Python interactive interpreter for trying out 
code snippets and reading help(); and another tab for running tests.



-- 
Steven

From ramit.prasad at jpmorgan.com  Tue May  7 16:26:03 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Tue, 7 May 2013 14:26:03 +0000
Subject: [Tutor] Text Editors and Linux (was Re:  exit message)
In-Reply-To: <20130507045019.GC5145@ando>
References: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
	<20130507045019.GC5145@ando>
Message-ID: <5B80DD153D7D744689F57F4FB69AF474183A0676@SCACMX008.exchad.jpmchase.net>

Steven D'Aprano wrote:

> * a decent console app that supports multiple tabs;

Any reason to prefer tabs to virtual terminals (i.e. screen)?


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

From bicofino at gmail.com  Tue May  7 16:57:27 2013
From: bicofino at gmail.com (Danilo Chilene)
Date: Tue, 7 May 2013 11:57:27 -0300
Subject: [Tutor] Argparse functions with N parameters
Message-ID: <CA+_2i1SoYXswCDcMTLT-WG9Rmsto4T6Yfnby78H0nyoUWo0udg@mail.gmail.com>

Hello,

I have the code below:

import argparse
class Myclass(object):

    def foo(self):
        print 'foo'

    def bar(self):
        print 'bar'

    def test(self,name,place):
        print name, place

class Main(Myclass):
    def __init__(self):
        foo_parser = argparse.ArgumentParser()
        foo_parser.add_argument('method')
        self.args = foo_parser.parse_args()

    def __call__(self, *args, **kws):
        method = self.args.method
        return getattr(self, method)(*args, **kws)

if __name__ == "__main__":
    main = Main()

    main()

It's working for functions foo and bar:

5: python arg.py foo
foo

5: python arg.py bar
bar

5: python arg.py test a b
usage: arg.py [-h] method
arg.py: error: unrecognized arguments: a b


But for function test I guess I'm missing something, the idea is to
have N functions and N param.

Any ideas?

Best Regards,

Danilo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130507/b094249b/attachment.html>

From __peter__ at web.de  Tue May  7 18:10:49 2013
From: __peter__ at web.de (Peter Otten)
Date: Tue, 07 May 2013 18:10:49 +0200
Subject: [Tutor] Argparse functions with N parameters
References: <CA+_2i1SoYXswCDcMTLT-WG9Rmsto4T6Yfnby78H0nyoUWo0udg@mail.gmail.com>
Message-ID: <kmb925$cn5$1@ger.gmane.org>

Danilo Chilene wrote:

> Hello,
> 
> I have the code below:
> 
> import argparse
> class Myclass(object):
> 
>     def foo(self):
>         print 'foo'
> 
>     def bar(self):
>         print 'bar'
> 
>     def test(self,name,place):
>         print name, place
> 
> class Main(Myclass):
>     def __init__(self):
>         foo_parser = argparse.ArgumentParser()
>         foo_parser.add_argument('method')
>         self.args = foo_parser.parse_args()
> 
>     def __call__(self, *args, **kws):
>         method = self.args.method
>         return getattr(self, method)(*args, **kws)
> 
> if __name__ == "__main__":
>     main = Main()
> 
>     main()
> 
> It's working for functions foo and bar:
> 
> 5: python arg.py foo
> foo
> 
> 5: python arg.py bar
> bar
> 
> 5: python arg.py test a b
> usage: arg.py [-h] method
> arg.py: error: unrecognized arguments: a b
> 
> 
> But for function test I guess I'm missing something, the idea is to
> have N functions and N param.
> 
> Any ideas?

You can either keep it simple and use sys.argv with

getattr(self, sys.argv[1])(*sys.argv[2:])

or you can have a look at subparsers. I took a stab at that:

$ cat automatic_subparsers.py
import argparse
import inspect

class Myclass(object):

    def foo(self):
        print 'foo'

    def bar(self):
        print 'bar'

    def test(self,name,place):
        print name, place

class Main(Myclass):
    def __init__(self):
        parser = argparse.ArgumentParser()
        subparsers = parser.add_subparsers()

        for name in dir(self):
            if not name.startswith("_"):
                p = subparsers.add_parser(name)
                method = getattr(self, name)
                argnames = inspect.getargspec(method).args[1:]
                for argname in argnames:
                    p.add_argument(argname)
                p.set_defaults(func=method, argnames=argnames)
        self.args = parser.parse_args()

    def __call__(self):
        a = self.args
        callargs = [getattr(a, name) for name in a.argnames]
        return self.args.func(*callargs)

if __name__ == "__main__":
    main = Main()

    main()
$ python automatic_subparsers.py -h
usage: automatic_subparsers.py [-h] {bar,foo,test} ...

positional arguments:
  {bar,foo,test}

optional arguments:
  -h, --help      show this help message and exit
$ python automatic_subparsers.py bar -h
usage: automatic_subparsers.py bar [-h]

optional arguments:
  -h, --help  show this help message and exit
$ python automatic_subparsers.py bar 
bar
$ python automatic_subparsers.py test -h
usage: automatic_subparsers.py test [-h] name place

positional arguments:
  name
  place

optional arguments:
  -h, --help  show this help message and exit
$ python automatic_subparsers.py test me here
me here

There may be a library out there that does this with bells and whistles, but 
I haven't looked.



From ramit.prasad at jpmorgan.com  Tue May  7 18:15:55 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Tue, 7 May 2013 16:15:55 +0000
Subject: [Tutor] Argparse functions with N parameters
In-Reply-To: <kmb925$cn5$1@ger.gmane.org>
References: <CA+_2i1SoYXswCDcMTLT-WG9Rmsto4T6Yfnby78H0nyoUWo0udg@mail.gmail.com>
	<kmb925$cn5$1@ger.gmane.org>
Message-ID: <5B80DD153D7D744689F57F4FB69AF474183A0B2E@SCACMX008.exchad.jpmchase.net>

Peter Otten wrote:
[snip]
> 
> There may be a library out there that does this with bells and whistles, but
> I haven't looked.
> 

This is not related to the OP, but have you [Peter/tutors] taken a look at the
docopt library? Any thoughts compared to argparse/optparse?


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

From bjorn.h.madsen at googlemail.com  Tue May  7 19:10:15 2013
From: bjorn.h.madsen at googlemail.com (Bjorn Madsen)
Date: Tue, 7 May 2013 18:10:15 +0100
Subject: [Tutor] Why do sets use 6 times as much memory as lists?
Message-ID: <CALCPZ6dwvmi0DDQ0eQ58FzH+PhRL4dHF6iBDSum7WvLFZZQiRg@mail.gmail.com>

>>> import sys
>>> L=[x for x in range(10000)]
>>> sys.getsizeof(L)
43816
>>> L={x for x in range(10000)}
>>> sys.getsizeof(L)
262260
?
kind regards,
Bjorn
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130507/1de8bfb7/attachment-0001.html>

From davea at davea.name  Tue May  7 19:39:46 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 07 May 2013 13:39:46 -0400
Subject: [Tutor] Why do sets use 6 times as much memory as lists?
In-Reply-To: <CALCPZ6dwvmi0DDQ0eQ58FzH+PhRL4dHF6iBDSum7WvLFZZQiRg@mail.gmail.com>
References: <CALCPZ6dwvmi0DDQ0eQ58FzH+PhRL4dHF6iBDSum7WvLFZZQiRg@mail.gmail.com>
Message-ID: <51893C62.2000000@davea.name>

On 05/07/2013 01:10 PM, Bjorn Madsen wrote:
>>>> import sys
>>>> L=[x for x in range(10000)]
>>>> sys.getsizeof(L)
> 43816
>>>> L={x for x in range(10000)}
>>>> sys.getsizeof(L)
> 262260
> ?
> kind regards,
> Bjorn
>
>
Just curious:  what did you expect?  Sets have a different purpose, 
basically to be able to do an 'in' operation instantly, while lists have 
to scan every item in the list.

I figure the ratio to be more like 75% larger, since the 10,000 objects 
are going to take up maybe 24 bytes each.

-- 
DaveA

From oscar.j.benjamin at gmail.com  Tue May  7 19:53:33 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Tue, 7 May 2013 18:53:33 +0100
Subject: [Tutor] Why do sets use 6 times as much memory as lists?
In-Reply-To: <CALCPZ6dwvmi0DDQ0eQ58FzH+PhRL4dHF6iBDSum7WvLFZZQiRg@mail.gmail.com>
References: <CALCPZ6dwvmi0DDQ0eQ58FzH+PhRL4dHF6iBDSum7WvLFZZQiRg@mail.gmail.com>
Message-ID: <CAHVvXxTc6DgV-OLNEh28xcXrGJqaR7OqcorJc0kH7X+bwXsDSw@mail.gmail.com>

On 7 May 2013 18:10, Bjorn Madsen <bjorn.h.madsen at googlemail.com> wrote:
>>>> import sys
>>>> L=[x for x in range(10000)]
>>>> sys.getsizeof(L)
> 43816
>>>> L={x for x in range(10000)}
>>>> sys.getsizeof(L)
> 262260

Firstly, these results may vary depending on operating system,
processor architecture and build options so this won't always be
exactly the same. I do get the same numbers as you, however, on
standard python 2.7 on 32-bit Windows.

So why do sets use extra memory? Under the hood a list is an array
which stores a pointer in each slot with no gaps between the pointers.

A set uses a hash-table which is an array that stores pointers at
randomish positions and only fills about half of its spaces. This
causes it to need twice as much memory for all the gaps in its array.
On top of that Python sets use a resizable hash table and to make
resizing efficient the hash of each object is stored in addition to
its pointer. This essentially requires a whole extra array so it
doubles your storage requirements again. With these two I would expect
a set to be something like 4 times bigger so the 6 times bigger that
you report seems reasonable to me (I may have missed something else in
this).


Oscar

From bjorn.h.madsen at googlemail.com  Tue May  7 20:09:52 2013
From: bjorn.h.madsen at googlemail.com (Bjorn Madsen)
Date: Tue, 7 May 2013 19:09:52 +0100
Subject: [Tutor] Why do sets use 6 times as much memory as lists?
In-Reply-To: <CAHVvXxTc6DgV-OLNEh28xcXrGJqaR7OqcorJc0kH7X+bwXsDSw@mail.gmail.com>
References: <CALCPZ6dwvmi0DDQ0eQ58FzH+PhRL4dHF6iBDSum7WvLFZZQiRg@mail.gmail.com>
	<CAHVvXxTc6DgV-OLNEh28xcXrGJqaR7OqcorJc0kH7X+bwXsDSw@mail.gmail.com>
Message-ID: <CALCPZ6dNBFvA9FU4aVujEKu3v7TkE=E5_=xjiyVSmGrmPM5hdA@mail.gmail.com>

Hi, Thanks for the quick response.

"Being curious" I actually expected something like this:
>>> L={x:None for x in range(10000)}
>>> sys.getsizeof(L)
196660
>>>

That is why I wondered why 6 times is a lot given that a dict can do the
same at 3/4 of the mem-footprint.
Just got surprised about the overhead as "sets" some are more lightweight
than dictionaries.

additional overhead must have something to do with set-specific operations,
I imagine such as:
set1 - set2
set | set2
set1 & set2
set1 <= set2
....

Thanks anyway!



On 7 May 2013 18:53, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:

> On 7 May 2013 18:10, Bjorn Madsen <bjorn.h.madsen at googlemail.com> wrote:
> >>>> import sys
> >>>> L=[x for x in range(10000)]
> >>>> sys.getsizeof(L)
> > 43816
> >>>> L={x for x in range(10000)}
> >>>> sys.getsizeof(L)
> > 262260
>
> Firstly, these results may vary depending on operating system,
> processor architecture and build options so this won't always be
> exactly the same. I do get the same numbers as you, however, on
> standard python 2.7 on 32-bit Windows.
>
> So why do sets use extra memory? Under the hood a list is an array
> which stores a pointer in each slot with no gaps between the pointers.
>
> A set uses a hash-table which is an array that stores pointers at
> randomish positions and only fills about half of its spaces. This
> causes it to need twice as much memory for all the gaps in its array.
> On top of that Python sets use a resizable hash table and to make
> resizing efficient the hash of each object is stored in addition to
> its pointer. This essentially requires a whole extra array so it
> doubles your storage requirements again. With these two I would expect
> a set to be something like 4 times bigger so the 6 times bigger that
> you report seems reasonable to me (I may have missed something else in
> this).
>
>
> Oscar
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130507/3fad52af/attachment.html>

From oscar.j.benjamin at gmail.com  Tue May  7 21:09:05 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Tue, 7 May 2013 20:09:05 +0100
Subject: [Tutor] Why do sets use 6 times as much memory as lists?
In-Reply-To: <CALCPZ6dNBFvA9FU4aVujEKu3v7TkE=E5_=xjiyVSmGrmPM5hdA@mail.gmail.com>
References: <CALCPZ6dwvmi0DDQ0eQ58FzH+PhRL4dHF6iBDSum7WvLFZZQiRg@mail.gmail.com>
	<CAHVvXxTc6DgV-OLNEh28xcXrGJqaR7OqcorJc0kH7X+bwXsDSw@mail.gmail.com>
	<CALCPZ6dNBFvA9FU4aVujEKu3v7TkE=E5_=xjiyVSmGrmPM5hdA@mail.gmail.com>
Message-ID: <CAHVvXxQ8m+26vvHVuZDHYXx7z_Prh7GThO5bCW0LF9zg7hddcg@mail.gmail.com>

On 7 May 2013 19:09, Bjorn Madsen <bjorn.h.madsen at googlemail.com> wrote:
> Hi, Thanks for the quick response.
>
> "Being curious" I actually expected something like this:
>>>> L={x:None for x in range(10000)}
>>>> sys.getsizeof(L)
> 196660
>>>>
>
> That is why I wondered why 6 times is a lot given that a dict can do the
> same at 3/4 of the mem-footprint.
> Just got surprised about the overhead as "sets" some are more lightweight
> than dictionaries.

I think that the 3/4 is pretty much random. sets and dicts resize
peroidically depending on how they are used.

> additional overhead must have something to do with set-specific operations,
> I imagine such as:
> set1 - set2
> set | set2
> set1 & set2
> set1 <= set2
> ....

I don't think so. Here's the results on a 64-bit Linux machine (Python 2.7):
>>> import sys
>>> sys.getsizeof([x for x in range(10000)])
87632
>>> sys.getsizeof({x for x in range(10000)})
524520
>>> sys.getsizeof({x: None for x in range(10000)})
786712

So in this case the set ends up being 2/3 the size of the dict. As I
said before these results will not be consistent from one computer to
another.


Oscar

From staffordbaines at yahoo.com  Tue May  7 23:37:16 2013
From: staffordbaines at yahoo.com (Stafford Baines)
Date: Tue, 7 May 2013 22:37:16 +0100
Subject: [Tutor] Games from Mark Dawson#'s book
Message-ID: <004001ce4b6b$0cd1c120$26754360$@com>

I recently wrote to this forum about the games downloaded from Mark Dawson's
book Python Programming 3rd Edition

and couldn't get the graphics games (chapters 11 and 12 of the book) to
work. I had helpful and friendly advice from boB and Dave.

 

The book has been written around python 3.1 and I had been using python 3.3.
In desperation I downloaded 3.1 and

the games seem to be working. At least those in chapter 11. I shall try
those in chapter 12 tomorrow. I'm going

to bed now otherwise  I'll be seeing flying pizzas all night in my dreams.
'll be reverting to python 3.3 eventually 

as I would like to see why the graphics it weren't working with it.

 

Regards to all and thanks for the advice.

 

Stafford

 

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130507/cf098774/attachment-0001.html>

From breamoreboy at yahoo.co.uk  Wed May  8 00:24:13 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 07 May 2013 23:24:13 +0100
Subject: [Tutor] Argparse functions with N parameters
In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474183A0B2E@SCACMX008.exchad.jpmchase.net>
References: <CA+_2i1SoYXswCDcMTLT-WG9Rmsto4T6Yfnby78H0nyoUWo0udg@mail.gmail.com>
	<kmb925$cn5$1@ger.gmane.org>
	<5B80DD153D7D744689F57F4FB69AF474183A0B2E@SCACMX008.exchad.jpmchase.net>
Message-ID: <kmbuua$d4m$1@ger.gmane.org>

On 07/05/2013 17:15, Prasad, Ramit wrote:
> Peter Otten wrote:
> [snip]
>>
>> There may be a library out there that does this with bells and whistles, but
>> I haven't looked.
>>
>
> This is not related to the OP, but have you [Peter/tutors] taken a look at the
> docopt library? Any thoughts compared to argparse/optparse?
>
>
> ~Ramit
>

I've just started using docopt. It's brilliant in its simplicity.

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From steve at pearwood.info  Wed May  8 03:21:39 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 08 May 2013 11:21:39 +1000
Subject: [Tutor] Why do sets use 6 times as much memory as lists?
In-Reply-To: <CALCPZ6dwvmi0DDQ0eQ58FzH+PhRL4dHF6iBDSum7WvLFZZQiRg@mail.gmail.com>
References: <CALCPZ6dwvmi0DDQ0eQ58FzH+PhRL4dHF6iBDSum7WvLFZZQiRg@mail.gmail.com>
Message-ID: <5189A8A3.7030407@pearwood.info>

On 08/05/13 03:10, Bjorn Madsen wrote:
>>>> import sys
>>>> L=[x for x in range(10000)]
>>>> sys.getsizeof(L)
> 43816
>>>> L={x for x in range(10000)}
>>>> sys.getsizeof(L)
> 262260
> ?


Both sets and lists may be over-allocated. I expect that lists created with a list comprehension may not be over-allocated, but if you append a single item to it, Python *may* resize it and quadruple or double the size. If you don't over-allocate, then *every* append becomes slow:

[a, b, c, d] append e:

copy the list, plus one extra slot:

[a, b, c, d]
[a, b, c, d, UNUSED]

insert e:

[a, b, c, d]
[a, b, c, d, e]

delete the original:

[a, b, c, d, e]


Instead of adding just one extra slot, Python quadruples (for small lists) or doubles the size, so that *nearly always* your list has plenty of extra slots to append into instantly. This makes appending an almost-constant time operation, on average, regardless of how big your list is, and big list will never use more than twice the amount of memory needed. That's a good trade off of space versus time (memory versus speed).


Sets, and dicts, are also over-allocated, because of the nature of how hash tables work. They also trade off space for time. The hash table is a big array of slots, some of which are flagged as "empty", some of which have an item in them:

[EMPTY, EMPTY, b, EMPTY, d, c, EMPTY, EMPTY, EMPTY, a, EMPTY, e]

When you do a lookup on (say) c, Python calculates a hash of c to get the index to look. Say it gets index 5, it looks at index 5 and sees c is there. This means it only needs to look in one slot instead of up to 12.

The more empty slots, the better the hash table will perform. If you would like more details on how hash tables work, you can google it, or just ask here, but the short answer is that in order to get extremely fast almost constant-time insertion, deletion and lookup of items in dicts and sets, they trade off some memory for speed.


-- 
Steven

From eryksun at gmail.com  Wed May  8 03:30:21 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 7 May 2013 21:30:21 -0400
Subject: [Tutor] Why do sets use 6 times as much memory as lists?
In-Reply-To: <CALCPZ6dNBFvA9FU4aVujEKu3v7TkE=E5_=xjiyVSmGrmPM5hdA@mail.gmail.com>
References: <CALCPZ6dwvmi0DDQ0eQ58FzH+PhRL4dHF6iBDSum7WvLFZZQiRg@mail.gmail.com>
	<CAHVvXxTc6DgV-OLNEh28xcXrGJqaR7OqcorJc0kH7X+bwXsDSw@mail.gmail.com>
	<CALCPZ6dNBFvA9FU4aVujEKu3v7TkE=E5_=xjiyVSmGrmPM5hdA@mail.gmail.com>
Message-ID: <CACL+1auO+B_gu5FyK_d+ix4uwGZoDrCq=FoS_Jp+SOo_pSY4GQ@mail.gmail.com>

On Tue, May 7, 2013 at 2:09 PM, Bjorn Madsen
<bjorn.h.madsen at googlemail.com> wrote:
>
> "Being curious" I actually expected something like this:
>>>> L={x:None for x in range(10000)}
>>>> sys.getsizeof(L)
> 196660
>
> That is why I wondered why 6 times is a lot given that a dict can do the
> same at 3/4 of the mem-footprint. Just got surprised about the overhead
> as "sets" some are more lightweight than dictionaries.

Minus the basic object size, for the same size table a set should be
about 2/3 the size of a dict.

I suppose you're using Python 3.3. To reduce memory usage, the dict
type in 3.3 allows splitting tables to share keys/hashes among
instances:

http://www.python.org/dev/peps/pep-0412

That's not directly related to the size difference here, but at the
same time it was decided to also cut the initial growth rate to save
memory. In previous versions when the table is 2/3 full it gets
quadrupled in size, which slows to doubling after 50,000 active keys.
In 3.3 a dict always uses doubling.

So in 3.2 a fresh dict or set with 10,000 entries will have a table
sized 32768, while in 3.3 the table is sized 16384 for a dict and
32768 for a set. Keep in mind that as keys are added and removed the
table sizes will diverge, even for same number of active keys. Dummy
keys left in the table count toward the table utilization, but get
purged by a resize.

From eryksun at gmail.com  Wed May  8 03:43:15 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 7 May 2013 21:43:15 -0400
Subject: [Tutor] Why do sets use 6 times as much memory as lists?
In-Reply-To: <CACL+1auO+B_gu5FyK_d+ix4uwGZoDrCq=FoS_Jp+SOo_pSY4GQ@mail.gmail.com>
References: <CALCPZ6dwvmi0DDQ0eQ58FzH+PhRL4dHF6iBDSum7WvLFZZQiRg@mail.gmail.com>
	<CAHVvXxTc6DgV-OLNEh28xcXrGJqaR7OqcorJc0kH7X+bwXsDSw@mail.gmail.com>
	<CALCPZ6dNBFvA9FU4aVujEKu3v7TkE=E5_=xjiyVSmGrmPM5hdA@mail.gmail.com>
	<CACL+1auO+B_gu5FyK_d+ix4uwGZoDrCq=FoS_Jp+SOo_pSY4GQ@mail.gmail.com>
Message-ID: <CACL+1atj_7ok66aFx9kOV+PMBc-RSZFPEn0iEgwo_EJK9cGEEw@mail.gmail.com>

On Tue, May 7, 2013 at 9:30 PM, eryksun <eryksun at gmail.com> wrote:
>
>> That is why I wondered why 6 times is a lot given that a dict can do the
>> same at 3/4 of the mem-footprint.

I hope it's clear that 3/4 here comes from 1/2 * 3/2. In other words
the dict table has 1/2 the number of entries, and each entry is 3/2
times the size, accounting for the pointer to the value.

From wescpy at gmail.com  Wed May  8 05:51:10 2013
From: wescpy at gmail.com (wesley chun)
Date: Tue, 7 May 2013 20:51:10 -0700
Subject: [Tutor] Why do sets use 6 times as much memory as lists?
In-Reply-To: <CAHVvXxQ8m+26vvHVuZDHYXx7z_Prh7GThO5bCW0LF9zg7hddcg@mail.gmail.com>
References: <CALCPZ6dwvmi0DDQ0eQ58FzH+PhRL4dHF6iBDSum7WvLFZZQiRg@mail.gmail.com>
	<CAHVvXxTc6DgV-OLNEh28xcXrGJqaR7OqcorJc0kH7X+bwXsDSw@mail.gmail.com>
	<CALCPZ6dNBFvA9FU4aVujEKu3v7TkE=E5_=xjiyVSmGrmPM5hdA@mail.gmail.com>
	<CAHVvXxQ8m+26vvHVuZDHYXx7z_Prh7GThO5bCW0LF9zg7hddcg@mail.gmail.com>
Message-ID: <CAB6eaA47=3K7Fr=X0+iYLpQMuOPsKOn-esn=_uD5W1cnPBqBpw@mail.gmail.com>

Following Oscar's comment, It's also O(n) vs. O(1) tradeoff.

--wesley


On Tue, May 7, 2013 at 12:09 PM, Oscar Benjamin
<oscar.j.benjamin at gmail.com>wrote:

> On 7 May 2013 19:09, Bjorn Madsen <bjorn.h.madsen at googlemail.com> wrote:
> > Hi, Thanks for the quick response.
> >
> > "Being curious" I actually expected something like this:
> >>>> L={x:None for x in range(10000)}
> >>>> sys.getsizeof(L)
> > 196660
> >>>>
> >
> > That is why I wondered why 6 times is a lot given that a dict can do the
> > same at 3/4 of the mem-footprint.
> > Just got surprised about the overhead as "sets" some are more lightweight
> > than dictionaries.
>
> I think that the 3/4 is pretty much random. sets and dicts resize
> peroidically depending on how they are used.
>
> > additional overhead must have something to do with set-specific
> operations,
> > I imagine such as:
> > set1 - set2
> > set | set2
> > set1 & set2
> > set1 <= set2
> > ....
>
> I don't think so. Here's the results on a 64-bit Linux machine (Python
> 2.7):
> >>> import sys
> >>> sys.getsizeof([x for x in range(10000)])
> 87632
> >>> sys.getsizeof({x for x in range(10000)})
> 524520
> >>> sys.getsizeof({x: None for x in range(10000)})
> 786712
>
> So in this case the set ends up being 2/3 the size of the dict. As I
> said before these results will not be consistent from one computer to
> another.
>
>
> Oscar
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"A computer never does what you want... only what you tell it."
    +wesley chun : wescpy at gmail : @wescpy
    Python training & consulting : http://CyberwebConsulting.com
    "Core Python" books : http://CorePython.com
    Python blog: http://wescpy.blogspot.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130507/175d55af/attachment.html>

From cybervigilante at gmail.com  Wed May  8 10:10:12 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Wed, 8 May 2013 01:10:12 -0700
Subject: [Tutor] PyScripter header?
Message-ID: <CALRAYNUOFGrDd_0dhm7shTeE2MbinSByiC-7N=RYQqK38g-EiQ@mail.gmail.com>

I'm trying PyScripter instead of Wing 101. It works fine and has a lot
more PyLearner features than Wing 101 (at the same price ;'), such as
popups showing the parameters for methods, profiler, lint,
programmable snippets, etc. It also lets you choose your Python
version and finds the right one, which is handy, since I'm learning on
3.3 but a lot of good stuff is older.

However, a new file in PyScripter always starts with:
_____________________________________________

def main():
    pass

if __name__ == '__main__':
    main()
_____________________________________________

What is that stuff?  I thought I was getting away from all this
business of defining a main entry point. I don't see it in any of the
Py library files or other Py programs.

PyScripter has enough extra features, that I'll probably switch to it.
But has anyone found any odd problems with it? Tks.

Jim

From amitsaha.in at gmail.com  Wed May  8 10:14:31 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Wed, 8 May 2013 18:14:31 +1000
Subject: [Tutor] PyScripter header?
In-Reply-To: <CALRAYNUOFGrDd_0dhm7shTeE2MbinSByiC-7N=RYQqK38g-EiQ@mail.gmail.com>
References: <CALRAYNUOFGrDd_0dhm7shTeE2MbinSByiC-7N=RYQqK38g-EiQ@mail.gmail.com>
Message-ID: <CANODV3mu43kE2bGHGVXx9TRr57pJhSJVYLn01m-x_ZaVBE7CuA@mail.gmail.com>

On Wed, May 8, 2013 at 6:10 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> I'm trying PyScripter instead of Wing 101. It works fine and has a lot
> more PyLearner features than Wing 101 (at the same price ;'), such as
> popups showing the parameters for methods, profiler, lint,
> programmable snippets, etc. It also lets you choose your Python
> version and finds the right one, which is handy, since I'm learning on
> 3.3 but a lot of good stuff is older.
>
> However, a new file in PyScripter always starts with:
> _____________________________________________
>
> def main():
>     pass
>
> if __name__ == '__main__':
>     main()
> _____________________________________________

This allows you to write your program in such a way that main() is
called only when you are running it as a standalone script.

If you import your program in another program, the condition: if
__name__=='__main__'  evaluates  to False and hence your main()
function is not called.

If you had written your program like this:

def main():
    pass

main()

Your  main() function would be called in both cases.

Some good answers here [1].

[1] http://stackoverflow.com/questions/419163/what-does-if-name-main-do


>
> What is that stuff?  I thought I was getting away from all this
> business of defining a main entry point. I don't see it in any of the
> Py library files or other Py programs.

Yes, it just a case of you defining the entry point..you are not required to.

HTH,
Amit.


--
http://echorand.me

From eryksun at gmail.com  Wed May  8 13:21:37 2013
From: eryksun at gmail.com (eryksun)
Date: Wed, 8 May 2013 07:21:37 -0400
Subject: [Tutor] PyScripter header?
In-Reply-To: <CALRAYNUOFGrDd_0dhm7shTeE2MbinSByiC-7N=RYQqK38g-EiQ@mail.gmail.com>
References: <CALRAYNUOFGrDd_0dhm7shTeE2MbinSByiC-7N=RYQqK38g-EiQ@mail.gmail.com>
Message-ID: <CACL+1atD2ZW3+-SF7EgJU3Q0qJRJBv+RtC1i2BDzv7-uhQoRFQ@mail.gmail.com>

On Wed, May 8, 2013 at 4:10 AM, Jim Mooney <cybervigilante at gmail.com> wrote:
>
> def main():
>     pass
>
> if __name__ == '__main__':
>     main()
>
> What is that stuff?  I thought I was getting away from all this
> business of defining a main entry point. I don't see it in any of the
> Py library files or other Py programs.

http://docs.python.org/3/library/__main__

For Windows multiprocessing see the "Safe import of main module" section:

http://docs.python.org/3/library/multiprocessing#windows

As to the standard library, excluding obvious test modules, I count
approximately 150 uses in 3.3.1.

http://pastebin.com/t78Aab8N

http://hg.python.org/cpython/file/d9893d13c628/Lib

In a couple of cases where the file is named __main__.py, the
following test is used instead:

    if sys.argv[0].endswith("__main__.py"):

Much of what I left in the list are entry points for tests and demos,
but there are scripts too, such as pydoc, profile, tabnanny, and the
new venv module for creating virtual environments. You can run a
module as __main__ with the -m option. For example:

    python3 -m turtledemo.clock  # POSIX
    py -3 -m turtledemo.clock  # Windows w/ pylauncher

From steve at pearwood.info  Wed May  8 13:37:54 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 08 May 2013 21:37:54 +1000
Subject: [Tutor] PyScripter header?
In-Reply-To: <CALRAYNUOFGrDd_0dhm7shTeE2MbinSByiC-7N=RYQqK38g-EiQ@mail.gmail.com>
References: <CALRAYNUOFGrDd_0dhm7shTeE2MbinSByiC-7N=RYQqK38g-EiQ@mail.gmail.com>
Message-ID: <518A3912.8090204@pearwood.info>

On 08/05/13 18:10, Jim Mooney wrote:

> However, a new file in PyScripter always starts with:
> _____________________________________________
>
> def main():
>      pass
>
> if __name__ == '__main__':
>      main()
> _____________________________________________
>
> What is that stuff?  I thought I was getting away from all this
> business of defining a main entry point. I don't see it in any of the
> Py library files or other Py programs.


It's optional, but good practice, to separate your main program out into a separate subroutine.

Of course, Python is a pragmatic language, and you can write a plain script that just does what you want directly:


=== start file ===

# A rubbish script :-)
import sys
if sys.argv[1] == "hello":
     print "And hello to you too!"
else:
     print "Bah, why don't you say hello?"

=== end file ===


That's fine if all you are doing, ever, is running the script. But for more interesting scripts, it can be useful to design it so that you can both run the script directly, and import it as a Python module. Perhaps to re-use some of the components, or for testing, or to use at the interactive interpreter.

So in this case, you should factor out the main script and guard it with a "if __name__ == '__main__' clause. That's certainly not compulsory, but it is good practice. Naturally you don't have to call the main function "main".

Are you aware of what the "if __name__" bit does?

There is a global variable called __name__. Whenever a module is imported, Python automatically sets the __name__ variable to the name of the module, minus any .py or other extension. With one exception: when you are running a module as a script, Python does a little trick: it sets __name__ to the magic value "__main__" instead of the module's actual name. So a module can tell if it is being run as a script by looking at the global variable __name__ and seeing if it is equal to "__main__".

Yes, it is a bit of a hack, but it works acceptably most of the time.



-- 
Steven

From ricaraoz at gmail.com  Wed May  8 13:38:36 2013
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Wed, 08 May 2013 08:38:36 -0300
Subject: [Tutor] PyScripter header?
In-Reply-To: <CALRAYNUOFGrDd_0dhm7shTeE2MbinSByiC-7N=RYQqK38g-EiQ@mail.gmail.com>
References: <CALRAYNUOFGrDd_0dhm7shTeE2MbinSByiC-7N=RYQqK38g-EiQ@mail.gmail.com>
Message-ID: <518A393C.1090207@gmail.com>

El 08/05/13 05:10, Jim Mooney escribi?:
>
> PyScripter has enough extra features, that I'll probably switch to it.
> But has anyone found any odd problems with it? Tks.
>
> Jim
>

Given that your main() question ;c) has been answered, you might also 
want to give Spyder a try before switching.


From steve at pearwood.info  Wed May  8 14:13:27 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 08 May 2013 22:13:27 +1000
Subject: [Tutor] Text Editors and Linux (was Re:  exit message)
In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474183A0676@SCACMX008.exchad.jpmchase.net>
References: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
	<20130507045019.GC5145@ando>
	<5B80DD153D7D744689F57F4FB69AF474183A0676@SCACMX008.exchad.jpmchase.net>
Message-ID: <518A4167.90700@pearwood.info>

On 08/05/13 00:26, Prasad, Ramit wrote:
> Steven D'Aprano wrote:
>
>> * a decent console app that supports multiple tabs;
>
> Any reason to prefer tabs to virtual terminals (i.e. screen)?


Yes. I can see tabs, and click them with a mouse, they can have a meaningful title, and I can use spacial memory to associate them with tasks. "Tests = second last tab" is more natural for me to remember than "Tests = virtual terminal 7", and clicking with the mouse is much faster for me than remembering, and typing, "Ctrl-A 7".



-- 
Steven

From bicofino at gmail.com  Wed May  8 15:31:20 2013
From: bicofino at gmail.com (Danilo Chilene)
Date: Wed, 8 May 2013 10:31:20 -0300
Subject: [Tutor] Argparse functions with N parameters
In-Reply-To: <kmb925$cn5$1@ger.gmane.org>
References: <CA+_2i1SoYXswCDcMTLT-WG9Rmsto4T6Yfnby78H0nyoUWo0udg@mail.gmail.com>
	<kmb925$cn5$1@ger.gmane.org>
Message-ID: <CA+_2i1RSfBbzZdcSUm0uHNT0uwJp_CHTAski=L+aGQ9OdZyKUQ@mail.gmail.com>

<snip>

That solves my issue.

Thanks Peter.
To unsubscribe or change subscription options:

> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130508/12e1db3e/attachment.html>

From david at graniteweb.com  Wed May  8 18:57:30 2013
From: david at graniteweb.com (David Rock)
Date: Wed, 8 May 2013 11:57:30 -0500
Subject: [Tutor] Text Editors and Linux (was Re:  exit message)
In-Reply-To: <518A4167.90700@pearwood.info>
References: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
	<20130507045019.GC5145@ando>
	<5B80DD153D7D744689F57F4FB69AF474183A0676@SCACMX008.exchad.jpmchase.net>
	<518A4167.90700@pearwood.info>
Message-ID: <20130508165730.GF31171@wdfs.graniteweb.com>

* Steven D'Aprano <steve at pearwood.info> [2013-05-08 22:13]:
> On 08/05/13 00:26, Prasad, Ramit wrote:
> > Steven D'Aprano wrote:
> >
> >> * a decent console app that supports multiple tabs;
> >
> > Any reason to prefer tabs to virtual terminals (i.e. screen)?
> 
> 
> Yes. I can see tabs, and click them with a mouse, they can have a
> meaningful title, and I can use spacial memory to associate them with
> tasks. "Tests = second last tab" is more natural for me to remember
> than "Tests = virtual terminal 7", and clicking with the mouse is much
> faster for me than remembering, and typing, "Ctrl-A 7".

Well, not to start a flame war, but that is all subjective.  I find NOT
using a mouse to be much faster, and screen can be set up pretty much
the same way you describe (specific screens for a task, labels, etc).

So it's really more about personal taste than anything.  If you _like_
what you are using, that's fine.  I wouldn't like that setup.

All options are valid options.  Try them all and find what you like.

-- 
David Rock
david at graniteweb.com

From steve at pearwood.info  Thu May  9 02:29:17 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 09 May 2013 10:29:17 +1000
Subject: [Tutor] Text Editors and Linux (was Re:  exit message)
In-Reply-To: <20130508165730.GF31171@wdfs.graniteweb.com>
References: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
	<20130507045019.GC5145@ando>
	<5B80DD153D7D744689F57F4FB69AF474183A0676@SCACMX008.exchad.jpmchase.net>
	<518A4167.90700@pearwood.info>
	<20130508165730.GF31171@wdfs.graniteweb.com>
Message-ID: <518AEDDD.7070908@pearwood.info>

On 09/05/13 02:57, David Rock wrote:
> * Steven D'Aprano <steve at pearwood.info> [2013-05-08 22:13]:
>> On 08/05/13 00:26, Prasad, Ramit wrote:
>>> Steven D'Aprano wrote:
>>>
>>>> * a decent console app that supports multiple tabs;
>>>
>>> Any reason to prefer tabs to virtual terminals (i.e. screen)?
>>
>>
>> Yes. I can see tabs, and click them with a mouse, they can have a
>> meaningful title, and I can use spacial memory to associate them with
>> tasks. "Tests = second last tab" is more natural for me to remember
>> than "Tests = virtual terminal 7", and clicking with the mouse is much
>> faster for me than remembering, and typing, "Ctrl-A 7".
>
> Well, not to start a flame war, but that is all subjective.

Did I say otherwise? I was very careful to say "more natural FOR ME, faster FOR ME".


> So it's really more about personal taste than anything.  If you _like_
> what you are using, that's fine.  I wouldn't like that setup.

I'm sure that many people wouldn't.

On the other hand, I work with, and watch, a lot of techies who live in screen. They swear that they're more efficient, but watching them hunt for the right virtual terminal doesn't look very efficient to me. I often see them flip through three or four different VTs until they reach the one they were looking for. It is especially amusing when they end up shutting down the wrong server because they've gone to the wrong vt and haven't realised it.



-- 
Steven

From david at graniteweb.com  Thu May  9 03:33:03 2013
From: david at graniteweb.com (David Rock)
Date: Wed, 8 May 2013 20:33:03 -0500
Subject: [Tutor] Text Editors and Linux (was Re:  exit message)
In-Reply-To: <518AEDDD.7070908@pearwood.info>
References: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
	<20130507045019.GC5145@ando>
	<5B80DD153D7D744689F57F4FB69AF474183A0676@SCACMX008.exchad.jpmchase.net>
	<518A4167.90700@pearwood.info>
	<20130508165730.GF31171@wdfs.graniteweb.com>
	<518AEDDD.7070908@pearwood.info>
Message-ID: <20130509013303.GH31171@wdfs.graniteweb.com>

* Steven D'Aprano <steve at pearwood.info> [2013-05-09 10:29]:
> On 09/05/13 02:57, David Rock wrote:
> >
> > Well, not to start a flame war, but that is all subjective.
> 
> Did I say otherwise? I was very careful to say "more natural FOR ME,
> faster FOR ME".

Not at all, but it was suggested that console apps were not able to do
the same thing as tabbed apps, which isn't the case.  I also didn't say
you were wrong, I just don't want an option to be overlooked because of
a personal bias.  I have no argument against tabbed environments being
more natural, because they are.  There is a steep learning curve for
many console apps, but they can be rewarding if used properly.

> > So it's really more about personal taste than anything.  If you _like_
> > what you are using, that's fine.  I wouldn't like that setup.
> 
> I'm sure that many people wouldn't.
> 
> On the other hand, I work with, and watch, a lot of techies who live
> in screen. They swear that they're more efficient, but watching them
> hunt for the right virtual terminal doesn't look very efficient to me.
> I often see them flip through three or four different VTs until they
> reach the one they were looking for. 

Then they aren't using it correctly.  My screen sessions are labeled,
and show me exactly what window I'm in, just as well as a tabbed window
does.  I don't have to remember anything any more than you do.  Someone
using a tool inefficiently does not mean that tool is inefficient.

> It is especially amusing when they end up shutting down the wrong
> server because they've gone to the wrong vt and haven't realised it.

That's not an honor reserved for users of screen.  I see the same thing
from other folks using all manner of environments, including tabbed
ones.  

-- 
David Rock
david at graniteweb.com

From ramit.prasad at jpmorgan.com  Thu May  9 06:01:14 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Thu, 9 May 2013 04:01:14 +0000
Subject: [Tutor] Text Editors and Linux (was Re:  exit message)
In-Reply-To: <518AEDDD.7070908@pearwood.info>
References: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
	<20130507045019.GC5145@ando>
	<5B80DD153D7D744689F57F4FB69AF474183A0676@SCACMX008.exchad.jpmchase.net>
	<518A4167.90700@pearwood.info>	<20130508165730.GF31171@wdfs.graniteweb.com>
	<518AEDDD.7070908@pearwood.info>
Message-ID: <5B80DD153D7D744689F57F4FB69AF474183AA4B9@SCACMX008.exchad.jpmchase.net>

Steven D'Aprano wrote:
> On the other hand, I work with, and watch, a lot of techies who live in screen. They swear that
> they're more efficient, but watching them hunt for the right virtual terminal doesn't look very
> efficient to me. I often see them flip through three or four different VTs until they reach the one
> they were looking for. It is especially amusing when they end up shutting down the wrong server
> because they've gone to the wrong vt and haven't realised it.
> 

Not intending to start (or continue) a flame war, but wanted to point out that 

ctrl+a, <double quote>

will list all screen titles and let you navigate using arrow keys or typing in the number.
Of course, that assumes you correctly title your virtual terminal sessions. 

I was mostly curious because they seem roughly equivalent and mostly dependant on the
terminal I am using. I was wondering if maybe there was a trick or two that I was missing.

What I like about screen is the way sessions stay open when disconnected, but I find
tabbed terminals easier to scroll for history. If there is a tabbed terminal that will allow
split screens then all the neat features I know about in screen would exist...although
I rarely use that feature at the moment.


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

From alan.gauld at btinternet.com  Thu May  9 08:47:20 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 09 May 2013 07:47:20 +0100
Subject: [Tutor] Text Editors and Linux (was Re:  exit message)
In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474183AA4B9@SCACMX008.exchad.jpmchase.net>
References: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
	<20130507045019.GC5145@ando>
	<5B80DD153D7D744689F57F4FB69AF474183A0676@SCACMX008.exchad.jpmchase.net>
	<518A4167.90700@pearwood.info>	<20130508165730.GF31171@wdfs.graniteweb.com>
	<518AEDDD.7070908@pearwood.info>
	<5B80DD153D7D744689F57F4FB69AF474183AA4B9@SCACMX008.exchad.jpmchase.net>
Message-ID: <kmfgpj$bfr$1@ger.gmane.org>

On 09/05/13 05:01, Prasad, Ramit wrote:

> What I like about screen is the way sessions stay open when disconnected, but I find
> tabbed terminals easier to scroll for history. If there is a tabbed terminal that will allow
> split screens then all the neat features I know about in screen would exist...although
> I rarely use that feature at the moment.

Can't you use screen within a tabbed terminal?

Just a thought...

Or use emacs... :-)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From davea at davea.name  Thu May  9 13:02:33 2013
From: davea at davea.name (Dave Angel)
Date: Thu, 09 May 2013 07:02:33 -0400
Subject: [Tutor] Text Editors and Linux (was Re:  exit message)
In-Reply-To: <kmfgpj$bfr$1@ger.gmane.org>
References: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
	<20130507045019.GC5145@ando>
	<5B80DD153D7D744689F57F4FB69AF474183A0676@SCACMX008.exchad.jpmchase.net>
	<518A4167.90700@pearwood.info>	<20130508165730.GF31171@wdfs.graniteweb.com>
	<518AEDDD.7070908@pearwood.info>
	<5B80DD153D7D744689F57F4FB69AF474183AA4B9@SCACMX008.exchad.jpmchase.net>
	<kmfgpj$bfr$1@ger.gmane.org>
Message-ID: <518B8249.5000709@davea.name>

On 05/09/2013 02:47 AM, Alan Gauld wrote:
> On 09/05/13 05:01, Prasad, Ramit wrote:
>
>> What I like about screen is the way sessions stay open when
>> disconnected, but I find
>> tabbed terminals easier to scroll for history. If there is a tabbed
>> terminal that will allow
>> split screens then all the neat features I know about in screen would
>> exist...although
>> I rarely use that feature at the moment.
>
> Can't you use screen within a tabbed terminal?
>

I was going to jump in earlier with basically that comment.  When I'm 
logging in remotely, I use screen on the remote machine, and use only 
one ssh connection.  I have a .screen on each such machine, that changes 
a few defaults, and adds titles.  The titles represent different things 
I'm doing on the remote machine.

One chief advantage (for me) of using screen for that is that the VPN 
dies pretty easily, and I can reconnect to any given machine with only a 
couple of commands, since screen is still running remotely.

On my own machine, I use tabs, with only one tab for each given remote 
machine.  Those tabs are then labeled with the name of the remote machine.



-- 
DaveA

From fomcl at yahoo.com  Thu May  9 14:10:41 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Thu, 9 May 2013 05:10:41 -0700 (PDT)
Subject: [Tutor] MutableString/Class variables
Message-ID: <1368101441.50427.YahooMailNeo@web163805.mail.gq1.yahoo.com>

Hello,

I was just playing a bit with Python and I wanted to make a mutable string, that supports item assignment. Is the way below the way to do this??
The part I am not sure about is the class variable. Maybe I should also have reimplemented __init__, then call super inside this and add an updated version of "self" so __repr__ and __str__ return that. More general: when should class variables be used? I am reading about Django nd there they are all over the place, yet I have always had the impression their use is not that common.


# Python 2.7.3 (default, Sep 26 2012, 21:53:58)? [GCC 4.7.2] on linux2

class MutableStr(str):
??? s = None
??? def __repr__(self):
??? ??? return MutableStr.s
??? def __str__(self):
??? ??? return MutableStr.s
??? def __setitem__(self, key, item):
??? ??? ?print self[:key], item, self[key+1:]
??? ??? ?self = MutableStr.s = self[:key] + item + self[key+1:]
???? ??? ?return self

# all results below are as intended ??? ??? 
>>> mstr = MutableStr("01234X678")
>>> mstr[5] = "&"
01234 & 678
>>> mstr
01234&678
>>> str(mstr)
'01234&678'
>>> unicode(mstr)
u'01234&678'

Regards,
Albert-Jan


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
?~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~?

From alan.gauld at btinternet.com  Thu May  9 14:23:42 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 09 May 2013 13:23:42 +0100
Subject: [Tutor] MutableString/Class variables
In-Reply-To: <1368101441.50427.YahooMailNeo@web163805.mail.gq1.yahoo.com>
References: <1368101441.50427.YahooMailNeo@web163805.mail.gq1.yahoo.com>
Message-ID: <kmg4g9$rrm$1@ger.gmane.org>

On 09/05/13 13:10, Albert-Jan Roskam wrote:

> class MutableStr(str):
>      s = None

Why make s a class variable?
I'd expect it to be an instance attribute.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From davea at davea.name  Thu May  9 14:42:53 2013
From: davea at davea.name (Dave Angel)
Date: Thu, 09 May 2013 08:42:53 -0400
Subject: [Tutor] MutableString/Class variables
In-Reply-To: <1368101441.50427.YahooMailNeo@web163805.mail.gq1.yahoo.com>
References: <1368101441.50427.YahooMailNeo@web163805.mail.gq1.yahoo.com>
Message-ID: <518B99CD.90002@davea.name>

On 05/09/2013 08:10 AM, Albert-Jan Roskam wrote:
> Hello,
>
> I was just playing a bit with Python and I wanted to make a mutable string, that supports item assignment. Is the way below the way to do this?
> The part I am not sure about is the class variable. Maybe I should also have reimplemented __init__, then call super inside this and add an updated version of "self" so __repr__ and __str__ return that. More general: when should class variables be used? I am reading about Django nd there they are all over the place, yet I have always had the impression their use is not that common.
>

You use a class attribute (not class variable) whenever you want to have 
exactly one such value for the entire program.  If you want to be able 
to manipulate more than one, then you use an instance attribute, 
typically inside the __init__() method.

Your code will fail totally as soon as you try to make a second such 
variable.
     a = MutableStr("01234")
     b = MutableStr("ABCDEFG")

As for how to do it by inheriting from str, I have no idea.  I know that 
inheriting from native types, you generally need to override __new__() 
instead of, or in addition to __init__().  But modifying self the way 
you do in MutableStr isn't going to work the way you expect.  You're 
just modifying a local variable inside the method.  And __setitem__ 
needn't return a value, since nobody's going to look at it.

If I were doing it, I'd have an instance attribute for the string.  But 
I don't know how I could do it without rewriting nearly every str method 
in my class.

>
> # Python 2.7.3 (default, Sep 26 2012, 21:53:58)  [GCC 4.7.2] on linux2
>
> class MutableStr(str):
>      s = None
>      def __repr__(self):
>          return MutableStr.s
>      def __str__(self):
>          return MutableStr.s
>      def __setitem__(self, key, item):
>           print self[:key], item, self[key+1:]
>           self = MutableStr.s = self[:key] + item + self[key+1:]
>            return self
>
> # all results below are as intended
>>>> mstr = MutableStr("01234X678")
>>>> mstr[5] = "&"
> 01234 & 678
>>>> mstr
> 01234&678
>>>> str(mstr)
> '01234&678'
>>>> unicode(mstr)
> u'01234&678'
>


-- 
DaveA

From fomcl at yahoo.com  Thu May  9 15:16:49 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Thu, 9 May 2013 06:16:49 -0700 (PDT)
Subject: [Tutor] MutableString/Class variables
In-Reply-To: <518B99CD.90002@davea.name>
References: <1368101441.50427.YahooMailNeo@web163805.mail.gq1.yahoo.com>
	<518B99CD.90002@davea.name>
Message-ID: <1368105409.66150.YahooMailNeo@web163803.mail.gq1.yahoo.com>



> Subject: Re: [Tutor] MutableString/Class variables
> 
> On 05/09/2013 08:10 AM, Albert-Jan Roskam wrote:
>>  Hello,
>> 
>>  I was just playing a bit with Python and I wanted to make a mutable string, 
> that supports item assignment. Is the way below the way to do this?
>>  The part I am not sure about is the class variable. Maybe I should also 
> have reimplemented __init__, then call super inside this and add an updated 
> version of "self" so __repr__ and __str__ return that. More general: 
> when should class variables be used? I am reading about Django nd there they are 
> all over the place, yet I have always had the impression their use is not that 
> common.
>> 
> 
> You use a class attribute (not class variable) whenever you want to have 
> exactly one such value for the entire program.? If you want to be able 
> to manipulate more than one, then you use an instance attribute, 
> typically inside the __init__() method.

Hmmm, so is it fair to say that this is the OOP equivalent of 'nonlocal' in Python 3? It has meaning inside the entire scope of the class, not outside it, there not 'global'.

Here's a modified version; in my previous attempts I messed up the arguments of super(). ;-) This feels better. But then again, I never *really* understood __new__ entirely.

class MutableStr(str):
??? def __init__(self, s):
??????? super(str, MutableStr).__init__(s)
??????? self.s = s
??? def __repr__(self):
??????? return self.s
??? def __str__(self):
??????? return self.s
??? def __setitem__(self, key, item):
??????? self.s = self[:key] + item + self[key+1:]

# produce results as intended
mstr = MutableStr("01234X678")
mstr[5] = "&"
print str(mstr)
print unicode(mstr)
mstr = MutableStr("01234X678")
mstr[8] = "&"
print str(mstr)
print unicode(mstr)

# output:
01234&678
01234&678
01234X67&
01234X67&


From oscar.j.benjamin at gmail.com  Thu May  9 15:47:23 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Thu, 9 May 2013 14:47:23 +0100
Subject: [Tutor] MutableString/Class variables
In-Reply-To: <1368105409.66150.YahooMailNeo@web163803.mail.gq1.yahoo.com>
References: <1368101441.50427.YahooMailNeo@web163805.mail.gq1.yahoo.com>
	<518B99CD.90002@davea.name>
	<1368105409.66150.YahooMailNeo@web163803.mail.gq1.yahoo.com>
Message-ID: <CAHVvXxR_hJa7Nzd+xU95ns3ynqR7JRes_PKVph5g5X7pMuCEQg@mail.gmail.com>

On 9 May 2013 14:16, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
>
>
>> Subject: Re: [Tutor] MutableString/Class variables
>>
>> On 05/09/2013 08:10 AM, Albert-Jan Roskam wrote:
>>>  Hello,
>>>
>>>  I was just playing a bit with Python and I wanted to make a mutable string,
>> that supports item assignment. Is the way below the way to do this?
>>>  The part I am not sure about is the class variable. Maybe I should also
>> have reimplemented __init__, then call super inside this and add an updated
>> version of "self" so __repr__ and __str__ return that. More general:
>> when should class variables be used? I am reading about Django nd there they are
>> all over the place, yet I have always had the impression their use is not that
>> common.

Django code often uses classes to hold collections of essentially
static data. An example from the docs:

from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

In the code above the class attributes are used to customise the
behaviour of the models.Model class. This is quite nicely presented
compared with more typical ways of doing it e.g.:

Poll = models.Model(question = models.CharField(max_length=200)
                    pub_date = models.DateTimeField('date published'))

or perhaps something like

Poll = models.Model()
Poll.add(question = models.CharField(max_length=200))
Poll.add(pub_date = models.DateTimeField('date published'))



>>>
>>
>> You use a class attribute (not class variable) whenever you want to have
>> exactly one such value for the entire program.  If you want to be able
>> to manipulate more than one, then you use an instance attribute,
>> typically inside the __init__() method.
>
> Hmmm, so is it fair to say that this is the OOP equivalent of 'nonlocal' in Python 3? It has meaning inside the entire scope of the class, not outside it, there not 'global'.

Class attributes can be accessed from a class or an instance whereas
instance attributes are only accessible from an instance:

>>> class A:
...   class_attribute = 1
...   def __init__(self):
...     self.instance_attribute = 2
...
>>> a = A()
>>> a.instance_attribute
2
>>> a.class_attribute
1
>>> A.class_attribute
1
>>> A.instance_attribute
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: class A has no attribute 'instance_attribute'


>
> Here's a modified version; in my previous attempts I messed up the arguments of super(). ;-) This feels better. But then again, I never *really* understood __new__ entirely.
>
> class MutableStr(str):

You don't want to inherit from str. You want a mutable string and if
you inherit from str you will awlays be extending an immutable builtin
object. All of the inherited string methods will use that immutable
data and ignore any extra data that you associate with your instances
(or your class). This means that there is no point in inheriting them.
Otherwise you should override all of them since your class would have
a load of methods that do the wrong thing.

What happens if you have an instance of your class, mutate it and then
call its join method? What happens if you create two equal instances,
mutate them to be different and try to use both as dictionary keys? Or
if you compare them with a==b?

>     def __init__(self, s):
>         super(str, MutableStr).__init__(s)
>         self.s = s

If you're storing the string as an attribute there's really no point
in inheriting from str.

>     def __repr__(self):
>         return self.s
>     def __str__(self):
>         return self.s

You don't need both of __repr__ and __str__ if they just do the same thing.

>     def __setitem__(self, key, item):
>         self.s = self[:key] + item + self[key+1:]

You should probably also have __setslice__, __getslice__, __getitem__,
and so on.

> # produce results as intended
> mstr = MutableStr("01234X678")
> mstr[5] = "&"
> print str(mstr)
> print unicode(mstr)
> mstr = MutableStr("01234X678")
> mstr[8] = "&"
> print str(mstr)
> print unicode(mstr)

What about "print mstr[8]" (you need to override __getitem__)?

> # output:
> 01234&678
> 01234&678
> 01234X67&
> 01234X67&

By the way since you're using Python 2 your strings are all byte
strings so you can get a mutable string easily using a bytearray:

>>> b = bytearray('hello')
>>> b
bytearray(b'hello')
>>> b[2] = 'r'
>>> b
bytearray(b'herlo')
>>> bytearray
<type 'bytearray'>

Note that bytearray already implements all of the string methods:

>>> dir(bytearray)
['__add__', '__alloc__', '__class__', '__contains__', '__delattr__',
'__delitem__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__',
'__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__',
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__',
'__str__', '__subclasshook__', 'append', 'capitalize', 'center',
'count', 'decode', 'endswith', 'expandtabs', 'extend', 'find',
'fromhex', 'index', 'insert', 'isalnum', 'isalpha', 'isdigit',
'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower',
'lstrip', 'partition', 'pop', 'remove', 'replace',
'reverse', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']

All you need to do is override __str__ and this will look just like a
mutable string.


Oscar

From davea at davea.name  Thu May  9 16:26:21 2013
From: davea at davea.name (Dave Angel)
Date: Thu, 09 May 2013 10:26:21 -0400
Subject: [Tutor] MutableString/Class variables
In-Reply-To: <1368105409.66150.YahooMailNeo@web163803.mail.gq1.yahoo.com>
References: <1368101441.50427.YahooMailNeo@web163805.mail.gq1.yahoo.com>
	<518B99CD.90002@davea.name>
	<1368105409.66150.YahooMailNeo@web163803.mail.gq1.yahoo.com>
Message-ID: <518BB20D.5090404@davea.name>

On 05/09/2013 09:16 AM, Albert-Jan Roskam wrote:
>
>
>> Subject: Re: [Tutor] MutableString/Class variables
>>
>> On 05/09/2013 08:10 AM, Albert-Jan Roskam wrote:
>>>   Hello,
>>>
>>>   I was just playing a bit with Python and I wanted to make a mutable string,
>> that supports item assignment. Is the way below the way to do this?
>>>   The part I am not sure about is the class variable. Maybe I should also
>> have reimplemented __init__, then call super inside this and add an updated
>> version of "self" so __repr__ and __str__ return that. More general:
>> when should class variables be used? I am reading about Django nd there they are
>> all over the place, yet I have always had the impression their use is not that
>> common.
>>>
>>
>> You use a class attribute (not class variable) whenever you want to have
>> exactly one such value for the entire program.  If you want to be able
>> to manipulate more than one, then you use an instance attribute,
>> typically inside the __init__() method.
>
> Hmmm, so is it fair to say that this is the OOP equivalent of 'nonlocal' in Python 3? It has meaning inside the entire scope of the class, not outside it, there not 'global'.
>
> Here's a modified version; in my previous attempts I messed up the arguments of super(). ;-) This feels better. But then again, I never *really* understood __new__ entirely.
>
> class MutableStr(str):
>      def __init__(self, s):
>          super(str, MutableStr).__init__(s)
>          self.s = s
>      def __repr__(self):
>          return self.s
>      def __str__(self):
>          return self.s
>      def __setitem__(self, key, item):
>          self.s = self[:key] + item + self[key+1:]
>
> # produce results as intended
> mstr = MutableStr("01234X678")
> mstr[5] = "&"
> print str(mstr)
> print unicode(mstr)
> mstr = MutableStr("01234X678")
> mstr[8] = "&"
> print str(mstr)
> print unicode(mstr)
>
> # output:
> 01234&678
> 01234&678
> 01234X67&
> 01234X67&
>
>
>

That's all well and good as long as you only use those particular 
methods.  But try:

print "aaa" + mstr
    #The changes you made to mstr have "vanished"

print(type(mstr))
mstr += "def"
print(mstr)
print(type(mstr))
     #now it's no longer a MutablsStr


-- 
DaveA

From staffordbaines at yahoo.com  Thu May  9 16:36:04 2013
From: staffordbaines at yahoo.com (Stafford Baines)
Date: Thu, 9 May 2013 15:36:04 +0100
Subject: [Tutor] Pi xels
Message-ID: <F701860B-8FA2-495F-A1AC-C831B9B64631@yahoo.com>

Is there a way of controlling pixels on a graphics screen? I want to be able to draw lines and curves. Is this possible with with Python?

Stafford

Sent from my iPhone

From david at graniteweb.com  Thu May  9 16:42:30 2013
From: david at graniteweb.com (David Rock)
Date: Thu, 9 May 2013 09:42:30 -0500
Subject: [Tutor] Text Editors and Linux (was Re:  exit message)
In-Reply-To: <kmfgpj$bfr$1@ger.gmane.org>
References: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
	<20130507045019.GC5145@ando>
	<5B80DD153D7D744689F57F4FB69AF474183A0676@SCACMX008.exchad.jpmchase.net>
	<518A4167.90700@pearwood.info>
	<20130508165730.GF31171@wdfs.graniteweb.com>
	<518AEDDD.7070908@pearwood.info>
	<5B80DD153D7D744689F57F4FB69AF474183AA4B9@SCACMX008.exchad.jpmchase.net>
	<kmfgpj$bfr$1@ger.gmane.org>
Message-ID: <20130509144230.GB32155@wdfs.graniteweb.com>

* Alan Gauld <alan.gauld at btinternet.com> [2013-05-09 07:47]:
> On 09/05/13 05:01, Prasad, Ramit wrote:
> 
> > What I like about screen is the way sessions stay open when
> > disconnected, but I find tabbed terminals easier to scroll for
> > history. If there is a tabbed terminal that will allow split screens
> > then all the neat features I know about in screen would
> > exist...although I rarely use that feature at the moment.
> 
> Can't you use screen within a tabbed terminal?
> 
> Just a thought...
> 

Actually, no (at least not for scrolling). If you scroll in a window
that has screen running, you won't scroll the content of the screen
session, which is what you actually want to see.  It will just show
what's in the buffer from before starting the screen session.  You would
still need to use the scrollback buffer in screen (ctrl-a ESC), which
again, works well, but is not necessarily intuitive.

> Or use emacs... :-)

There's always one.  You aren't helping the case for console apps with
that one at all.  :-)

-- 
David Rock
david at graniteweb.com

From david at graniteweb.com  Thu May  9 16:57:13 2013
From: david at graniteweb.com (David Rock)
Date: Thu, 9 May 2013 09:57:13 -0500
Subject: [Tutor] Text Editors and Linux (was Re:  exit message)
In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474183AA4B9@SCACMX008.exchad.jpmchase.net>
References: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
	<20130507045019.GC5145@ando>
	<5B80DD153D7D744689F57F4FB69AF474183A0676@SCACMX008.exchad.jpmchase.net>
	<518A4167.90700@pearwood.info>
	<20130508165730.GF31171@wdfs.graniteweb.com>
	<518AEDDD.7070908@pearwood.info>
	<5B80DD153D7D744689F57F4FB69AF474183AA4B9@SCACMX008.exchad.jpmchase.net>
Message-ID: <20130509145713.GC32155@wdfs.graniteweb.com>

* Prasad, Ramit <ramit.prasad at jpmorgan.com> [2013-05-09 04:01]:
> Steven D'Aprano wrote:
> > On the other hand, I work with, and watch, a lot of techies who live
> > in screen. They swear that they're more efficient, but watching them
> > hunt for the right virtual terminal doesn't look very efficient to
> > me. I often see them flip through three or four different VTs until
> > they reach the one they were looking for. It is especially amusing
> > when they end up shutting down the wrong server because they've gone
> > to the wrong vt and haven't realised it.
> > 
> 
> ctrl+a, <double quote>
> 
> will list all screen titles and let you navigate using arrow keys or
> typing in the number.  Of course, that assumes you correctly title
> your virtual terminal sessions. 
> 
> I was mostly curious because they seem roughly equivalent and mostly
> dependant on the terminal I am using. I was wondering if maybe there
> was a trick or two that I was missing.

I'll defend Steven on this one.  Yes, that works, but it's far from
efficient.  What I use in my .screenrc is:
hardstatus alwayslastline "%w"

Which effectively puts titled tabs on the last row of the screen.
Admittedly, if you have a lot of sessions open, you are limited by space
a bit doing this, in which case the ctrl+a " may be necessary, but you
have bigger issues if you have that many open at one time. :-)

> What I like about screen is the way sessions stay open when
> disconnected, but I find tabbed terminals easier to scroll for
> history. If there is a tabbed terminal that will allow split screens
> then all the neat features I know about in screen would
> exist...although I rarely use that feature at the moment.

Yes, the disconnect/reconnect is nice (I use it a lot). It's not exactly
relevant to merits of console interfaces vs GUI, though.  That's more of
a "this is a cool baked-in capability for working with lousy network
connections", which you can also do with things like VNC for a remote
GUI.

-- 
David Rock
david at graniteweb.com

From hugo.yoshi at gmail.com  Thu May  9 17:12:39 2013
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Thu, 9 May 2013 17:12:39 +0200
Subject: [Tutor] Pi xels
In-Reply-To: <F701860B-8FA2-495F-A1AC-C831B9B64631@yahoo.com>
References: <F701860B-8FA2-495F-A1AC-C831B9B64631@yahoo.com>
Message-ID: <CAJmBOfnu6e7MOjoKJMtzt_6LT4XNi6f5PuOLUbViD6tinSqZ2g@mail.gmail.com>

On Thu, May 9, 2013 at 4:36 PM, Stafford Baines <staffordbaines at yahoo.com>wrote:

> Is there a way of controlling pixels on a graphics screen? I want to be
> able to draw lines and curves. Is this possible with with Python?
>
> Stafford
>

There are various libraries available for drawing. Check these links, they
might be useful:

http://stackoverflow.com/questions/326300/python-best-library-for-drawing
http://wiki.python.org/moin/GuiProgramming
http://programmers.stackexchange.com/questions/62069/what-good-graphics-libraries-are-there-for-python-not-necessarily-having-to-be


HTH,
Hugo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130509/7b042e2e/attachment.html>

From alan.gauld at btinternet.com  Thu May  9 17:50:37 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 09 May 2013 16:50:37 +0100
Subject: [Tutor] Text Editors and Linux (was Re:  exit message)
In-Reply-To: <20130509144230.GB32155@wdfs.graniteweb.com>
References: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
	<20130507045019.GC5145@ando>
	<5B80DD153D7D744689F57F4FB69AF474183A0676@SCACMX008.exchad.jpmchase.net>
	<518A4167.90700@pearwood.info>
	<20130508165730.GF31171@wdfs.graniteweb.com>
	<518AEDDD.7070908@pearwood.info>
	<5B80DD153D7D744689F57F4FB69AF474183AA4B9@SCACMX008.exchad.jpmchase.net>
	<kmfgpj$bfr$1@ger.gmane.org>
	<20130509144230.GB32155@wdfs.graniteweb.com>
Message-ID: <kmggk8$581$1@ger.gmane.org>

On 09/05/13 15:42, David Rock wrote:

>> Or use emacs... :-)
>
> There's always one.  You aren't helping the case for console apps with
> that one at all.  :-)

Not necessarily since you can run  emacs in a non GUI mode and create 
multiple shell buffers. Each of these can be scrolled/split etc. (In 
fact the original reason I started using emacs back in the late '80s was 
the ability to connect to different machines and run remote shells as 
well as remotely view/edit files via archie...a kind of prototypical web 
for those too young to remember! And all on a VT220... :-)

But the OP wasn't specifically asking about console apps just the use of 
"Linux as an IDE" and emacs, even in its GUI format, definitely plays in 
that space, it can use grep/errors/trace etc. as well as present 
multiple 'consoles'.

But then emacs can also be considered an IDE in its own right so its 
maybe a special case.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From steve at pearwood.info  Thu May  9 20:26:12 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 10 May 2013 04:26:12 +1000
Subject: [Tutor] Pi xels
In-Reply-To: <F701860B-8FA2-495F-A1AC-C831B9B64631@yahoo.com>
References: <F701860B-8FA2-495F-A1AC-C831B9B64631@yahoo.com>
Message-ID: <518BEA44.5010107@pearwood.info>

On 10/05/13 00:36, Stafford Baines wrote:
> Is there a way of controlling pixels on a graphics screen? I want to be able to draw lines and curves. Is this possible with with Python?


There are many powerful libraries for working with graphics in Python, but they often have a very steep learning curve. An easy place to start is with the turtle graphics module, inspired by Logo.

http://docs.python.org/2/library/turtle.html

http://docs.python.org/3/library/turtle.html


-- 
Steven

From johnsteedman360 at gmail.com  Thu May  9 21:38:05 2013
From: johnsteedman360 at gmail.com (John Steedman)
Date: Thu, 9 May 2013 20:38:05 +0100
Subject: [Tutor] Fwd:  Pi xels
In-Reply-To: <F701860B-8FA2-495F-A1AC-C831B9B64631@yahoo.com>
References: <F701860B-8FA2-495F-A1AC-C831B9B64631@yahoo.com>
Message-ID: <CAF50Yh8SUxG3F6Y01Jw1S=Oz0MEZqLL2L5su8dzBJkcupsZ_KQ@mail.gmail.com>

I once dabbled with wxPython.  The code below may not run straight off as
I've cut it out of a bigger routine, but it may give you a flavour of a
basic (very basic) set up.

import wx

import math

def drawCircle (radius, canvas, strCol):

  centre = (100,100)
  cX = centre[0]
  cY = centre[1]

  dc = canvas
  dc.SetPen(wx.Pen(strCol, 5))

  x1 = 0
  y1 = math.sqrt ( math.pow (radius,2) - math.pow(x1, 2) )

  for x2 in range ( 1, radius + 1 , 1 ):

    y2 = math.sqrt ( math.pow (radius,2) - math.pow(x2, 2) )
    dc.DrawLine ( cX+ x1 , yCorr ( cY + y1 ), cX + x2, yCorr (cY + y2) )
    dc.DrawLine ( cX+ x1 , yCorr ( cY - y1 ), cX + x2, yCorr (cY - y2) )
    dc.DrawLine ( cX- x1 , yCorr ( cY + y1 ), cX - x2, yCorr (cY + y2) )
    dc.DrawLine ( cX- x1 , yCorr ( cY - y1 ), cX - x2, yCorr (cY - y2) )

    y1 = y2
    x1 = x2


def on_paint(event):
  dc = wx.PaintDC(event.GetEventObject())
  dc.Clear()
  drawCircle ( 50, dc, 'GREEN')


app = wx.App(False)


frame = wx.Frame(None, title="Draw on Panel")
panel = wx.Panel(frame)
panel.Bind(wx.EVT_PAINT, on_paint)
#panel.Bind(wx.EVT_LEFT_DOWN, on_mouseClick)

panel.SetFocusIgnoringChildren()
panel.Bind(wx.EVT_KEY_DOWN, on_KeyDown )

frame.Show(True)
app.MainLoop()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130509/bc471403/attachment.html>

From david at graniteweb.com  Thu May  9 22:19:48 2013
From: david at graniteweb.com (David Rock)
Date: Thu, 9 May 2013 15:19:48 -0500
Subject: [Tutor] Text Editors and Linux (was Re:  exit message)
In-Reply-To: <kmggk8$581$1@ger.gmane.org>
References: <CAF3XjbxCnrC1b9Ex902h74hX04MVnd29CZBaCuGEKkLgzPca+w@mail.gmail.com>
	<20130507045019.GC5145@ando>
	<5B80DD153D7D744689F57F4FB69AF474183A0676@SCACMX008.exchad.jpmchase.net>
	<518A4167.90700@pearwood.info>
	<20130508165730.GF31171@wdfs.graniteweb.com>
	<518AEDDD.7070908@pearwood.info>
	<5B80DD153D7D744689F57F4FB69AF474183AA4B9@SCACMX008.exchad.jpmchase.net>
	<kmfgpj$bfr$1@ger.gmane.org>
	<20130509144230.GB32155@wdfs.graniteweb.com>
	<kmggk8$581$1@ger.gmane.org>
Message-ID: <20130509201948.GD32155@wdfs.graniteweb.com>

* Alan Gauld <alan.gauld at btinternet.com> [2013-05-09 16:50]:
> On 09/05/13 15:42, David Rock wrote:
> 
> >> Or use emacs... :-)
> >
> > There's always one.  You aren't helping the case for console apps with
> > that one at all.  :-)
> 
> But then emacs can also be considered an IDE in its own right so its 
> maybe a special case.

Yeah, emacs is definitely a special case.  There aren't many examples
out there of a single application that can do so many things.  :-)

-- 
David Rock
david at graniteweb.com

From alan.gauld at btinternet.com  Thu May  9 23:05:13 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 09 May 2013 22:05:13 +0100
Subject: [Tutor] Pi xels
In-Reply-To: <F701860B-8FA2-495F-A1AC-C831B9B64631@yahoo.com>
References: <F701860B-8FA2-495F-A1AC-C831B9B64631@yahoo.com>
Message-ID: <kmh324$dhg$1@ger.gmane.org>

On 09/05/13 15:36, Stafford Baines wrote:
> Is there a way of controlling pixels on a graphics screen?
 > I want to be able to draw lines and curves.
 > Is this possible with with Python?

Yes, there are lots of options.

Any GUI library will have a canvas object upon which you can draw 
primitive graphics like lines and curves. This includes the Tkinter 
library that comes with Python.

There are also graphing/plotting libraries if that's what you
want to produce.

There are games libraries if you want to play games.

There are also interfaces to standard graphics tools
like OpenGL too.

There is PIL for manipulating graphics produced in other tools

And also you can use third party tools like ImageMagick

It all depends on how sophisticated you want to be and
what your performance constraints are.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From cybervigilante at gmail.com  Fri May 10 02:37:35 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Thu, 9 May 2013 17:37:35 -0700
Subject: [Tutor] Tutor Digest, Vol 111, Issue 19
In-Reply-To: <mailman.8282.1368059375.3113.tutor@python.org>
References: <mailman.8282.1368059375.3113.tutor@python.org>
Message-ID: <CALRAYNVtKsetcWmJyOn4PVYBB0bUDcJ21R9Ajj55+eZ6OE7HHA@mail.gmail.com>

> Given that your main() question ;c) has been answered, you might also
> want to give Spyder a try before switching.

Thanks - I'll try that if it's not overkill for a basic learning tool,
or has a ton of dependencies I have to install, or isn't  up to Py3.3.

PyScripter had an odd bug. Whenever I started a parentheses or dot,
for a function or method, it would autocomplete the paren, then pop up
a type error warning. On dots it popped up every other letter I typed.
Quite annoying, so I've turned it off until I see if there's a tweak
to fix that or I'm just doing something stupid (which is always
possible ;')

Jim

From cybervigilante at gmail.com  Fri May 10 07:45:17 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Thu, 9 May 2013 22:45:17 -0700
Subject: [Tutor] bad name in module
Message-ID: <CALRAYNXjxqSeteYjiTkMoMoLkAF8kpfS64T-8rTY1FfYJwywRg@mail.gmail.com>

I have a simple program, below, to create a specified list of random
integers, which works fine.
I saved it to Lib as makeRandomList.py, then imported it to a
sorter.py program, like so. The import doesn't fail:

import makeRandomList

newRandomList = createRandomList()

  But I then get the following error:

File "c:\Python33\Progs\sorter.py", line 3, in <module>
builtins.NameError: name 'createRandomList' is not defined

  What am I doing wrong in creating the library module below, which
works fine as a standalone?

====================================  program saved to Lib directory
as makeRandomList.py
import random
random.seed()

def createRandomList():
    while True:
        listLength = input("How big a list do ya want, Corky? ")
        try:
            listLength = int(listLength)
            break
        except:
            print("That's not an integer, Corky - try again: ")

    while True:
        maxNumberSize = input("How big should the biggest number in
the list be? ")
        try:
            maxNumberSize = int(maxNumberSize)
            break
        except:
            print("That's not an integer, Corky - try again: ")

    randomList = []

    for c in range(0,listLength):
        randNum = random.randint(0,maxNumberSize)
        randomList.append(randNum)

    return randomList


-- 
Jim Mooney

?For anything that matters, the timing is never quite right, the
resources are always a little short, and the people who affect the
outcome are always ambivalent.?

From alan.gauld at btinternet.com  Fri May 10 08:33:58 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 10 May 2013 07:33:58 +0100
Subject: [Tutor] bad name in module
In-Reply-To: <CALRAYNXjxqSeteYjiTkMoMoLkAF8kpfS64T-8rTY1FfYJwywRg@mail.gmail.com>
References: <CALRAYNXjxqSeteYjiTkMoMoLkAF8kpfS64T-8rTY1FfYJwywRg@mail.gmail.com>
Message-ID: <kmi4ch$i76$1@ger.gmane.org>

On 10/05/13 06:45, Jim Mooney wrote:

> import makeRandomList
>
> newRandomList = createRandomList()
>

As with any other module you need to specify the module when using its 
contents:

newRandomList = makeRandomList.createRandomList()

BTW. A better name for the module is probably just randomlist

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From davea at davea.name  Fri May 10 11:50:02 2013
From: davea at davea.name (Dave Angel)
Date: Fri, 10 May 2013 05:50:02 -0400
Subject: [Tutor] bad name in module
In-Reply-To: <CALRAYNXjxqSeteYjiTkMoMoLkAF8kpfS64T-8rTY1FfYJwywRg@mail.gmail.com>
References: <CALRAYNXjxqSeteYjiTkMoMoLkAF8kpfS64T-8rTY1FfYJwywRg@mail.gmail.com>
Message-ID: <518CC2CA.4010405@davea.name>

On 05/10/2013 01:45 AM, Jim Mooney wrote:
> I have a simple program, below, to create a specified list of random
> integers, which works fine.
> I saved it to Lib as makeRandomList.py, then imported it to a
> sorter.py program, like so. The import doesn't fail:
>
> import makeRandomList
>
> newRandomList = createRandomList()
>
>    But I then get the following error:
>
> File "c:\Python33\Progs\sorter.py", line 3, in <module>
> builtins.NameError: name 'createRandomList' is not defined
>
>    What am I doing wrong in creating the library module below, which
> works fine as a standalone?
>

The module is fine, but you need to understand better how to reference 
it when importing.

The normal import statement makes a namespace, which contains all the 
top-level symbols in the module.

So  import makeRandomList

creates a new namespace makeRandomList, which contains in this case one 
symbol.  To call the function, you need to use that namespace:

newRandomList = makeRandomList.createRandomList()


Alternatively, if there are only a few symbols (one in this case) you 
need from the imported namespace, you can name them in the other import 
form:

from makeRandomList import createRandomList

Now you can just call createRandomList() directly.


These are the same rules you use when importing from somebody else's 
library.  So when you want to use the argv symbol from the sys library, 
you can either do this:

import sys

and use  sys.argv in your code.  Or you can use

from sys import argv

and now you can use argv directly.



-- 
DaveA

From fomcl at yahoo.com  Fri May 10 12:42:52 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Fri, 10 May 2013 03:42:52 -0700 (PDT)
Subject: [Tutor] MutableString/Class variables
In-Reply-To: <518BB20D.5090404@davea.name>
References: <1368101441.50427.YahooMailNeo@web163805.mail.gq1.yahoo.com>
	<518B99CD.90002@davea.name>
	<1368105409.66150.YahooMailNeo@web163803.mail.gq1.yahoo.com>
	<518BB20D.5090404@davea.name>
Message-ID: <1368182572.5481.YahooMailNeo@web163801.mail.gq1.yahoo.com>

>Subject: Re: [Tutor] MutableString/Class variables

>On 05/09/2013 09:16 AM, Albert-Jan Roskam wrote:
>>> On 05/09/2013 08:10 AM, Albert-Jan Roskam wrote:
>>>>???Hello,
>>>>
>>>>???I was just playing a bit with Python and I wanted to make a mutable string,
>>> that supports item assignment. Is the way below the way to do this?
>>>>???The part I am not sure about is the class variable. Maybe I should also
>>> have reimplemented __init__, then call super inside this and add an updated
>>> version of "self" so __repr__ and __str__ return that. More general:
>>> when should class variables be used? I am reading about Django nd there they are
>>> all over the place, yet I have always had the impression their use is not that
>>> common.
>>>>
>>>
>>> You use a class attribute (not class variable) whenever you want to have
>>> exactly one such value for the entire program.? If you want to be able
>>> to manipulate more than one, then you use an instance attribute,
>>> typically inside the __init__() method.
>>
>> Hmmm, so is it fair to say that this is the OOP equivalent of 'nonlocal' in Python 3? It has meaning inside the entire scope of the class, not outside it, there not 'global'.
>>
>> Here's a modified version; in my previous attempts I messed up the arguments of super(). ;-) This feels better. But then again, I never *really* understood __new__ entirely.
>>
>> class MutableStr(str):
>>? ? ? def __init__(self, s):
>>? ? ? ? ? super(str, MutableStr).__init__(s)
>>? ? ? ? ? self.s = s
>>? ? ? def __repr__(self):
>>? ? ? ? ? return self.s
>>? ? ? def __str__(self):
>>? ? ? ? ? return self.s
>>? ? ? def __setitem__(self, key, item):
>>? ? ? ? ? self.s = self[:key] + item + self[key+1:]
>>
>> # produce results as intended
>> mstr = MutableStr("01234X678")
>> mstr[5] = "&"
>> print str(mstr)
>> print unicode(mstr)
>> mstr = MutableStr("01234X678")
>> mstr[8] = "&"
>> print str(mstr)
>> print unicode(mstr)
>>
>> # output:
>> 01234&678
>> 01234&678
>> 01234X67&
>> 01234X67&
>>
>>
>>
>
>That's all well and good as long as you only use those particular 
>methods.? But try:
>
>print "aaa" + mstr
>? ? #The changes you made to mstr have "vanished"
>
>print(type(mstr))
>mstr += "def"
>print(mstr)
>print(type(mstr))
>? ???#now it's no longer a MutablsStr


Hi Oscar, Dave, Alan,

Thanks. I agree that the conclusion is that inheriting from str is not a good idea (unless I'd reimplement each and every method, which would largely make inheritance useless). Using a bytearray as a basis instead is an ingenious alternative.

Regards,
Albert-Jan


From fomcl at yahoo.com  Fri May 10 12:47:56 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Fri, 10 May 2013 03:47:56 -0700 (PDT)
Subject: [Tutor] PyScripter header?
In-Reply-To: <518A393C.1090207@gmail.com>
References: <CALRAYNUOFGrDd_0dhm7shTeE2MbinSByiC-7N=RYQqK38g-EiQ@mail.gmail.com>
	<518A393C.1090207@gmail.com>
Message-ID: <1368182876.46931.YahooMailNeo@web163803.mail.gq1.yahoo.com>



> Sent: Wednesday, May 8, 2013 1:38 PM

> Subject: Re: [Tutor] PyScripter header?
> 
> El 08/05/13 05:10, Jim Mooney escribi?:
>> 
>>  PyScripter has enough extra features, that I'll probably switch to it.
>>  But has anyone found any odd problems with it? Tks.
>> 
>>  Jim
>> 
> 
> Given that your main() question ;c) has been answered, you might also 
> want to give Spyder a try before switching.

Spyder looks pretty cool. I will also give it a try. Does it have integretion with e,g Git?

From steve at pearwood.info  Fri May 10 13:28:57 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 10 May 2013 21:28:57 +1000
Subject: [Tutor] MutableString/Class variables
In-Reply-To: <1368101441.50427.YahooMailNeo@web163805.mail.gq1.yahoo.com>
References: <1368101441.50427.YahooMailNeo@web163805.mail.gq1.yahoo.com>
Message-ID: <518CD9F9.3070507@pearwood.info>

On 09/05/13 22:10, Albert-Jan Roskam wrote:
> Hello,
>
> I was just playing a bit with Python and I wanted to make a mutable string, that supports item assignment. Is the way below the way to do this?


Guido's time machine strikes again:

py> from UserString import MutableString
py> s = MutableString("Hello world!")
py> s[-1] = '?'
py> print s
Hello world?


You can see the source code here:

http://hg.python.org/cpython/file/2.7/Lib/UserString.py

and the docs:

http://docs.python.org/2/library/userdict.html#module-UserString


Note, however, that MutableString is (allegedly) very inefficient, and has been removed from Python 3.x. (It seems to me that it cannot possibly be that much more inefficient than using immutable strings. It's just a wrapper around an immutable string with a few convenience methods.)

But really, unless you are dealing with truly humongous strings, you're better off just sticking to the standard Python built-in string (unicode) type. And if by chance you really do need a mutable string-like data structure, you probably should look at something like ropes, implemented in C or Cython.

http://en.wikipedia.org/wiki/Rope_(data_structure)



-- 
Steven

From fomcl at yahoo.com  Fri May 10 16:56:19 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Fri, 10 May 2013 07:56:19 -0700 (PDT)
Subject: [Tutor] MutableString/Class variables
In-Reply-To: <518CD9F9.3070507@pearwood.info>
References: <1368101441.50427.YahooMailNeo@web163805.mail.gq1.yahoo.com>
	<518CD9F9.3070507@pearwood.info>
Message-ID: <1368197779.80323.YahooMailNeo@web163806.mail.gq1.yahoo.com>



> From: Steven D'Aprano <steve at pearwood.info>

> To: tutor at python.org
> Cc: 
> Sent: Friday, May 10, 2013 1:28 PM
> Subject: Re: [Tutor] MutableString/Class variables
> 
> On 09/05/13 22:10, Albert-Jan Roskam wrote:
>>  Hello,
>> 
>>  I was just playing a bit with Python and I wanted to make a mutable string, 
> that supports item assignment. Is the way below the way to do this?
> 
> 
> Guido's time machine strikes again:
> 
> py> from UserString import MutableString
> py> s = MutableString("Hello world!")
> py> s[-1] = '?'
> py> print s
> Hello world?
> 
> 
> You can see the source code here:
> 
> http://hg.python.org/cpython/file/2.7/Lib/UserString.py
> 
> and the docs:
> 
> http://docs.python.org/2/library/userdict.html#module-UserString
> 
> 
> Note, however, that MutableString is (allegedly) very inefficient, and has been 
> removed from Python 3.x. (It seems to me that it cannot possibly be that much 
> more inefficient than using immutable strings. It's just a wrapper around an 
> immutable string with a few convenience methods.)
> 
> But really, unless you are dealing with truly humongous strings, you're 
> better off just sticking to the standard Python built-in string (unicode) type. 
> And if by chance you really do need a mutable string-like data structure, you 
> probably should look at something like ropes, implemented in C or Cython.
> 
> http://en.wikipedia.org/wiki/Rope_(data_structure)

Hi Steven,

"[...] the purpose of this class is an educational one: to prevent people from inventing their own mutable string class"
Waaaahh, twilight zone! ;-)))
Still interesting to see how the author implemented __setitem__. In my version, slices were not supported.
Interesting to hear about ropes. I did not know about this. Here is another page where a Python implementation of a rope data structure is mentioned: http://kmike.ru/python-data-structures/#ropes

Regards,
Albert-Jan

?
> 
> 
> -- 
> Steven
> _______________________________________________
> Tutor maillist? -? Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 

From cybervigilante at gmail.com  Fri May 10 18:42:30 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Fri, 10 May 2013 09:42:30 -0700
Subject: [Tutor] Tutor Digest, Vol 111, Issue 24
In-Reply-To: <mailman.17.1368180002.5505.tutor@python.org>
References: <mailman.17.1368180002.5505.tutor@python.org>
Message-ID: <CALRAYNWzFusEg3=4eYX5ouRh+Vm_u3BnWC2bS3wq4y_qr7ncxw@mail.gmail.com>

> As with any other module you need to specify the module when using its
> contents:
>
> newRandomList = makeRandomList.createRandomList()
>
> BTW. A better name for the module is probably just randomlist
>
> HTH
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/

Ah, me so stupid.  That workede. Although I recall making a very
simple test program that didn't use the module prefix and it worked
for some odd reason.  I just made a dummy prog that said
print('thisworks'), put it in Lib, imported with a test prog, and it
printed out. Which is why I got confused. Oh well, I'll just ignore
that and use the prefix.

BTW, does your "better name" mean that camelCaps are discouraged in
Python? I loathe finding the underline key and figured it was a good
way to always avoid Python reserved words.

Jim

From michael at seomoz.org  Fri May 10 19:58:45 2013
From: michael at seomoz.org (Michael O'Leary)
Date: Fri, 10 May 2013 10:58:45 -0700
Subject: [Tutor] Python debugger/IDE that can be launched from a remote
	command line
Message-ID: <CAFp7J1bGOumVayfcXAcs13WXdoyNA4ncyJ+NOySOXhd93p=zqg@mail.gmail.com>

I am working on a project in which the code and data I am working with are
all on an Amazon EC2 machine. So far I have been ssh'ing to the EC2 machine
in two terminal windows, running emacs or vi in one of them to view and
update the code and running the "python -m pdb ..." debugger in the other
one to step through the code.

I would prefer to work with an IDE that displays and updates program state
automatically, but I don't know which ones I could launch from a remote
machine and have it display within a terminal window or use XWindows or GTK
to display in its own window. Are there any Python debuggers or IDEs that
can be used in this kind of setting?
Thanks,
Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130510/c5bffe55/attachment.html>

From abhishek.vit at gmail.com  Fri May 10 20:06:53 2013
From: abhishek.vit at gmail.com (Abhishek Pratap)
Date: Fri, 10 May 2013 11:06:53 -0700
Subject: [Tutor] Python debugger/IDE that can be launched from a remote
 command line
In-Reply-To: <CAFp7J1bGOumVayfcXAcs13WXdoyNA4ncyJ+NOySOXhd93p=zqg@mail.gmail.com>
References: <CAFp7J1bGOumVayfcXAcs13WXdoyNA4ncyJ+NOySOXhd93p=zqg@mail.gmail.com>
Message-ID: <CAJbA1KB9wO_RuzT8XVv_ZUDN4mmXEhq7uDrj5nT9jnaLwzzR8g@mail.gmail.com>

On Fri, May 10, 2013 at 10:58 AM, Michael O'Leary <michael at seomoz.org>wrote:

> I am working on a project in which the code and data I am working with are
> all on an Amazon EC2 machine. So far I have been ssh'ing to the EC2 machine
> in two terminal windows, running emacs or vi in one of them to view and
> update the code and running the "python -m pdb ..." debugger in the other
> one to step through the code.
>
> I would prefer to work with an IDE that displays and updates program state
> automatically, but I don't know which ones I could launch from a remote
> machine and have it display within a terminal window or use XWindows or GTK
> to display in its own window. Are there any Python debuggers or IDEs that
> can be used in this kind of setting?
> Thanks,
> Mike
>
>
I think IPython could be a useful here. Kick start a IPython notebook on
Amazon machine and open it over https locally. More information on this here

http://ipython.org/ipython-doc/dev/interactive/htmlnotebook.html


-Abhi



> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130510/180aebdf/attachment.html>

From cybervigilante at gmail.com  Fri May 10 21:02:21 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Fri, 10 May 2013 12:02:21 -0700
Subject: [Tutor] Tutor Digest, Vol 111, Issue 24
In-Reply-To: <518D325A.9050200@btinternet.com>
References: <mailman.17.1368180002.5505.tutor@python.org>
	<CALRAYNWzFusEg3=4eYX5ouRh+Vm_u3BnWC2bS3wq4y_qr7ncxw@mail.gmail.com>
	<518D325A.9050200@btinternet.com>
Message-ID: <CALRAYNUJXxPT2LJd=XQAG-PSBuoXwai4nMFp-wYFnaQ22z171A@mail.gmail.com>

>> BTW, does your "better name" mean that camelCaps are discouraged in
>> Python?
>
> No, although most Python modules are all lowercase. But I really meant that
> your module should be for more than just making lists, it should eventually
> have all the functions needed to manage the list.
>
> Eventually maybe even a class to encapsulate those functions
> as methods.

Good point. But I'm just making a test list for now to feed into a
sort program, so I'll gussy it up later. I'm not using sort(), so I
can get the practice of raw-coding sorts. Since getting indexes is
roundabout in a Py for-loop, I'll have to think about the best
algorithm ;')

As regards camelCaps, all I see in the Py Lib is underlines, so I
guess that's more of a convention and I might as well stick to it,
since some programs might become modules. I don't want to spend
forever deciding what style to use, when I could be programming. I see
there is a proposed manual of style at
http://www.python.org/dev/peps/pep-0008/ so I'll look at that.

I think both camelCaps and underlines are often artifacts having to
use short names years ago.

A plain language phrase that isn't hard to spell or almost purposely
confusing (like repeated letters on a word boundary) should do most
times without camelCaps or underlines, unless you really need them for
clarity, so I'll go with underlines, but only when needed for clarity.
And of course, a plain, descriptive name makes a program almost
self-documenting, so you save on hashmarks.

I'm using Windows, which doesn't recognize case difference, so camel
caps for a program name are confusing, anyway. I never figured why
Msoft did that. Even in normal English, cASe is enfOrcEd for good
reason. By trying to make it simpler, Msoft made it harder (Not the
first time that's been done ;')

Since this is a beginner list, I think bringing up Python Preferred
Style is reasonably on topic. I'm a retired webmaster, so readability
and idiot-proofing are a BIG item with me.

Jim

From alan.gauld at btinternet.com  Fri May 10 22:17:38 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 10 May 2013 21:17:38 +0100
Subject: [Tutor] Tutor Digest, Vol 111, Issue 24
In-Reply-To: <CALRAYNUJXxPT2LJd=XQAG-PSBuoXwai4nMFp-wYFnaQ22z171A@mail.gmail.com>
References: <mailman.17.1368180002.5505.tutor@python.org>
	<CALRAYNWzFusEg3=4eYX5ouRh+Vm_u3BnWC2bS3wq4y_qr7ncxw@mail.gmail.com>
	<518D325A.9050200@btinternet.com>
	<CALRAYNUJXxPT2LJd=XQAG-PSBuoXwai4nMFp-wYFnaQ22z171A@mail.gmail.com>
Message-ID: <kmjkkt$lk4$1@ger.gmane.org>

On 10/05/13 20:02, Jim Mooney wrote:

> As regards camelCaps, all I see in the Py Lib is underlines, so I
> guess that's more of a convention and I might as well stick to it,

Yep.

> I think both camelCaps and underlines are often artifacts having to
> use short names years ago.

Not so much short names but the fact that white space wasn't allowed and 
you needed a way to separate words. When space was short - often
only 6 significant characters (and in at least one case I've seen, only 
4) - it was common to miss out vowels and other such tricks. Although on 
bigger projects a name index was maintained(*) and all variables had 
unique numeric IDs prefixing the meaningful name (although only 4
or 6 chars were meaningful often you could have up to 32 or
64 chars in total...). And of course early BASIC just gave you single 
character variables although you had separate lists for numbers and 
strings (A and A$ for example).

And of course lisp uses hyphens for its names like: make-list

(*) And there would be a project name meister to whom you had
to apply for a set of numeric prefixes to use on your variables!
If you needed to create a new variable it could take a couple
of days before you could actually use it in your code!
Ah, the joys of big projects! :-)

> caps for a program name are confusing, anyway. I never figured why
> Msoft did that.

Because DOS came from CP/M and CP/M did that.
And CP/M was influenced by the early Dartmouth mainframes which used 
upper-case only... And on an 8 bit computing platform limiting the 
number of different names possible was a good thing!

Pascal is still case agnostic and in that community its often seen
as a benefit since it avoids a whole class of "error" - when you type
the case of a word wrongly...

Even modern IBM mainframes are still case insensitive - or more 
specifically they convert it all to upper case. One of the reasons
I dislike COBOL programming!

> Since this is a beginner list, I think bringing up Python Preferred
> Style is reasonably on topic.

For sure, it crops up regularly.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From cybervigilante at gmail.com  Fri May 10 23:19:25 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Fri, 10 May 2013 14:19:25 -0700
Subject: [Tutor] range efficiency
Message-ID: <CALRAYNWyMJq1juqWe9fhie0=2++9ugnWYz0LgGjiAfrFk4zdLA@mail.gmail.com>

If I'm using a variable-dependent range in a for loop, is Python smart
enough to figure the variable once so I don't have to hoist it up?

That is for c in range(0,x+2), is x+2 figured once or every time
through the loop? I'm assuming it's once but I like to verify.

I'll figure this myself once I get an editor I like with a profiler,
but I'm still trying editors and don't want to spend all my time on
them. So far I'm in between too simple, overkill, or buggy. And I
don't want anything that uses Java. I'm allergic to Java ;')

-- 
Jim Mooney

?For anything that matters, the timing is never quite right, the
resources are always a little short, and the people who affect the
outcome are always ambivalent.?

From davea at davea.name  Fri May 10 23:45:14 2013
From: davea at davea.name (Dave Angel)
Date: Fri, 10 May 2013 17:45:14 -0400
Subject: [Tutor] range efficiency
In-Reply-To: <CALRAYNWyMJq1juqWe9fhie0=2++9ugnWYz0LgGjiAfrFk4zdLA@mail.gmail.com>
References: <CALRAYNWyMJq1juqWe9fhie0=2++9ugnWYz0LgGjiAfrFk4zdLA@mail.gmail.com>
Message-ID: <518D6A6A.6090108@davea.name>

On 05/10/2013 05:19 PM, Jim Mooney wrote:
> If I'm using a variable-dependent range in a for loop, is Python smart
> enough to figure the variable once so I don't have to hoist it up?
>
> That is for c in range(0,x+2), is x+2 figured once or every time
> through the loop? I'm assuming it's once but I like to verify.

It's only done once.

>
> I'll figure this myself once I get an editor I like with a profiler,
> but I'm still trying editors and don't want to spend all my time on
> them. So far I'm in between too simple, overkill, or buggy. And I
> don't want anything that uses Java. I'm allergic to Java ;')
>

You don't need to use a profiler, or an IDE to answer a question like 
this.  A very useful thing is the dis module:

http://pymotw.com/2/dis/index.html
http://docs.python.org/library/dis.html#dis.disassemble

It shows you the output of the Python compiler.  It doesn't take long to 
learn to read the code it displays.

-- 
DaveA

From ramit.prasad at jpmorgan.com  Fri May 10 23:27:44 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Fri, 10 May 2013 21:27:44 +0000
Subject: [Tutor] range efficiency
In-Reply-To: <CALRAYNWyMJq1juqWe9fhie0=2++9ugnWYz0LgGjiAfrFk4zdLA@mail.gmail.com>
References: <CALRAYNWyMJq1juqWe9fhie0=2++9ugnWYz0LgGjiAfrFk4zdLA@mail.gmail.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF474183AF372@SCACMX008.exchad.jpmchase.net>

Jim Mooney wrote:
> If I'm using a variable-dependent range in a for loop, is Python smart
> enough to figure the variable once so I don't have to hoist it up?
> 
> That is for c in range(0,x+2), is x+2 figured once or every time
> through the loop? I'm assuming it's once but I like to verify.
> 
> I'll figure this myself once I get an editor I like with a profiler,
> but I'm still trying editors and don't want to spend all my time on
> them. So far I'm in between too simple, overkill, or buggy. And I
> don't want anything that uses Java. I'm allergic to Java ;')
> 
> --
> Jim Mooney
> 
> "For anything that matters, the timing is never quite right, the
> resources are always a little short, and the people who affect the
> outcome are always ambivalent."

x+2 is only calculated once and then passed to range. The for loop
then iterates over the range object. It is not recreating/re-calling
range(). 

Note in python 2 you should use xrange as it is a generator and 1. lazy 
2. more memory efficient. Unlike Python 2, in Python 3 range is a 
generator.


~Ramit




This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

From jacklittlemc at yahoo.com  Sat May 11 04:13:19 2013
From: jacklittlemc at yahoo.com (Jack Little)
Date: Fri, 10 May 2013 19:13:19 -0700 (PDT)
Subject: [Tutor] Unknown Cause of Error
Message-ID: <1368238399.25400.YahooMailNeo@web124506.mail.ne1.yahoo.com>

I have a slight problem. My program will not open. On top of that, I have written similar programs all to no avail. I am creating a text adventure and want there to be different rooms. Here is my code:



def menu():
? ? print "Welcome to Tomb Explorer!"
? ? print "A game of Exploration from Bulldog Development"
? ? print "Press [1] to Play or [2] to Exit"
? ? menu1=raw_input(" >> ")
? ? if menu1== "2":
? ? ? ? quit()
? ? if menu1== "1":
? ? ? ? room1()
? ? menu()







Thanks A Ton!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130510/acbdcf6e/attachment.html>

From amitsaha.in at gmail.com  Sat May 11 04:17:42 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Sat, 11 May 2013 12:17:42 +1000
Subject: [Tutor] Unknown Cause of Error
In-Reply-To: <1368238399.25400.YahooMailNeo@web124506.mail.ne1.yahoo.com>
References: <1368238399.25400.YahooMailNeo@web124506.mail.ne1.yahoo.com>
Message-ID: <CANODV3kOkCx2zeefn06w1sQ=9Xpfk9e_ig41uewJEMuwffOyEw@mail.gmail.com>

On Sat, May 11, 2013 at 12:13 PM, Jack Little <jacklittlemc at yahoo.com> wrote:
> I have a slight problem. My program will not open. On top of that, I have
> written similar programs all to no avail. I am creating a text adventure and
> want there to be different rooms. Here is my code:
>
>
> def menu():
>     print "Welcome to Tomb Explorer!"
>     print "A game of Exploration from Bulldog Development"
>     print "Press [1] to Play or [2] to Exit"
>     menu1=raw_input(" >> ")
>     if menu1== "2":
>         quit()
>     if menu1== "1":
>         room1()
>     menu()

You are not calling your function: menu(). Just move the menu() ( your
last line) to the left:

def menu():
    print "Welcome to Tomb Explorer!"
    print "A game of Exploration from Bulldog Development"
    print "Press [1] to Play or [2] to Exit"
    menu1=raw_input(" >> ")
    if menu1== "2":
        quit()
    if menu1== "1":
        room1()

 menu()

HTH,Amit.


--
http://echorand.me

From steve at pearwood.info  Sat May 11 08:12:56 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 11 May 2013 16:12:56 +1000
Subject: [Tutor] Unknown Cause of Error
In-Reply-To: <1368238399.25400.YahooMailNeo@web124506.mail.ne1.yahoo.com>
References: <1368238399.25400.YahooMailNeo@web124506.mail.ne1.yahoo.com>
Message-ID: <518DE168.7080806@pearwood.info>

On 11/05/13 12:13, Jack Little wrote:
> I have a slight problem. My program will not open.


What do you mean "open"? How are you trying to open it? What editor are you opening it in?

Or do you mean your program will not *run*? How are you trying to run it?


>On top of that, I have written similar programs all to no avail. I am creating a text adventure and want there to be different rooms. Here is my code:
>
>
>
> def menu():
>      print "Welcome to Tomb Explorer!"
>      print "A game of Exploration from Bulldog Development"
>      print "Press [1] to Play or [2] to Exit"
>      menu1=raw_input(" >> ")
>      if menu1== "2":
>          quit()
>      if menu1== "1":
>          room1()
>      menu()


I can see two obvious problems here. First, you define a function, "menu", but do not call it when the program runs. You must call the function, or it will not do anything.

The second problem is that *inside* the "menu" function you make a recursive call to itself. While that is sometimes a legitimate technique, this time it will lead to problems as the menu function gets called again and again and again and again in an (almost) infinite loop.

Fortunately, you can fix both problems with one edit: *indented* code is part of the function, code that is not indented is not. So:


def menu():
     print "Welcome to Tomb Explorer!"
     print "A game of Exploration from Bulldog Development"
     print "Press [1] to Play or [2] to Exit"
     menu1=raw_input(" >> ")
     if menu1== "2":
         quit()
     if menu1== "1":
         room1()


menu()




-- 
Steven

From steve at pearwood.info  Sat May 11 08:27:40 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 11 May 2013 16:27:40 +1000
Subject: [Tutor] range efficiency
In-Reply-To: <CALRAYNWyMJq1juqWe9fhie0=2++9ugnWYz0LgGjiAfrFk4zdLA@mail.gmail.com>
References: <CALRAYNWyMJq1juqWe9fhie0=2++9ugnWYz0LgGjiAfrFk4zdLA@mail.gmail.com>
Message-ID: <518DE4DC.40609@pearwood.info>

On 11/05/13 07:19, Jim Mooney wrote:
> If I'm using a variable-dependent range in a for loop, is Python smart
> enough to figure the variable once so I don't have to hoist it up?
>
> That is for c in range(0,x+2), is x+2 figured once or every time
> through the loop? I'm assuming it's once but I like to verify.

Yes, it is calculated once.

Remember that range() is not a syntax feature, it is a function that returns an object. Since it is a function, its argument must be figured *before* the function is called, and once the range function has returned, it is done.

So you can write something like this in Python 3:


py> x = 3
py> values = range(0, x+2)
py> print(values)
range(0, 5)
py> for c in values:
...     print(c)
...
0
1
2
3
4


Python 2 is the same, except that instead of getting that mysterious "range(0, 5)" line printed, you get an actual list of values [0, 1, 2, 3, 4].


By the way, you don't need to include the starting value of 0 for range. range(0, x+2) is exactly the same as range(x+2).



Here are a couple of "monkey-patching" tricks for testing things like this. Let's patch the range function to display when it is called, and make a chatty little object that prints when it is added to.

=== cut ===

saved_range = range
def range(*args):
     print("calling range function")
     return saved_range(*args)

class Chatty(int):
     def __add__(self, other):
         print("adding %s and %s" % (self, other))
         return int.__add__(self, other)

x = Chatty(3)
for c in range(x+2):
     print(c)

=== cut ===


If you copy the code between the "cut" lines, and paste into an interactive interpreter, you will see what Python does when executing this sort of for-loop.



-- 
Steven

From steve at pearwood.info  Sat May 11 08:51:27 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 11 May 2013 16:51:27 +1000
Subject: [Tutor] Tutor Digest, Vol 111, Issue 24
In-Reply-To: <kmjkkt$lk4$1@ger.gmane.org>
References: <mailman.17.1368180002.5505.tutor@python.org>
	<CALRAYNWzFusEg3=4eYX5ouRh+Vm_u3BnWC2bS3wq4y_qr7ncxw@mail.gmail.com>
	<518D325A.9050200@btinternet.com>
	<CALRAYNUJXxPT2LJd=XQAG-PSBuoXwai4nMFp-wYFnaQ22z171A@mail.gmail.com>
	<kmjkkt$lk4$1@ger.gmane.org>
Message-ID: <518DEA6F.8050604@pearwood.info>

On 11/05/13 06:17, Alan Gauld wrote:

> Pascal is still case agnostic and in that community its often seen
> as a benefit since it avoids a whole class of "error" - when you type
> the case of a word wrongly...


Interesting that you say that. Just the other week I was reading a page somewhere talking about some Pascal compiler, and it made a comment that "by popular request" the next version would allow case sensitive variables.


Personally, I don't understand how moderately intelligent English-speaking people can apparently have so much trouble with capitalization. It's very simple: capitalization is the difference between:

"I helped my Uncle Jack off a horse."

and

"I helped my uncle jack off a horse."


Case sensitivity really helps when programming too. For example, the usual convention is that classes have an initial capital letter. (Although built-in classes tend to break this convention, mostly for pragmatic reasons.) Instances tend to be lower case. So for example I have code that looks like this:


history = History()  # actual code, copied from one of my modules


and to anyone who understands the convention, it is obvious: I take a History class, create an instance, and call it history. There is no conflict between the two, since they differ in case.


-- 
Steven

From alan.gauld at btinternet.com  Sat May 11 08:56:43 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 11 May 2013 07:56:43 +0100
Subject: [Tutor] Unknown Cause of Error
In-Reply-To: <518DE168.7080806@pearwood.info>
References: <1368238399.25400.YahooMailNeo@web124506.mail.ne1.yahoo.com>
	<518DE168.7080806@pearwood.info>
Message-ID: <kmkq36$e91$1@ger.gmane.org>

On 11/05/13 07:12, Steven D'Aprano wrote:

>> def menu():
>>      print "Welcome to Tomb Explorer!"
>>      print "A game of Exploration from Bulldog Development"
>>      print "Press [1] to Play or [2] to Exit"
>>      menu1=raw_input(" >> ")
>>      if menu1== "2":
>>          quit()
>>      if menu1== "1":
>>          room1()
>>      menu()
>
> The second problem is that *inside* the "menu" function you make a
> recursive call to itself. While that is sometimes a legitimate
> technique, this time it will lead to problems as the menu function gets
> called again and again and again and again in an (almost) infinite loop.

To the OP, not Steven...
Beginners often use this technique to deliberately create a loop within 
their functions. If that is what you wanted then it's better to use one 
of Pythons native loop structures, 'while' or 'for'.

'for' is generally used when the number of iterations is known or can be 
calculated. So in your case a 'while' loop is more appropriate. 
Typically your code should look like:

while True:   # loop 'forever'
     # ...display menu
     if menu1== "2":
          break   # exit the while loop
     elif menu1== "1":
          room1()
     elif... # other menu choices.
     else:
        # display invalid choice error


HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From eryksun at gmail.com  Sat May 11 08:59:57 2013
From: eryksun at gmail.com (eryksun)
Date: Sat, 11 May 2013 02:59:57 -0400
Subject: [Tutor] range efficiency
In-Reply-To: <CALRAYNWyMJq1juqWe9fhie0=2++9ugnWYz0LgGjiAfrFk4zdLA@mail.gmail.com>
References: <CALRAYNWyMJq1juqWe9fhie0=2++9ugnWYz0LgGjiAfrFk4zdLA@mail.gmail.com>
Message-ID: <CACL+1as4Cnj11KUYZqRg=n4zcjvYhK6u49CB51V6ZiTJtumHmw@mail.gmail.com>

On Fri, May 10, 2013 at 5:19 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> If I'm using a variable-dependent range in a for loop, is Python smart
> enough to figure the variable once so I don't have to hoist it up?

At the start of a for loop, the interpreter gets an iterator for the
iterable. The latter is  evaluated from the expression or
expression-list (tuple). If this fails it raises a TypeError.

iteration is an object protocol, using the special methods __iter__
and __next__, and the exception StopIteration. An iterator maintains
its own state. You can get an iterator manually with built-in iter()
and step through it with built-in next().

    >>> it = iter('abc')
    >>> type(it)
    <class 'str_iterator'>
    >>> next(it), next(it), next(it)
    ('a', 'b', 'c')
    >>> next(it)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration

    >>> it = iter(range(5))
    >>> type(it)
    <class 'range_iterator'>
    >>> list(it)
    [0, 1, 2, 3, 4]
    >>> next(it)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration

From alan.gauld at btinternet.com  Sat May 11 18:28:25 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 11 May 2013 17:28:25 +0100
Subject: [Tutor] Tutor Digest, Vol 111, Issue 24
In-Reply-To: <518DEA6F.8050604@pearwood.info>
References: <mailman.17.1368180002.5505.tutor@python.org>
	<CALRAYNWzFusEg3=4eYX5ouRh+Vm_u3BnWC2bS3wq4y_qr7ncxw@mail.gmail.com>
	<518D325A.9050200@btinternet.com>
	<CALRAYNUJXxPT2LJd=XQAG-PSBuoXwai4nMFp-wYFnaQ22z171A@mail.gmail.com>
	<kmjkkt$lk4$1@ger.gmane.org> <518DEA6F.8050604@pearwood.info>
Message-ID: <kmlrj4$vov$1@ger.gmane.org>

On 11/05/13 07:51, Steven D'Aprano wrote:

>> Pascal is still case agnostic and in that community its often seen
>> as a benefit...

> Interesting that you say that. Just the other week I was reading a page
> somewhere talking about some Pascal compiler, and it made a comment that
> "by popular request" the next version would allow case sensitive variables.

Yes, I think that more and more people are coming to Pascal from non 
Pascal backgrounds. When you've been used to case sensitive languages 
like C, Java, etc, then Pascal and COBOL seem arecane. But as someone 
who started life in Pascal (Traditional Basic doesn't count! :-) before 
moving to C, I made a huge number of case based errors in the early days.

But nowadays I wouldn't like to be without the flexibility of using 
mixed case such as:

> history = History()  # actual code, copied from one of my modules

And this is one of the areas where I don't personally like
Python's PEP8 naming conventions...


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From dsm3 at att.net  Sat May 11 22:44:05 2013
From: dsm3 at att.net (Daniel Magruder)
Date: Sat, 11 May 2013 15:44:05 -0500
Subject: [Tutor] Making a Primary Number List generator
Message-ID: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>

Dear Tutor at Python.org,
I am new to the python language and have been teaching myself through various online resources. I found an exercise where I am to create a program that prints a list of the first 1000 prime numbers. After many attempts and looking at other answers for other ways around the problem (which I did not understand), I am seeking your guidance.
Here is what I have so far. While I understand there are many ways to do this, I would like advice on how to finish this program based on the initial path I started out on.

def counting_primes():
	primelist = [] # I want a list of 1000 primes
	prime = f(0) # so that when I divid I get a true non int answer
	x = 1 # to test and make sure no other number goes into prime besides prime and one
	while len(primelist)<1000: # start a loop for as long as my list is not 1000 items in length
 		if prime % x == num and x < prime:
			x = x + 1  # keep the dividing loop going until  x and prime are equal
			if prime % x == 0: and prime != x: # if prime is not yet a prime number i.e. 8 and x is a number like 4, this prevents false positives
				x= x+1
				if prime = x:
					primelist = primelist + x # add x to my list of primes
					prime = prime + 1 # check to see if next number is prime

	return primelist

Please walk me through any logical errors, I really want to understand this.
Sincerely,
Dan

From davea at davea.name  Sun May 12 00:34:07 2013
From: davea at davea.name (Dave Angel)
Date: Sat, 11 May 2013 18:34:07 -0400
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
Message-ID: <518EC75F.2090206@davea.name>

On 05/11/2013 04:44 PM, Daniel Magruder wrote:
> Dear Tutor at Python.org,
> I am new to the python language and have been teaching myself through various online resources. I found an exercise where I am to create a program that prints a list of the first 1000 prime numbers. After many attempts and looking at other answers for other ways around the problem (which I did not understand), I am seeking your guidance.
> Here is what I have so far. While I understand there are many ways to do this, I would like advice on how to finish this program based on the initial path I started out on.
>
> def counting_primes():
> 	primelist = [] # I want a list of 1000 primes
> 	prime = f(0) # so that when I divid I get a true non int answer
> 	x = 1 # to test and make sure no other number goes into prime besides prime and one
> 	while len(primelist)<1000: # start a loop for as long as my list is not 1000 items in length
>   		if prime % x == num and x < prime:
> 			x = x + 1  # keep the dividing loop going until  x and prime are equal
> 			if prime % x == 0: and prime != x: # if prime is not yet a prime number i.e. 8 and x is a number like 4, this prevents false positives
> 				x= x+1
> 				if prime = x:
> 					primelist = primelist + x # add x to my list of primes
> 					prime = prime + 1 # check to see if next number is prime
>
> 	return primelist
>
> Please walk me through any logical errors, I really want to understand this.

First you have to add a top-level call to this function.  Otherwise the 
program does nothing useful.

myprimes = counting_primes()
print len(myprimes)  #how many did we find ?
print myprimes[:10]  #what are the first ten ?

Then you have to eliminate your two syntax errors.  There's only one 
colon in an if statement, and it's at the end.  And you cannot use = for 
comparison, that's what == is for.,

Then you have to eliminate the references to undefined functions and 
variables.  There's no f() defined in your code, and all you want is 0, 
so simply set prime = 0, not f(0).  Actually, you probably want to set 
prime to 2, as zero and 1 could be problematic.  Once it works, you may 
want to see if you could start at 1 instead.  You have no num defined in 
your code, so you'll have to decide what was actually intended there.

You now have a function which never returns, but at least it executes.

You have one loop which will only exit when the size of primelist 
reaches 1000, and inside it, logic will will not add to that length. 
You don't have the necessary loop inside this one to test the candidate.

If I were you, I'd break this code into two functions.  The first one 
will check a given number to see if it is prime, and return True or 
False.  The second one will repeatedly call the first on successively 
higher numbers till it has enough.  As it stands now, you have far too 
much logic incrementing x and prime, and nothing that resets x back to 2 
for the next iteration.

So the two functions, in pseudocode, should be something like:

def testprime(candidate)
     check all ints between 2 and candidate, and return true if any of 
them divide the candidate evenly
     Otherwise return false

def counting_primes()
     build a list of primes, where a number is put in the list if 
testprime() confirms that it is prime.
     return the list once it's big enough


It's actually easier to write two functions this way than to get the 
logic right for the nested loops that you otherwise need.

Note that testprime() can use a for-loop, it needn't look like 
transliterated Fortran.


-- 
DaveA

From dyoo at hashcollision.org  Sun May 12 04:41:54 2013
From: dyoo at hashcollision.org (Danny Yoo)
Date: Sat, 11 May 2013 20:41:54 -0600
Subject: [Tutor] range efficiency
In-Reply-To: <CALRAYNWyMJq1juqWe9fhie0=2++9ugnWYz0LgGjiAfrFk4zdLA@mail.gmail.com>
References: <CALRAYNWyMJq1juqWe9fhie0=2++9ugnWYz0LgGjiAfrFk4zdLA@mail.gmail.com>
Message-ID: <CAGZAPF43shRtvyX=T53BQp5LQvxnq=wkEAPnVtVZ0qpNCN4C_g@mail.gmail.com>

On Fri, May 10, 2013 at 3:19 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> If I'm using a variable-dependent range in a for loop, is Python smart
> enough to figure the variable once so I don't have to hoist it up?

Hi Jim,


The gritty details say "yes":

    http://docs.python.org/2/reference/compound_stmts.html#the-for-statement

when it says: "The expression list is evaluated once; it should yield
an iterable object."

From eryksun at gmail.com  Sun May 12 12:21:41 2013
From: eryksun at gmail.com (eryksun)
Date: Sun, 12 May 2013 06:21:41 -0400
Subject: [Tutor] range efficiency
In-Reply-To: <CAGZAPF43shRtvyX=T53BQp5LQvxnq=wkEAPnVtVZ0qpNCN4C_g@mail.gmail.com>
References: <CALRAYNWyMJq1juqWe9fhie0=2++9ugnWYz0LgGjiAfrFk4zdLA@mail.gmail.com>
	<CAGZAPF43shRtvyX=T53BQp5LQvxnq=wkEAPnVtVZ0qpNCN4C_g@mail.gmail.com>
Message-ID: <CACL+1atW-o54EpPdUtBVUPJnSBHy+TeRPAk4tPTtk5fuDKNccg@mail.gmail.com>

On Sat, May 11, 2013 at 10:41 PM, Danny Yoo <dyoo at hashcollision.org> wrote:
> On Fri, May 10, 2013 at 3:19 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
>> If I'm using a variable-dependent range in a for loop, is Python smart
>> enough to figure the variable once so I don't have to hoist it up?
>
> The gritty details say "yes":
>
>     http://docs.python.org/2/reference/compound_stmts.html#the-for-statement
>
> when it says: "The expression list is evaluated once; it should yield
> an iterable object."

On the other hand,  at each iteration the target_list is assigned
"using the standard rules for assignments". The following expressions
are valid targets for assignment: Name (identifier), Attribute,
Subscript (slices), and a list/tuple of the latter. 3.x also accepts
starred targets in a list/tuple, as spec'd in PEP 3132.

For an attribute target of value.identifier, "value" can use an
expression. For a subscript target of value[slice], both "value" and
"slice" can use expressions (the ASDL treats an index as a kind of
slice). Here's an example with a subscript target:

    >>> even, odd = [0]*3, [0]*3
    >>> for i, (odd if i % 2 else even)[i // 2] in enumerate(range(6)):
    ...     print(i, even, odd)
    ...
    0 [0, 0, 0] [0, 0, 0]
    1 [0, 0, 0] [1, 0, 0]
    2 [0, 2, 0] [1, 0, 0]
    3 [0, 2, 0] [1, 3, 0]
    4 [0, 2, 4] [1, 3, 0]
    5 [0, 2, 4] [1, 3, 5]

Not that I'm recommending anyone do something this silly. Maybe
someone else can come up with a more practical example. But I prefer
the target_list to be as simple as possible, preferably just names in
the local scope.

Reference (3.3.1):
http://hg.python.org/cpython/file/d9893d13c628/Parser/Python.asdl

From davea at davea.name  Sun May 12 13:43:52 2013
From: davea at davea.name (Dave Angel)
Date: Sun, 12 May 2013 07:43:52 -0400
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
Message-ID: <518F8078.9030902@davea.name>

On 05/11/2013 09:58 PM, Daniel Magruder wrote:

Please respond to the list, not the individual.  Otherwise you're 
robbing yourself and others of the possibility of learning from and 
helping multiple people.  I don't mind if you ALSO reply to me (which is 
what reply-all does by default), but many people do object.  In 
Thunderbird, you normally just do Reply-list, and it does the right 
thing.  But with other email programs, you might do reply-all, and 
remove whichever recipients you don't need.

> Dear Dave,
> I can't tell you how much I appreciate your assistance, however as a novice I doubt my ability to crawl. I sincerely envy your depth of understanding about this and in trying to learning would really benefit if you could please expound on a few notions.
> Why must I top-level call? What is that actually? Several of the sources I have seen like learnpython.org suggest that def function(): is sufficient...

A function is defined by a def, but a program that never calls any of 
them will do nothing at all (except look for syntax errors and the 
like).  There are probably tens of thousands of defined functions in the 
library, but running python will only execute the ones you call.

Typically at the bottom of every script there needs to be at least one 
function call that gets things started.  (Unless the script is so 
trivial that it's written without using any functions).  But in either 
case, some top-level code is needed.

That top-level code can be as simple as a single call, or it might 
define a few variables, and then make the call(s).

> I thought I had to define prime as f(0) so that it would be a float, not an integer division. Am I wrong? I am so utterly confused.

I'm afraid you're wrong in a couple of points.  There's no such function 
as f() in the standard library.  If you wanted to define a literal 
float, you could either use 0.0, or use float(0).  But you do not want a 
float there, everything can be done with ints.

> In many sample codes I have seen num or int seem to be short hand for anything that is a number, because I though I was dividing and would receive a float remainder for non-prime numbers, I wan't to use that as a test.

int and float are types (and act like functions), and if you needed to 
check the type of an object, you'd use  isinstance(myvar, int) or 
isinstance(myvar, float).  You can't just do a comparison with int.  But 
dividing two ints will give an int in Python 2.x and will give a float 
in Python 3.x.   And that's regardless of whether it comes out even or 
not.  Which version of Python are you using?

Fortunately, there's a much better way of telling if an int can be 
divided by another int:  The modulo operator, represented by a "%" symbol.

     prime%n   will give the remainder, and if it's zero, you know that 
prime is evenly divisible by n  (and therefore isn't prime).


> For your suggestion:
>> def testprime(candidate)
>>     check all ints between 2 and candidate, and return true if any of them divide the candidate evenly
> I don't mean to be so dependent, but how would I do this? Also what is the difference between return and print?
>>     Otherwise return false
>>

The return statement is the way a function returns a value to its 
caller.  Let's suppose you wanted a function that returned true if its 
int argument was odd.  You could do it like this:

def isodd(candidate):
     if candidate%2 ==0:
         return False
     else:
         return True

Now, the body of that function could be done in one line, but I wanted 
to illustrate the returning of useful values, and also the possibility 
that the return might not be at the end, and that there might be  more 
than one place the function returns.

Why not get the other function to call this one temporarily, and see if 
you can make the program find the first 1000 odd numbers instead.  Then 
you can come back to the testprime() function and see if you can create 
one that returns True for primes, and False for anything else.  Clearly 
that function will need a loop.

>> def counting_primes()
>>     build a list of primes, where a number is put in the list if testprime() confirms that it is prime.
> Again, how would I do this, so if I had something that told me a number was prime, how would I take that prime and put it in a list if the function is on loop?
>>     return the list once it's big enough

You're already doing that in the code you showed.  You initialized the 
primelist, then started a while loop.  The difference I'm suggesting is 
that instead of dealing with x in this function, you defer that to the 
testprime() function.  So your loop would call testprime() and 
conditionally append the value prime to the primelist.

def counting_primes():
     primelist=[]
     prime = 2
     while len(primelist) < 1000:
         if isodd(prime):
              primelist.append(prime)
         prime += 1
     return primelist

> Despite going to many sources I can not seem to find a single source that adequately explains Python 100% without any technical jargon or assumptions of prior knowledge. What I mean by this, is that I now have the gist of the utmost basics, but I would say my understanding is befuddled. Furthermore if I were to attempt to write code (such as this exercise) I am completely lost. What do you recommend for a good source to learn Python? I have tried MIT open course ware, but again even their intro explains the obvious, but not how to use it collectively.
> Sincerely,
> Dan
>
>

With no experience in programming other languages, you'd need a 
different kind of tutorial than I sought when I was learning Python. 
And you absolutely need to match your tutorial against the version of 
Python you're running on your machine.  2.x and 3.x aren't VERY 
different, but there were enough changes that you don't want to be 
dealing with that while learning initially.

Anybody else want to recommend a tutorial for someone who has no 
programming experience in other languages?

--
DaveA


From alan.gauld at btinternet.com  Sun May 12 14:57:08 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 12 May 2013 13:57:08 +0100
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <518F8078.9030902@davea.name>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
Message-ID: <kmo3iv$fd8$1@ger.gmane.org>

On 12/05/13 12:43, Dave Angel wrote:

>> Despite going to many sources I can not seem to find a single source
>> that adequately explains Python 100% without any technical jargon or
>> assumptions of prior knowledge.

Its impossible to learn to program without learning technical jargon, 
but there are tutorials that try to teach you that technical jargon 
before using it!

>> this exercise) I am completely lost. What do you recommend for a good
>> source to learn Python? I have tried MIT open course ware, but again
>> even their intro explains the obvious, but not how to use it
>> collectively.

Using it 2collectively" is the hardest bit about programming in any 
language and there are very few resources that even attempt such a 
thing. Most take the approach of building ever increasingly complex 
programs so that you absorb the technique through use.

> Anybody else want to recommend a tutorial for someone who has no
> programming experience in other languages?

Tutorials are highly subjective but have you (the OP) looked at the 
non-programmers page on the Python web site? It lists several tutorials 
aimed at the complete beginner. Being biased I favour my one!
(see below)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From robertvstepp at gmail.com  Sun May 12 19:36:23 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 12 May 2013 12:36:23 -0500
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <518F8078.9030902@davea.name>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
Message-ID: <CANDiX9LyMKEg6pCRPSdNkbziV-WFgqEFtassRLTr7b1mZUDh0g@mail.gmail.com>

On Sun, May 12, 2013 at 6:43 AM, Dave Angel <davea at davea.name> wrote:
[...]

> With no experience in programming other languages, you'd need a different
> kind of tutorial than I sought when I was learning Python. And you
> absolutely need to match your tutorial against the version of Python you're
> running on your machine.  2.x and 3.x aren't VERY different, but there were
> enough changes that you don't want to be dealing with that while learning
> initially.
>
> Anybody else want to recommend a tutorial for someone who has no programming
> experience in other languages?
>

I have not been looking at tutorials per se, but mostly books. Of the
ones I have actually looked at, "Python Programming for the Absolute
Beginner", 3rd ed., by Michael Dawson, and "More Python Programming
for the Absolute Beginner" by Jonathan S. Harbour look to be fairly
good and try to make things interesting by making their examples
always using games. However, one recent poster had trouble in the
second half of the first book when the text was introducing multimedia
games programming. However, that appeared to be due to getting the
PyGame module to work with his Python installation. The authors look
to be trying to accomplish their goal implied in their titles.

Another option, if the OP is not put off by books for "kids", is to
try one of several Python books that are available for free online
targeting kids. I am currently reviewing one, "Invent Your Own
Computer Games with Python" by Al Sweigart, that I am thinking of
using with my kids this summer. I have found that by looking at this
book (and others that I have examined as candidates for my kids) that
I have learned quite a bit without realizing it and have seen
clarifications of technical points that I had puzzled over in my other
texts oriented at adults. If nothing else, the OP could find one of
these, skim through it to get the true basics, and then go back to
another, more "adult" source.

Cheers!
boB

From ayjayn1101 at gmail.com  Sun May 12 21:40:10 2013
From: ayjayn1101 at gmail.com (Alex Norton)
Date: Sun, 12 May 2013 20:40:10 +0100
Subject: [Tutor] help regarding game code
Message-ID: <CAAQ2WQxy6WcsvwkExzwuUd3vVp_TZnBohHNcV9ahNV7kbr0MvA@mail.gmail.com>

im new to python and im in the middle of making a RPS game for a college
unit.

i have used PyQt to create the GUI and i have received help regarding
adding the code to the buttons.

but its missing something as the error

'Traceback (most recent call last): File "C:\Users\Me\Desktop\testy.py",
line 174, in bWater.clicked.connect( water_clicked ) AttributeError: 'int'
object has no attribute 'clicked'' appears when i run the module.

i was wondering if somebody could walk me through making the game complete
and to add the results of the game (win/lose/stalemate) to the loutcome
label

 attached is the game file.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130512/a913901b/attachment-0001.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: testy.py
Type: application/octet-stream
Size: 8339 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20130512/a913901b/attachment-0001.obj>

From chigga101 at gmail.com  Sun May 12 23:44:01 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Sun, 12 May 2013 22:44:01 +0100
Subject: [Tutor] help regarding game code
In-Reply-To: <CAAQ2WQxy6WcsvwkExzwuUd3vVp_TZnBohHNcV9ahNV7kbr0MvA@mail.gmail.com>
References: <CAAQ2WQxy6WcsvwkExzwuUd3vVp_TZnBohHNcV9ahNV7kbr0MvA@mail.gmail.com>
Message-ID: <CACzNyA18Ep-aJcySZe+STcVBvw4Ge90-qxcmgcefDr-sFTO62A@mail.gmail.com>

>> bWater.clicked.connect( water_clicked ) AttributeError: 'int

use a paste site like http://bpaste.net/+python to show us the code.

i am no expert @ programming myself but that error is telling you you
used an int and tried to access an int method called connect somewhere
in your code. ints do not have this method. However some PyQt objects
(mostly button widgets) do have this method, which is actually a
signal called clicked for when you mouse click on the widget(button).
So basically ints (integers) do not have signals, try and connect the
name(variable name) of what you are clicking to that method, instead
of the int object (bWater)

bWater.clicked.connect( water_clicked )  should become:

button_name.clicked.connect( water_clicked )

From amitsaha.in at gmail.com  Mon May 13 00:33:51 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Mon, 13 May 2013 08:33:51 +1000
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <518F8078.9030902@davea.name>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
Message-ID: <CANODV3m9suLCQ1RZJaUPOGW-7LMJKiYSJ4d+yQkpBmNetg1d_A@mail.gmail.com>

On Sun, May 12, 2013 at 9:43 PM, Dave Angel <davea at davea.name> wrote:
> On 05/11/2013 09:58 PM, Daniel Magruder wrote:
>
> Please respond to the list, not the individual.  Otherwise you're robbing
> yourself and others of the possibility of learning from and helping multiple
> people.  I don't mind if you ALSO reply to me (which is what reply-all does
> by default), but many people do object.  In Thunderbird, you normally just
> do Reply-list, and it does the right thing.  But with other email programs,
> you might do reply-all, and remove whichever recipients you don't need.
>
<snip>

>
> Anybody else want to recommend a tutorial for someone who has no programming
> experience in other languages?

I thought "Python for Kids" was a great book. The first "half" of the
book teaches the Python basics while focusing on writing games in the
second. I think it's worth a look.

No starch press: http://nostarch.com/pythonforkids
Amazon: http://www.amazon.com/Python-Kids-Playful-Introduction-Programming/dp/1593274076

-Amit.

--
http://echorand.me

From breamoreboy at yahoo.co.uk  Mon May 13 01:02:48 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Mon, 13 May 2013 00:02:48 +0100
Subject: [Tutor] help regarding game code
In-Reply-To: <CACzNyA18Ep-aJcySZe+STcVBvw4Ge90-qxcmgcefDr-sFTO62A@mail.gmail.com>
References: <CAAQ2WQxy6WcsvwkExzwuUd3vVp_TZnBohHNcV9ahNV7kbr0MvA@mail.gmail.com>
	<CACzNyA18Ep-aJcySZe+STcVBvw4Ge90-qxcmgcefDr-sFTO62A@mail.gmail.com>
Message-ID: <kmp72j$j1p$1@ger.gmane.org>

On 12/05/2013 22:44, Matthew Ngaha wrote:
>>> bWater.clicked.connect( water_clicked ) AttributeError: 'int
>
> use a paste site like http://bpaste.net/+python to show us the code.
>

No, please put the code inline.  If the original is too long cut it down 
as requested here http://www.sscce.org/

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From davea at davea.name  Mon May 13 01:26:13 2013
From: davea at davea.name (Dave Angel)
Date: Sun, 12 May 2013 19:26:13 -0400
Subject: [Tutor] help regarding game code
In-Reply-To: <CAAQ2WQxy6WcsvwkExzwuUd3vVp_TZnBohHNcV9ahNV7kbr0MvA@mail.gmail.com>
References: <CAAQ2WQxy6WcsvwkExzwuUd3vVp_TZnBohHNcV9ahNV7kbr0MvA@mail.gmail.com>
Message-ID: <51902515.3060609@davea.name>

On 05/12/2013 03:40 PM, Alex Norton wrote:
> im new to python and im in the middle of making a RPS game for a college
> unit.
>
>
You sent this message 20 minutes after posting a similar one, with a 
DIFFERENT title, on python-list.  You really ought to pick a target and 
pull the trigger once.  Only if no useful responses happen within a day 
or two should you bother the same people a second time on the other forum.

This is not a beginner question, so it belonged on python-list as you 
did first.


-- 
DaveA

From hobbestigrou at erakis.eu  Mon May 13 14:36:02 2013
From: hobbestigrou at erakis.eu (Natal =?iso-8859-1?Q?Ng=E9tal?=)
Date: Mon, 13 May 2013 14:36:02 +0200
Subject: [Tutor] Introducing myself.
Message-ID: <20130513123602.GA30101@hobbyone.CNFILMS>

Hi,

I'm new to the mailing list, I think it is interesting to present. I'm a
developer, I use Python and Perl yes it is also a great language. I use
Python to work, but I also love the language for its simplicity, its
community, and its clean syntax. Lacks a more advanced pypi like CPAN,
that parses the pydoc to show documentation, there readthedocs but it's
different, it is also interesting that pypi launches module tests, there
travis.ci but it is yet another platform, something centralized would
be more practical.

Otherwise, I am registered on the ml to help if I can, and I'd also like
to know the kind of question that can be asked, or stops the beginner
level, because I think remain an eternal beginner. What are the other ml
can advise you on the language in general ? Otherwise nothing to do, but
is it that there would be people who would need help for develop on open
source projects in Python, whether it interests me.

My best regards

-- 
\0/ Hobbestigrou
site web: erakis.eu
L'Europe est trop grande pour ?tre unie. Mais elle est trop petite pour
?tre
divis?e. Son double destin est l?

From Robert.Treder at morganstanley.com  Mon May 13 16:12:31 2013
From: Robert.Treder at morganstanley.com (Treder, Robert)
Date: Mon, 13 May 2013 10:12:31 -0400
Subject: [Tutor] creating a corpus from a csv file
In-Reply-To: <mailman.7347.1367656208.3113.tutor@python.org>
References: <mailman.7347.1367656208.3113.tutor@python.org>
Message-ID: <E84A3AA0F1F20E41953E8486223DD65057F533AF90@NYWEXMBX2130.msad.ms.com>


Message: 1
Date: Fri, 03 May 2013 23:05:32 +0100
From: Alan Gauld <alan.gauld at btinternet.com>
To: tutor at python.org
Subject: Re: [Tutor] creating a corpus from a csv file
Message-ID: <km1cb8$ist$1 at ger.gmane.org>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

On 03/05/13 21:48, Treder, Robert wrote:

> I'm very new to python and am trying to figure out how to
 > make a corpus from a text file.

Hi, I for one have no idea what a corpus is or looks like so you will need to help us out a little before we can help you.

> I have a csv file (actually pipe '|' delimited) where each row 
> corresponds to a different text document.

> Each row contains a communication note.
 > Other columns correspond to categories of types of communications.

> I am able to read the csv file and print the notes column as follows:
>
> import csv
> with open('notes.txt', 'rb') as infile:
>      reader = csv.reader(infile, delimiter = '|')
>      i = 0
>      for row in reader:
>      if i <= 25: print row[8]
>      i = i+1

You don't need to manually manage 'i'.

you could do this instead:

with open('notes.txt', 'rb') as infile:
      reader = csv.reader(infile, delimiter = '|')
      for count, row in enumerate(reader):
          if count <= 25: print row[8]  # I assume indented?
          else: break                   # save time if its a big file

> I would like to convert this to a categorized corpus with
 > some of the other columns corresponding to the categories.

You might be able to use a dictionary but for now I'm still not clear what you mean. Can you show us some sample input and output data?

 > documentation on how to use csv.reader with PlaintextCorpusReader

never heard of the latter - is it an external module?

HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/




Message: 7
Date: Sat, 04 May 2013 10:29:57 +0200
From: Peter Otten <__peter__ at web.de>
To: tutor at python.org
Subject: Re: [Tutor] creating a corpus from a csv file
Message-ID: <km2gtu$o7a$1 at ger.gmane.org>
Content-Type: text/plain; charset="ISO-8859-1"

Treder, Robert wrote:

> I'm very new to python and am trying to figure out how to make a corpus
> from a text file. I have a csv file (actually pipe '|' delimited) where
> each row corresponds to a different text document. Each row contains a
> communication note. Other columns correspond to categories of types of
> communications. I am able to read the csv file and print the notes column
> as follows:
>  
> import csv
> with open('notes.txt', 'rb') as infile:
>     reader = csv.reader(infile, delimiter = '|')
>     i = 0
>     for row in reader:
>     if i <= 25: print row[8]
>     i = i+1
> 
> I would like to convert this to a categorized corpus with some of the
> other columns corresponding to the categories. All of the columns are text
> (i.e., strings). I have looked for documentation on how to use csv.reader
> with PlaintextCorpusReader but have been unsuccessful in finding a 
> example similar to what I want to do. Can someone please help?

This mailing list is for learning Python. For problems with a specific 
library you should use the general python list 

<http://mail.python.org/mailman/listinfo/python-list>

or a forum dedicated to that library

<http://groups.google.com/group/nltk-users>

If you ask on a general forum you should give some context -- the name of 
the library would be the bare minimum.

The following comes with no warranties as I'm not an nltk user:

import csv
from nltk.corpus.reader.plaintext import CategorizedPlaintextCorpusReader
from itertools import islice, chain

LIMIT_SIZE = 25 # set to None if not debugging

def pairs(filename):
    """Generate (filename, list_of_categories) pairs from a csv file
    """
    with open(filename, "rb") as infile:
        rows = islice(csv.reader(infile, delimiter="|"), LIMIT_SIZE)
        for row in rows:
            # assume that columns 10 and above contain categories
            yield row[8], row[9:]

if __name__ == "__main__":
    import random
    FILENAME = "notes.txt"

    # assume that every filename occurs only once in the file
    file_to_categories = dict(pairs(FILENAME))

    files = list(file_to_categories)

    all_categories = 
set(chain.from_iterable(file_to_categories.itervalues()))

    reader = CategorizedPlaintextCorpusReader(".", files, 
cat_map=file_to_categories)

    # print words for a random category
    category = random.choice(list(all_categories))
    print "words for category {}:".format(category)
    print sorted(set(reader.words(categories=category)))

------------------------------
Alan, Peter, 

Thanks for your responses. Sorry about the lack of context and module information in my initial post. Peter got the context right - creating python object(s) from a collection of text documents (the corpus) in preparation to doing text mining and modeling. The modified script from Peter follows. I dropped the size limitation and have included some test data below. 

Problems still exist. The code attempts to read files with names based on concatenating the first and third columns, the data that is coming form the yield . Consequently, I'm convinced I will need to write a custom csvCorpusReader. I've received some tips for that from an nltk email group. 

If anyone has additional suggestions or comments I would love to hear them. 

Thanks, 
Bob


#####  Code below here   #####

import csv
from nltk.corpus.reader.plaintext import CategorizedPlaintextCorpusReader
from itertools import islice, chain

#filename = 'L:/gps_pa/DEV/TextMining/EmailTickerInterest/Data/testNotes.txt'# set to None if not debugging
filename = "C:/nltk_data/corpora/notes/testNotes.txt" # set to None if not debugging

def pairs(filename):
    """Generate (filename, list_of_categories) pairs from a csv file
    """
    with open(filename, "rb") as infile:
        rows = csv.reader(infile, delimiter="|")
        for row in rows:
            yield row[0], row[2]
            print row[0], row[2]

if __name__ == "__main__":
    import random
    FILENAME = "C:/nltk_data/corpora/notes/testNotes.txt"

    # assume that every filename occurs only once in the file
    file_to_categories = dict(pairs(FILENAME))

    files = list(file_to_categories)

    all_categories = set(chain.from_iterable(file_to_categories.itervalues()))
    print all_categories

    reader = CategorizedPlaintextCorpusReader(".", files, cat_map=file_to_categories)

    # print words for a random category
    category = random.choice(list(all_categories))
    print "words for category {}:".format(category)
    print sorted(set(reader.words(categories=category)))

Some test data looks like the following, the first row being column headers: 

CID|X|MID|note
1|not|101|note 1
2|any|102|note 2
3|thing|103|note 3
4|tbd|104|note 4





Modifying Peter's code to get it to run as far as possible.  

--------------------------------------------------------------------------------

NOTICE: Morgan Stanley is not acting as a municipal advisor and the opinions or views contained herein are not intended to be, and do not constitute, advice within the meaning of Section 975 of the Dodd-Frank Wall Street Reform and Consumer Protection Act. If you have received this communication in error, please destroy all electronic and paper copies and notify the sender immediately. Mistransmission is not intended to waive confidentiality or privilege. Morgan Stanley reserves the right, to the extent permitted under applicable law, to monitor electronic communications. This message is subject to terms available at the following link: http://www.morganstanley.com/disclaimers. If you cannot access these links, please notify us by reply message and we will send the contents to you. By messaging with Morgan Stanley you consent to the foregoing.

From alan.gauld at btinternet.com  Mon May 13 17:36:24 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 13 May 2013 16:36:24 +0100
Subject: [Tutor] Introducing myself.
In-Reply-To: <20130513123602.GA30101@hobbyone.CNFILMS>
References: <20130513123602.GA30101@hobbyone.CNFILMS>
Message-ID: <kmr19j$7bl$1@ger.gmane.org>

On 13/05/13 13:36, Natal Ng?tal wrote:

Welcome,

> Otherwise, I am registered on the ml to help if I can, and I'd also like
> to know the kind of question that can be asked, or stops the beginner
> level, because I think remain an eternal beginner.

The audience of the list is people learning Python. It is deliberately 
open ended, you decide when you are no longer a beginner :-)

We cover the Python language, idioms and the standard library.
Occasionally we will branch into non standard packages, especially the 
better known ones (wxPython, NumPy, Django etc) but generally those are 
better targeted at their own fora.

Finally, we also diverge into general computing theory, tools and other 
non Python topics that might be of value to beginners.

Read the posts and reply when you feel able to contribute.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From hobbestigrou at erakis.eu  Mon May 13 17:52:15 2013
From: hobbestigrou at erakis.eu (Natal =?iso-8859-1?Q?Ng=E9tal?=)
Date: Mon, 13 May 2013 17:52:15 +0200
Subject: [Tutor] Introducing myself.
In-Reply-To: <kmr19j$7bl$1@ger.gmane.org>
References: <20130513123602.GA30101@hobbyone.CNFILMS>
	<kmr19j$7bl$1@ger.gmane.org>
Message-ID: <20130513155214.GA2429@hobbyone.CNFILMS>

On 05/13/13 16:36, Alan Gauld wrote:
> The audience of the list is people learning Python. It is
> deliberately open ended, you decide when you are no longer a
> beginner :-)
Ok thanks for your response. As said, I think being a beginner eternal.

> We cover the Python language, idioms and the standard library.
> Occasionally we will branch into non standard packages, especially
> the better known ones (wxPython, NumPy, Django etc) but generally
> those are better targeted at their own fora.
Ok cool, yes you're right it's better to use their own mailing-list. But
small projects is not necessarily their own mailing list.

> Finally, we also diverge into general computing theory, tools and
> other non Python topics that might be of value to beginners.
Cool.

> Read the posts and reply when you feel able to contribute.
Ok thanks again.

-- 
\0/ Hobbestigrou
site web: erakis.eu
L'Europe est trop grande pour ?tre unie. Mais elle est trop petite pour ?tre
divis?e. Son double destin est l?


From hobbestigrou at erakis.eu  Mon May 13 17:58:02 2013
From: hobbestigrou at erakis.eu (Natal =?iso-8859-1?Q?Ng=E9tal?=)
Date: Mon, 13 May 2013 17:58:02 +0200
Subject: [Tutor] First Python module I publish.
Message-ID: <20130513155802.GB2429@hobbyone.CNFILMS>

Hi,

Sorry for this little pub, some time ago that I published my first
Python module on pypi. This is a port of a Perl module is a very simple
text localization system. I am very happy to have your opinion, ideas
and feedback. I have also a question I use % for the display of
the chain, but I think I understand it is now recommended to use format
or template, but i'm not sure.

This repository on github:

https://github.com/hobbestigrou/Pylocwolowitz

My best regards


-- 
\0/ Hobbestigrou
site web: erakis.eu
L'Europe est trop grande pour ?tre unie. Mais elle est trop petite pour ?tre
divis?e. Son double destin est l?


From staffordbaines at yahoo.com  Mon May 13 18:21:47 2013
From: staffordbaines at yahoo.com (Stafford Baines)
Date: Mon, 13 May 2013 17:21:47 +0100
Subject: [Tutor] under, under
Message-ID: <001b01ce4ff5$f80df850$e829e8f0$@com>

Please explain the significance of __some term__.  For example  __name__ as
in 

If __name__ == '__main__':

  main()

 

When is the under, under used?

 

Regards,

 

Stafford

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130513/e4ebf200/attachment.html>

From hobbestigrou at erakis.eu  Mon May 13 18:32:21 2013
From: hobbestigrou at erakis.eu (Natal =?iso-8859-1?Q?Ng=E9tal?=)
Date: Mon, 13 May 2013 18:32:21 +0200
Subject: [Tutor] under, under
In-Reply-To: <001b01ce4ff5$f80df850$e829e8f0$@com>
References: <001b01ce4ff5$f80df850$e829e8f0$@com>
Message-ID: <20130513163221.GA2780@hobbyone.CNFILMS>

On 05/13/13 17:21, Stafford Baines wrote:
> When is the under, under used?
It depends the context, for example __name__ represent the name of the current
package. The __init__ it's object methode to initialize the object, and
so on.

-- 
\0/ Hobbestigrou
site web: erakis.eu
L'Europe est trop grande pour ?tre unie. Mais elle est trop petite pour ?tre
divis?e. Son double destin est l?


From joel.goldstick at gmail.com  Mon May 13 18:41:23 2013
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Mon, 13 May 2013 12:41:23 -0400
Subject: [Tutor] under, under
In-Reply-To: <20130513163221.GA2780@hobbyone.CNFILMS>
References: <001b01ce4ff5$f80df850$e829e8f0$@com>
	<20130513163221.GA2780@hobbyone.CNFILMS>
Message-ID: <CAPM-O+wGK5WzZPxPt0smfyE-a9afPgVdSXPnm9cLTsKdnsNN7A@mail.gmail.com>

I have seen (and enjoy) people calling double underscore as 'Dunder'


On Mon, May 13, 2013 at 12:32 PM, Natal Ng?tal <hobbestigrou at erakis.eu>wrote:

> On 05/13/13 17:21, Stafford Baines wrote:
> > When is the under, under used?
> It depends the context, for example __name__ represent the name of the
> current
> package. The __init__ it's object methode to initialize the object, and
> so on.
>
> --
> \0/ Hobbestigrou
> site web: erakis.eu
> L'Europe est trop grande pour ?tre unie. Mais elle est trop petite pour
> ?tre
> divis?e. Son double destin est l?
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
http://joelgoldstick.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130513/93531c91/attachment.html>

From staffordbaines at yahoo.com  Mon May 13 18:44:47 2013
From: staffordbaines at yahoo.com (Stafford Baines)
Date: Mon, 13 May 2013 17:44:47 +0100
Subject: [Tutor] under, under
Message-ID: <002601ce4ff9$2e640180$8b2c0480$@com>

 

Please explain the significance of __some term__.    For example  __name__
as in 

If __name__ == '__main__':

  main()

 

When is the under, under used?

 

Regards,

 

Stafford

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130513/99609f7c/attachment.html>

From davea at davea.name  Mon May 13 19:18:45 2013
From: davea at davea.name (Dave Angel)
Date: Mon, 13 May 2013 13:18:45 -0400
Subject: [Tutor] under, under
In-Reply-To: <001b01ce4ff5$f80df850$e829e8f0$@com>
References: <001b01ce4ff5$f80df850$e829e8f0$@com>
Message-ID: <51912075.9060003@davea.name>

On 05/13/2013 12:21 PM, Stafford Baines wrote:
> Please explain the significance of __some term__.  For example  __name__ as
> in
>
> If __name__ == '__main__':
>
>    main()
>
> When is the under, under used?
>

(Please don't start a second thread with identical content 20 minutes 
after the first)

Underscores aren't anything special to the Python language itself, 
whether leading or trailing.  Thus there is no implicit connection 
between __name__ and name, for example.  However there is a convention 
for single and double underscores, and when the latter are at both start 
and end of a symbol, they have the cute nickname of dunder.

Dunder names are ones defined by the language as having special purpose. 
  We should never make up our own such names, as we might conflict with 
a dunder name that gets added in a later version of Python.

There are a few of them that are just data. One example is the __name__ 
builtin, and it is defined automatically by the import mechanism.  And 
since the script itself is "sort-of" imported, it gets a special name of 
a literal "__main__"   This lets you write code that behaves differently 
when run as a script then when it's imported explicitly from another 
module or script.

Most are methods, and these method names are called "special methods." 
The __init__() method for initializing is the most important, since it's 
implicitly called when a class instance is being initialized.  Likewise 
__new__().  Another (__str__()) is called implicitly when you try to 
interpret an object as a string (such as when you print it).

The debugger uses the __repr__() special method.  When you use the 
addition syntax
     a + b

you'll be using the __add__() and/or the __radd__() methods.

All these are pre-defined for the built-in types.  And you can see such 
a list of them for a given type by doing something like:
   a = list()
   print dir(a)

In the debugger, you might get:

  dir([])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', 
'__delslice__', '__doc__', '__eq__', '__format__', '__ge__', 
'__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', 
'__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', 
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', 
'__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 
'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

A key point is you can defined these in your own classes.  So you can 
define for example what it means for instances to be equal, or how you 
"add" them, or "subscript" them.

Normally, you do not directly call most of these special methods, 
they'll be called implicitly by various other means.  But you do write 
them in your code.


See:
http://docs.python.org/2/reference/datamodel.html#special-method-names

for a start.

-- 
DaveA

From jguadamuz at gmail.com  Mon May 13 19:21:01 2013
From: jguadamuz at gmail.com (=?ISO-8859-1?Q?Jonat=E1n_Guadamuz_Espinoza?=)
Date: Mon, 13 May 2013 11:21:01 -0600
Subject: [Tutor] under, under
In-Reply-To: <001b01ce4ff5$f80df850$e829e8f0$@com>
References: <001b01ce4ff5$f80df850$e829e8f0$@com>
Message-ID: <CAN66OYkBNYMne1K3BTweS9haP0YkcCjt0yA5OkqeMD_c9cH6VQ@mail.gmail.com>

On Mon, May 13, 2013 at 10:21 AM, Stafford Baines <staffordbaines at yahoo.com>
wrote:
>
> Please explain the significance of __some term__.  For example  __name__
as in
>
> If __name__ == ?__main__?:
>
>   main()
>
> When is the under, under used?

Section 2.3.2
http://docs.python.org/3/reference/lexical_analysis.html#reserved-classes-of-identifiers

Explain as follows:
__*__System-defined names. These names are defined by the interpreter and
its implementation (including the standard library). Current system names
are discussed in the Special method names section and elsewhere. More will
likely be defined in future versions of Python. Any use of __*__ names, in
any context, that does not follow explicitly documented use, is subject to
breakage without warning.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130513/1a26de83/attachment-0001.html>

From eryksun at gmail.com  Mon May 13 23:47:17 2013
From: eryksun at gmail.com (eryksun)
Date: Mon, 13 May 2013 17:47:17 -0400
Subject: [Tutor] under, under
In-Reply-To: <51912075.9060003@davea.name>
References: <001b01ce4ff5$f80df850$e829e8f0$@com> <51912075.9060003@davea.name>
Message-ID: <CACL+1asS7F7Gd4SJZPNTs7D5kSzxmv4iF8-jONOQ8KYUQKOBXQ@mail.gmail.com>

On Mon, May 13, 2013 at 1:18 PM, Dave Angel <davea at davea.name> wrote:
> Underscores aren't anything special to the Python language itself, whether
> leading or trailing.

I'm pretty sure you were just talking about dunder, dunder.
Underscores in general do have special uses in the language. They're
used to enable name mangling and to implicitly control star imports.

In a class definition, a leading dunder without a trailing dunder
enables name mangling with the class name:

    class Bar:
        def foo(self):
            self.__attr = 'spam'

    >>> obj = Bar()
    >>> obj.foo()
    >>> obj._Bar__attr
    'spam'

A subclass with a different name will use a different mangling, so
this provides a semi-private name. The purpose is to protect a private
implementation detail in the base class from being modified by a
subclass, either accidentally or intentionally.  I won't debate the
merits of this. Generally, however, one signals that an attribute is
'private' by using a single leading underscore. This is just a hint to
other programmers.

Name mangling is a compile-time operation. The compiler replaces all
identifiers that have a leading dunder (and no trailing dunder) with
the corresponding mangled name:

    >>> Bar.foo.__code__.co_names
    ('_Bar__attr',)

Another use of underscore is in a star import. To show this, create a module:

    >>> import sys, imp
    >>> sys.modules['mod'] = mod = imp.new_module(name='mod')

Add two global variables to the module, one with a leading underscore:

    >>> mod._foo = 'foo'
    >>> mod.bar = 'bar'

Do a star import. Observe that the name with the leading underscore was skipped:

    >>> from mod import *
    >>> '_foo' in locals()
    False
    >>> 'bar' in locals()
    True

Typically it's better to specify the names used in a star import by
defining __all__:

    >>> mod.__all__ = ['_foo', 'bar']
    >>> from mod import *
    >>> '_foo' in locals()
    True

From cybervigilante at gmail.com  Mon May 13 23:51:51 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Mon, 13 May 2013 14:51:51 -0700
Subject: [Tutor] variable in format string throwing error
Message-ID: <CALRAYNXfBmEcsnHpwR-=XfX5Q_H7qj=Jvy98aYMqkuVP=deqxA@mail.gmail.com>

I'm trying variable substitution in a format string that looks like one
that works, but I get an error. What am I doing wrong? tks

x = 40
s = 'John flew to the {0:-^{x}} yesterday'
print(s.format('moon', x))

Error is builtins.KeyError: 'x'

-- 
Jim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130513/64a21077/attachment.html>

From eryksun at gmail.com  Tue May 14 00:17:43 2013
From: eryksun at gmail.com (eryksun)
Date: Mon, 13 May 2013 18:17:43 -0400
Subject: [Tutor] variable in format string throwing error
In-Reply-To: <CALRAYNXfBmEcsnHpwR-=XfX5Q_H7qj=Jvy98aYMqkuVP=deqxA@mail.gmail.com>
References: <CALRAYNXfBmEcsnHpwR-=XfX5Q_H7qj=Jvy98aYMqkuVP=deqxA@mail.gmail.com>
Message-ID: <CACL+1avoUmrimeo5XnpZwEG2XAx47a5_8R5u9fUKwh84+CTpHw@mail.gmail.com>

On Mon, May 13, 2013 at 5:51 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> I'm trying variable substitution in a format string that looks like one that
> works, but I get an error. What am I doing wrong? tks
>
> x = 40
> s = 'John flew to the {0:-^{x}} yesterday'
> print(s.format('moon', x))
>
> Error is builtins.KeyError: 'x'

You need to use a keyword argument, x=x:

    >>> print(s.format('moon', x=x))
    John flew to the ------------------moon------------------ yesterday

Or change it to use a positional argument:

    >>> s = 'John flew to the {0:-^{1}} yesterday'
    >>> print(s.format('moon', x))
    John flew to the ------------------moon------------------ yesterday

From dsm3 at att.net  Tue May 14 01:01:51 2013
From: dsm3 at att.net (Daniel Magruder)
Date: Mon, 13 May 2013 18:01:51 -0500
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <518F8078.9030902@davea.name>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
Message-ID: <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>

Dear Dave,
I am using python 2.
I am still confused as what return does. What does it mean if a function returns True to the caller? What is the caller? 
Your code worked for returning a list of 1000 items of odd numbers, so I then tried writing a code to replay isodd to give True or False for isprime. However, 
> def isodd(candidate):
>    if candidate%2 ==0:
>        return False
>    else:
>        return True
The meaning of this I am still confused about. What does it mean if the value is returned as false if it has 0 remainder, what does it mean if it is returned as true? Is this like a dictionary with keys and values? 
Also, here is my new code, which still does not work. I have no idea why not, and am getting very frustrated by the fact that making a program that determines if a number is prime or not is so hard for me. I would appreciate any assistance, and a verbal walk through of how to logically determine if a number is prime. 

def isprime(x):
    test=2
    numberinquestion = x
    while test < numberinquestion:
        if numberinquestion % test == 0:
            test += 1
            return False
        elif numberinquestion / test == int:
            test += 1
            return False
    if test == numberinquestion:
        return True
            
def counting_primes():
    prime = 2
    primelist=[]
    while len(primelist) < 1000:
        if isprime(prime):
            primelist.append(prime)
        prime += 1
    return primelist
Sincerely,
Dan
On May 12, 2013, at 6:43 AM, Dave Angel <davea at davea.name> wrote:

> On 05/11/2013 09:58 PM, Daniel Magruder wrote:
> 
> Please respond to the list, not the individual.  Otherwise you're robbing yourself and others of the possibility of learning from and helping multiple people.  I don't mind if you ALSO reply to me (which is what reply-all does by default), but many people do object.  In Thunderbird, you normally just do Reply-list, and it does the right thing.  But with other email programs, you might do reply-all, and remove whichever recipients you don't need.
> 
>> Dear Dave,
>> I can't tell you how much I appreciate your assistance, however as a novice I doubt my ability to crawl. I sincerely envy your depth of understanding about this and in trying to learning would really benefit if you could please expound on a few notions.
>> Why must I top-level call? What is that actually? Several of the sources I have seen like learnpython.org suggest that def function(): is sufficient...
> 
> A function is defined by a def, but a program that never calls any of them will do nothing at all (except look for syntax errors and the like).  There are probably tens of thousands of defined functions in the library, but running python will only execute the ones you call.
> 
> Typically at the bottom of every script there needs to be at least one function call that gets things started.  (Unless the script is so trivial that it's written without using any functions).  But in either case, some top-level code is needed.
> 
> That top-level code can be as simple as a single call, or it might define a few variables, and then make the call(s).
> 
>> I thought I had to define prime as f(0) so that it would be a float, not an integer division. Am I wrong? I am so utterly confused.
> 
> I'm afraid you're wrong in a couple of points.  There's no such function as f() in the standard library.  If you wanted to define a literal float, you could either use 0.0, or use float(0).  But you do not want a float there, everything can be done with ints.
> 
>> In many sample codes I have seen num or int seem to be short hand for anything that is a number, because I though I was dividing and would receive a float remainder for non-prime numbers, I wan't to use that as a test.
> 
> int and float are types (and act like functions), and if you needed to check the type of an object, you'd use  isinstance(myvar, int) or isinstance(myvar, float).  You can't just do a comparison with int.  But dividing two ints will give an int in Python 2.x and will give a float in Python 3.x.   And that's regardless of whether it comes out even or not.  Which version of Python are you using?
> 
> Fortunately, there's a much better way of telling if an int can be divided by another int:  The modulo operator, represented by a "%" symbol.
> 
>    prime%n   will give the remainder, and if it's zero, you know that prime is evenly divisible by n  (and therefore isn't prime).
> 
> 
>> For your suggestion:
>>> def testprime(candidate)
>>>    check all ints between 2 and candidate, and return true if any of them divide the candidate evenly
>> I don't mean to be so dependent, but how would I do this? Also what is the difference between return and print?
>>>    Otherwise return false
>>> 
> 
> The return statement is the way a function returns a value to its caller.  Let's suppose you wanted a function that returned true if its int argument was odd.  You could do it like this:
> 
> def isodd(candidate):
>    if candidate%2 ==0:
>        return False
>    else:
>        return True
> 
> Now, the body of that function could be done in one line, but I wanted to illustrate the returning of useful values, and also the possibility that the return might not be at the end, and that there might be  more than one place the function returns.
> 
> Why not get the other function to call this one temporarily, and see if you can make the program find the first 1000 odd numbers instead.  Then you can come back to the testprime() function and see if you can create one that returns True for primes, and False for anything else.  Clearly that function will need a loop.
> 
>>> def counting_primes()
>>>    build a list of primes, where a number is put in the list if testprime() confirms that it is prime.
>> Again, how would I do this, so if I had something that told me a number was prime, how would I take that prime and put it in a list if the function is on loop?
>>>    return the list once it's big enough
> 
> You're already doing that in the code you showed.  You initialized the primelist, then started a while loop.  The difference I'm suggesting is that instead of dealing with x in this function, you defer that to the testprime() function.  So your loop would call testprime() and conditionally append the value prime to the primelist.
> 
> def counting_primes():
>    primelist=[]
>    prime = 2
>    while len(primelist) < 1000:
>        if isodd(prime):
>             primelist.append(prime)
>        prime += 1
>    return primelist
> 
>> Despite going to many sources I can not seem to find a single source that adequately explains Python 100% without any technical jargon or assumptions of prior knowledge. What I mean by this, is that I now have the gist of the utmost basics, but I would say my understanding is befuddled. Furthermore if I were to attempt to write code (such as this exercise) I am completely lost. What do you recommend for a good source to learn Python? I have tried MIT open course ware, but again even their intro explains the obvious, but not how to use it collectively.
>> Sincerely,
>> Dan
>> 
>> 
> 
> With no experience in programming other languages, you'd need a different kind of tutorial than I sought when I was learning Python. And you absolutely need to match your tutorial against the version of Python you're running on your machine.  2.x and 3.x aren't VERY different, but there were enough changes that you don't want to be dealing with that while learning initially.
> 
> Anybody else want to recommend a tutorial for someone who has no programming experience in other languages?
> 
> --
> DaveA
> 


From breamoreboy at yahoo.co.uk  Tue May 14 01:09:15 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 14 May 2013 00:09:15 +0100
Subject: [Tutor] variable in format string throwing error
In-Reply-To: <CALRAYNXfBmEcsnHpwR-=XfX5Q_H7qj=Jvy98aYMqkuVP=deqxA@mail.gmail.com>
References: <CALRAYNXfBmEcsnHpwR-=XfX5Q_H7qj=Jvy98aYMqkuVP=deqxA@mail.gmail.com>
Message-ID: <kmrrqo$6uv$1@ger.gmane.org>

On 13/05/2013 22:51, Jim Mooney wrote:
> I'm trying variable substitution in a format string that looks like one
> that works, but I get an error. What am I doing wrong? tks
>
> x = 40
> s = 'John flew to the {0:-^{x}} yesterday'
> print(s.format('moon', x))
>
> Error is builtins.KeyError: 'x'
>
> --
> Jim
>

Using over complicated modern string formatting?  Stick with the old C 
style % style and it's much easier.  Contrary to popular belief it's not 
going away :)

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From alan.gauld at btinternet.com  Tue May 14 01:55:55 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 14 May 2013 00:55:55 +0100
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
Message-ID: <kmrui6$van$1@ger.gmane.org>

On 14/05/13 00:01, Daniel Magruder wrote:

> I am still confused as what return does.
 > What does it mean if a function returns True to the caller?
 > What is the caller?

The caller is the program code that calls the function.
For example if I write a function

def square(x):
     return x*x

and write another function to display the first 5 squares:

def square5():
     for n in range(1:6):
         result = square(n)
         print result

square5() is the caller of square() and the return value (x*x)
is stored in result.

return always terminates a function and the value of
the expression following return is the value of the function.

>> def isodd(candidate):
>>     if candidate%2 ==0:
>>         return False
>>     else:
>>         return True

> The meaning of this I am still confused about.
 > What does it mean if the value is returned as false
> if it has 0 remainder,
> what does it mean if it is returned as true?

The function is answering the question "is candidate odd?"
It returns True if candidate is dd and False if candidate
is even. It determines whether candidate is even by dividing candidate 
by 2 and checking to see if there is a zero remainder. If the remainder 
is zero then candidate is even and isodd returns(evaluates to) False.

We can then use it in an if statement like

x = int(raw_input('number: '))
if isodd(x):
    print x,'is odd'
else:
    print x, 'is even'

> Is this like a dictionary with keys and values?

No, it's just the value of the function.

> def isprime(x):
>      test=2
>      numberinquestion = x
>      while test < numberinquestion:
>          if numberinquestion % test == 0:
>              test += 1
>              return False

Down to here is fine. All you need now is to
return True if you get to the end of the while loop.
(actually you probably don't want/need to increment
test here either but that's a nicety)

>          elif numberinquestion / test == int:

But this doesn't work because int is a type not a value.
I'm not quite sure what you think it might be doing but in practice it 
won't work because you are comparing a numeric value to a type.
(type is an object in Python) You could do it like:

          elif type(numberinquestion / test) == int:

But for various reasons isinstance() is the preferred method.

>              test += 1
>              return False


>      if test == numberinquestion:
>          return True

You don't really need the if test here since you only exit the while 
loop if test == numberinquestion

> def counting_primes():
>      prime = 2
>      primelist=[]
>      while len(primelist) < 1000:
>          if isprime(prime):
>              primelist.append(prime)
>          prime += 1
>      return primelist

That seems OK but it would be simpler with a for loop:

def counting_primes():
    primelist = []
    for prime in range(2,1000):
       if isprime(prime):
          primelist.append(prime)
    return primelist

And even shorter with a list comprehension

def counting_primes():
     return [n for n in range(2,1000) if isprime(n)]

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From marc.tompkins at gmail.com  Tue May 14 02:13:51 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Mon, 13 May 2013 17:13:51 -0700
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
Message-ID: <CAKK8jXZ7d8pzC6P+wNA0pG+NDhNuTYmWwwWF7VQ1FCmWWjfOdQ@mail.gmail.com>

On Mon, May 13, 2013 at 4:01 PM, Daniel Magruder <dsm3 at att.net> wrote:

> Dear Dave,
> I am using python 2.
> I am still confused as what return does. What does it mean if a function
> returns True to the caller? What is the caller?
>

You've defined a function - isodd - but it doesn't automatically execute.
It has to be invoked - "called" - from the main process of your script.
Generically, "the caller" is the process that invoked the function.

When you call a function, you pass input to it - "arguments" or
"parameters" - and you (optionally) get back a result.  The way the
function delivers that result is via "return".  The function can "return"
whatever you want it to; this is Python, and you are in control.  True and
False (NOT the same as the strings "True" and "False", by the way!) are two
special values that we use for clarity; you could substitute ANY true
statement for True, and ANY false statement for False.
In fact, you could shorten your isodd() function to:
> def isodd(candidate):
>    return candidate%2 !=0:
and it would function identically.



> Your code worked for returning a list of 1000 items of odd numbers, so I
> then tried writing a code to replay isodd to give True or False for
> isprime. However,
> > def isodd(candidate):
> >    if candidate%2 ==0:
> >        return False
> >    else:
> >        return True
> The meaning of this I am still confused about. What does it mean if the
> value is returned as false if it has 0 remainder, what does it mean if it
> is returned as true?


If you divide a number by 2 and there's no remainder, it's even.  If there
IS a remainder, it's odd.
Since we're trying to see whether the number "is odd", we return False in
the first case, and True in the second.


Is this like a dictionary with keys and values?
> Also, here is my new code, which still does not work. I have no idea why
> not, and am getting very frustrated by the fact that making a program that
> determines if a number is prime or not is so hard for me. I would
> appreciate any assistance, and a verbal walk through of how to logically
> determine if a number is prime.
>

There are two truisms of education that I consider absolutely vital:
-  If you can't explain it simply, you don't fully understand it yourself
-  The best way to learn something is to try to teach someone else.

When you write a program, you are explaining the problem - in the simplest
possible terms - to a student who truly knows NOTHING of what you're
talking about.  So it is absolutely vital that you understand it
yourself... but at the same time, once you've finished your program you
will understand the problem better than before you started.

A prime number is one whose only integer factors are itself and 1.

Anyway, a very simplistic test for whether X is prime:
a -  2 is the first prime.  Add it to your list of primes.
b -  starting from 3, take a number Y and try to divide it by every item in
the list of primes.
   -  for each item in the list, if the remainder is 0 then Y is not prime
   -  if you reach the end of the list and haven't had a 0 remainder, add Y
to the list.
c -  if Y is equal to or greater than X, you've finished building your list.
d -  if X is in the list, it's prime.

As you can see, this method requires testing every number UP TO X* in order
to determine whether X is prime; your job is actually simpler - you can
stop at c).

* Actually, you only need to test numbers up to the square root of X, but
let's keep it simple for the moment.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130513/5219f865/attachment.html>

From marc.tompkins at gmail.com  Tue May 14 02:16:50 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Mon, 13 May 2013 17:16:50 -0700
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <CAKK8jXZ7d8pzC6P+wNA0pG+NDhNuTYmWwwWF7VQ1FCmWWjfOdQ@mail.gmail.com>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<CAKK8jXZ7d8pzC6P+wNA0pG+NDhNuTYmWwwWF7VQ1FCmWWjfOdQ@mail.gmail.com>
Message-ID: <CAKK8jXaR2ikwvzU4etZhsP+-QEeQY_=Dr=z0XMT8wscZNQ8xyw@mail.gmail.com>

On Mon, May 13, 2013 at 5:13 PM, Marc Tompkins <marc.tompkins at gmail.com>wrote:

> In fact, you could shorten your isodd() function to:
> > def isodd(candidate):
> >    return candidate%2 !=0:
> and it would function identically.
>

Sorry - that should be
> def isodd(candidate):
>    return candidate%2 !=0
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130513/3ec6f3d0/attachment.html>

From davea at davea.name  Tue May 14 02:35:01 2013
From: davea at davea.name (Dave Angel)
Date: Mon, 13 May 2013 20:35:01 -0400
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
Message-ID: <519186B5.50400@davea.name>

On 05/13/2013 07:01 PM, Daniel Magruder wrote:
> Dear Dave,
> I am using python 2.
> I am still confused as what return does.   What does it mean if a
 > function returns True to the caller? What is the caller?

Have you ever used (called) a function?  If so, you've written a caller. 
  For example, if you want the absolute value of an integer, you might do:

import math

x = float(raw_input("Type an integer"))
y = math.fabs(x)        #Here I'm calling the function
print "Absolute value is", y

Now, somewhere in the Python library, a function was defined called 
fabs(), and it had a return statement with the value you want.

> Your code worked for returning a list of 1000 items of odd numbers, so I then tried writing a code to replay isodd to give True or False for isprime. However,
>> def isodd(candidate):
>>     if candidate%2 ==0:
>>         return False
>>     else:
>>         return True
> The meaning of this I am still confused about. What does it mean if the value is returned as false if it has 0 remainder, what does it mean if it is returned as true? Is this like a dictionary with keys and values?

I don't have a clue what you're confused about.  Do you not understand 
remainders?  If the remainder is 1 then the number is odd, while if the 
remainder is 0 then the number is even.  That's math, not programming.


> Also, here is my new code, which still does not work. I have no idea why not, and am getting very frustrated by the fact that making a program that determines if a number is prime or not is so hard for me. I would appreciate any assistance, and a verbal walk through of how to logically determine if a number is prime.
>
> def isprime(x):
>      test=2
>      numberinquestion = x
>      while test < numberinquestion:
>          if numberinquestion % test == 0:
>              test += 1
>              return False
>          elif numberinquestion / test == int:

Here you go again;  int is a type, not a value. Anyway, all the testing 
you needed was already done, if there's a nonzero remainder you already 
returned a False.  If there is a remainder, there's nothing more to test 
for this value of 'test'.  So increment and loop around.

>              test += 1
>              return False
>      if test == numberinquestion:

This is also unneeded.  If the while has finished, then you can return True.

>          return True
>
> def counting_primes():
>      prime = 2
>      primelist=[]
>      while len(primelist) < 1000:
>          if isprime(prime):
>              primelist.append(prime)
>          prime += 1
>      return primelist
> Sincerely,
> Dan



-- 
DaveA

From steve at pearwood.info  Tue May 14 03:03:39 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 14 May 2013 11:03:39 +1000
Subject: [Tutor] under, under
In-Reply-To: <001b01ce4ff5$f80df850$e829e8f0$@com>
References: <001b01ce4ff5$f80df850$e829e8f0$@com>
Message-ID: <51918D6B.7040903@pearwood.info>

On 14/05/13 02:21, Stafford Baines wrote:
> Please explain the significance of __some term__.  For example  __name__ as
> in
>
> If __name__ == '__main__':
>
>    main()
>
>
>
> When is the under, under used?


Underscores are legal characters in names. So you can write:

some_term = whatever()

and it is a legal name.

*Leading* underscores have a special meaning. A single leading underscore is considered to be "private":

_name = 42

means that _name should be considered "private, hands off". Or at least, "if you break it, you bought it". No guarantees are valid if you change a private value and things break.

Names with Double leading and trailing UNDERscores ("dunder") are reserved for Python's internal use. They get used for special methods, and a few other things. For example, to override the + operator, you write a class that defines __add__ and __radd__ methods. To override the == operator, you write a class that defines a __eq__ method. There are many examples of such, you can read the docs for a current list:

http://docs.python.org/2/reference/datamodel.html#special-method-names


__name__ is a special variable automatically created by Python. Modules and packages are automatically given a variable called __name__ which contains their name. When you are executing a module as a script, that variable gets set to the special value "__main__" instead of the module's actual name. So you can detect whether your code is being run as a script with a tiny bit of boilerplate code:


if __name__ == '__main__':
     ...


-- 
Steven

From davea at davea.name  Tue May 14 03:37:09 2013
From: davea at davea.name (Dave Angel)
Date: Mon, 13 May 2013 21:37:09 -0400
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <kmrui6$van$1@ger.gmane.org>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<kmrui6$van$1@ger.gmane.org>
Message-ID: <51919545.8090905@davea.name>

On 05/13/2013 07:55 PM, Alan Gauld wrote:
> On 14/05/13 00:01, Daniel Magruder wrote:
>
>>    <SNIP>
>
>
>
> That seems OK but it would be simpler with a for loop:
>
> def counting_primes():
>     primelist = []
>     for prime in range(2,1000):
>        if isprime(prime):
>           primelist.append(prime)
>     return primelist

Actually no, since the OP's looking for the first 1000 primes not for 
all the primes under 1000.

-- 
DaveA

From davea at davea.name  Tue May 14 04:29:36 2013
From: davea at davea.name (Dave Angel)
Date: Mon, 13 May 2013 22:29:36 -0400
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <6062F59A-0968-4A07-AC62-EB74F49B2D61@att.net>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<519186B5.50400@davea.name>
	<6062F59A-0968-4A07-AC62-EB74F49B2D61@att.net>
Message-ID: <5191A190.7090407@davea.name>

(Please don't top-post.  And don't reply privately, as I'm not the only 
one reading this thread.  Post the reply to the list, as you did last 
time with your reply-all)

On 05/13/2013 09:45 PM, Daniel Magruder wrote:
> Dear Dave,
>
>> I don't have a clue what you're confused about.  Do you not understand remainders?  If the remainder is 1 then the number is odd, while if the remainder is 0 then the number is even.  That's math, not programming.
>>
> I understand remainders, I am confused with some of the innate functions of python, such as what it assumes. For example here is my code, and maybe this well help explain where I am confused...
>
> def isprime(x): # this is a function to find out if a number, x, is prime
>      test=2 # this number will test to see if x is prime by exhaustive division
>      numberinquestion = x
>      while test < numberinquestion: # so long as test is less than the number I am testing, then I will compute the following block
>          if numberinquestion % test == 0: # if the the remainder is zero then the number is not prime
>              test += 1 # I am increasing test by one to make sure I exhaustively go through all the numbers
>             # between test and x

Well that increment is misplaced, since you're about to return,  Who 
cares what test is since it's discarded upon function returning?

  I am unsure if the while loop would automatically increase test
if I did not specify +=1. While 6%5 gives a remainder, 15% 5 does not, 
but 15%6 does.

If just one case has no remainder, you've found a non-prime and you can 
return.  Who cares if some of the others have remainders?

>              return False # if this condition is met, then the number is not prime.  How do i know that false is assigned to x not test?

It's False, not false, and it's not assigned to any local variables. 
It's returned.  So in your case, the caller is testing it for True, 
since the caller is in an if test.  The caller will then skip his 
append(), and the value won't be added to the list.

At this point, you're missing the other increment of test.  This is 
where the    test += 1 is needed.

>      return True # I am unsure why this works, does it only get to this point after going through the while, so test = x?

Yes.

  How do I know that this works?

That's the definition of a while loop.  it won't fall out of the loop as 
long as the condition is true.  So at this point, we can be sure that 
test is not less than numberinquestion.  Since it was incremented by 
only 1 each time, it must be equal to numberinquestion.

I mean, couldn't the interpreter go through the while and then assign 
true to a non-prime number?

No, because if the number was non-prime then one of the numberinquestion 
%test  would have been zero, and we would already have returned from the 
function without getting to this line.

  Also, since before this is an if statement, that means if x % test != 
0 then it automatically

No idea what you mean by "it" in this question.  Nowhere is there an 
assignment to True in this function.  Returning False does not assign 
anything, and it also ends the function.

> is assigned to true, even if the test number is 4 and x is 15. So wouldn't this not go to 5 and find the remainder? How do I know this will continue to test every possibility?  HERE IS MY CONFUSION.
>

When x is 15, it has already exited before it gets to 4.  So let's 
pretend you're asking about x being 25.

when test is 4 and x is 25, it will skip the return False, increment 
test (once you move that line), and go back to the while statement. 
That time around it will find a zero remainder, and return False.
>
> def counting_primes(): # a function to create a list of primes
>      prime = 2 # two is the first prime and can problematic so starting at two
>      primelist=[] # I want to start with an empty list
>      while len(primelist) < 1000: # I want a list with 1000 items in it, so to do that, I will use while the length is less than 1000
>          if isprime(prime): # conditional calling is prime function
>              primelist.append(prime) # appending the variable prime to primelist if the value is true, but I am worried if this will give false positives based on my previous comments above

No, by definition, you trust the function above. If it's broken, fix it, 
don't worry about it here.

>          prime += 1 # check the next number to see if it is prime
>      return primelist # still not totally sure what return is doing, it doesn't print, so is it the same as primelist = primelist? is it reassigning my empty primelist at the start of the function to what ever it is now at the end of the conditional?
>>
>> Here you go again;  int is a type, not a value.
> I was thinking that if you do something like 15%4, there is a remainder 3 which is an int, and as primes got excessively large that ==0 may not be enough to recognize primes that are (except two) odd

You can't explain a return without mentioning the caller, and you've 
removed the caller from this code.  Return passes the value directly 
back to the caller of the function.

#top-level code:
myprimes = counting_primes()
print myprimes[7]

   If that caller assigns it to a variable  myprimes then you have (in 
effect)   myprimes = primelist.  It does not print it.  But the 
top-level code can then use the returned value any way it likes.


Modulo will work accurately for int and long up to the point where you 
run out of memory, which will be typically for a number hundreds of 
millions of digits long.  You're thinking of floats, which are 
inherently flawed for this type of work.

>>
>>
>>>              test += 1
>>>              return False

>>>      if test == numberinquestion:
>>
>> This is also unneeded.  If the while has finished, then you can return True.
> Yeah I guess your write that is unneeded, but I wasn't sure if after the first if conditional test would return to 2??
>

Only if you had the prime = 2 inside the while loop.

>
> So does this clarify why I do not understand this? Also, that code above, I tried it and it did not work, it gave a general syntax error...
> Sincerely,
> Dan
>
>

That gives me no clue to help you with.  A syntax error points to a 
particular line, and column within that line.  Sometimes the actual 
error is in the previous line, but that does narrow it down quite a lot.

So when you say it gives an error, show the full traceback.

def isprime(x): # this is a function to find out if a number, x, is prime
     test=2 # this number will test to see if x is prime by exhaustive 
division
     numberinquestion = x
     while test < numberinquestion: # so long as test is less than the 
number I am testing, then I will compute the following block
         if numberinquestion % test == 0: # if the the remainder is zero 
then the number is not prime
             return False # if this condition is met, then the number is 
not prime.
	test += 1
     return True # It made it all the way, and had nonzero remainders 
everywhere


def counting_primes(): # a function to create a list of primes
     prime = 2 # two is the first prime and can problematic so starting 
at two
     primelist=[] # I want to start with an empty list
     while len(primelist) < 1000: # I want a list with 1000 items in it
         if isprime(prime): # conditionally execute next line based on 
isprime() return value
             primelist.append(prime) # appending the variable prime to 
primelist if the value is true
         prime += 1 # get ready to check the next number
     return primelist # still not totally sure what return is doing, it 
doesn't print, so is it the


myprimes = counting_primes()
print len(myprimes)
print myprimes[:10]

This code is not the way I would write it, but it follows your original 
logic, and works.  Only once you understand why it works should you try 
to optimize it.

--
DaveA


From alan.gauld at btinternet.com  Tue May 14 10:22:55 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 14 May 2013 09:22:55 +0100
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <51919545.8090905@davea.name>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<kmrui6$van$1@ger.gmane.org> <51919545.8090905@davea.name>
Message-ID: <kmss8q$8kk$1@ger.gmane.org>

On 14/05/13 02:37, Dave Angel wrote:

>> def counting_primes():
>>     primelist = []
>>     for prime in range(2,1000):
>>        if isprime(prime):
>>           primelist.append(prime)
>>     return primelist
>
> Actually no, since the OP's looking for the first 1000 primes not for
> all the primes under 1000.

Ah yes, I forgot that and didn't read the code properly, sorry.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From alan.gauld at btinternet.com  Tue May 14 10:51:11 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 14 May 2013 09:51:11 +0100
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
Message-ID: <kmsttq$qj6$1@ger.gmane.org>

On 14/05/13 00:01, Daniel Magruder wrote:

> I am still confused as what return does.

Having seen the other replies I'll try a slightly
different explanation.

All programs are formed by a hierarchy of functions.
You start with a top level driver block which then utilizes or calls 
helper functions. Those helper functions, in turn, call other helper 
functions. We can show it diagrammatically as a tree and several 
software design notations exist that do this. Here is one example:

http://www.smartdraw.com/resources/tutorials/Entity-Structure-Diagrams

Since this is a text forum I'll do it in a different format...

Driver block
    helper1
       funcA
       funcB
    helper2
       funcA
       funcC
    helper3

In this hierarchy the Driver calls 3 functions.
The helper functions call 2,2 and zero functions respectively.
funcA is called by both helper1 and helper2. When a function calls 
another function it effectively pauses its own execution and hands 
control to the called function.

Inside each of these 6 functions there are return statements(*) the 
purpose of which is to return control to the next higher level in the 
hierarchy. The function stops as soon as it reaches a return statement 
and control reverts to the previous level.

Thus in funcA the first time it is called it will return to helper1.
The second time it is called it will return control to helper2.

return also has a secondary purpose which is to pass back a value to the 
caller which value is the result of the functions calculations.

(*) Some functions do not have an explicit return statement. In these 
cases they run to completion and control then reverts to the calling 
function with an implied return value of None.

Does that help?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From mguptal at aol.com  Tue May 14 12:33:37 2013
From: mguptal at aol.com (mguptal at aol.com)
Date: Tue, 14 May 2013 06:33:37 -0400 (EDT)
Subject: [Tutor] (no subject)
Message-ID: <8D01EA5A0A121C9-164C-13777@webmail-d148.sysops.aol.com>

http://spelencasino.net/facebook_xml.php?xtafmvfp821dutqi































































































































==========================
I am sure that we will be very proud of you when we have launched you into the world... -- Alain Martin (to Adam Rifkin???)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130514/f767f754/attachment.html>

From blndepemployees at gmail.com  Tue May 14 18:09:28 2013
From: blndepemployees at gmail.com (SSGC Balochistan Deprived Employees)
Date: Tue, 14 May 2013 21:09:28 +0500
Subject: [Tutor] ok received open account
Message-ID: <CAE+d4iJoDk_WfX=B3Q9iZ8kCCxnuE2RQipb2izARNVL5-j57PA@mail.gmail.com>


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130514/f500f4fa/attachment.html>

From marc.tompkins at gmail.com  Tue May 14 18:11:22 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Tue, 14 May 2013 09:11:22 -0700
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <kmsttq$qj6$1@ger.gmane.org>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<kmsttq$qj6$1@ger.gmane.org>
Message-ID: <CAKK8jXaGp0XRPCwLzj_1t=tb8wEUMFPBSuzoJ8rtsHp-T_Z3Hg@mail.gmail.com>

On Tue, May 14, 2013 at 1:51 AM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> On 14/05/13 00:01, Daniel Magruder wrote:
>
>  I am still confused as what return does.
>>
>
> This isn't a direct response to Alan, but to something the OP expressed
many, many messages ago...

The OP expressed some confusion between what a function DOES and what it
RETURNS.  It occurs to me that the print() function (or, more generically,
ANY print() function - it doesn't have to be Python 3) is a good
demonstration.

Our first exposure to print() is very simple: display something on the
screen - what could possibly go wrong?  However, print() can redirect its
output to files, printers, skywriters, etc. - and sometimes it will be a
real question whether print() succeeded in producing any output.  (If your
program is trying to write data into a file, you'd probably like to know
whether it worked or not.)  So print() - like all functions - has an
optional return value, which your program can read to see whether it needs
to retry, display an error message, etc.

Again, the return value of print() - e.g. success/failure - is separate
from what print() actually prints.

In general, all functions can have effects - like the output of print() -
and/or return something.  Sometimes you're interested in one and not the
other; for instance, most of the time you don't care about print()'s return
value.  On the other hand, there's a style of programming called
"functional", in which everything is a function and NOTHING has any side
effects at all - I must confess, I find it hard to get my head around that.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130514/cd555d01/attachment.html>

From blndepemployees at gmail.com  Tue May 14 18:08:59 2013
From: blndepemployees at gmail.com (SSGC Balochistan Deprived Employees)
Date: Tue, 14 May 2013 21:08:59 +0500
Subject: [Tutor] ok this is received open my account
Message-ID: <CAE+d4iKS6YH5q4xuFkq6J2KQgODzrew8B9y=4rzB=TZfw_aPgQ@mail.gmail.com>


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130514/7f75cda5/attachment.html>

From chigga101 at gmail.com  Tue May 14 21:54:00 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Tue, 14 May 2013 20:54:00 +0100
Subject: [Tutor] env var packages
Message-ID: <CACzNyA3N38knCLE_3c7VUnWzoLzQV4N5rCARfQXYEvghKZPJFQ@mail.gmail.com>

i have to install django and ive come across some weird instructions.
it says to set Django's  django-admin.py file to my environment
variable. I was instructed to get django via easy installer that was
located in my Python/Scripts folder. it installed django to a
different place in site-packages, where django-admin.py resides.But
now its telling me to add this file to my env variable and it should
also be located in Python/Scripts .. but as i've said, its clearly not
there, it is somewhere in a site-packages/django sub folder. so is
this an error? or do i go ahead and add Python/Scripts to the env
variable, even those the file points somewhere else?

My 2nd problem is it says after adding it i will get a python
interpreter and Django's djando-admin.py commad up and running. What
does this mean? both files open? it was specific about adding the path
to the env variable, but if i already have python added, why do i need
to add django? shouldnt it already be added? i will quote:

"You should make sure "djando-admin.py" is in your PATH environment
variable so that it can be executed from the command-line (unless you
like calling interpreters by using full pathnames)"

does this mean in a terminal, that i can be in
"Python/myproject/script_one/" and be able to open a .py file in
"Python/myproject/script_two/" by simpling typing its file name
without having to cd into its directory or typing its full path?

From pprakashsingh72 at gmail.com  Wed May 15 08:08:22 2013
From: pprakashsingh72 at gmail.com (prakash singh)
Date: Wed, 15 May 2013 06:08:22 +0000 (UTC)
Subject: [Tutor] Invitation to connect on LinkedIn
Message-ID: <1434548604.4311424.1368598102082.JavaMail.app@ela4-bed77.prod>

LinkedIn
------------



I'd like to add you to my professional network on LinkedIn.

- prakash

prakash singh
Lte tester at SAI Technology
Chennai Area, India

Confirm that you know prakash singh:
https://www.linkedin.com/e/-229nms-hgq3z226-6s/isd/13280421960/AGfwWxhN/?hs=false&tok=0T4dkEL2hM3lM1

--
You are receiving Invitation to Connect emails. Click to unsubscribe:
http://www.linkedin.com/e/-229nms-hgq3z226-6s/IZPPfNL6humFkJadIejjoAnrWJn/goo/tutor%40python%2Eorg/20061/I4399249361_1/?hs=false&tok=2MUMrt18RM3lM1

(c) 2012 LinkedIn Corporation. 2029 Stierlin Ct, Mountain View, CA 94043, USA.


  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130515/18d55dca/attachment-0001.html>

From volk.vasiliy at gmail.com  Wed May 15 10:26:08 2013
From: volk.vasiliy at gmail.com (vasya)
Date: Wed, 15 May 2013 12:26:08 +0400
Subject: [Tutor] env var packages
In-Reply-To: <CACFVp03a8QMGJZNW-cW0TBVZYnF1fMv3PaRBQs_X9TZX1-NWGQ@mail.gmail.com>
References: <CACzNyA3N38knCLE_3c7VUnWzoLzQV4N5rCARfQXYEvghKZPJFQ@mail.gmail.com>
	<CACFVp03a8QMGJZNW-cW0TBVZYnF1fMv3PaRBQs_X9TZX1-NWGQ@mail.gmail.com>
Message-ID: <CACFVp03JJaCmSjTMGy0dPPuwUeuX+XJL8_oWjCELe7=8x7JdDA@mail.gmail.com>

2013/5/15 vasya <volk.vasiliy at gmail.com>

> Hi, Matthew
>
> First of all, please state what OS do you using?
> I think its ubuntu because some kind of this problem I've alredy solved
> some time ago: when I've need something like to add "djando-admin.py"  to
> my PATH.
>
> What you need to do is to delete your django install that you make from
> easy_install and install django from package-manager that provide your
> system. How to delete is described here:
> https://docs.djangoproject.com/en/dev/topics/install/#remove-any-old-versions-of-django
>
> And how to install django depends from system to system... As I said
> specify it. For ubuntu it is "apt-get install python-django". BTW
> installing packages from packet-manager the most common and the most
> clearly and best way to install. Do not try to clone it from git or tar.gz
> source code unless you what you do. Or try to use checkinstall (in ubuntu).
>
> About what "djando-admin.py" do. This is script file that generates simple
> structure of your future code, small enviroment like "hello world" in other
> programming languages. In some distributions (like ubuntu AFAIK) its also
> can start simple HTTP server for debugging your django project. On
> different systems there is also exists "manage.py" module which also do
> this (and this is common way that describes in books). Also it provides
> some interface to manipulate on different settings of your django project.
> To make simple "hello world" enviroment you should write in your terminal
> something like: "django-admin startproject helloworld"
>
>
> 2013/5/14 Matthew Ngaha <chigga101 at gmail.com>
>
>> i have to install django and ive come across some weird instructions.
>> it says to set Django's  django-admin.py file to my environment
>> variable. I was instructed to get django via easy installer that was
>> located in my Python/Scripts folder. it installed django to a
>> different place in site-packages, where django-admin.py resides.But
>> now its telling me to add this file to my env variable and it should
>> also be located in Python/Scripts .. but as i've said, its clearly not
>> there, it is somewhere in a site-packages/django sub folder. so is
>> this an error? or do i go ahead and add Python/Scripts to the env
>> variable, even those the file points somewhere else?
>>
>> My 2nd problem is it says after adding it i will get a python
>> interpreter and Django's djando-admin.py commad up and running. What
>> does this mean? both files open? it was specific about adding the path
>> to the env variable, but if i already have python added, why do i need
>> to add django? shouldnt it already be added? i will quote:
>>
>> "You should make sure "djando-admin.py" is in your PATH environment
>> variable so that it can be executed from the command-line (unless you
>> like calling interpreters by using full pathnames)"
>>
>> does this mean in a terminal, that i can be in
>> "Python/myproject/script_one/" and be able to open a .py file in
>> "Python/myproject/script_two/" by simpling typing its file name
>> without having to cd into its directory or typing its full path?
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
> Sorry for top-post. Google mail make it by default... :-(
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130515/4c611e2e/attachment.html>

From volk.vasiliy at gmail.com  Wed May 15 10:25:25 2013
From: volk.vasiliy at gmail.com (vasya)
Date: Wed, 15 May 2013 12:25:25 +0400
Subject: [Tutor] env var packages
In-Reply-To: <CACzNyA3N38knCLE_3c7VUnWzoLzQV4N5rCARfQXYEvghKZPJFQ@mail.gmail.com>
References: <CACzNyA3N38knCLE_3c7VUnWzoLzQV4N5rCARfQXYEvghKZPJFQ@mail.gmail.com>
Message-ID: <CACFVp03a8QMGJZNW-cW0TBVZYnF1fMv3PaRBQs_X9TZX1-NWGQ@mail.gmail.com>

Hi, Matthew

First of all, please state what OS do you using?
I think its ubuntu because some kind of this problem I've alredy solved
some time ago: when I've need something like to add "djando-admin.py"  to
my PATH.

What you need to do is to delete your django install that you make from
easy_install and install django from package-manager that provide your
system. How to delete is described here:
https://docs.djangoproject.com/en/dev/topics/install/#remove-any-old-versions-of-django

And how to install django depends from system to system... As I said
specify it. For ubuntu it is "apt-get install python-django". BTW
installing packages from packet-manager the most common and the most
clearly and best way to install. Do not try to clone it from git or tar.gz
source code unless you what you do. Or try to use checkinstall (in ubuntu).

About what "djando-admin.py" do. This is script file that generates simple
structure of your future code, small enviroment like "hello world" in other
programming languages. In some distributions (like ubuntu AFAIK) its also
can start simple HTTP server for debugging your django project. On
different systems there is also exists "manage.py" module which also do
this (and this is common way that describes in books). Also it provides
some interface to manipulate on different settings of your django project.
To make simple "hello world" enviroment you should write in your terminal
something like: "django-admin startproject helloworld"


2013/5/14 Matthew Ngaha <chigga101 at gmail.com>

> i have to install django and ive come across some weird instructions.
> it says to set Django's  django-admin.py file to my environment
> variable. I was instructed to get django via easy installer that was
> located in my Python/Scripts folder. it installed django to a
> different place in site-packages, where django-admin.py resides.But
> now its telling me to add this file to my env variable and it should
> also be located in Python/Scripts .. but as i've said, its clearly not
> there, it is somewhere in a site-packages/django sub folder. so is
> this an error? or do i go ahead and add Python/Scripts to the env
> variable, even those the file points somewhere else?
>
> My 2nd problem is it says after adding it i will get a python
> interpreter and Django's djando-admin.py commad up and running. What
> does this mean? both files open? it was specific about adding the path
> to the env variable, but if i already have python added, why do i need
> to add django? shouldnt it already be added? i will quote:
>
> "You should make sure "djando-admin.py" is in your PATH environment
> variable so that it can be executed from the command-line (unless you
> like calling interpreters by using full pathnames)"
>
> does this mean in a terminal, that i can be in
> "Python/myproject/script_one/" and be able to open a .py file in
> "Python/myproject/script_two/" by simpling typing its file name
> without having to cd into its directory or typing its full path?
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130515/4b5ddbe0/attachment.html>

From oscar.j.benjamin at gmail.com  Wed May 15 11:03:20 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Wed, 15 May 2013 10:03:20 +0100
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <CAKK8jXaGp0XRPCwLzj_1t=tb8wEUMFPBSuzoJ8rtsHp-T_Z3Hg@mail.gmail.com>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<kmsttq$qj6$1@ger.gmane.org>
	<CAKK8jXaGp0XRPCwLzj_1t=tb8wEUMFPBSuzoJ8rtsHp-T_Z3Hg@mail.gmail.com>
Message-ID: <CAHVvXxR+zyewGGnzPoCYtZFc-yr5xsKhWMDVSTZ3+ke1Vzvv8Q@mail.gmail.com>

On 14 May 2013 17:11, Marc Tompkins <marc.tompkins at gmail.com> wrote:
>
> The OP expressed some confusion between what a function DOES and what it RETURNS.  It occurs to me that the print() function (or, more generically, ANY print() function - it doesn't have to be Python 3) is a good demonstration.
>
> Our first exposure to print() is very simple: display something on the screen - what could possibly go wrong?  However, print() can redirect its output to files, printers, skywriters, etc. - and sometimes it will be a real question whether print() succeeded in producing any output.  (If your program is trying to write data into a file, you'd probably like to know whether it worked or not.)  So print() - like all functions - has an optional return value, which your program can read to see whether it needs to retry, display an error message, etc.
>
> Again, the return value of print() - e.g. success/failure - is separate from what print() actually prints.


I was surprised by this so I've just tested it and checked the docs;
the print() function does not return anything (i.e. it returns None).

>>> a = print('qwe')
qwe
>>> a
>>> print(a)
None

http://docs.python.org/3/library/functions.html#print


Oscar

From steve at pearwood.info  Wed May 15 11:26:23 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 15 May 2013 19:26:23 +1000
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <CAHVvXxR+zyewGGnzPoCYtZFc-yr5xsKhWMDVSTZ3+ke1Vzvv8Q@mail.gmail.com>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<kmsttq$qj6$1@ger.gmane.org>
	<CAKK8jXaGp0XRPCwLzj_1t=tb8wEUMFPBSuzoJ8rtsHp-T_Z3Hg@mail.gmail.com>
	<CAHVvXxR+zyewGGnzPoCYtZFc-yr5xsKhWMDVSTZ3+ke1Vzvv8Q@mail.gmail.com>
Message-ID: <20130515092622.GE9103@ando>

On Wed, May 15, 2013 at 10:03:20AM +0100, Oscar Benjamin wrote:
> On 14 May 2013 17:11, Marc Tompkins <marc.tompkins at gmail.com> wrote:

> > Again, the return value of print() - e.g. success/failure - is 
> > separate from what print() actually prints.
> 
> 
> I was surprised by this so I've just tested it and checked the docs;
> the print() function does not return anything (i.e. it returns None).

I assumed Marc was talking hypothetically. A print function *could* 
return a result, even if Python's print function does not.


-- 
Steven

From eryksun at gmail.com  Wed May 15 16:24:34 2013
From: eryksun at gmail.com (eryksun)
Date: Wed, 15 May 2013 10:24:34 -0400
Subject: [Tutor] env var packages
In-Reply-To: <CACzNyA3N38knCLE_3c7VUnWzoLzQV4N5rCARfQXYEvghKZPJFQ@mail.gmail.com>
References: <CACzNyA3N38knCLE_3c7VUnWzoLzQV4N5rCARfQXYEvghKZPJFQ@mail.gmail.com>
Message-ID: <CACL+1av8M=kJ1zxasCRqAcDttXhwGq8hohk+GkRBVRH6eCr7QQ@mail.gmail.com>

On Tue, May 14, 2013 at 3:54 PM, Matthew Ngaha <chigga101 at gmail.com> wrote:
> I was instructed to get django via easy installer that was
> located in my Python/Scripts folder. it installed django to a
> different place in site-packages, where django-admin.py resides.

You appear to be using Windows, since you talk about a "Scripts"
directory (other platforms use a "bin" directory such as "/usr/bin").

easy_install *should* have created django-admin.py in the Scripts
directory. It worked for me on a fresh install of a 3.3.1, installing
Django 1.5.1. Maybe the problem is minor, and you can just copy
django-admin.py to the Scripts directory manually. If possible I'd
start over fresh. Also, I'd use pip instead of easy_install. It's
easier to uninstall with pip. If you decide to start fresh, first
install Python, distribute, and pip; then add the Scripts directory to
PATH; then run "pip install django".

Here are the scripts for installing distribute and pip:

http://python-distribute.org/distribute_setup.py
https://raw.github.com/pypa/pip/master/contrib/get-pip.py

Use a "command prompt" with elevated privileges (i.e. "Run as Administrator").

> it was specific about adding the path to the env variable, but if i already
> have python added, why do i need to add django? shouldnt it already
> be added?

When you open (execute) a file without a full or relative path, the
shell searches for the file in the directories listed in the PATH
environment variable. Additionally, if you don't specify an extension,
the cmd shell searches for the filename plus each extension listed in
PATHEXT (e.g. .EXE, .BAT). The first match becomes the fully qualified
path. Given a valid path, the shell executes the "open" command
associated with the file's extension, which is found in the system
registry under HKCR (classes root).

Specifically, when you add the Scripts directory to PATH, it allows
you to execute the files in that directory as commands, irrespective
of your current working directory. Additionally if you add .PY to the
PATHEXT environment variable, you can skip using the .py extension.
For example, you would simply run "django-admin".

One limitation with this scheme is that the file type can only be
configured for a particular executable at a time. It doesn't take into
account, for example, having multiple Python interpreters installed on
the same machine, all of which contend for the same .py extension. The
new launcher for Windows (py.exe) gets around this problem by acting
as a dispatcher based on the first line of the script (the "shebang").
The launcher is installed with 3.3 and available as a separate
download for previous versions:

https://bitbucket.org/pypa/pylauncher
https://bitbucket.org/pypa/pylauncher/raw/tip/Doc/launcher.rst

From chigga101 at gmail.com  Wed May 15 17:48:59 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Wed, 15 May 2013 16:48:59 +0100
Subject: [Tutor] env var packages
In-Reply-To: <CACL+1av8M=kJ1zxasCRqAcDttXhwGq8hohk+GkRBVRH6eCr7QQ@mail.gmail.com>
References: <CACzNyA3N38knCLE_3c7VUnWzoLzQV4N5rCARfQXYEvghKZPJFQ@mail.gmail.com>
	<CACL+1av8M=kJ1zxasCRqAcDttXhwGq8hohk+GkRBVRH6eCr7QQ@mail.gmail.com>
Message-ID: <CACzNyA1rUfSR3oPMGD6TMGh5aHSBe7zKEdY3b_yh6J9uPvmN2g@mail.gmail.com>

Thank you Vasya and Eryksun. Sorry i didn't mention my OS i am on
windows. Thanks for the links and detailed explanations which after
following, i now have django up and running! thanks again

From marc.tompkins at gmail.com  Wed May 15 17:51:32 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 15 May 2013 08:51:32 -0700
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <20130515092622.GE9103@ando>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<kmsttq$qj6$1@ger.gmane.org>
	<CAKK8jXaGp0XRPCwLzj_1t=tb8wEUMFPBSuzoJ8rtsHp-T_Z3Hg@mail.gmail.com>
	<CAHVvXxR+zyewGGnzPoCYtZFc-yr5xsKhWMDVSTZ3+ke1Vzvv8Q@mail.gmail.com>
	<20130515092622.GE9103@ando>
Message-ID: <CAKK8jXYDSiH4Bkc-oKuN4=AAWErZb7=BgHSi094_GMm8VTy23A@mail.gmail.com>

On Wed, May 15, 2013 at 2:26 AM, Steven D'Aprano <steve at pearwood.info>wrote:

I assumed Marc was talking hypothetically. A print function *could*
> return a result, even if Python's print function does not.
>
> Actually, I was mixing up my memory of an overloaded print() function with
Python's built-in print().  I _have_ used versions of print() that returned
values, and relied on them for program flow - but somehow I forgot that
that was a custom function!

Yet another argument in the ongoing controversy "why change print from a
statement to a function?"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130515/a858125d/attachment.html>

From alan.gauld at btinternet.com  Wed May 15 22:02:17 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 15 May 2013 21:02:17 +0100
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <CAKK8jXYDSiH4Bkc-oKuN4=AAWErZb7=BgHSi094_GMm8VTy23A@mail.gmail.com>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<kmsttq$qj6$1@ger.gmane.org>
	<CAKK8jXaGp0XRPCwLzj_1t=tb8wEUMFPBSuzoJ8rtsHp-T_Z3Hg@mail.gmail.com>
	<CAHVvXxR+zyewGGnzPoCYtZFc-yr5xsKhWMDVSTZ3+ke1Vzvv8Q@mail.gmail.com>
	<20130515092622.GE9103@ando>
	<CAKK8jXYDSiH4Bkc-oKuN4=AAWErZb7=BgHSi094_GMm8VTy23A@mail.gmail.com>
Message-ID: <kn0pk4$ib6$1@ger.gmane.org>

On 15/05/13 16:51, Marc Tompkins wrote:

> Actually, I was mixing up my memory of an overloaded print() function

And C's printf() returns the number of chars printed.
I actually wish python had followed suit because, as Marc says,
it can occasionally be useful...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From marc.tompkins at gmail.com  Wed May 15 23:21:34 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 15 May 2013 14:21:34 -0700
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <kn0pk4$ib6$1@ger.gmane.org>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<kmsttq$qj6$1@ger.gmane.org>
	<CAKK8jXaGp0XRPCwLzj_1t=tb8wEUMFPBSuzoJ8rtsHp-T_Z3Hg@mail.gmail.com>
	<CAHVvXxR+zyewGGnzPoCYtZFc-yr5xsKhWMDVSTZ3+ke1Vzvv8Q@mail.gmail.com>
	<20130515092622.GE9103@ando>
	<CAKK8jXYDSiH4Bkc-oKuN4=AAWErZb7=BgHSi094_GMm8VTy23A@mail.gmail.com>
	<kn0pk4$ib6$1@ger.gmane.org>
Message-ID: <CAKK8jXZtk4BqMG=3d6rQwXOwEsd83EX=wOrcDGQE6RCbKFwfVw@mail.gmail.com>

On Wed, May 15, 2013 at 1:02 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> On 15/05/13 16:51, Marc Tompkins wrote:
>
>  Actually, I was mixing up my memory of an overloaded print() function
>>
>
> And C's printf() returns the number of chars printed.
> I actually wish python had followed suit because, as Marc says,
> it can occasionally be useful...
>
>
I wonder if this would be a good PEP suggestion?  Unlike the switch from
print to print(), I think this could be done in a future-proof way...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130515/80ce2e8f/attachment.html>

From oscar.j.benjamin at gmail.com  Thu May 16 00:43:57 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Wed, 15 May 2013 23:43:57 +0100
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <CAKK8jXZtk4BqMG=3d6rQwXOwEsd83EX=wOrcDGQE6RCbKFwfVw@mail.gmail.com>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<kmsttq$qj6$1@ger.gmane.org>
	<CAKK8jXaGp0XRPCwLzj_1t=tb8wEUMFPBSuzoJ8rtsHp-T_Z3Hg@mail.gmail.com>
	<CAHVvXxR+zyewGGnzPoCYtZFc-yr5xsKhWMDVSTZ3+ke1Vzvv8Q@mail.gmail.com>
	<20130515092622.GE9103@ando>
	<CAKK8jXYDSiH4Bkc-oKuN4=AAWErZb7=BgHSi094_GMm8VTy23A@mail.gmail.com>
	<kn0pk4$ib6$1@ger.gmane.org>
	<CAKK8jXZtk4BqMG=3d6rQwXOwEsd83EX=wOrcDGQE6RCbKFwfVw@mail.gmail.com>
Message-ID: <CAHVvXxSf-9YTh9aUjmgmmeTyxKoz_1DcRFPWWV6xRLYMQcha-A@mail.gmail.com>

On 15 May 2013 22:21, Marc Tompkins <marc.tompkins at gmail.com> wrote:
> On Wed, May 15, 2013 at 1:02 PM, Alan Gauld <alan.gauld at btinternet.com>
> wrote:
>>
>> And C's printf() returns the number of chars printed.
>> I actually wish python had followed suit because, as Marc says,
>> it can occasionally be useful...
>>
>
> I wonder if this would be a good PEP suggestion?  Unlike the switch from
> print to print(), I think this could be done in a future-proof way...
>

It would be a bit confusing in an interactive session:

>>> def print_(data):
...     print(data)
...     return len(data)
...
>>> print_('asd')
asd
3


Oscar

From marc.tompkins at gmail.com  Thu May 16 00:52:20 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 15 May 2013 15:52:20 -0700
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <CAHVvXxSf-9YTh9aUjmgmmeTyxKoz_1DcRFPWWV6xRLYMQcha-A@mail.gmail.com>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<kmsttq$qj6$1@ger.gmane.org>
	<CAKK8jXaGp0XRPCwLzj_1t=tb8wEUMFPBSuzoJ8rtsHp-T_Z3Hg@mail.gmail.com>
	<CAHVvXxR+zyewGGnzPoCYtZFc-yr5xsKhWMDVSTZ3+ke1Vzvv8Q@mail.gmail.com>
	<20130515092622.GE9103@ando>
	<CAKK8jXYDSiH4Bkc-oKuN4=AAWErZb7=BgHSi094_GMm8VTy23A@mail.gmail.com>
	<kn0pk4$ib6$1@ger.gmane.org>
	<CAKK8jXZtk4BqMG=3d6rQwXOwEsd83EX=wOrcDGQE6RCbKFwfVw@mail.gmail.com>
	<CAHVvXxSf-9YTh9aUjmgmmeTyxKoz_1DcRFPWWV6xRLYMQcha-A@mail.gmail.com>
Message-ID: <CAKK8jXb9GuG3n+KQqiLNE8EXLNkX6n6XiBkXe9i1Ghn=-ZHw8g@mail.gmail.com>

On Wed, May 15, 2013 at 3:43 PM, Oscar Benjamin
<oscar.j.benjamin at gmail.com>wrote:

> On 15 May 2013 22:21, Marc Tompkins <marc.tompkins at gmail.com> wrote:
> > On Wed, May 15, 2013 at 1:02 PM, Alan Gauld <alan.gauld at btinternet.com>
> > wrote:
> >>
> >> And C's printf() returns the number of chars printed.
> >> I actually wish python had followed suit because, as Marc says,
> >> it can occasionally be useful...
> >>
> >
> > I wonder if this would be a good PEP suggestion?  Unlike the switch from
> > print to print(), I think this could be done in a future-proof way...
> >
>
> It would be a bit confusing in an interactive session:
>
> >>> def print_(data):
> ...     print(data)
> ...     return len(data)
> ...
> >>> print_('asd')
> asd
> 3
>
>
I was thinking along the lines of an optional parameter ("verbose" or
something similar), so print() would supply a return value if you asked it
to but keep stumm if you didn't.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130515/2dcb0c55/attachment.html>

From oscar.j.benjamin at gmail.com  Thu May 16 01:14:47 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Thu, 16 May 2013 00:14:47 +0100
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <CAKK8jXb9GuG3n+KQqiLNE8EXLNkX6n6XiBkXe9i1Ghn=-ZHw8g@mail.gmail.com>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<kmsttq$qj6$1@ger.gmane.org>
	<CAKK8jXaGp0XRPCwLzj_1t=tb8wEUMFPBSuzoJ8rtsHp-T_Z3Hg@mail.gmail.com>
	<CAHVvXxR+zyewGGnzPoCYtZFc-yr5xsKhWMDVSTZ3+ke1Vzvv8Q@mail.gmail.com>
	<20130515092622.GE9103@ando>
	<CAKK8jXYDSiH4Bkc-oKuN4=AAWErZb7=BgHSi094_GMm8VTy23A@mail.gmail.com>
	<kn0pk4$ib6$1@ger.gmane.org>
	<CAKK8jXZtk4BqMG=3d6rQwXOwEsd83EX=wOrcDGQE6RCbKFwfVw@mail.gmail.com>
	<CAHVvXxSf-9YTh9aUjmgmmeTyxKoz_1DcRFPWWV6xRLYMQcha-A@mail.gmail.com>
	<CAKK8jXb9GuG3n+KQqiLNE8EXLNkX6n6XiBkXe9i1Ghn=-ZHw8g@mail.gmail.com>
Message-ID: <CAHVvXxTJpk3EyRFgPaSjX_qduwxmhfdL8R0x=xYruFmN0egpOA@mail.gmail.com>

On 15 May 2013 23:52, Marc Tompkins <marc.tompkins at gmail.com> wrote:
> On Wed, May 15, 2013 at 3:43 PM, Oscar Benjamin <oscar.j.benjamin at gmail.com>
> wrote:
>>
>> On 15 May 2013 22:21, Marc Tompkins <marc.tompkins at gmail.com> wrote:
>> > On Wed, May 15, 2013 at 1:02 PM, Alan Gauld <alan.gauld at btinternet.com>
>> > wrote:
>> >>
>> >> And C's printf() returns the number of chars printed.
>> >> I actually wish python had followed suit because, as Marc says,
>> >> it can occasionally be useful...
>> >>
>> >
>> > I wonder if this would be a good PEP suggestion?  Unlike the switch from
>> > print to print(), I think this could be done in a future-proof way...
>> >
>>
>> It would be a bit confusing in an interactive session:
>>
>> >>> def print_(data):
>> ...     print(data)
>> ...     return len(data)
>> ...
>> >>> print_('asd')
>> asd
>> 3
>>
>
> I was thinking along the lines of an optional parameter ("verbose" or
> something similar), so print() would supply a return value if you asked it
> to but keep stumm if you didn't.

I don't really understand what the reason for having the information
is. Would it return the number of characters written or the number of
bytes?


Oscar

From marc.tompkins at gmail.com  Thu May 16 01:18:21 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 15 May 2013 16:18:21 -0700
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <CAKK8jXb9GuG3n+KQqiLNE8EXLNkX6n6XiBkXe9i1Ghn=-ZHw8g@mail.gmail.com>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<kmsttq$qj6$1@ger.gmane.org>
	<CAKK8jXaGp0XRPCwLzj_1t=tb8wEUMFPBSuzoJ8rtsHp-T_Z3Hg@mail.gmail.com>
	<CAHVvXxR+zyewGGnzPoCYtZFc-yr5xsKhWMDVSTZ3+ke1Vzvv8Q@mail.gmail.com>
	<20130515092622.GE9103@ando>
	<CAKK8jXYDSiH4Bkc-oKuN4=AAWErZb7=BgHSi094_GMm8VTy23A@mail.gmail.com>
	<kn0pk4$ib6$1@ger.gmane.org>
	<CAKK8jXZtk4BqMG=3d6rQwXOwEsd83EX=wOrcDGQE6RCbKFwfVw@mail.gmail.com>
	<CAHVvXxSf-9YTh9aUjmgmmeTyxKoz_1DcRFPWWV6xRLYMQcha-A@mail.gmail.com>
	<CAKK8jXb9GuG3n+KQqiLNE8EXLNkX6n6XiBkXe9i1Ghn=-ZHw8g@mail.gmail.com>
Message-ID: <CAKK8jXakVvYZ=jGbuLn0ruASCQF6Be4ujqH4Z6HE5mkdd7uR1w@mail.gmail.com>

On Wed, May 15, 2013 at 3:52 PM, Marc Tompkins <marc.tompkins at gmail.com>wrote:


> I was thinking along the lines of an optional parameter ("verbose" or
> something similar), so print() would supply a return value if you asked it
> to but keep stumm if you didn't.
>

After I hit Send, I thought of the obvious problem...  you'd have to know
ahead of time which version of print() was available, because you'll get a
TypeError if you pass undefined keyword arguments to print().

On the other hand, it'd be a quickie to do that test at the top of your
code...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130515/d2c89c0a/attachment.html>

From marc.tompkins at gmail.com  Thu May 16 01:29:30 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 15 May 2013 16:29:30 -0700
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <CAHVvXxTJpk3EyRFgPaSjX_qduwxmhfdL8R0x=xYruFmN0egpOA@mail.gmail.com>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<kmsttq$qj6$1@ger.gmane.org>
	<CAKK8jXaGp0XRPCwLzj_1t=tb8wEUMFPBSuzoJ8rtsHp-T_Z3Hg@mail.gmail.com>
	<CAHVvXxR+zyewGGnzPoCYtZFc-yr5xsKhWMDVSTZ3+ke1Vzvv8Q@mail.gmail.com>
	<20130515092622.GE9103@ando>
	<CAKK8jXYDSiH4Bkc-oKuN4=AAWErZb7=BgHSi094_GMm8VTy23A@mail.gmail.com>
	<kn0pk4$ib6$1@ger.gmane.org>
	<CAKK8jXZtk4BqMG=3d6rQwXOwEsd83EX=wOrcDGQE6RCbKFwfVw@mail.gmail.com>
	<CAHVvXxSf-9YTh9aUjmgmmeTyxKoz_1DcRFPWWV6xRLYMQcha-A@mail.gmail.com>
	<CAKK8jXb9GuG3n+KQqiLNE8EXLNkX6n6XiBkXe9i1Ghn=-ZHw8g@mail.gmail.com>
	<CAHVvXxTJpk3EyRFgPaSjX_qduwxmhfdL8R0x=xYruFmN0egpOA@mail.gmail.com>
Message-ID: <CAKK8jXazyu0mj3zO-nCuJVSFwLJ_aatpmZpbtQ3f5UnWfdY4ZA@mail.gmail.com>

On Wed, May 15, 2013 at 4:14 PM, Oscar Benjamin
<oscar.j.benjamin at gmail.com>wrote:

> I don't really understand what the reason for having the information
> is. Would it return the number of characters written or the number of
> bytes?
>

It's absolutely useless in an interactive session, or any time that print()
is printing to the screen and the user can see it happening.  But when
you're printing to some other device - a disk file, a printer, a serial
port - it can be EXTREMELY handy to know 1) did it succeed or not and 2) if
it failed, how far did it get before it failed?

As for characters or bytes, that would depend on whether you were working
in ASCII or Unicode, I suppose...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130515/2a01edb9/attachment.html>

From alan.gauld at btinternet.com  Thu May 16 01:57:36 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 16 May 2013 00:57:36 +0100
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <CAKK8jXakVvYZ=jGbuLn0ruASCQF6Be4ujqH4Z6HE5mkdd7uR1w@mail.gmail.com>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<kmsttq$qj6$1@ger.gmane.org>
	<CAKK8jXaGp0XRPCwLzj_1t=tb8wEUMFPBSuzoJ8rtsHp-T_Z3Hg@mail.gmail.com>
	<CAHVvXxR+zyewGGnzPoCYtZFc-yr5xsKhWMDVSTZ3+ke1Vzvv8Q@mail.gmail.com>
	<20130515092622.GE9103@ando>
	<CAKK8jXYDSiH4Bkc-oKuN4=AAWErZb7=BgHSi094_GMm8VTy23A@mail.gmail.com>
	<kn0pk4$ib6$1@ger.gmane.org>
	<CAKK8jXZtk4BqMG=3d6rQwXOwEsd83EX=wOrcDGQE6RCbKFwfVw@mail.gmail.com>
	<CAHVvXxSf-9YTh9aUjmgmmeTyxKoz_1DcRFPWWV6xRLYMQcha-A@mail.gmail.com>
	<CAKK8jXb9GuG3n+KQqiLNE8EXLNkX6n6XiBkXe9i1Ghn=-ZHw8g@mail.gmail.com>
	<CAKK8jXakVvYZ=jGbuLn0ruASCQF6Be4ujqH4Z6HE5mkdd7uR1w@mail.gmail.com>
Message-ID: <kn17db$r96$1@ger.gmane.org>

On 16/05/13 00:18, Marc Tompkins wrote:
> On Wed, May 15, 2013 at 3:52 PM, Marc Tompkins <marc.tompkins at gmail.com
> <mailto:marc.tompkins at gmail.com>> wrote:
>
>     I was thinking along the lines of an optional parameter ("verbose"
>     or something similar), so print() would supply a return value if you
>     asked it to but keep stumm if you didn't.
>
>
> After I hit Send, I thought of the obvious problem...  you'd have to
> know ahead of time which version of print() was available, because
> you'll get a TypeError if you pass undefined keyword arguments to print().
>
> On the other hand, it'd be a quickie to do that test at the top of your
> code...

Or maybe we need a printf function in Python that has the C behaviour 
(and takes other arguments, such as output stream?)

As to bytes v characters I'd opt for bytes since in dealing with 
hardware/networks the bytes are more significant than the
characters...


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From grace_k_porter at earthlink.net  Thu May  2 00:04:32 2013
From: grace_k_porter at earthlink.net (Grace Kathryn)
Date: Wed, 1 May 2013 18:04:32 -0400
Subject: [Tutor] Python Programming for the Absolute Beginner
Message-ID: <E435AC57-DFFB-45AA-B706-EF8ACC010007@earthlink.net>

Hello~

I'm working through the Book Python Programming for the Absolute Beginner and am wondering if you could help me out with the coding to certain
Challenges at the end of the book, specifically chapter 7 challenges 1 and 2 and chapter 8 challenges 1 and 3.
Could you help? I need something to compare my coding to.

Thank you!

~Grace
Sent from my iPad
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130501/632ac7b6/attachment-0001.html>

From bhanu.bais at gmail.com  Sat May  4 07:15:04 2013
From: bhanu.bais at gmail.com (Bhanu Pratap Singh)
Date: Sat, 4 May 2013 10:45:04 +0530
Subject: [Tutor] changing char list to int list isn't working
In-Reply-To: <CALRAYNV+2suCqjJnvYPkCmrxpskXDudugCLt_EfHaQxxqvvcWw@mail.gmail.com>
References: <CALRAYNV+2suCqjJnvYPkCmrxpskXDudugCLt_EfHaQxxqvvcWw@mail.gmail.com>
Message-ID: <000901ce4886$597943a0$0c6bcae0$@com>

Hi Jim,
When you replace num = int(num); it's not changing a list.
Due to It only pick a value from a list.
You have to pointing to list so,
You have to use list[position] using while loop like below

listOfNumChars = list(str(intNum))
i = 0
while i < len(listOfNumChars):
	listOfNumChars[i] = int(listOfNumChars[i])
	i += 1

print(listOfNumChars)

#--> [4, 5, 5] (if you entered 455)


Best,
Bhanu Pratap


-----Original Message-----
From: Tutor [mailto:tutor-bounces+bhanubais=gmail.com at python.org] On Behalf Of Jim Mooney
Sent: Saturday, May 04, 2013 9:43 AM
To: tutor at python.org
Subject: [Tutor] changing char list to int list isn't working

I'm turning an integer into a string so I can make a list of separate chars, then turn those chars back into individual ints, but the resulting list still looks like string chars when I print it. What am I doing wrong?


listOfNumChars = list(str(intNum))
for num in listOfNumChars:
    num = int(num)

print(listOfNumChars)

# result of 455 entered is ['4', '5', '5']

--
Jim Mooney

?For anything that matters, the timing is never quite right, the resources are always a little short, and the people who affect the outcome are always ambivalent.?
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


From japhy at pearachute.com  Mon May  6 20:27:37 2013
From: japhy at pearachute.com (Japhy Bartlett)
Date: Mon, 6 May 2013 13:27:37 -0500
Subject: [Tutor] POST MULTI PART DATA WITH PYTHON
In-Reply-To: <CAKHNSow6VRax=1fe+qvSErGigzGmnMWNn9Kvy-mPiJJwspowOA@mail.gmail.com>
References: <CAKHNSow6VRax=1fe+qvSErGigzGmnMWNn9Kvy-mPiJJwspowOA@mail.gmail.com>
Message-ID: <CANTsVHJodkQNAHsDzjgM3yxbX1OfwqW882JDDAAyPppn3R7e9g@mail.gmail.com>

In your code, you're not actually inserting the contents of the file into
your MIME part (you're only constructing headers), which is why the
content-length is not right.

The 404 is probably the site detecting this as a script/robot/violation of
their TOS and blocking you.  Which you can probably get around by modifying
your user-agent string, but as a security guy I suppose you can figure that
out.

If you understand that there are better libraries but refuse to use them,
you might try at least looking at how they implement this.


On Mon, May 6, 2013 at 12:05 PM, Ajin Abraham <ajin25 at gmail.com> wrote:

> Hi,
>    I was working on a python project that requires to upload an image
> using httplib. Here i need to POST a MULTI PART DATA with Python using
> inbuilt libraries. I know there are better libraries like requests and
> poster. but i need to do it with httplib itself.
>
> I will attach a screenshot==> http://s1.postimg.org/qjjhy445q/file.jpg
>
> So here i think there is some problem with my code that the
> 'Content-Length is different and i am getting a 404 not found
> response. i placed the file "screenshot.png" together with my python
> source file.
>
> Here is my source code==>http://bpaste.net/show/V2xbtcBSpYsNbwGPCmFM/
>
> Please tell me what's wrong in my code. and please don't suggest me
> other libraries.
>
> Regards,
> Ajin Abraham
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130506/defa6795/attachment-0001.html>

From lm.raaijmakers at gmail.com  Tue May  7 22:10:49 2013
From: lm.raaijmakers at gmail.com (Linsey Raaijmakers)
Date: Tue, 7 May 2013 16:10:49 -0400
Subject: [Tutor] question already discussed with oscar benjamin
Message-ID: <CA+1vXfip1KwUJYj51rVWTjX_GbyZ_m1m3xPJnnaFgoquEX-bpg@mail.gmail.com>

Hi,

Im trying to work with the help Oscar provided me, but I still get stuck :(
So what I'm trying to do now is write the program with the following input
and output:

Input:
action,start,apex,stop
3, 12, 13, 15
4, 15, 15, 15
3, 20, 21, 25
5, 21, 23, 30
...

And when you run your program it prints out:
actions, start, stop
[3], 12, 13
[], 14,15
[4], 15, 15
[], 16, 19
[3], 20, 21
[3, 5], 21, 21
[5], 22, 23
...

I don't want to use the stop. Only the start till apex is important.

This is the code I have now:

now = onset_list[0]
end = apex_list[0]
active = action_list[0]

for i in range(1,len(onset_list)):
  next_start = onset_list[i]
  next_end = apex_list[i]
  next_active = action_list[i]
  prev_end = apex_list[i-1]

  while next_start > end:
    print active+"\t"+now+'\t'+end
    end = next_end
    now = next_start
    active = next_active
  print active+','+next_active+'\t'+now+'\t'+next_end

But my output will print now:

3    12    13
4,4  15    15
4     15    15
3,3   20    21
3,5   20    25

How do I fix that it doesn't print out the double ones?
I'm sorry that I can't figure it out without your help. Im really trying..
:(
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130507/1a82334c/attachment-0001.html>

From ddw2424 at gmail.com  Wed May  8 04:30:35 2013
From: ddw2424 at gmail.com (Sky Flyinz)
Date: Tue, 7 May 2013 21:30:35 -0500
Subject: [Tutor] Looking for python 3 tutorial
Message-ID: <CAGBXxV50Od86nC8rQ_ZUN_9atoMZ5sGnoGjVFFiPPss1QZkYYQ@mail.gmail.com>

Where can I find a  web programming python tutorial online either book?

 Are social media, email, live talk, and etc that called web programming
for browser?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130507/342e2b8d/attachment-0001.html>

From lm.raaijmakers at gmail.com  Wed May  8 21:27:08 2013
From: lm.raaijmakers at gmail.com (Linsey Raaijmakers)
Date: Wed, 8 May 2013 15:27:08 -0400
Subject: [Tutor] Help needed!!
Message-ID: <CA+1vXfhqsYLXBV8_36D0hpSso2R7SZQ3_ozBbc_+q7rNPctRrg@mail.gmail.com>

Hello,

I have a file with actions and time points at which they occur.
I want to find how many times an action occurs, and how many times it
occurs in combination with an other action at the same time point
(overlapping between onset and apex)

Below is the input file. in this file, action 50 occurs 3 times, so I want
to output that with the apex of those occurrences. It also occurs in
combination with action 45, so I also want to output that combination plus
the number of times it occurs.
In this case 50 overlaps 45 and 45 also overlaps 50, but I only want to
output this combination once. So not [50,45] and [45,50]

I'm working on it for some days now, but I can't figure out how to do this.
I first wanted to make a list of the first action and just add the next
action to that list if it is overlapping the first one. And keep doing that
until the next action isn't overlapping anymore and create a new list, but
I'm doing something wrong what makes it not doing what I want.

Can somebody please help me? :)

INPUT:
  Action Unit Onset Frame Apex Frame Offset Frame  50 5321 5321 5424  7 5323
5347 5441  12 5339 5351 5449  45 5373 5373 5373  45 5420 5420 5420  25 5425
5425 5450  26 5425 5425 5450  50 5451 5451 5498  45 5452 5452 5452  14 5497
5503 5509  26 5513 5513 5532  25 5517 5517 5532  45 5533 5533 5533  50 5533
5533 5580  5 5537 5540 5583  25 5580 5580 5633  45 5586 5586 5586  26 5595
5595 5633
OUTPUT:

action     times observed    apex
[50]        3                         5321, 5451, 5533
[50,45]   1                          5533;5533
[7]          1                         5347
[7,12]      1                         5347; 5351
..
....

Multiple combinations of actions are possible, as long as they overlap
between onset and apex.




CODE:

from collections import Counter
f = open('and.txt','r');

action_list = []
onset_list = []
apex_list = []
offset_list = []
action_counter = 0
combination_list = []

for line in f:
  action, onset, apex, offset = line.split()

  action_list.append(action)
  onset_list.append(onset)
  apex_list.append(apex)
  offset_list.append(offset)

action_cnvrt = map(int, action_list)
c = Counter(action_cnvrt)

filtered = list(set(action_list))
filtered_cnvrt = map(int, filtered)

for a in filtered_cnvrt:
  action_count = str(a)+"\t"+str(c[a])

now = int(onset_list[0])
end = int(apex_list[0])
active = action_list[0]

for i in range(1,len(onset_list)):
  next_start = int(onset_list[i])
  next_end = int(apex_list[i])
  next_active = action_list[i]
  prev_end = int(apex_list[i-1])
  combination_list.append(action_list[i-1])

  print combination_list
  while next_start <= end:
    combination_list.append(action_list[i])
    end = next_end
  combination_list = []
  end = next_end
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130508/45aeaca8/attachment.html>

From krishnagpal96 at gmail.com  Fri May 10 22:44:18 2013
From: krishnagpal96 at gmail.com (Krish Nagpal)
Date: Fri, 10 May 2013 16:44:18 -0400
Subject: [Tutor] (no subject)
Message-ID: <CAMe3Wqg84LpQyU8Oq8Luo8FSEzKspNBPSYPYgA8iE1JFcMx67Q@mail.gmail.com>

Good Afternoon,
I have a quick question based on python 2.7. Do you know how to write a web
server with a form. (Pthyon) When the webserver gets a GET request, I need
to serve the HTML document with a form. In response to a POST, i want to
write the resulting data to a form.

Do you know how to do this. Can you please help me quickly. Thanks a lot.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130510/e9e8e9b5/attachment.html>

From raymond75.jackson at gmail.com  Sat May 11 14:50:51 2013
From: raymond75.jackson at gmail.com (Raymond Jackson)
Date: Sat, 11 May 2013 08:50:51 -0400
Subject: [Tutor] Interested in learning Python
Message-ID: <CAGtDk9HyjWSiaN2_JPadsqtvSspgYros2Yd0WU12wDNGhWY2mQ@mail.gmail.com>

Hello My name is Raymond Jackson I am currently on your tutorial site and
trying to teach my self this new language I haven't done this before
so i'm open to any suggestions going about this
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130511/63f8ac66/attachment.html>

From subhakrishh at gmail.com  Mon May  6 07:26:24 2013
From: subhakrishh at gmail.com (subha krishna)
Date: Mon, 6 May 2013 17:26:24 +1200
Subject: [Tutor] python beginner-doubt
Message-ID: <CAD70sHXpPK22tsaNc0niUAS0vVvu5Z1rs2cbUGhDvSzcwnQOOA@mail.gmail.com>

hi,

  i need an help in the following program

i just started to learn.

if speed >= 80:
print 'License and registration please'
if mood == 'terrible' or speed >= 100:
print 'You have the right to remain silent.'
elif mood == 'bad' or speed >= 90:
print "I'm going to have to write you a ticket."
write_ticket()
else:
print "Let's try to keep it under 80 ok?"

in this prgm how to give  the value of speed  and mood.

i have written like this to get the value

def main():
    print 'enter the speed and mood'
    print 'enter the speed',speed
    if speed >= 80:
        print 'License and registration please'
    print 'enter the mood',mood
    if mood== 'terrible' or speed >=100
        print 'you hve the right to remain silent.'
    elif mood =='bad' or speed >=90:
        print "I 'm going to have to write you a ticket."
        write_ticket()
    else:
        print "Let's try to keep it under 80 ok?"

i am getting  error in this line (if mood== 'terrible' or speed >=100)

kindly give me an idea about the mistake and how to get the values...


thanks and regards
subha
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130506/54e97233/attachment.html>

From amitsaha.in at gmail.com  Thu May 16 02:03:50 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Thu, 16 May 2013 10:03:50 +1000
Subject: [Tutor] Python Programming for the Absolute Beginner
In-Reply-To: <E435AC57-DFFB-45AA-B706-EF8ACC010007@earthlink.net>
References: <E435AC57-DFFB-45AA-B706-EF8ACC010007@earthlink.net>
Message-ID: <CANODV3kgyirQ_+FjwhL55ytRzrR4BGL7=aXY4FRt3o5KGN3TBg@mail.gmail.com>

Hi Grace,


On Thu, May 2, 2013 at 8:04 AM, Grace Kathryn
<grace_k_porter at earthlink.net>wrote:

> Hello~
>
> I'm working through the Book Python Programming for the Absolute Beginner
> and am wondering if you could help me out with the coding to certain
> Challenges at the end of the book, specifically chapter 7 challenges 1 and
> 2 and chapter 8 challenges 1 and 3.
> Could you help? I need something to compare my coding to.
>

Welcome. I am sure somebody will be able to help you out. However,  you
would need to tell what exactly the challenges are and if possible, any
specific problem you are facing for someone to help you. Not all of the
members in this list may have access to the book.

Best,
Amit.


>
> Thank you!
>
> ~Grace
> Sent from my iPad
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
http://echorand.me
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130516/2ebaa09c/attachment-0001.html>

From steve at pearwood.info  Thu May 16 02:07:48 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 16 May 2013 10:07:48 +1000
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <kn0pk4$ib6$1@ger.gmane.org>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<kmsttq$qj6$1@ger.gmane.org>
	<CAKK8jXaGp0XRPCwLzj_1t=tb8wEUMFPBSuzoJ8rtsHp-T_Z3Hg@mail.gmail.com>
	<CAHVvXxR+zyewGGnzPoCYtZFc-yr5xsKhWMDVSTZ3+ke1Vzvv8Q@mail.gmail.com>
	<20130515092622.GE9103@ando>
	<CAKK8jXYDSiH4Bkc-oKuN4=AAWErZb7=BgHSi094_GMm8VTy23A@mail.gmail.com>
	<kn0pk4$ib6$1@ger.gmane.org>
Message-ID: <51942354.4080908@pearwood.info>

On 16/05/13 06:02, Alan Gauld wrote:
> On 15/05/13 16:51, Marc Tompkins wrote:
>
>> Actually, I was mixing up my memory of an overloaded print() function
>
> And C's printf() returns the number of chars printed.
> I actually wish python had followed suit because, as Marc says,
> it can occasionally be useful...


Guido's time machine strikes again.


py> import sys
py> sys.stdout.write('NOBODY expects the Spanish Inquisition!\n')
NOBODY expects the Spanish Inquisition!
40


The write() method of file objects in Python 3 return the number of characters written.



-- 
Steven

From robert.sjoblom at gmail.com  Thu May 16 02:08:50 2013
From: robert.sjoblom at gmail.com (Robert Sjoblom)
Date: Thu, 16 May 2013 02:08:50 +0200
Subject: [Tutor] Python Programming for the Absolute Beginner
In-Reply-To: <E435AC57-DFFB-45AA-B706-EF8ACC010007@earthlink.net>
References: <E435AC57-DFFB-45AA-B706-EF8ACC010007@earthlink.net>
Message-ID: <CAJKU7g0V21cQGCAMzENkZKtGhFiPSn8fm_+Jvax9pCXzwMk2vA@mail.gmail.com>

> I'm working through the Book Python Programming for the Absolute Beginner and am wondering if you could help me out with the coding to certain
> Challenges at the end of the book, specifically chapter 7 challenges 1 and 2 and chapter 8 challenges 1 and 3.
Since I personally don't have that particular book, and I imagine many
others on this mailing list don't either, it'll be hard for us to
comment on the challenges, given that we don't know what they are.
--
best regards,
Robert S.

From davea at davea.name  Thu May 16 02:33:02 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 15 May 2013 20:33:02 -0400
Subject: [Tutor] python beginner-doubt
In-Reply-To: <CAD70sHXpPK22tsaNc0niUAS0vVvu5Z1rs2cbUGhDvSzcwnQOOA@mail.gmail.com>
References: <CAD70sHXpPK22tsaNc0niUAS0vVvu5Z1rs2cbUGhDvSzcwnQOOA@mail.gmail.com>
Message-ID: <5194293E.6090702@davea.name>

Somehow, your message didn't appear here for 9 days.  That's probably 
why you haven't seen any responses yet.

On 05/06/2013 01:26 AM, subha krishna wrote:
> hi,
>
>    i need an help in the following program
>
> i just started to learn.
>
> if speed >= 80:
> print 'License and registration please'

Indentation is lost here and elsewhere in the program.  That's probably 
because your email program is mistakenly set to send html messages. 
Please use text mail on this forum.  Losing indentation is just one of 
the problems triggered by html, but it's very important in python.

> if mood == 'terrible' or speed >= 100:
> print 'You have the right to remain silent.'
> elif mood == 'bad' or speed >= 90:
> print "I'm going to have to write you a ticket."
> write_ticket()
> else:
> print "Let's try to keep it under 80 ok?"
>
> in this prgm how to give  the value of speed  and mood.
>
> i have written like this to get the value
>
> def main():
>      print 'enter the speed and mood'
>      print 'enter the speed',speed
>      if speed >= 80:
>          print 'License and registration please'
>      print 'enter the mood',mood
>      if mood== 'terrible' or speed >=100
>          print 'you hve the right to remain silent.'
>      elif mood =='bad' or speed >=90:
>          print "I 'm going to have to write you a ticket."
>          write_ticket()
>      else:
>          print "Let's try to keep it under 80 ok?"
>
> i am getting  error in this line (if mood== 'terrible' or speed >=100)

When you show an error, you should give the complete traceback.  in this 
case, it didn't matter, however.

An if statement must end with a colon.

>
> kindly give me an idea about the mistake and how to get the values...
>

You would use the raw_input() statement.  print() doesn't wait for any 
keystrokes from the user, it just displays things.

Note that the return value of raw_input() is a string, so in the case of 
speed, you'll need to convert it to an int or float.


-- 
DaveA

From davea at davea.name  Thu May 16 02:49:30 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 15 May 2013 20:49:30 -0400
Subject: [Tutor] Interested in learning Python
In-Reply-To: <CAGtDk9HyjWSiaN2_JPadsqtvSspgYros2Yd0WU12wDNGhWY2mQ@mail.gmail.com>
References: <CAGtDk9HyjWSiaN2_JPadsqtvSspgYros2Yd0WU12wDNGhWY2mQ@mail.gmail.com>
Message-ID: <51942D1A.5030903@davea.name>

(Your message suddenly appeared here today, after four days in limbo)


On 05/11/2013 08:50 AM, Raymond Jackson wrote:
> Hello My name is Raymond Jackson I am currently on your tutorial site

Be explicit.  There are lots of tutorial sites around.  Perhaps you mean 
  http://docs.python.org/tutorial/
or http://www.alan-g.me.uk/


> and trying to teach my self this new language I haven't done this before
> so i'm open to any suggestions going about this
>

Many people are new to Python, but have programmed in one or ten other 
languages.  Others are entirely new to programming, but very proficient 
with a computer, both with applications and the commandline.  Still 
others know nothing about computers other than how to find a web page.

Describe yourself a little better, and somebody will have a suggestion 
that'll help you at your particular level.  Part of that description 
will include your OS, and the version of Python you're trying to use.


Generically speaking, find a tutorial that fits your level, and that 
matches the version of Python you're experimenting on (2.x or 3.x), and 
dig in.  Do all the exercises, and don't skip ahead if you don't 
understand something.  Either study it till you do, or ask a question 
somewhere.  At the least, make an explicit note, so you'll know what to 
come back to, to fill in the gaps.

Still generically, find an interactive environment that you're 
comfortable with, and experiment.  Python is especially good at that, in 
that you can fire up the interpreter by just typing  python3.3  or 
similar at the shell prompt.

-- 
DaveA

From chigga101 at gmail.com  Thu May 16 03:14:47 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Thu, 16 May 2013 02:14:47 +0100
Subject: [Tutor] Python Programming for the Absolute Beginner
In-Reply-To: <E435AC57-DFFB-45AA-B706-EF8ACC010007@earthlink.net>
References: <E435AC57-DFFB-45AA-B706-EF8ACC010007@earthlink.net>
Message-ID: <CACzNyA2dOMQc0oW16nwdySkgYgeeN0hZXmk=KO_iW=MCDWifMQ@mail.gmail.com>

i completed this book and i did every exercise. are you asking for
help with the challenges, or have you completed them and want code to
compare yours too? im relunctant to share challenge code, incase you
havent done them. They are really good exercises to try doing.

From marc.tompkins at gmail.com  Thu May 16 03:17:34 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 15 May 2013 18:17:34 -0700
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <51942354.4080908@pearwood.info>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<kmsttq$qj6$1@ger.gmane.org>
	<CAKK8jXaGp0XRPCwLzj_1t=tb8wEUMFPBSuzoJ8rtsHp-T_Z3Hg@mail.gmail.com>
	<CAHVvXxR+zyewGGnzPoCYtZFc-yr5xsKhWMDVSTZ3+ke1Vzvv8Q@mail.gmail.com>
	<20130515092622.GE9103@ando>
	<CAKK8jXYDSiH4Bkc-oKuN4=AAWErZb7=BgHSi094_GMm8VTy23A@mail.gmail.com>
	<kn0pk4$ib6$1@ger.gmane.org> <51942354.4080908@pearwood.info>
Message-ID: <CAKK8jXbx39+wx5pJUOA+RQkJweBhcVAqEJxdA1qLUz+H+aWbSA@mail.gmail.com>

On Wed, May 15, 2013 at 5:07 PM, Steven D'Aprano <steve at pearwood.info>wrote:


> Guido's time machine strikes again.
>
>
> py> import sys
> py> sys.stdout.write('NOBODY expects the Spanish Inquisition!\n')
> NOBODY expects the Spanish Inquisition!
> 40
>
>
> The write() method of file objects in Python 3 return the number of
> characters written.
>

Awesome!  Thank you Steven; I don't need it today but I suspect I will
shortly.

Meanwhile, for tutees following along at home and wondering what that was
all about: when you do this in an interactive session, as above, it's
confusing.
When you use it in the course of a program, your program doesn't "see" what
gets printed; it only "sees" what gets returned by the function.  So you
would use the return value something like this:

import sys
outString = "NOBODY expects the Spanish Inquisition!\n"
if sys.stdout.write(outString) == len(outString):
    print("We're good")
else:
    print("Oopsie!")

In other words, if the value returned by write() is the same as the length
of the object you passed to it, the write operation was successful;
otherwise there was a problem and you need to deal with it.

Notice also that you don't _have_ to do anything with the return value; if
you don't assign it to something, or compare it to something (as I did in
my example) it just gets garbage collected and disappears.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130515/77e329e2/attachment-0001.html>

From chigga101 at gmail.com  Thu May 16 03:29:30 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Thu, 16 May 2013 02:29:30 +0100
Subject: [Tutor] Interested in learning Python
In-Reply-To: <CAGtDk9HyjWSiaN2_JPadsqtvSspgYros2Yd0WU12wDNGhWY2mQ@mail.gmail.com>
References: <CAGtDk9HyjWSiaN2_JPadsqtvSspgYros2Yd0WU12wDNGhWY2mQ@mail.gmail.com>
Message-ID: <CACzNyA2wWik+tQRLwaEFZvgPEtNJ=bFHcW_teYdDV2Vd8ucAOw@mail.gmail.com>

i recommend getting a copy of Python Programming for the absolute
beginner. It offers end of chapter exercises to make sure you
understand everything you are reading. It was a great read for me and
made my learning experience really fun. I garantee by the end you
would have gained a lot of confidence and will be able to pick up and
learn many new things

From cybervigilante at gmail.com  Thu May 16 06:53:39 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Wed, 15 May 2013 21:53:39 -0700
Subject: [Tutor] Bugs came home
Message-ID: <CALRAYNUvWg=91RQsfJxDC_sL+UYDB0zpE_8DZJoWx0BpOcs7wA@mail.gmail.com>

Just a note about PyScripter since I was whining here about some bugs,
but the bugs were mine ;')

I downloaded Py 64-bit for Py  3.3 but for some reason installed 32
bit for Py 2.7. PyScripter runs multiple Pys but it apparently choked
on the different word lengths. Once I installed 64 bit for both Pys,
the bugs died.  Now I can run Py 2.7 from the Taskbar, since all the
graphics modules and a lot of other kewl stuff are still mostly for
2.7, but continue to explore 3.3 from the Start Menu. PyScripter does
have some nice stuff - multiple Pys, Projects, Debugger, Regex search,
templates, startup scripts, and other useful tools not in Wing unless
you buy the paid version.

But it's easy to use out of the box if you don't want to mess with
that stuff right off. And its folder has a start link for each
installed Py, so you don't have to set anything up except the path to
each Py.

So my bad on the reported PyScripter bugs ;')

--
Jim Mooney

From eryksun at gmail.com  Thu May 16 07:42:41 2013
From: eryksun at gmail.com (eryksun)
Date: Thu, 16 May 2013 01:42:41 -0400
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <51942354.4080908@pearwood.info>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<kmsttq$qj6$1@ger.gmane.org>
	<CAKK8jXaGp0XRPCwLzj_1t=tb8wEUMFPBSuzoJ8rtsHp-T_Z3Hg@mail.gmail.com>
	<CAHVvXxR+zyewGGnzPoCYtZFc-yr5xsKhWMDVSTZ3+ke1Vzvv8Q@mail.gmail.com>
	<20130515092622.GE9103@ando>
	<CAKK8jXYDSiH4Bkc-oKuN4=AAWErZb7=BgHSi094_GMm8VTy23A@mail.gmail.com>
	<kn0pk4$ib6$1@ger.gmane.org> <51942354.4080908@pearwood.info>
Message-ID: <CACL+1ascPrHQLDKVv-skyHZLLTU0Y+j2dn4=CTmr7OBXXjkx5g@mail.gmail.com>

On Wed, May 15, 2013 at 8:07 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On 16/05/13 06:02, Alan Gauld wrote:
>>
>> And C's printf() returns the number of chars printed.
>> I actually wish python had followed suit because, as Marc says,
>> it can occasionally be useful...
>
> Guido's time machine strikes again.
>
> py> import sys
> py> sys.stdout.write('NOBODY expects the Spanish Inquisition!\n')
> NOBODY expects the Spanish Inquisition!
> 40
>
> The write() method of file objects in Python 3 return the number of
> characters written.

sys.stdout is a TextIOWrapper, so the return value is the number of
Unicode code points written. If this returns (barring exception), the
return value is guaranteed to be the length of the string; it returns
PyLong_FromSsize_t(textlen).

If you want the number of bytes written, use the underlying
BufferedWriter instead:

    >>> sys.stdout.encoding
    'UTF-8'
    >>> sys.stdout.write('\u0200\n')
    ?
    2
    >>> sys.stdout.buffer.write('\u0200\n'.encode())
    ?
    3

The return value is the length in bytes. Whatever isn't immediately
written to the file is saved in the buffer to be written later.

Having a return value that's less than the length is possible for
non-buffered IO (not available for text I/O). Here's an example
comparing raw vs buffered I/O after setting a file-size resource limit
of 1000 bytes:

    >>> import resource
    >>> resource.setrlimit(resource.RLIMIT_FSIZE, (1000, 1000))

An unbuffered FileIO object is immediately honest about the number of
bytes written:

    >>> f = open('temp.bin', 'wb', buffering=0)
    >>> f.write(b'spam' * 1000)
    1000
    >>> f.close()

 On the other hand a BufferedWriter will buffer the remaining 3000
bytes that can't be written. You won't find out until an exception is
raised when the file is closed:

    >>> f = open('temp.bin', 'wb')
    >>> f.write(b'spam' * 1000)
    4000
    >>> f.close()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    OSError: [Errno 27] File too large

Regarding built-in print(), you'd have to modify the underlying
PyFile_WriteObject and PyFile_WriteString functions. Currently they
throw away the return object of the file's write() method and instead
return a C int, either 0 (success) or -1 (error). But considering
print() only works with text I/O, for which the underlying write()
simply returns the string length, what's the use case?

From cybervigilante at gmail.com  Thu May 16 08:06:25 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Wed, 15 May 2013 23:06:25 -0700
Subject: [Tutor] Pygraphics crashed
Message-ID: <CALRAYNUhZ60ZVSOqT6xJaKFxHRPoX8poVHPJs890JL4tF7n=dg@mail.gmail.com>

How do I uninstall modules? I installed Pygraphics, which worked fine,
along with some other mods, like numpy, but when I installed 64 bit py
2.7
I get the message "The _imaging C module is not installed" when
running a prog that worked fine before. I think I have a higher
dot-version - Py 2.7.4 as opposed to 2.7.3  - what's the easiest way
to fix this? Will uninstalling and reinstalling the modules do
anything or do I have to revert to an older Py (I'm on Win 7)

And regardless of the answer to that I still want to know how to
uninstall modules. Do I just find and delete them? And are they all in
the same place?

-- 
Jim Mooney

From cybervigilante at gmail.com  Thu May 16 08:12:58 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Wed, 15 May 2013 23:12:58 -0700
Subject: [Tutor] Can't install latest PIL
Message-ID: <CALRAYNUpzMgSFxrFZXEiGc_oQpLk_02Bj96LFuOtZyvU96PLTw@mail.gmail.com>

Okay, I'm trying to install the latest PIL on win 7. It claims Python
2.7 was not found in the registry, although it's installed, on a path,
and works fine. The install box lets you type in a directory but won't
accept typing. I'm stumped.

I guess the way around this is to know what I have to put in the registry.

-- 
Jim Mooney

?For anything that matters, the timing is never quite right, the
resources are always a little short, and the people who affect the
outcome are always ambivalent.?

From eryksun at gmail.com  Thu May 16 11:29:24 2013
From: eryksun at gmail.com (eryksun)
Date: Thu, 16 May 2013 05:29:24 -0400
Subject: [Tutor] Can't install latest PIL
In-Reply-To: <CALRAYNUpzMgSFxrFZXEiGc_oQpLk_02Bj96LFuOtZyvU96PLTw@mail.gmail.com>
References: <CALRAYNUpzMgSFxrFZXEiGc_oQpLk_02Bj96LFuOtZyvU96PLTw@mail.gmail.com>
Message-ID: <CACL+1av0eSSY3GwAUuDANVGL=XD4MP+0QOXAEGGfTbMUCfP0=g@mail.gmail.com>

On Thu, May 16, 2013 at 2:12 AM, Jim Mooney <cybervigilante at gmail.com> wrote:
> Okay, I'm trying to install the latest PIL on win 7. It claims Python
> 2.7 was not found in the registry, although it's installed, on a path,
> and works fine. The install box lets you type in a directory but won't
> accept typing. I'm stumped.
>
> I guess the way around this is to know what I have to put in the registry.

Make sure you have the correct architecture. The builds from
PythonWare are 32-bit. Christoph Gohlke has 64-bit builds here:

http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil

As far as the registry goes, installing for everyone uses HKLM (local
machine), else an installation uses HKCU (current user). The installed
versions are in subkeys of [HKLM|HKCU]\Software\Python\PythonCore.
Also, for WoW64 processes (i.e. 32-bit running on 64-bit Windows) the
"Software" key is redirected to Software\Wow64Node.

From wprins at gmail.com  Thu May 16 11:38:35 2013
From: wprins at gmail.com (Walter Prins)
Date: Thu, 16 May 2013 10:38:35 +0100
Subject: [Tutor] Can't install latest PIL
In-Reply-To: <CALRAYNUpzMgSFxrFZXEiGc_oQpLk_02Bj96LFuOtZyvU96PLTw@mail.gmail.com>
References: <CALRAYNUpzMgSFxrFZXEiGc_oQpLk_02Bj96LFuOtZyvU96PLTw@mail.gmail.com>
Message-ID: <CANLXbfB-RvTj5=8jtQYoPWHGoBN7iCTKipD1EN67ZT9bGOQtJg@mail.gmail.com>

Hi,


On 16 May 2013 07:12, Jim Mooney <cybervigilante at gmail.com> wrote:

> Okay, I'm trying to install the latest PIL on win 7. It claims Python
> 2.7 was not found in the registry, although it's installed, on a path,
> and works fine. The install box lets you type in a directory but won't
> accept typing. I'm stumped.


Are you using Python 32-bit or Python 64-bit?   I'm guessing/seem to
remember from your other posts, it's 64-bit and I'm guessing you're trying
to install PIL for 32-bit Windows, which behaves in the way you describe if
you try to use it on a Python 64-bit build.  If I'm right, and you're
indeed running 64-bit Windows, then you need to instead get a 64-bit build
of PIL to match your Python build.   Unfortunately the official PIL page
does not contain 64-bit builds, however you can get an unofficial (meaning,
done by a third party) version here:
http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130516/86b6e61a/attachment-0001.html>

From eryksun at gmail.com  Thu May 16 11:44:17 2013
From: eryksun at gmail.com (eryksun)
Date: Thu, 16 May 2013 05:44:17 -0400
Subject: [Tutor] Pygraphics crashed
In-Reply-To: <CALRAYNUhZ60ZVSOqT6xJaKFxHRPoX8poVHPJs890JL4tF7n=dg@mail.gmail.com>
References: <CALRAYNUhZ60ZVSOqT6xJaKFxHRPoX8poVHPJs890JL4tF7n=dg@mail.gmail.com>
Message-ID: <CACL+1avAVP8eaRnbDtbe+bKYq6qALLtR1+UqhpmStoHDX3YJ9Q@mail.gmail.com>

On Thu, May 16, 2013 at 2:06 AM, Jim Mooney <cybervigilante at gmail.com> wrote:
>
> And regardless of the answer to that I still want to know how to
> uninstall modules. Do I just find and delete them? And are they all in
> the same place?

You should be able to uninstall msi or exe packages just like any
other Windows program. pip has an uninstall command if you used it to
install a package. If you used easy_install, you'll have to manually
delete associated eggs and egg-info directories from
Lib\site-packages, defunct scripts in Scripts, and also edit
Lib\site-packages\easy-install.pth to remove deleted cruft. It's
definitely not easy_uninstall.

From oscar.j.benjamin at gmail.com  Thu May 16 12:00:05 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Thu, 16 May 2013 11:00:05 +0100
Subject: [Tutor] question already discussed with oscar benjamin
In-Reply-To: <CA+1vXfip1KwUJYj51rVWTjX_GbyZ_m1m3xPJnnaFgoquEX-bpg@mail.gmail.com>
References: <CA+1vXfip1KwUJYj51rVWTjX_GbyZ_m1m3xPJnnaFgoquEX-bpg@mail.gmail.com>
Message-ID: <CAHVvXxRGM00n4myX1wzerZ+-bxvT25ROAQyy9H=Af_RUCBK5sA@mail.gmail.com>

On 7 May 2013 21:10, Linsey Raaijmakers <lm.raaijmakers at gmail.com> wrote:
> Hi,
>
> Im trying to work with the help Oscar provided me, but I still get stuck :(

For the benefit of everyone else here, this is referring to a question
that was asked on python-list. The discussion there went off-list and
I recommended that it take place on-list but on this list instead of
python-list.

> So what I'm trying to do now is write the program with the following input
> and output:

The input/output specification below was my own suggestion of a
subproblem to solve. The idea is that actions with integer identifiers
have integer start/apex/end times and the program should read a file
containing those and identify when actions are occurring
simultaneously. The events in the file appear in order of start time.

> Input:
> action,start,apex,stop
> 3, 12, 13, 15
> 4, 15, 15, 15
> 3, 20, 21, 25
> 5, 21, 23, 30
> ...
>
> And when you run your program it prints out:
> actions, start, stop
> [3], 12, 13
> [], 14,15
> [4], 15, 15
> [], 16, 19
> [3], 20, 21
> [3, 5], 21, 21
> [5], 22, 23
> ...
>
> I don't want to use the stop. Only the start till apex is important.
>
> This is the code I have now:

Not it's not. This code doesn't work. Can you post a complete program
that actually runs rather than just a segment of it? See here:
http://sscce.org/

>
> now = onset_list[0]
> end = apex_list[0]
> active = action_list[0]
>
> for i in range(1,len(onset_list)):
>   next_start = onset_list[i]
>   next_end = apex_list[i]
>   next_active = action_list[i]
>   prev_end = apex_list[i-1]
>
>   while next_start > end:
>     print active+"\t"+now+'\t'+end
>     end = next_end
>     now = next_start
>     active = next_active
>   print active+','+next_active+'\t'+now+'\t'+next_end

This will just print each event and the following event. That is not
what you want. You need to keep a list of currently active events and
as you loop forward through the times you should remove events that
have finished and add events that have started.

> But my output will print now:
>
> 3    12    13
> 4,4  15    15
> 4     15    15
> 3,3   20    21
> 3,5   20    25
>
> How do I fix that it doesn't print out the double ones?

The problem is not that it prints the double ones. The problem is that
it does not keep track of a list of currently active events. I'll make
the problem a bit simpler: make a program that gives the following
input/output.

Input:
action,start,apex,stop
3, 12, 13, 15
4, 15, 15, 15
3, 20, 21, 25
5, 21, 23, 30
...

And when you run your program it prints out:
actions, time
[3], 12
[3], 13
[], 14
[4], 15
[], 16
[], 17
[], 18
[], 19
[3], 20
[3, 5], 21
[5], 22
[5], 23
...

The first column in this output is the list of active events at the
times given in the second column. Your code will need to actually have
a list that it adds and removes from as events start and stop


Oscar

From alan.gauld at btinternet.com  Thu May 16 13:37:01 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 16 May 2013 12:37:01 +0100
Subject: [Tutor] Looking for python 3 tutorial
In-Reply-To: <CAGBXxV50Od86nC8rQ_ZUN_9atoMZ5sGnoGjVFFiPPss1QZkYYQ@mail.gmail.com>
References: <CAGBXxV50Od86nC8rQ_ZUN_9atoMZ5sGnoGjVFFiPPss1QZkYYQ@mail.gmail.com>
Message-ID: <kn2gco$vol$1@ger.gmane.org>

On 08/05/13 03:30, Sky Flyinz wrote:
> Where can I find a  web programming python tutorial online either book?

How do you define web programming?
Do you mean building web sites? Or scraping web sites?
Or do you mean using web APIs?

There is a web programming HowTo on the python web site that will get 
you started but without context its hard to recommend anything.

At a general level the book Python Network Programming covers the basics.

>   Are social media, email, live talk, and etc that called web
> programming for browser?

They are all on the web and you can do programming on a browser but 
that's usually via JavaScript. Alternatively you can emulate a browser 
which is usually called web scraping. OTOH if you want to create a 
social media platform then that would be server side programming.

Its not clear what exactly you want to find out.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From alan.gauld at btinternet.com  Thu May 16 13:49:45 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 16 May 2013 12:49:45 +0100
Subject: [Tutor] Web forms  was: Re: (no subject)
In-Reply-To: <CAMe3Wqg84LpQyU8Oq8Luo8FSEzKspNBPSYPYgA8iE1JFcMx67Q@mail.gmail.com>
References: <CAMe3Wqg84LpQyU8Oq8Luo8FSEzKspNBPSYPYgA8iE1JFcMx67Q@mail.gmail.com>
Message-ID: <kn2h4k$8ei$1@ger.gmane.org>

Please use a meaningful subject when posting it makes it easier to find 
things in the archives and identify related posts.

On 10/05/13 21:44, Krish Nagpal wrote:
> I have a quick question based on python 2.7. Do you know how to write a
> web server with a form.

I have no idea what you mean.
A web server reacts to http requests and responds with HTML.
HTML defines how to create forms. You just need to output the 
appropriate HTML text and your user will see a form.

> When the webserver gets a GET request,
> I need to serve the HTML document with a form. In response to a POST, i
> want to write the resulting data to a form.

How do you distinguish between serving the form and writing data
to the form? I don't understand the difference? Do you mean you want the 
same form but in some cases populated with data and in others blank?

> Do you know how to do this. Can you please help me quickly.

The clearer you express the problem the quicker you will get an answer.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From eryksun at gmail.com  Thu May 16 17:21:04 2013
From: eryksun at gmail.com (eryksun)
Date: Thu, 16 May 2013 11:21:04 -0400
Subject: [Tutor] Making a Primary Number List generator
In-Reply-To: <CACL+1ascPrHQLDKVv-skyHZLLTU0Y+j2dn4=CTmr7OBXXjkx5g@mail.gmail.com>
References: <B1CE1A12-1D81-43CC-ABAB-ECCABBE33CC2@att.net>
	<518EC75F.2090206@davea.name>
	<E6A10B5E-D80C-41C2-8DFE-7D9745B91556@att.net>
	<518F8078.9030902@davea.name>
	<8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net>
	<kmsttq$qj6$1@ger.gmane.org>
	<CAKK8jXaGp0XRPCwLzj_1t=tb8wEUMFPBSuzoJ8rtsHp-T_Z3Hg@mail.gmail.com>
	<CAHVvXxR+zyewGGnzPoCYtZFc-yr5xsKhWMDVSTZ3+ke1Vzvv8Q@mail.gmail.com>
	<20130515092622.GE9103@ando>
	<CAKK8jXYDSiH4Bkc-oKuN4=AAWErZb7=BgHSi094_GMm8VTy23A@mail.gmail.com>
	<kn0pk4$ib6$1@ger.gmane.org> <51942354.4080908@pearwood.info>
	<CACL+1ascPrHQLDKVv-skyHZLLTU0Y+j2dn4=CTmr7OBXXjkx5g@mail.gmail.com>
Message-ID: <CACL+1avoWMCPGWdAJq7-nF=mgE9H1vt_aLeF6zYSyp6iioBg4w@mail.gmail.com>

On Thu, May 16, 2013 at 1:42 AM, eryksun <eryksun at gmail.com> wrote:
> On the other hand a BufferedWriter will buffer the remaining 3000
> bytes that can't be written. You won't find out until an exception is
> raised when the file is closed:

Actually it was buffering all 4000 bytes. I forgot about the fast path
that initially fills the buffer. The default buffer size is 4 KiB to
match the block size on my ext4 file system. So if I limit file size
to 1000 bytes, I can 'write' 5096 bytes before it raises an exception:

    >>> resource.setrlimit(resource.RLIMIT_FSIZE, (1000, -1))
    >>> f = open('temp.bin', 'wb')
    >>> f.write(b'spam'*1274)
    5096
    >>> f.write(b's')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    OSError: [Errno 27] File too large

From kseebohm at yahoo.com  Thu May 16 20:17:02 2013
From: kseebohm at yahoo.com (kyle seebohm)
Date: Thu, 16 May 2013 11:17:02 -0700 (PDT)
Subject: [Tutor] Python Idle Crashing
Message-ID: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com>

I recently created a program that searches through a computer's drive to make a list of all the files in that drive. However, the drive I am attempting to parse through is extremely large and when I run my program, it runs for about 5 or 10 minutes then proceeds to not respond and not finish parsing through the entire drive. Is there a way around this or does the drive just contain too many files?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130516/54293862/attachment.html>

From fred.f.bat at gmail.com  Thu May 16 20:26:43 2013
From: fred.f.bat at gmail.com (frederico Batista)
Date: Thu, 16 May 2013 15:26:43 -0300
Subject: [Tutor] Python Idle Crashing
In-Reply-To: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com>
References: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com>
Message-ID: <CAOi=Wa2VVZo=jBV04ACuDWS=JNoG=Tb3chs40nyXEZBy6mz5Uw@mail.gmail.com>

I don't think running this on Idle is the best.
Did you try to run your program in the command line?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130516/178b9106/attachment-0001.html>

From rafael.knuth at gmail.com  Thu May 16 20:58:33 2013
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Thu, 16 May 2013 20:58:33 +0200
Subject: [Tutor] Issue with string method: str(variable ** n)
Message-ID: <CAM-E2X6QEbm-yjCdNMEg74WivvfgQq1BX=MfY8PURTjcK-SOTg@mail.gmail.com>

Hej,

I wrote a tiny little program which I was hoping would take a number as
input, square and print it:

square = input ("Enter a number. ")
print (str(square) + " squared is " + str(square ** 2))

It seems I can't work with variables within the str() string method, and I
was wondering if anyone can help?

PS. I am using Python 3.3.0

Thank you in advance!

Rafael
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130516/48a42f67/attachment.html>

From davea at davea.name  Thu May 16 21:14:52 2013
From: davea at davea.name (Dave Angel)
Date: Thu, 16 May 2013 15:14:52 -0400
Subject: [Tutor] Issue with string method: str(variable ** n)
In-Reply-To: <CAM-E2X6QEbm-yjCdNMEg74WivvfgQq1BX=MfY8PURTjcK-SOTg@mail.gmail.com>
References: <CAM-E2X6QEbm-yjCdNMEg74WivvfgQq1BX=MfY8PURTjcK-SOTg@mail.gmail.com>
Message-ID: <5195302C.9060104@davea.name>

On 05/16/2013 02:58 PM, Rafael Knuth wrote:
> Hej,
>
> I wrote a tiny little program which I was hoping would take a number as
> input, square and print it:
>
> square = input ("Enter a number. ")
> print (str(square) + " squared is " + str(square ** 2))
>
> It seems I can't work with variables within the str() string method, and I
> was wondering if anyone can help?
>
> PS. I am using Python 3.3.0
>
> Thank you in advance!
>
> Rafael
>
>
In Python 3.3.0, input returns a string.  So square is a string.  There 
isn't any meaning to squaring a string.


You probably want either:

square = float(input("Enter a number.")
or
square = int(input("Enter a number.")

Suggestion for next time - include the error traceback.

-- 
DaveA

From zachary.ware+pytut at gmail.com  Thu May 16 21:18:24 2013
From: zachary.ware+pytut at gmail.com (Zachary Ware)
Date: Thu, 16 May 2013 14:18:24 -0500
Subject: [Tutor] Issue with string method: str(variable ** n)
In-Reply-To: <CAM-E2X6QEbm-yjCdNMEg74WivvfgQq1BX=MfY8PURTjcK-SOTg@mail.gmail.com>
References: <CAM-E2X6QEbm-yjCdNMEg74WivvfgQq1BX=MfY8PURTjcK-SOTg@mail.gmail.com>
Message-ID: <CAKJDb-Nq42ApoaMvYcW20cm9dS+U-fWu73Lsy0JS=DEg7zeSaw@mail.gmail.com>

On Thu, May 16, 2013 at 1:58 PM, Rafael Knuth <rafael.knuth at gmail.com> wrote:
> Hej,

Hi Rafael,

> I wrote a tiny little program which I was hoping would take a number as
> input, square and print it:
>
> square = input ("Enter a number. ")
> print (str(square) + " squared is " + str(square ** 2))
>
> It seems I can't work with variables within the str() string method, and I
> was wondering if anyone can help?
>
> PS. I am using Python 3.3.0

In the future, it's always very helpful to post any tracebacks you
get, everything from "Traceback (most recent call last):" to the last
thing printed.

In this case, it seems that your problem is that in Python3, input()
returns the input as a string.  Python2's input() function would
actually evaluate the input, which was incredibly insecure.

You can fix your program by calling int() on square at the end of your
print call.  If I were writing this myself, I would do this, though:

number = int(input("Enter a number. "))
print("{} squared is {}".format(number, number**2))

You might find the tutorial page on Input and Output[1] instructive,
particularly about the format method I used above.

Hope this helps,

Zach

[1] http://docs.python.org/3/tutorial/inputoutput.html

>
> Thank you in advance!
>
> Rafael
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From davea at davea.name  Thu May 16 21:23:48 2013
From: davea at davea.name (Dave Angel)
Date: Thu, 16 May 2013 15:23:48 -0400
Subject: [Tutor] Python Idle Crashing
In-Reply-To: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com>
References: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com>
Message-ID: <51953244.4070207@davea.name>

On 05/16/2013 02:17 PM, kyle seebohm wrote:
> I recently created a program that searches through a computer's drive to make a list of all the files in that drive. However, the drive I am attempting to parse through is extremely large and when I run my program, it runs for about 5 or 10 minutes then proceeds to not respond and not finish parsing through the entire drive. Is there a way around this or does the drive just contain too many files?
>
>
>

Not clear why you would think that Idle had anything to do with it.  It 
didn't crash, it hung, or maybe is just taking a very long time, or 
maybe it has an infinite loop in the code, or you're thrashing after 
filling up memory?

Still, if you think it was IDLE, it's simple to just run the program 
without IDLE.

What's your environment, besides "extremely large drive"?  What OS, what 
version of Python?  And what's your code look like?

What does top say?  Is the disk light still blinking?  Do you have any 
symbolic links and does your code handle them correctly?


-- 
DaveA

From rafael.knuth at gmail.com  Thu May 16 21:26:01 2013
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Thu, 16 May 2013 21:26:01 +0200
Subject: [Tutor] Issue with string method: str(variable ** n)
In-Reply-To: <5195302C.9060104@davea.name>
References: <CAM-E2X6QEbm-yjCdNMEg74WivvfgQq1BX=MfY8PURTjcK-SOTg@mail.gmail.com>
	<5195302C.9060104@davea.name>
Message-ID: <CAM-E2X7FQsYmyZwX=Ss1CRkp9Ux02pD-sp0iS=o9TfX=Z_DhPg@mail.gmail.com>

Thank you - that makes perfectly sense.

Also, I am new to the list, and I appreciate your suggestion.
I will include error tracebacks in the future.

All the best,
Rafael


On Thu, May 16, 2013 at 9:14 PM, Dave Angel <davea at davea.name> wrote:

> On 05/16/2013 02:58 PM, Rafael Knuth wrote:
>
>> Hej,
>>
>> I wrote a tiny little program which I was hoping would take a number as
>> input, square and print it:
>>
>> square = input ("Enter a number. ")
>> print (str(square) + " squared is " + str(square ** 2))
>>
>> It seems I can't work with variables within the str() string method, and I
>> was wondering if anyone can help?
>>
>> PS. I am using Python 3.3.0
>>
>> Thank you in advance!
>>
>> Rafael
>>
>>
>>  In Python 3.3.0, input returns a string.  So square is a string.  There
> isn't any meaning to squaring a string.
>
>
> You probably want either:
>
> square = float(input("Enter a number.")
> or
> square = int(input("Enter a number.")
>
> Suggestion for next time - include the error traceback.
>
> --
> DaveA
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130516/67868632/attachment.html>

From arvind.s.virk at hotmail.co.uk  Thu May 16 22:03:03 2013
From: arvind.s.virk at hotmail.co.uk (Arvind Virk)
Date: Thu, 16 May 2013 21:03:03 +0100
Subject: [Tutor] Word Jumble - Chpt4 (Explanation)
Message-ID: <DUB103-W3869BED9ED957BAB2C48FE1A30@phx.gbl>

Hi guys!
This is my first post so go gentle. I'm just getting into Python programming and am having an issue understanding the Word Jumble Game.
import random
WORDS = ('python','jumble','easy','difficult','lower','high')word = random.choice(WORDS)correct = wordjumble = ""
while word:    position = random.randrange(len(word))    jumble += word[position]    word = word[:position] + word[(position+1):]  
======
I cannot understand what it is trying to do in the while loop.If the word was python and position lets say was 3 then jumble would = python(3). I cannot understand what the next line does! Please help!
Thanks in advance!

 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130516/96b9b199/attachment-0001.html>

From ramit.prasad at jpmorgan.com  Thu May 16 22:03:48 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Thu, 16 May 2013 20:03:48 +0000
Subject: [Tutor] Python Idle Crashing
In-Reply-To: <51953244.4070207@davea.name>
References: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com>
	<51953244.4070207@davea.name>
Message-ID: <5B80DD153D7D744689F57F4FB69AF474183CDEB3@SCACMX008.exchad.jpmchase.net>

Dave Angel wrote:
> On 05/16/2013 02:17 PM, kyle seebohm wrote:
> > I recently created a program that searches through a computer's drive to make a list of all the
> files in that drive. However, the drive I am attempting to parse through is extremely large and when I
> run my program, it runs for about 5 or 10 minutes then proceeds to not respond and not finish parsing
> through the entire drive. Is there a way around this or does the drive just contain too many files?
> >
> >
> >
> 
> Not clear why you would think that Idle had anything to do with it.  It
> didn't crash, it hung, or maybe is just taking a very long time, or
> maybe it has an infinite loop in the code, or you're thrashing after
> filling up memory?
> 
> Still, if you think it was IDLE, it's simple to just run the program
> without IDLE.
> 
> What's your environment, besides "extremely large drive"?  What OS, what
> version of Python?  And what's your code look like?
> 
> What does top say?  Is the disk light still blinking?  Do you have any
> symbolic links and does your code handle them correctly?
> 

Also, what version of Python? What OS? What file system? Do you have any 
logging (actual logs or even just print statements to console)?


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

From ramit.prasad at jpmorgan.com  Thu May 16 22:22:22 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Thu, 16 May 2013 20:22:22 +0000
Subject: [Tutor] Word Jumble - Chpt4 (Explanation)
In-Reply-To: <DUB103-W3869BED9ED957BAB2C48FE1A30@phx.gbl>
References: <DUB103-W3869BED9ED957BAB2C48FE1A30@phx.gbl>
Message-ID: <5B80DD153D7D744689F57F4FB69AF474183CE208@SCACMX008.exchad.jpmchase.net>

Arvind Virk wrote:
> Hi guys!
> 
> This is my first post so go gentle. I'm just getting into Python programming and am having an issue
> understanding the Word Jumble Game.
> 
> import random
> 
> WORDS = ('python','jumble','easy','difficult','lower','high')
> word = random.choice(WORDS)
> correct = word
> jumble = ""
> 
> while word:
> ? ? position = random.randrange(len(word))
> ? ? jumble += word[position]
> ? ? word = word[:position] + word[(position+1):]
> 
> ======
> 
> I cannot understand what it is trying to do in the while loop.
> If the word was python and position lets say was 3 then jumble would = python(3). I cannot understand
> what the next line does! Please help!
> 
> Thanks in advance!
> 

The best way to understand a program is to watch what it is 
doing and follow through the code. This is called debugging.
Simple programs like this you might be able to debug in your
mind but in a real program chances are you will need a debugger
or some other method. A very common way to debug is to put in 
print statements so you can follow the actions of data. Look
at the code I put below and the output. Can you follow?

>>> word = 'python'
>>> jumble = ""
>>> while word:
...     position = random.randrange(len(word))
...     print 'position {0} | jumble "{1}"'.format( position, jumble )
...     tempchar = word[position]
...     jumble += tempchar
...     word = word[:position] + word[(position+1):]
...     print 'After jumble "{0}" | word "{1}" | tempchar {2}'.format( jumble, word, tempchar )
...     
position 5 | jumble ""
After jumble "n" | word "pytho" | tempchar n
position 2 | jumble "n"
After jumble "nt" | word "pyho" | tempchar t
position 3 | jumble "nt"
After jumble "nto" | word "pyh" | tempchar o
position 1 | jumble "nto"
After jumble "ntoy" | word "ph" | tempchar y
position 0 | jumble "ntoy"
After jumble "ntoyp" | word "h" | tempchar p
position 0 | jumble "ntoyp"
After jumble "ntoyph" | word "" | tempchar h


So based on the above output I would say that it is removing a 
random character from word and adding it to jumble to create a 
jumbled version of the word. Of course, the std library
can do it for you better. :) I leave the exercise of actually
understanding the character manipulation to you as a learning
exercise, but if you get stuck feel free to post back.

>>> t = list("python")
>>> random.shuffle(t)
>>> ''.join(t)
'optynh'


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

From cybervigilante at gmail.com  Fri May 17 00:12:03 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Thu, 16 May 2013 15:12:03 -0700
Subject: [Tutor] Can't install latest PIL
In-Reply-To: <CACL+1av0eSSY3GwAUuDANVGL=XD4MP+0QOXAEGGfTbMUCfP0=g@mail.gmail.com>
References: <CALRAYNUpzMgSFxrFZXEiGc_oQpLk_02Bj96LFuOtZyvU96PLTw@mail.gmail.com>
	<CACL+1av0eSSY3GwAUuDANVGL=XD4MP+0QOXAEGGfTbMUCfP0=g@mail.gmail.com>
Message-ID: <CALRAYNUwH1TcewAYNUw5bT_CdmQBnjD75uvFF8+1+-2syFL7uw@mail.gmail.com>

Make sure you have the correct architecture. The builds from
PythonWare are 32-bit. Christoph Gohlke has 64-bit builds here:

http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil

==
Okay, I installed the 64 bit for Py 2.7, it installed, I see  PIL
directory in Site-Packages. (Actually, it's the Pillow fork, but it
still seems to be named PIL)  I tried "import image from pil" and got
the following error: SyntaxError   invalid syntax (python_init.py,
line 1)

I don't see where that prog is, so it's an install somewhere and I
don't want to mess with it anyway.

Oh well, be nice to get back to learning Python after wrestling with
editors, installs, and Windows ;')

Jim

From cybervigilante at gmail.com  Fri May 17 00:15:04 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Thu, 16 May 2013 15:15:04 -0700
Subject: [Tutor] Pygraphics crashed
In-Reply-To: <CACL+1avAVP8eaRnbDtbe+bKYq6qALLtR1+UqhpmStoHDX3YJ9Q@mail.gmail.com>
References: <CALRAYNUhZ60ZVSOqT6xJaKFxHRPoX8poVHPJs890JL4tF7n=dg@mail.gmail.com>
	<CACL+1avAVP8eaRnbDtbe+bKYq6qALLtR1+UqhpmStoHDX3YJ9Q@mail.gmail.com>
Message-ID: <CALRAYNXbKU4fqEcuaSTKnxsuLZKmPQQJmQF=xEFdJga8g7VDJg@mail.gmail.com>

How do I install PIL with easy-install? I used that once but forget
how.  I seem to recall reading it installs a version that is Py native
and doesn't choke on your OS. Or did I read that wrong?

Jim

On 16 May 2013 02:44, eryksun <eryksun at gmail.com> wrote:
> On Thu, May 16, 2013 at 2:06 AM, Jim Mooney <cybervigilante at gmail.com> wrote:
>>
>> And regardless of the answer to that I still want to know how to
>> uninstall modules. Do I just find and delete them? And are they all in
>> the same place?
>
> You should be able to uninstall msi or exe packages just like any
> other Windows program. pip has an uninstall command if you used it to
> install a package. If you used easy_install, you'll have to manually
> delete associated eggs and egg-info directories from
> Lib\site-packages, defunct scripts in Scripts, and also edit
> Lib\site-packages\easy-install.pth to remove deleted cruft. It's
> definitely not easy_uninstall.



-- 
Jim Mooney

?For anything that matters, the timing is never quite right, the
resources are always a little short, and the people who affect the
outcome are always ambivalent.?

From jeanpierreda at gmail.com  Fri May 17 00:25:13 2013
From: jeanpierreda at gmail.com (Devin Jeanpierre)
Date: Thu, 16 May 2013 18:25:13 -0400
Subject: [Tutor] Pygraphics crashed
In-Reply-To: <CALRAYNUhZ60ZVSOqT6xJaKFxHRPoX8poVHPJs890JL4tF7n=dg@mail.gmail.com>
References: <CALRAYNUhZ60ZVSOqT6xJaKFxHRPoX8poVHPJs890JL4tF7n=dg@mail.gmail.com>
Message-ID: <CABicbJJtccfvm9NwDWnNzCSWu_tH7EssLEHNWaPVhkHBUPLWwg@mail.gmail.com>

On Thu, May 16, 2013 at 2:06 AM, Jim Mooney <cybervigilante at gmail.com> wrote:
> How do I uninstall modules? I installed Pygraphics, which worked fine,
> along with some other mods, like numpy, but when I installed 64 bit py
> 2.7
> I get the message "The _imaging C module is not installed" when
> running a prog that worked fine before. I think I have a higher
> dot-version - Py 2.7.4 as opposed to 2.7.3  - what's the easiest way
> to fix this? Will uninstalling and reinstalling the modules do
> anything or do I have to revert to an older Py (I'm on Win 7)

On windows it's generally easiest to use a 32 bit Python. If you
uninstall python, and install a 32 bit version and the 32 bit modules
and so on, it should work.

By the way, do you mind if I ask why you're using PyGraphics? It's
only meant to be used for education (and even there, AFAIK the only
users are the University of Toronto (and even there, I think they
stopped using it because they switched to Python 3 for Coursera and
didn't care enough to upgrade PyGraphics (I am mad about this))).

-- Devin

From cybervigilante at gmail.com  Fri May 17 00:49:07 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Thu, 16 May 2013 15:49:07 -0700
Subject: [Tutor] Pygraphics crashed
In-Reply-To: <CABicbJJtccfvm9NwDWnNzCSWu_tH7EssLEHNWaPVhkHBUPLWwg@mail.gmail.com>
References: <CALRAYNUhZ60ZVSOqT6xJaKFxHRPoX8poVHPJs890JL4tF7n=dg@mail.gmail.com>
	<CABicbJJtccfvm9NwDWnNzCSWu_tH7EssLEHNWaPVhkHBUPLWwg@mail.gmail.com>
Message-ID: <CALRAYNV16p6OYvVadJ6zY22xjJDzV1JCfw4TZ+LN+YOysZO+_g@mail.gmail.com>

> By the way, do you mind if I ask why you're using PyGraphics? It's
> only meant to be used for education (and even there, AFAIK the only
> users are the University of Toronto (and even there, I think they
> stopped using it because they switched to Python 3 for Coursera and
> didn't care enough to upgrade PyGraphics (I am mad about this))).
>

Yeah, I'm tired of fighting 64 bit windows. I'm going to uninstall
everything and use 32 bit I was reading some advice to use 64 bit for
speed but I'm only learning - I don't need to keep wrestling with this
crap just get top speed for twenty line programs ;')

PyGraphics was an import in a program right at the front of a book I'm
using. Worked fine for displaying jpgs very easily, before I started
fooling with 64 bit. Let me see, the book is called:
Practical Progamming - an introduction to computer science using
Python by Jennifer Campbell, et al.

It's not my main book - it's just for doing something more active
while I slug through Guttag's MIT open courseware on Python. Guttag
covers all the bases, but in the meantime I want to see pretty
pictures and see what Python can do ;')

Right now I'm using both Py 2.7 and Py 3.3 since I want to learn 3.3
but half the good libs are still in 2.7.

Actually, neither the book or Guttag is pure Python, but just using
Python to teach computer science. I'm a retired webmaster and hacked
away just enough at javascript, jquery, and php to get something done
on a site, but I figured I'd actually learn this from the ground up
now that I have time and don't have to be hustling a site all the
time, and just grab some jquery and get it done. I may have to look at
a dedicated Python book for detail, since the book and course I have
admit they just scant Python to get on with computer science.

Jim

From eire1130 at gmail.com  Fri May 17 01:11:59 2013
From: eire1130 at gmail.com (James Reynolds)
Date: Thu, 16 May 2013 19:11:59 -0400
Subject: [Tutor] Can't install latest PIL
In-Reply-To: <CALRAYNUwH1TcewAYNUw5bT_CdmQBnjD75uvFF8+1+-2syFL7uw@mail.gmail.com>
References: <CALRAYNUpzMgSFxrFZXEiGc_oQpLk_02Bj96LFuOtZyvU96PLTw@mail.gmail.com>
	<CACL+1av0eSSY3GwAUuDANVGL=XD4MP+0QOXAEGGfTbMUCfP0=g@mail.gmail.com>
	<CALRAYNUwH1TcewAYNUw5bT_CdmQBnjD75uvFF8+1+-2syFL7uw@mail.gmail.com>
Message-ID: <CAE0jAbqBcjy=RU2CjYRNu1HX4aprDp+D3BxQBVrKWFAHY7KHGw@mail.gmail.com>

You may want to consider pillow. Oil hasn't been maintained in some time.
 On May 16, 2013 6:12 PM, "Jim Mooney" <cybervigilante at gmail.com> wrote:

> Make sure you have the correct architecture. The builds from
> PythonWare are 32-bit. Christoph Gohlke has 64-bit builds here:
>
> http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil
>
> ==
> Okay, I installed the 64 bit for Py 2.7, it installed, I see  PIL
> directory in Site-Packages. (Actually, it's the Pillow fork, but it
> still seems to be named PIL)  I tried "import image from pil" and got
> the following error: SyntaxError   invalid syntax (python_init.py,
> line 1)
>
> I don't see where that prog is, so it's an install somewhere and I
> don't want to mess with it anyway.
>
> Oh well, be nice to get back to learning Python after wrestling with
> editors, installs, and Windows ;')
>
> Jim
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130516/b5b23dcd/attachment.html>

From marc.tompkins at gmail.com  Fri May 17 01:44:47 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 16 May 2013 16:44:47 -0700
Subject: [Tutor] Word Jumble - Chpt4 (Explanation)
In-Reply-To: <DUB103-W3869BED9ED957BAB2C48FE1A30@phx.gbl>
References: <DUB103-W3869BED9ED957BAB2C48FE1A30@phx.gbl>
Message-ID: <CAKK8jXYTmY1EAR_sKsR0HV1Dn-4KsEkwCQNX5hG6Jx9P4rEyhg@mail.gmail.com>

On Thu, May 16, 2013 at 1:03 PM, Arvind Virk <arvind.s.virk at hotmail.co.uk>wrote:

 import random
>
> WORDS = ('python','jumble','easy','difficult','lower','high')
> word = random.choice(WORDS)
> correct = word
> jumble = ""
>
> while word:
>     position = random.randrange(len(word))
>     jumble += word[position]
>     word = word[:position] + word[(position+1):]
>
> ======
>
> I cannot understand what it is trying to do in the while loop.
> If the word was python and position lets say was 3 then jumble would =
> python(3). I cannot understand what the next line does! Please help!
>
> First, about "while word" - A 'while' loop runs as long as its condition
evaluates to True; an explanation of what evaluates to True can be found
here: http://docs.python.org/2/library/stdtypes.html, but for our purposes
it boils down to "as long as 'word' is not an empty string, keep going".

Second, what it's doing inside that while loop - it's picking a random
letter out of 'word', adding it to the end of 'jumble', and then removing
it from 'word'.  It's doing it by means of slices:  it takes all of 'word'
up to (but not including) 'position', then adds all of 'word' starting one
character AFTER 'position'.  'word' is now one character shorter than it
started out; keep this up long enough and you'll be left with an empty
string, which evaluates to False - and the 'while' loop terminates.

This is definitely not the most efficient way to do things, but it's a
pretty good introduction to slices (which are awesome, by the way.)
There's a very good introduction to Python's slice notation about halfway
down this page: http://docs.python.org/2/tutorial/introduction.html, in
section 3.1.2 "Strings".  Just remember that lists and indices start with
0, not 1, and you'll be on your way.

Finally, as Ramit mentioned, print statements (or print() functions, if
you're on Python 3) are your friend!  Don't be afraid or ashamed to put in
lots of them whenever you're not sure what your code is doing!  (Just
remember to take out the unnecessary one when you're done.)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130516/9c16ce28/attachment.html>

From cybervigilante at gmail.com  Fri May 17 01:46:49 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Thu, 16 May 2013 16:46:49 -0700
Subject: [Tutor] Can't install latest PIL
In-Reply-To: <CAE0jAbqBcjy=RU2CjYRNu1HX4aprDp+D3BxQBVrKWFAHY7KHGw@mail.gmail.com>
References: <CALRAYNUpzMgSFxrFZXEiGc_oQpLk_02Bj96LFuOtZyvU96PLTw@mail.gmail.com>
	<CACL+1av0eSSY3GwAUuDANVGL=XD4MP+0QOXAEGGfTbMUCfP0=g@mail.gmail.com>
	<CALRAYNUwH1TcewAYNUw5bT_CdmQBnjD75uvFF8+1+-2syFL7uw@mail.gmail.com>
	<CAE0jAbqBcjy=RU2CjYRNu1HX4aprDp+D3BxQBVrKWFAHY7KHGw@mail.gmail.com>
Message-ID: <CALRAYNVaZOK_DGRUTN-NS_0rO-hXKh+HOF+pWuq3tNq8rM37jg@mail.gmail.com>

On 16 May 2013 16:11, James Reynolds <eire1130 at gmail.com> wrote:
> You may want to consider pillow. Oil hasn't been maintained in some time.

Actually, I installed Pillow. But then I deleted everything and
started over with 32 bit. I got greedy figuring I'd get the fastest Py
with 64 bit, but there are too many kludges involved and I'm tired of
it so heave-ho on all the 64 bit.

Back to 32 bit. All modules and showing pretty pictures with Py work
again. It doesn't pay to be greedy (except with regular expressions,
of course)

Jim

From alan.gauld at btinternet.com  Fri May 17 02:49:27 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 17 May 2013 01:49:27 +0100
Subject: [Tutor] Python Idle Crashing
In-Reply-To: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com>
References: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com>
Message-ID: <kn3uqi$hu5$1@ger.gmane.org>

On 16/05/13 19:17, kyle seebohm wrote:
> I recently created a program that searches through a computer's drive to
> make a list of all the files in that drive. However, the drive I am
> attempting to parse through is extremely large and when I run my
> program, it runs for about 5 or 10 minutes then proceeds to not respond
> and not finish parsing through the entire drive.

First, don't run programs on real data using IDLE. IDLE is for 
developing programs not running them.

Second, 5-10 minutes is not that long, how do you know it had stopped? 
Do you have progress markers printed that stopped printing? If not I 
suggest you add them - just a dot after each file (or each 10, 100, etc 
files) will do. Have you checked Task Manager (assuming windows, top on 
*nix) to see if the process is still using CPU?


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From alan.gauld at btinternet.com  Fri May 17 02:56:55 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 17 May 2013 01:56:55 +0100
Subject: [Tutor] Word Jumble - Chpt4 (Explanation)
In-Reply-To: <DUB103-W3869BED9ED957BAB2C48FE1A30@phx.gbl>
References: <DUB103-W3869BED9ED957BAB2C48FE1A30@phx.gbl>
Message-ID: <kn3v8i$m16$1@ger.gmane.org>

On 16/05/13 21:03, Arvind Virk wrote:

> This is my first post so go gentle. I'm just getting into Python
> programming and am having an issue understanding the Word Jumble Game.

Welcome.
First thing is we have no idea what Chapter 4 refers to so please tell 
us the source you are working from (alsoi OS and Python version helps too)
Secondly tell us what happens when you run it and what you expected and 
what you got and why you are surprised/puzzled.


> import random
>
> WORDS = ('python','jumble','easy','difficult','lower','high')
> word = random.choice(WORDS)
> correct = word

FWIW I don't understand the above line. It does nothing useful and 
correct is not used again...

> jumble = ""
>
> while word:
>      position = random.randrange(len(word))
>      jumble += word[position]
>      word = word[:position] + word[(position+1):]
>

Also since there are no print statements it all seems a tad pointless, 
are you sure that's the whole program?


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From eryksun at gmail.com  Fri May 17 04:51:33 2013
From: eryksun at gmail.com (eryksun)
Date: Thu, 16 May 2013 22:51:33 -0400
Subject: [Tutor] Can't install latest PIL
In-Reply-To: <CALRAYNUwH1TcewAYNUw5bT_CdmQBnjD75uvFF8+1+-2syFL7uw@mail.gmail.com>
References: <CALRAYNUpzMgSFxrFZXEiGc_oQpLk_02Bj96LFuOtZyvU96PLTw@mail.gmail.com>
	<CACL+1av0eSSY3GwAUuDANVGL=XD4MP+0QOXAEGGfTbMUCfP0=g@mail.gmail.com>
	<CALRAYNUwH1TcewAYNUw5bT_CdmQBnjD75uvFF8+1+-2syFL7uw@mail.gmail.com>
Message-ID: <CACL+1auAkbxG5BAsVM4kpVwYOGuszpd-Y1i-25tDwg1MPzdF1w@mail.gmail.com>

On Thu, May 16, 2013 at 6:12 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> I tried "import image from pil" and got the following error:
> SyntaxError   invalid syntax (python_init.py, line 1)

If you see a syntax error, that means your code could not be compiled.
Python's parser doesn't grok "import image from pil". In natural
language we have the freedom to swap the order of clauses, but
programming languages are generally more rigid. The correct order is
"from pil import image" -- but actually it has to be "from PIL import
Image".

From eryksun at gmail.com  Fri May 17 06:56:29 2013
From: eryksun at gmail.com (eryksun)
Date: Fri, 17 May 2013 00:56:29 -0400
Subject: [Tutor] Pygraphics crashed
In-Reply-To: <CALRAYNXbKU4fqEcuaSTKnxsuLZKmPQQJmQF=xEFdJga8g7VDJg@mail.gmail.com>
References: <CALRAYNUhZ60ZVSOqT6xJaKFxHRPoX8poVHPJs890JL4tF7n=dg@mail.gmail.com>
	<CACL+1avAVP8eaRnbDtbe+bKYq6qALLtR1+UqhpmStoHDX3YJ9Q@mail.gmail.com>
	<CALRAYNXbKU4fqEcuaSTKnxsuLZKmPQQJmQF=xEFdJga8g7VDJg@mail.gmail.com>
Message-ID: <CACL+1auk6U3gsRWyeh9tO7z3isd+f2yM+jmKS9TO1XQ8vF8H0Q@mail.gmail.com>

On Thu, May 16, 2013 at 6:15 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> How do I install PIL with easy-install? I used that once but forget
> how.  I seem to recall reading it installs a version that is Py native
> and doesn't choke on your OS. Or did I read that wrong?

I recommend pip instead of easy_install because it allows you to
easily uninstall.

First install distribute:
http://python-distribute.org/distribute_setup.py

Next install pip:
https://raw.github.com/pypa/pip/master/contrib/get-pip.py

Quickstart guide:
http://www.pip-installer.org/en/1.3.1/quickstart.html

On Windows, pip and easy_install are a bit limited. I gather that the
new Wheel package format (.whl) and compatibility tags should solve
the problem (see PEPs 427 and 425). The development version of pip
supports Wheel. As is, pip works just fine for installing pure Python
packages from source. easy_install also supports binary eggs, but I
dislike not having an easy way to uninstall. At least an exe/msi
installer lets you uninstall using the Windows control panel.

If you have a supported C compiler configured, you can use pip to
install packages that have self-contained C extensions (i.e. no
dependencies -- such as psutil or cython). Visual Studio [Express] is
recommended (2008 for 2.6-3.2; 2010 for 3.3), especially if C++ is
used, but MinGW-w64 can be made to work. The big problem here is
Windows lacks dependency management for installing libraries and
development files (headers and import libs) to known system locations.
So compiling an extension module that has dependencies needs to be
configured manually.

PIL has a lot of dependencies: libjpeg, libtiff, zlib, freetype2,
littleCMS, libwebp, and Tcl/Tk. Building it is a moderately
challenging process on Windows -- not really suited for a beginner.
Building NumPy/SciPy would be even more work since they need a Fortran
compiler, too. Fortunately for Windows users, Christoph Gohlke has
already done all the hard work for dozens of the most popular
packages.

From __peter__ at web.de  Fri May 17 08:50:32 2013
From: __peter__ at web.de (Peter Otten)
Date: Fri, 17 May 2013 08:50:32 +0200
Subject: [Tutor] Python Idle Crashing
References: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com>
Message-ID: <kn4jv5$3kb$1@ger.gmane.org>

kyle seebohm wrote:

> I recently created a program that searches through a computer's drive to
> make a list of all the files in that drive. However, the drive I am
> attempting to parse through is extremely large and when I run my program,
> it runs for about 5 or 10 minutes then proceeds to not respond and not
> finish parsing through the entire drive. Is there a way around this or
> does the drive just contain too many files?

What do you want to do with it once the list of files is complete?
Can you process the filenames independently or do you really need them all 
at once?


From cybervigilante at gmail.com  Fri May 17 09:23:50 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Fri, 17 May 2013 00:23:50 -0700
Subject: [Tutor] Can't install latest PIL
In-Reply-To: <CACL+1auAkbxG5BAsVM4kpVwYOGuszpd-Y1i-25tDwg1MPzdF1w@mail.gmail.com>
References: <CALRAYNUpzMgSFxrFZXEiGc_oQpLk_02Bj96LFuOtZyvU96PLTw@mail.gmail.com>
	<CACL+1av0eSSY3GwAUuDANVGL=XD4MP+0QOXAEGGfTbMUCfP0=g@mail.gmail.com>
	<CALRAYNUwH1TcewAYNUw5bT_CdmQBnjD75uvFF8+1+-2syFL7uw@mail.gmail.com>
	<CACL+1auAkbxG5BAsVM4kpVwYOGuszpd-Y1i-25tDwg1MPzdF1w@mail.gmail.com>
Message-ID: <CALRAYNVES=OSWvdn2h+yePnTb=N+4+5t2CxqY454GHBPa4WFaw@mail.gmail.com>

> If you see a syntax error, that means your code could not be compiled.
> Python's parser doesn't grok "import image from pil". In natural
> language we have the freedom to swap the order of clauses, but
> programming languages are generally more rigid. The correct order is
> "from pil import image" -- but actually it has to be "from PIL import
> Image".

Yeah, I fixed that but it still blew a fuse. Going back to 32 bit
fixed everything.

from ** import ** just sounds backward to me, so I'll get it wrong
until I get it right.

Actually, it is backward by standard English - a design flub ;')

BTW, I noticed that Msoft Visual Studio has Python. Does that mean I
could made a standalone Win executable with Python, or would a user
still need the Py interpreter installed? It would be nice if you could
make an exe.

Jim

From eryksun at gmail.com  Fri May 17 10:19:28 2013
From: eryksun at gmail.com (eryksun)
Date: Fri, 17 May 2013 04:19:28 -0400
Subject: [Tutor] Can't install latest PIL
In-Reply-To: <CALRAYNVES=OSWvdn2h+yePnTb=N+4+5t2CxqY454GHBPa4WFaw@mail.gmail.com>
References: <CALRAYNUpzMgSFxrFZXEiGc_oQpLk_02Bj96LFuOtZyvU96PLTw@mail.gmail.com>
	<CACL+1av0eSSY3GwAUuDANVGL=XD4MP+0QOXAEGGfTbMUCfP0=g@mail.gmail.com>
	<CALRAYNUwH1TcewAYNUw5bT_CdmQBnjD75uvFF8+1+-2syFL7uw@mail.gmail.com>
	<CACL+1auAkbxG5BAsVM4kpVwYOGuszpd-Y1i-25tDwg1MPzdF1w@mail.gmail.com>
	<CALRAYNVES=OSWvdn2h+yePnTb=N+4+5t2CxqY454GHBPa4WFaw@mail.gmail.com>
Message-ID: <CACL+1av7KAOmyTFayYUiYOwmyiKF8HsNLopmd1v6oYieLVTK+g@mail.gmail.com>

On Fri, May 17, 2013 at 3:23 AM, Jim Mooney <cybervigilante at gmail.com> wrote:
> BTW, I noticed that Msoft Visual Studio has Python. Does that mean I
> could made a standalone Win executable with Python, or would a user
> still need the Py interpreter installed? It would be nice if you could
> make an exe.

Are you referring to Python Tools for Visual Studio? PTVS lets you use
Visual Studio as a Python IDE:

http://pytools.codeplex.com

For CPython, one option for creating an exe is py2exe:

http://www.py2exe.org/index.cgi/Tutorial

If you're referring to IronPython, that's a .NET implementation of Python:

http://ironpython.codeplex.com
http://www.ironpython.info

Here's a tutorial on creating an exe with IronPython:

http://dbaportal.eu/2009/12/21/ironpython-how-to-compile-exe

From wprins at gmail.com  Fri May 17 12:44:14 2013
From: wprins at gmail.com (Walter Prins)
Date: Fri, 17 May 2013 11:44:14 +0100
Subject: [Tutor] Pygraphics crashed
In-Reply-To: <CALRAYNV16p6OYvVadJ6zY22xjJDzV1JCfw4TZ+LN+YOysZO+_g@mail.gmail.com>
References: <CALRAYNUhZ60ZVSOqT6xJaKFxHRPoX8poVHPJs890JL4tF7n=dg@mail.gmail.com>
	<CABicbJJtccfvm9NwDWnNzCSWu_tH7EssLEHNWaPVhkHBUPLWwg@mail.gmail.com>
	<CALRAYNV16p6OYvVadJ6zY22xjJDzV1JCfw4TZ+LN+YOysZO+_g@mail.gmail.com>
Message-ID: <CANLXbfAFJ1KhyMe4SizfyGcbSi+0+7UBDRj6Jxc5B4s1y+O14w@mail.gmail.com>

Hi,


On 16 May 2013 23:49, Jim Mooney <cybervigilante at gmail.com> wrote:

> > By the way, do you mind if I ask why you're using PyGraphics? It's
> > only meant to be used for education (and even there, AFAIK the only
> > users are the University of Toronto (and even there, I think they
> > stopped using it because they switched to Python 3 for Coursera and
> > didn't care enough to upgrade PyGraphics (I am mad about this))).
> >
>
> Yeah, I'm tired of fighting 64 bit windows. I'm going to uninstall
> everything and use 32 bit I was reading some advice to use 64 bit for
> speed but I'm only learning - I don't need to keep wrestling with this
> crap just get top speed for twenty line programs ;')
>

I hope by "uninstall everything" you're not also intending to uninstall
Windows 64-bit itself -- you can (should) keep Windows 64-bit and just
install 32-bit everything else (Python etc) on it as desired.

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130517/6e48b6c8/attachment.html>

From oscar.j.benjamin at gmail.com  Fri May 17 16:31:40 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Fri, 17 May 2013 15:31:40 +0100
Subject: [Tutor] Pygraphics crashed
In-Reply-To: <CACL+1auk6U3gsRWyeh9tO7z3isd+f2yM+jmKS9TO1XQ8vF8H0Q@mail.gmail.com>
References: <CALRAYNUhZ60ZVSOqT6xJaKFxHRPoX8poVHPJs890JL4tF7n=dg@mail.gmail.com>
	<CACL+1avAVP8eaRnbDtbe+bKYq6qALLtR1+UqhpmStoHDX3YJ9Q@mail.gmail.com>
	<CALRAYNXbKU4fqEcuaSTKnxsuLZKmPQQJmQF=xEFdJga8g7VDJg@mail.gmail.com>
	<CACL+1auk6U3gsRWyeh9tO7z3isd+f2yM+jmKS9TO1XQ8vF8H0Q@mail.gmail.com>
Message-ID: <CAHVvXxThxfsdgX2arQJqXgL=DDmZ97kvUOm6Thy4zM+CmrmqXQ@mail.gmail.com>

On 17 May 2013 05:56, eryksun <eryksun at gmail.com> wrote:
> On Thu, May 16, 2013 at 6:15 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
>> How do I install PIL with easy-install? I used that once but forget
>> how.  I seem to recall reading it installs a version that is Py native
>> and doesn't choke on your OS. Or did I read that wrong?
>
> I recommend pip instead of easy_install because it allows you to
> easily uninstall.

I don't recommend using pip over easy_install for something like PIL
on Windows (for the reasons that you list below).

>
> First install distribute:
> http://python-distribute.org/distribute_setup.py
>
> Next install pip:
> https://raw.github.com/pypa/pip/master/contrib/get-pip.py
>
> Quickstart guide:
> http://www.pip-installer.org/en/1.3.1/quickstart.html
>
> On Windows, pip and easy_install are a bit limited. I gather that the
> new Wheel package format (.whl) and compatibility tags should solve
> the problem (see PEPs 427 and 425).

The wheel format will solve part of the problem in that it will make
it safer and easier to install prebuilt binaries. It will still
require someone to create all of the prebuilt binaries for each
OS/architecture/Python version and it doesn't really make this step
any easier than creating e.g. an MSI installer is now.

> The development version of pip
> supports Wheel. As is, pip works just fine for installing pure Python
> packages from source. easy_install also supports binary eggs, but I
> dislike not having an easy way to uninstall. At least an exe/msi
> installer lets you uninstall using the Windows control panel.

Precisely. I would probably use an MSI for this (if available).

> If you have a supported C compiler configured, you can use pip to
> install packages that have self-contained C extensions (i.e. no
> dependencies -- such as psutil or cython). Visual Studio [Express] is
> recommended (2008 for 2.6-3.2; 2010 for 3.3), especially if C++ is
> used, but MinGW-w64 can be made to work. The big problem here is
> Windows lacks dependency management for installing libraries and
> development files (headers and import libs) to known system locations.
> So compiling an extension module that has dependencies needs to be
> configured manually.

Since my own Windows machine has the wrong version of Visual Studio
(and out IT policy won't let me change it) I use mingw. However, every
time I install a new Python I have to patch distutils to fix the
'-mnocygwin' bug that prevents current Python from working with it.
Why this issue (http://bugs.python.org/issue12641) is still unresolved
despite being fully understood two years ago I don't understand.

> PIL has a lot of dependencies: libjpeg, libtiff, zlib, freetype2,
> littleCMS, libwebp, and Tcl/Tk. Building it is a moderately
> challenging process on Windows -- not really suited for a beginner.
> Building NumPy/SciPy would be even more work since they need a Fortran
> compiler, too. Fortunately for Windows users, Christoph Gohlke has
> already done all the hard work for dozens of the most popular
> packages.

My own suggestion to coworkers who are new to Python and using Windows
or OSX (without macports) is to use either the Enthought Python
Distribution (free for academic use) or Python(x, y) (free for
anyone). These will install and setup the bulk of packages commonly
used in scientific work from a single installer. Either distribution
will install and setup numpy, scipy, PIL, mingw, pip, distribute, and
many more hard to build packages.

See here for the lists of what each distribution includes:
https://www.enthought.com/products/canopy/package-index/
https://code.google.com/p/pythonxy/wiki/Welcome


Oscar

From web.jedi at yahoo.com  Fri May 17 16:39:07 2013
From: web.jedi at yahoo.com (Web Jedi)
Date: Fri, 17 May 2013 10:39:07 -0400
Subject: [Tutor] unsubscribe
In-Reply-To: <mailman.19.1368784801.27875.tutor@python.org>
References: <mailman.19.1368784801.27875.tutor@python.org>
Message-ID: <E263A9D9-28C4-4822-B77B-93F9A9C3E288@yahoo.com>

unsubscribe

On May 17, 2013, at 6:00 AM, 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
>    http://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: Pygraphics crashed (eryksun)
>   2. Re: Python Idle Crashing (Peter Otten)
>   3. Re: Can't install latest PIL (Jim Mooney)
>   4. Re: Can't install latest PIL (eryksun)
> 
> 
> ----------------------------------------------------------------------
> 
> Message: 1
> Date: Fri, 17 May 2013 00:56:29 -0400
> From: eryksun <eryksun at gmail.com>
> To: Jim Mooney <cybervigilante at gmail.com>
> Cc: tutor at python.org
> Subject: Re: [Tutor] Pygraphics crashed
> Message-ID:
>    <CACL+1auk6U3gsRWyeh9tO7z3isd+f2yM+jmKS9TO1XQ8vF8H0Q at mail.gmail.com>
> Content-Type: text/plain; charset=UTF-8
> 
> On Thu, May 16, 2013 at 6:15 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
>> How do I install PIL with easy-install? I used that once but forget
>> how.  I seem to recall reading it installs a version that is Py native
>> and doesn't choke on your OS. Or did I read that wrong?
> 
> I recommend pip instead of easy_install because it allows you to
> easily uninstall.
> 
> First install distribute:
> http://python-distribute.org/distribute_setup.py
> 
> Next install pip:
> https://raw.github.com/pypa/pip/master/contrib/get-pip.py
> 
> Quickstart guide:
> http://www.pip-installer.org/en/1.3.1/quickstart.html
> 
> On Windows, pip and easy_install are a bit limited. I gather that the
> new Wheel package format (.whl) and compatibility tags should solve
> the problem (see PEPs 427 and 425). The development version of pip
> supports Wheel. As is, pip works just fine for installing pure Python
> packages from source. easy_install also supports binary eggs, but I
> dislike not having an easy way to uninstall. At least an exe/msi
> installer lets you uninstall using the Windows control panel.
> 
> If you have a supported C compiler configured, you can use pip to
> install packages that have self-contained C extensions (i.e. no
> dependencies -- such as psutil or cython). Visual Studio [Express] is
> recommended (2008 for 2.6-3.2; 2010 for 3.3), especially if C++ is
> used, but MinGW-w64 can be made to work. The big problem here is
> Windows lacks dependency management for installing libraries and
> development files (headers and import libs) to known system locations.
> So compiling an extension module that has dependencies needs to be
> configured manually.
> 
> PIL has a lot of dependencies: libjpeg, libtiff, zlib, freetype2,
> littleCMS, libwebp, and Tcl/Tk. Building it is a moderately
> challenging process on Windows -- not really suited for a beginner.
> Building NumPy/SciPy would be even more work since they need a Fortran
> compiler, too. Fortunately for Windows users, Christoph Gohlke has
> already done all the hard work for dozens of the most popular
> packages.
> 
> 
> ------------------------------
> 
> Message: 2
> Date: Fri, 17 May 2013 08:50:32 +0200
> From: Peter Otten <__peter__ at web.de>
> To: tutor at python.org
> Subject: Re: [Tutor] Python Idle Crashing
> Message-ID: <kn4jv5$3kb$1 at ger.gmane.org>
> Content-Type: text/plain; charset="ISO-8859-1"
> 
> kyle seebohm wrote:
> 
>> I recently created a program that searches through a computer's drive to
>> make a list of all the files in that drive. However, the drive I am
>> attempting to parse through is extremely large and when I run my program,
>> it runs for about 5 or 10 minutes then proceeds to not respond and not
>> finish parsing through the entire drive. Is there a way around this or
>> does the drive just contain too many files?
> 
> What do you want to do with it once the list of files is complete?
> Can you process the filenames independently or do you really need them all 
> at once?
> 
> 
> 
> ------------------------------
> 
> Message: 3
> Date: Fri, 17 May 2013 00:23:50 -0700
> From: Jim Mooney <cybervigilante at gmail.com>
> To: tutor at python.org
> Subject: Re: [Tutor] Can't install latest PIL
> Message-ID:
>    <CALRAYNVES=OSWvdn2h+yePnTb=N+4+5t2CxqY454GHBPa4WFaw at mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
> 
>> If you see a syntax error, that means your code could not be compiled.
>> Python's parser doesn't grok "import image from pil". In natural
>> language we have the freedom to swap the order of clauses, but
>> programming languages are generally more rigid. The correct order is
>> "from pil import image" -- but actually it has to be "from PIL import
>> Image".
> 
> Yeah, I fixed that but it still blew a fuse. Going back to 32 bit
> fixed everything.
> 
> from ** import ** just sounds backward to me, so I'll get it wrong
> until I get it right.
> 
> Actually, it is backward by standard English - a design flub ;')
> 
> BTW, I noticed that Msoft Visual Studio has Python. Does that mean I
> could made a standalone Win executable with Python, or would a user
> still need the Py interpreter installed? It would be nice if you could
> make an exe.
> 
> Jim
> 
> 
> ------------------------------
> 
> Message: 4
> Date: Fri, 17 May 2013 04:19:28 -0400
> From: eryksun <eryksun at gmail.com>
> To: Jim Mooney <cybervigilante at gmail.com>
> Cc: tutor at python.org
> Subject: Re: [Tutor] Can't install latest PIL
> Message-ID:
>    <CACL+1av7KAOmyTFayYUiYOwmyiKF8HsNLopmd1v6oYieLVTK+g at mail.gmail.com>
> Content-Type: text/plain; charset=UTF-8
> 
> On Fri, May 17, 2013 at 3:23 AM, Jim Mooney <cybervigilante at gmail.com> wrote:
>> BTW, I noticed that Msoft Visual Studio has Python. Does that mean I
>> could made a standalone Win executable with Python, or would a user
>> still need the Py interpreter installed? It would be nice if you could
>> make an exe.
> 
> Are you referring to Python Tools for Visual Studio? PTVS lets you use
> Visual Studio as a Python IDE:
> 
> http://pytools.codeplex.com
> 
> For CPython, one option for creating an exe is py2exe:
> 
> http://www.py2exe.org/index.cgi/Tutorial
> 
> If you're referring to IronPython, that's a .NET implementation of Python:
> 
> http://ironpython.codeplex.com
> http://www.ironpython.info
> 
> Here's a tutorial on creating an exe with IronPython:
> 
> http://dbaportal.eu/2009/12/21/ironpython-how-to-compile-exe
> 
> 
> ------------------------------
> 
> Subject: Digest Footer
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> ------------------------------
> 
> End of Tutor Digest, Vol 111, Issue 51
> **************************************

From steve at pearwood.info  Fri May 17 18:02:23 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 18 May 2013 02:02:23 +1000
Subject: [Tutor] unsubscribe
In-Reply-To: <E263A9D9-28C4-4822-B77B-93F9A9C3E288@yahoo.com>
References: <mailman.19.1368784801.27875.tutor@python.org>
	<E263A9D9-28C4-4822-B77B-93F9A9C3E288@yahoo.com>
Message-ID: <5196548F.2060003@pearwood.info>

On 18/05/13 00:39, Web Jedi wrote:
> unsubscribe


Please read the instructions printed immediately under your "unsubscribe" message:


>> To subscribe or unsubscribe via the World Wide Web, visit
>>     http://mail.python.org/mailman/listinfo/tutor
>> or, via email, send a message with subject or body 'help' to
>>     tutor-request at python.org


-- 
Steven

From eryksun at gmail.com  Fri May 17 18:04:50 2013
From: eryksun at gmail.com (eryksun)
Date: Fri, 17 May 2013 12:04:50 -0400
Subject: [Tutor] Pygraphics crashed
In-Reply-To: <CAHVvXxThxfsdgX2arQJqXgL=DDmZ97kvUOm6Thy4zM+CmrmqXQ@mail.gmail.com>
References: <CALRAYNUhZ60ZVSOqT6xJaKFxHRPoX8poVHPJs890JL4tF7n=dg@mail.gmail.com>
	<CACL+1avAVP8eaRnbDtbe+bKYq6qALLtR1+UqhpmStoHDX3YJ9Q@mail.gmail.com>
	<CALRAYNXbKU4fqEcuaSTKnxsuLZKmPQQJmQF=xEFdJga8g7VDJg@mail.gmail.com>
	<CACL+1auk6U3gsRWyeh9tO7z3isd+f2yM+jmKS9TO1XQ8vF8H0Q@mail.gmail.com>
	<CAHVvXxThxfsdgX2arQJqXgL=DDmZ97kvUOm6Thy4zM+CmrmqXQ@mail.gmail.com>
Message-ID: <CACL+1av6C4=wFELY3ehjPvLf4MF75f5iOvXkTgOFfRLOS6EfwA@mail.gmail.com>

On Fri, May 17, 2013 at 10:31 AM, Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
>
> The wheel format will solve part of the problem in that it will make
> it safer and easier to install prebuilt binaries. It will still
> require someone to create all of the prebuilt binaries for each
> OS/architecture/Python version and it doesn't really make this step
> any easier than creating e.g. an MSI installer is now.

I haven't played around with this myself, but the reference
implementation of Wheel can convert eggs and exes (wininst):

https://pypi.python.org/pypi/wheel/0.16.0

Currently in a virtual environment you have to use easy_install for
binary egg/exe installers. It'll be nice to just pip install
everything.

> Since my own Windows machine has the wrong version of Visual Studio
> (and out IT policy won't let me change it) I use mingw. However, every
> time I install a new Python I have to patch distutils to fix the
> '-mnocygwin' bug that prevents current Python from working with it.
> Why this issue (http://bugs.python.org/issue12641) is still unresolved
> despite being fully understood two years ago I don't understand.

Can you use the Windows SDK compiler?

It took a long time for that issue to get a patch up.  I pretty much
agree with ?ric's take on the matter, i.e. "more feedback, bug
reports, patches and reviews from the community would help" and
"testing the patches on your system would help".

> My own suggestion to coworkers who are new to Python and using Windows
> or OSX (without macports) is to use either the Enthought Python
> Distribution (free for academic use) or Python(x, y) (free for
> anyone). These will install and setup the bulk of packages commonly
> used in scientific work from a single installer. Either distribution
> will install and setup numpy, scipy, PIL, mingw, pip, distribute, and
> many more hard to build packages.
>
> See here for the lists of what each distribution includes:
> https://www.enthought.com/products/canopy/package-index/
> https://code.google.com/p/pythonxy/wiki/Welcome

I've used Python(x,y) and will doubly recommend it if you want a
hassle-free setup for scientific/engineering analysis. There's also
ActivePython, which has the PyPM package manager, though many packages
are only available to their paying customers.

From bgailer at gmail.com  Fri May 17 19:16:08 2013
From: bgailer at gmail.com (bob gailer)
Date: Fri, 17 May 2013 13:16:08 -0400
Subject: [Tutor] Python Idle Crashing
In-Reply-To: <kn3uqi$hu5$1@ger.gmane.org>
References: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com>
	<kn3uqi$hu5$1@ger.gmane.org>
Message-ID: <519665D8.9080103@gmail.com>

On 5/16/2013 8:49 PM, Alan Gauld wrote:
> don't run programs on real data using IDLE. IDLE is for developing 
> programs not running them.

That is really scary. Why do you say that? The IDLE documentation does 
NOT say that!

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From oscar.j.benjamin at gmail.com  Fri May 17 19:55:43 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Fri, 17 May 2013 18:55:43 +0100
Subject: [Tutor] Pygraphics crashed
In-Reply-To: <CACL+1av6C4=wFELY3ehjPvLf4MF75f5iOvXkTgOFfRLOS6EfwA@mail.gmail.com>
References: <CALRAYNUhZ60ZVSOqT6xJaKFxHRPoX8poVHPJs890JL4tF7n=dg@mail.gmail.com>
	<CACL+1avAVP8eaRnbDtbe+bKYq6qALLtR1+UqhpmStoHDX3YJ9Q@mail.gmail.com>
	<CALRAYNXbKU4fqEcuaSTKnxsuLZKmPQQJmQF=xEFdJga8g7VDJg@mail.gmail.com>
	<CACL+1auk6U3gsRWyeh9tO7z3isd+f2yM+jmKS9TO1XQ8vF8H0Q@mail.gmail.com>
	<CAHVvXxThxfsdgX2arQJqXgL=DDmZ97kvUOm6Thy4zM+CmrmqXQ@mail.gmail.com>
	<CACL+1av6C4=wFELY3ehjPvLf4MF75f5iOvXkTgOFfRLOS6EfwA@mail.gmail.com>
Message-ID: <CAHVvXxRd2S2ic-A2q4tx5goNoUj7aFV-CLNSEZCkoXJWQZiJyw@mail.gmail.com>

On 17 May 2013 17:04, eryksun <eryksun at gmail.com> wrote:
> On Fri, May 17, 2013 at 10:31 AM, Oscar Benjamin
> <oscar.j.benjamin at gmail.com> wrote:
>
>> Since my own Windows machine has the wrong version of Visual Studio
>> (and out IT policy won't let me change it) I use mingw. However, every
>> time I install a new Python I have to patch distutils to fix the
>> '-mnocygwin' bug that prevents current Python from working with it.
>> Why this issue (http://bugs.python.org/issue12641) is still unresolved
>> despite being fully understood two years ago I don't understand.
>
> Can you use the Windows SDK compiler?

Essentially it comes down to what I can install to my machine without
needing administrator privileges. Python and mingw are fine for that
if I apply the patch.

> It took a long time for that issue to get a patch up.  I pretty much
> agree with ?ric's take on the matter, i.e. "more feedback, bug
> reports, patches and reviews from the community would help" and
> "testing the patches on your system would help".

Perhaps I should report that I've been using the patch from pretty
much the time the issue was reported (I actually got the suggestion
from stackoverflow).

I don't really agree with the comments on the issue. It was known a
long time ago that the issue was only going to get worse. When it was
first reported it was possible to simply use an older version of
mingw. Switching to Visual Studio 2010 in Python means that current
Pythons are incompatible with older mingw as well as new. This means
that no version of mingw works with the current Pythons; I don't see
how the patch could break anything now.


Oscar

From steve at pearwood.info  Fri May 17 20:08:32 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 18 May 2013 04:08:32 +1000
Subject: [Tutor] Python Idle Crashing
In-Reply-To: <519665D8.9080103@gmail.com>
References: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com>
	<kn3uqi$hu5$1@ger.gmane.org> <519665D8.9080103@gmail.com>
Message-ID: <51967220.3020501@pearwood.info>

On 18/05/13 03:16, bob gailer wrote:
> On 5/16/2013 8:49 PM, Alan Gauld wrote:
>> don't run programs on real data using IDLE. IDLE is for developing programs not running them.
>
> That is really scary. Why do you say that? The IDLE documentation does NOT say that!

IDLE is an IDE, that is, Integrated DEVELOPMENT Environment (emphasis added). It is for development, not a general shell environment like your normal operating system shell.

Like all IDEs, IDLE is one extra layer between your code and the machine actually executing code:


Your Python source code
*** The IDE ***
The Python interpreter
The operating system
The hardware

IDLE does make some changes to the Python environment. In principle, none of the changes should be detectable, or at least not meaningful, but sometimes they do have visible effects. For instance, in my "vanilla" Python environment:


[steve at ando ~]$ python -E
Python 2.7.2 (default, May 18 2012, 18:25:10)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print u"?"
?
>>>


while here is the same result in IDLE:

Python 2.7.2 (default, May 18 2012, 18:25:10)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> print u"?"
???
>>>

Oops, IDLE has just played silly-buggers with the encoding of the (pseudo-)terminal, and consequently has not printed the Unicode character correctly.

Another example: if you raise SystemExit, the vanilla Python interpreter exits, as it is supposed to. But IDLE merely prints a traceback, then continues without exiting.

In a nutshell, while you *can* run code "live" in IDLE, as soon as you hit a bug or mysterious behaviour, you should always try running it without IDLE and see if the problem goes away.



-- 
Steven

From alan.gauld at btinternet.com  Fri May 17 20:19:13 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 17 May 2013 19:19:13 +0100
Subject: [Tutor] Python Idle Crashing
In-Reply-To: <519665D8.9080103@gmail.com>
References: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com>
	<kn3uqi$hu5$1@ger.gmane.org> <519665D8.9080103@gmail.com>
Message-ID: <kn5sas$o1d$1@ger.gmane.org>

On 17/05/13 18:16, bob gailer wrote:
> On 5/16/2013 8:49 PM, Alan Gauld wrote:
>> don't run programs on real data using IDLE. IDLE is for developing
>> programs not running them.
>
> That is really scary. Why do you say that? The IDLE documentation does
> NOT say that!

No, but IDLE is *intended* for development. It is not intended for 
running programs. You *can* do it but the results may not be what
you expect.

Lots of beginners seem to think that because they use IDLE to develop 
code that they must run it from there but its not an effective way of 
doing things. That's all I was meaning, not that terrible things might 
happen like the PC crashing or data being deleted. It's just easier and 
faster and more predictable to run finished code directly in the python 
interpreter.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From ramit.prasad at jpmorgan.com  Fri May 17 20:08:08 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Fri, 17 May 2013 18:08:08 +0000
Subject: [Tutor] Python Idle Crashing
In-Reply-To: <519665D8.9080103@gmail.com>
References: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com>
	<kn3uqi$hu5$1@ger.gmane.org> <519665D8.9080103@gmail.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF474183D0837@SCACMX008.exchad.jpmchase.net>

bob gailer wrote:
> 
> On 5/16/2013 8:49 PM, Alan Gauld wrote:
> > don't run programs on real data using IDLE. IDLE is for developing
> > programs not running them.
> 
> That is really scary. Why do you say that? The IDLE documentation does
> NOT say that!

Relates to IDEs and not IDLE in specific. I would *never* run
a production program from Eclipse (or any IDE). They tend to
modify things like std in/out/err and add some magic that can
be useful for development/debugging. The problem with the magic
is that it can have unintended consequences; although I suppose
if you wanted a program to *always* be run in a specific IDE
then you could code it to take advantage of the quirks....

> 
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

From fomcl at yahoo.com  Fri May 17 21:23:41 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Fri, 17 May 2013 12:23:41 -0700 (PDT)
Subject: [Tutor] why is unichr(sys.maxunicode) blank?
Message-ID: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com>

Hi,

I was curious what the "high" four-byte ut8 unicode characters look like. Why does the snippet below not print anything (well, it will eventually, I think, but at that point I have lost my patience already). Puh-lease tell me there are no such things as Mongolian, Chinese backspaces and other nonprintable characters. ;-)
? 
# Python 2.7.3 (default, Sep 26 2012, 21:53:58) [GCC 4.7.2] on linux2
>>> import sys

>>> sys.maxunicode
1114111

>>> for i in range(sys.maxunicode, 0, -1):
??? print "%s [%s: %sbytes: %s]" % (unichr(i), i, len(unichr(i).encode("utf-8")), hex(i)),
?
Regards,
Albert-Jan


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130517/fa732fea/attachment.html>

From ramit.prasad at jpmorgan.com  Fri May 17 21:35:39 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Fri, 17 May 2013 19:35:39 +0000
Subject: [Tutor] Python Idle Crashing
In-Reply-To: <CAKK8jXbGW7kiy7KGMD11fZdaC2SCQhhch+UxKvgidQeC_sbn7Q@mail.gmail.com>
References: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com>
	<kn3uqi$hu5$1@ger.gmane.org>	<519665D8.9080103@gmail.com>
	<5B80DD153D7D744689F57F4FB69AF474183D0837@SCACMX008.exchad.jpmchase.net>
	<CAKK8jXbGW7kiy7KGMD11fZdaC2SCQhhch+UxKvgidQeC_sbn7Q@mail.gmail.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF474183D0995@SCACMX008.exchad.jpmchase.net>

Forwarding to the list as I believe the reply was mistakenly sent only to me.

Marc Tompkins wrote:
> On Fri, May 17, 2013 at 11:08 AM, Prasad, Ramit <ramit.prasad at jpmorgan.com> wrote:
> bob gailer wrote:
> >
> > On 5/16/2013 8:49 PM, Alan Gauld wrote:
> > > don't run programs on real data using IDLE. IDLE is for developing
> > > programs not running them.
> >
> > That is really scary. Why do you say that? The IDLE documentation does
> > NOT say that!
> 
> Python is a GREAT learning language, but it's also a tool for Getting Stuff Done in the Real World.
> When you send your programs out into the wide world, it makes a really poor impression if you have to
> instruct your users to open an IDE first, load your script, and then press F5.? So at the very least,
> you should get into the habit of making your scripts work outside of IDLE, or whatever IDE you
> prefer.? (If nobody but you will ever run your stuff, I suppose this doesn't matter so much - but in
> that case, what Alan said about 'real data' doesn't apply either.)
> In addition, I find that the Tk-ness of IDLE interferes with any other GUI library you might prefer -
> I use wxPython, and while IDLE is great for quickly diagnosing the sorts of errors that prevent my
> programs from putting anything on the screen to begin with, it gets very crashy once wx gets
> initialized.? IDLE is a bit like the prize in CrackerJack - it's a nice extra, but it certainly
> shouldn't be the reason you bought the box!



This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

From marc.tompkins at gmail.com  Fri May 17 21:40:42 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Fri, 17 May 2013 12:40:42 -0700
Subject: [Tutor] Python Idle Crashing
In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474183D0995@SCACMX008.exchad.jpmchase.net>
References: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com>
	<kn3uqi$hu5$1@ger.gmane.org> <519665D8.9080103@gmail.com>
	<5B80DD153D7D744689F57F4FB69AF474183D0837@SCACMX008.exchad.jpmchase.net>
	<CAKK8jXbGW7kiy7KGMD11fZdaC2SCQhhch+UxKvgidQeC_sbn7Q@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF474183D0995@SCACMX008.exchad.jpmchase.net>
Message-ID: <CAKK8jXY8-y3mt0c2QWiu8c6R4uZVSZo=VxwvNYo6RyG6G+zD7g@mail.gmail.com>

On Fri, May 17, 2013 at 12:35 PM, Prasad, Ramit
<ramit.prasad at jpmorgan.com>wrote:

> Forwarding to the list as I believe the reply was mistakenly sent only to
> me.
>
Grr.  Sorry about that!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130517/c2471757/attachment.html>

From ramit.prasad at jpmorgan.com  Fri May 17 22:48:39 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Fri, 17 May 2013 20:48:39 +0000
Subject: [Tutor] Word Jumble - Chpt4 (Explanation)
In-Reply-To: <DUB103-W533D1C8B9503A9C9204F0BE1AC0@phx.gbl>
References: <DUB103-W3869BED9ED957BAB2C48FE1A30@phx.gbl>,
	<5B80DD153D7D744689F57F4FB69AF474183CE208@SCACMX008.exchad.jpmchase.net>
	<DUB103-W533D1C8B9503A9C9204F0BE1AC0@phx.gbl>
Message-ID: <5B80DD153D7D744689F57F4FB69AF474183D0AD8@SCACMX008.exchad.jpmchase.net>

Please always send to the list (use your email client's Reply-to-list or Reply-all functionality).

Arvind Virk wrote:
> Thanks Ramit!
> 
> I did try to use print statements to understand my outputs but I may have been best placed to utilse
> some formatting to make it more readable. I did not understand why the loop did not terminate after it
> had read the word once but from your example,
> I can see it is continually looping until it has utilised all the characters in the word?
> 
While loops continue until their condition evaluates to false. 
Strings evaluate to false when they are empty strings (e.g. '').
Containers evaluate to false when they have no contents.
This applies to if statements too.

if cookiejar:
   # pass jar and eat cookie

I am fairly confident you do not want the cookie jar if
it is empty or at least your actions will be different. :)

> line 1 is the word
> line 2 is a empty string
> line 4 is creating a range based on the length of word
> 
> line 6 is the letter of the word
> line 7 new letter for jumble
> line 8 word from beginning upto position + position onward? or one after position?
> 
> line 5 and 9 - I know these are your print statements but I haven't been introduced to .format (yet).
> How does printing jumble {0} return the entire jumble string? Why does word have to be {1}?
> 

String formatting has a mini-language of options.
See http://docs.python.org/2/library/string.html#formatstrings

Basically {0} means the first argument passed to format while {1}
means the second where the Nth argument will be {N-1}. I could also
have used named formatting by using {placeholder} and 
.format( placeholder='blah' ).

>>> 'After jumble "{jumble}" | word "{wrd}" | tempchar {char}'.format( jumble='jumble', wrd='some word here', char='more than a char' )
'After jumble "jumble" | word "some word here" | tempchar more than a char'

> 
> 1. word = 'python'
> 2. jumble = ""
> 3. while word:
> 4. position = random.randrange(len(word))
> 5. print 'position {0} | jumble "{1}"'.format( position, jumble )
> 6. tempchar = word[position]
> 7. jumble += tempchar
> 8. word = word[:position] + word[(position+1):]
> 9. print 'After jumble "{0}" | word "{1}" | tempchar {2}'.format( jumble, word, tempchar )
> 
> > position 5 | jumble ""
> > After jumble "n" | word "pytho" | tempchar n
> > position 2 | jumble "n"
> > After jumble "nt" | word "pyho" | tempchar t
> > position 3 | jumble "nt"
> > After jumble "nto" | word "pyh" | tempchar o
> > position 1 | jumble "nto"
> > After jumble "ntoy" | word "ph" | tempchar y
> > position 0 | jumble "ntoy"
> > After jumble "ntoyp" | word "h" | tempchar p
> > position 0 | jumble "ntoyp"
> > After jumble "ntoyph" | word "" | tempchar h
> 
> Thanks very much. It really helped.
> -
> Arvind Virk


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

From beachkidken at gmail.com  Sat May 18 00:37:27 2013
From: beachkidken at gmail.com (Ken G.)
Date: Fri, 17 May 2013 18:37:27 -0400
Subject: [Tutor] Python Idle Crashing
In-Reply-To: <kn5sas$o1d$1@ger.gmane.org>
References: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com>
	<kn3uqi$hu5$1@ger.gmane.org> <519665D8.9080103@gmail.com>
	<kn5sas$o1d$1@ger.gmane.org>
Message-ID: <5196B127.4000908@gmail.com>


On 05/17/2013 02:19 PM, Alan Gauld wrote:
> On 17/05/13 18:16, bob gailer wrote:
>> On 5/16/2013 8:49 PM, Alan Gauld wrote:
>>> don't run programs on real data using IDLE. IDLE is for developing
>>> programs not running them.
>>
>> That is really scary. Why do you say that? The IDLE documentation does
>> NOT say that!
>
> No, but IDLE is *intended* for development. It is not intended for 
> running programs. You *can* do it but the results may not be what
> you expect.
>
> Lots of beginners seem to think that because they use IDLE to develop 
> code that they must run it from there but its not an effective way of 
> doing things. That's all I was meaning, not that terrible things might 
> happen like the PC crashing or data being deleted. It's just easier 
> and faster and more predictable to run finished code directly in the 
> python interpreter.
>
>
I use Geany 0.21 as a fast and lightweight IDE for my Python programs.
MY OS is Ubuntu 12.04 LTS and currently using Python 2.7.3. I rarely use
IDLE v2.7.3.

Ken


From phil_lor at bigpond.com  Sat May 18 01:57:43 2013
From: phil_lor at bigpond.com (Phil)
Date: Sat, 18 May 2013 09:57:43 +1000
Subject: [Tutor] Retrieving data from a web site
Message-ID: <5196C3F7.6030507@bigpond.com>

I'd like to "download" eight digits from a web site where the digits are 
stored as individual graphics. Is this possible, using perhaps, one of 
the countless number of Python modules? Is this the function of a web 
scraper?

-- 
Regards,
Phil

From steve at pearwood.info  Sat May 18 02:46:03 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 18 May 2013 10:46:03 +1000
Subject: [Tutor] why is unichr(sys.maxunicode) blank?
In-Reply-To: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com>
References: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com>
Message-ID: <5196CF4B.20809@pearwood.info>

On 18/05/13 05:23, Albert-Jan Roskam wrote:
> Hi,
>
> I was curious what the "high" four-byte ut8 unicode characters look like.

What typeface are you using to print them? Most type faces ("fonts") only support a tiny portion of the Unicode range. For that matter, most of the Unicode range is currently unused.


> Why does the snippet below not print anything (well, it will eventually, I think, but at that point I have lost my patience already). Puh-lease tell me there are no such things as Mongolian, Chinese backspaces and other nonprintable characters. ;-)

Chinese backspaces? Probably not. But there may well be unprintable characters for all sorts of reasons:

- the font you are using simply doesn't have a glyph for the code-point;

- the code-point is not yet assigned, so there's nothing to show;

- the code-point represents an invisible character, like IDEOGRAPHIC SPACE, or a zero-width character, like MONGOLIAN VOWEL SEPARATOR;

- or it represents a non-printing control character;

- or a formatting mark like LEFT-TO-RIGHT EMBEDDING;

- or it is one of the sixty-six guaranteed "non-characters", such as the infamous byte-order marks U+FFFE and U+FFFF.




-- 
Steven

From davea at davea.name  Sat May 18 04:49:56 2013
From: davea at davea.name (Dave Angel)
Date: Fri, 17 May 2013 22:49:56 -0400
Subject: [Tutor] Retrieving data from a web site
In-Reply-To: <5196C3F7.6030507@bigpond.com>
References: <5196C3F7.6030507@bigpond.com>
Message-ID: <5196EC54.5040106@davea.name>

On 05/17/2013 07:57 PM, Phil wrote:
> I'd like to "download" eight digits from a web site where the digits are
> stored as individual graphics. Is this possible, using perhaps, one of
> the countless number of Python modules? Is this the function of a web
> scraper?
>

Anything's possible.  But if these "digits" are purposely hard to read, 
perhaps to avoid spamming, then the likelihood of your algorithmically 
reading them is vanishingly small.  For example, "captcha" pictures.

There are libraries to "scrape" textual information from the web page, 
no sweat.  But that information might not even point directly to the 8 
image files.  There could be many layers of indirection, through 
javascript and other tricks.

But most importantly, if the images are deliberately distorted parodies 
of digits, most of us would be stymied, and I don't know any library 
anywhere that's intended to "break" such coding.

As a result, I'd recommend starting there.  Visit the page in a regular 
browser, use screen capture techniques to capture each of the displayed 
images, and have at it.  If you have no luck with those, no point in 
writing the other code, which could be anything from easy to very hard.

-- 
DaveA

From davea at davea.name  Sat May 18 05:06:23 2013
From: davea at davea.name (Dave Angel)
Date: Fri, 17 May 2013 23:06:23 -0400
Subject: [Tutor] why is unichr(sys.maxunicode) blank?
In-Reply-To: <5196CF4B.20809@pearwood.info>
References: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<5196CF4B.20809@pearwood.info>
Message-ID: <5196F02F.5000508@davea.name>

On 05/17/2013 08:46 PM, Steven D'Aprano wrote:
> On 18/05/13 05:23, Albert-Jan Roskam wrote:
>> Hi,
>>
>> I was curious what the "high" four-byte ut8 unicode characters look like.
>
> What typeface are you using to print them? Most type faces ("fonts")
> only support a tiny portion of the Unicode range. For that matter, most
> of the Unicode range is currently unused.
>
>
>> Why does the snippet below not print anything (well, it will
>> eventually, I think, but at that point I have lost my patience
>> already). Puh-lease tell me there are no such things as Mongolian,
>> Chinese backspaces and other nonprintable characters. ;-)
>
> Chinese backspaces? Probably not. But there may well be unprintable
> characters for all sorts of reasons:
>
> - the font you are using simply doesn't have a glyph for the code-point;
>
> - the code-point is not yet assigned, so there's nothing to show;
>
> - the code-point represents an invisible character, like IDEOGRAPHIC
> SPACE, or a zero-width character, like MONGOLIAN VOWEL SEPARATOR;
>
> - or it represents a non-printing control character;
>
> - or a formatting mark like LEFT-TO-RIGHT EMBEDDING;
>
> - or it is one of the sixty-six guaranteed "non-characters", such as the
> infamous byte-order marks U+FFFE and U+FFFF.
>
>
>
>

One tool that can help is the name function in module unicodedata


  >>> import unicodedata
  >>> unicodedata.name(u'\xb0')
'DEGREE SIGN'

If you try that on the values near sys.maxunicode you get an exception:
ValueError: no such name


For example:

 >>> unicodedata.name(unichr(sys.maxunicode - 1))
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ValueError: no such name


-- 
DaveA

From eryksun at gmail.com  Sat May 18 05:08:22 2013
From: eryksun at gmail.com (eryksun)
Date: Fri, 17 May 2013 23:08:22 -0400
Subject: [Tutor] why is unichr(sys.maxunicode) blank?
In-Reply-To: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com>
References: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com>
Message-ID: <CACL+1avHj5NrW2WymFDmUzDmaz2N0717xYAJCzntn8Uha+XM=w@mail.gmail.com>

On Fri, May 17, 2013 at 3:23 PM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
>
> I was curious what the "high" four-byte ut8 unicode characters look like.
> Why does the snippet below not print anything (well, it will eventually, I
> think, but at that point I have lost my patience already).

The following site lists Unicode characters by block and category,
shown either with fonts or with images. It also lists fonts that
support particular blocks.

http://www.fileformat.info/info/unicode

Plane 15 (0x0F0000-0xFFFFD) is private use area A, and plane 16
(0x100000-0x10FFFD) is private use area B. There's also a private use
area in the BMP at 0xE000-0xF8FF. The latter has been used for
fictional languages such as Klingon.

http://en.wikipedia.org/wiki/Private_Use_%28Unicode%29
http://en.wikipedia.org/wiki/ConScript_Unicode_Registry

From eryksun at gmail.com  Sat May 18 05:28:55 2013
From: eryksun at gmail.com (eryksun)
Date: Fri, 17 May 2013 23:28:55 -0400
Subject: [Tutor] why is unichr(sys.maxunicode) blank?
In-Reply-To: <5196F02F.5000508@davea.name>
References: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<5196CF4B.20809@pearwood.info> <5196F02F.5000508@davea.name>
Message-ID: <CACL+1asO=2GxSgz34JwFQqsewoBmhOpagkO7MRb+HLSk1oBewA@mail.gmail.com>

On Fri, May 17, 2013 at 11:06 PM, Dave Angel <davea at davea.name> wrote:
> One tool that can help is the name function in module unicodedata
>
>  >>> import unicodedata
>  >>> unicodedata.name(u'\xb0')
> 'DEGREE SIGN'
>
> If you try that on the values near sys.maxunicode you get an exception:
> ValueError: no such name

There's no name since the code point isn't assigned, but the category
is defined:

    >>> unicodedata.category(u'\U0010FFFD')
    'Co'
    >>> unicodedata.category(u'\U0010FFFE')
    'Cn'
    >>> unicodedata.category(u'\U0010FFFF')
    'Cn'

'Co' is the private use category, and 'Cn' is for codes that aren't assigned.

From steve at pearwood.info  Sat May 18 05:49:38 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 18 May 2013 13:49:38 +1000
Subject: [Tutor] why is unichr(sys.maxunicode) blank?
In-Reply-To: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com>
References: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com>
Message-ID: <5196FA52.9090000@pearwood.info>

On 18/05/13 05:23, Albert-Jan Roskam wrote:

> I was curious what the "high" four-byte ut8 unicode characters look like.

By the way, your sentence above reflects a misunderstanding. Unicode characters (strictly speaking, code points) are not "bytes", four or otherwise. They are abstract entities represented by a number between 0 and 1114111, or in hex, 0x10FFFF. Code points can represent characters, or parts of characters (e.g. accents, diacritics, combining characters and similar), or non-characters.

Much confusion comes from conflating bytes and code points, or bytes and characters. The first step to being a Unicode wizard is to always keep them distinct in your mind. By analogy, the floating point number 23.42 is stored in memory or on disk as a bunch of bytes, but there is nothing to be gained from confusing the number 23.42 from the bytes 0xEC51B81E856B3740, which is how it is stored as a C double.

Unicode code points are abstract entities, but in the real world, they have to be stored in a computer's memory, or written to disk, or transmitted over a wire, and that requires *bytes*. So there are three Unicode schemes for storing code points as bytes. These are called *encodings*. Only encodings involve bytes, so it is nonsense to talk about "four-byte" unicode characters, since it conflates the abstract Unicode character set with one of various concrete encodings.

There are three standard Unicode encodings. (These are not to be confused with the dozens of "legacy encodings", a.k.a. code pages, used prior to the Unicode standard. They do not cover the entire range of Unicode, and are not part of the Unicode standard.) These encodings are:

UTF-8
UTF-16
UTF-32 (also sometimes known as UCS-4)

plus at least one older, obsolete encoding, UCS-2.

UTF-32 is the least common, but simplest. It simply maps every code point to four bytes. In the following, I will follow this convention:

- code points are written using the standard Unicode notation, U+xxxx where the x's are hexadecimal digits;

- bytes are written in hexadecimal, using a leading 0x.

Code point U+0000 -> bytes 0x00000000
Code point U+0001 -> bytes 0x00000001
Code point U+0002 -> bytes 0x00000002
...
Code point U+10FFFF -> bytes 0x0010FFFF


It is simple because the mapping is trivially simple, and uncommon because for typical English-language text, it wastes a lot of memory.

The only complication is that UTF-32 depends on the endianess of your system. In the above examples I glossed over this factor. In fact, there are two common ways that bytes can be stored:

- "big endian", where the most-significant (largest) byte is on the left (lowest address);
- "little endian", where the most-significant (largest) byte is on the right.

So in a little-endian system, we have this instead:

Code point U+0000 -> bytes 0x00000000
Code point U+0001 -> bytes 0x01000000
Code point U+0002 -> bytes 0x02000000
...
Code point U+10FFFF -> bytes 0xFFFF1000

(Note that little-endian is not merely the reverse of big-endian. It is the order of bytes that is reversed, not the order of digits, or the order of bits within each byte.)

So when you receive a bunch of bytes that you know represents text encoded using UTF-32, you can bunch the bytes in groups of four and convert them to Unicode code points. But you need to know the endianess. One way to do that is to add a Byte Order Mark at the beginning of the bytes. If you look at the first four bytes, and it looks like 0x0000FEFF, then you have big-endian UTF-32. But if it looks like 0xFFFE0000, then you have little-endian.

So that's UTF-32. UTF-16 is a little more complicated.

UTF-16 divides the Unicode range into two groups:

* The first (approximately) 65000 code points which are represented as two bytes;

* Everything else, which are represented as a pair of double bytes, so-called "surrogate pairs".

For the first 65000-odd code points, the mapping is trivial, and relatively compact:

code point U+0000 => bytes 0x0000
code point U+0001 => bytes 0x0001
code point U+0002 => bytes 0x0002
...
code point U+FFFF => bytes 0xFFFF


Code points beyond that point are encoded into a pair of double bytes (four bytes in total):

code point U+10000 => bytes 0xD800 DC00
...
code point U+10FFFF => bytes 0xDBFF DFFF


Notice a potential ambiguity here. If you receive a byte 0xD800, is that the start of a surrogate pair, or the code point U+D800? The Unicode standard resolves this ambiguity by officially reserving code points U+D800 through U+DFFF for use as surrogate pairs in UTF-16.

Like UTF-32, UTF-16 also has to distinguish between big-endian and little-endian. It does so with a leading BOM, only this time it is two bytes, not four:

0xFEFF => big-endian
0xFFFE => little-endian


Last but not least, we have UTF-8. UTF-8 is slowly becoming the standard for storing Unicode on disk, because it is very compact for common English-language text, backwards-compatible with ASCII text files, and doesn't require a BOM. (Although Microsoft software sometimes adds a UTF-8 signature at the start of files, namely the three bytes 0xEFBBBF.)

UTF-8 is also a variable-width encoding. Unicode code-points are mapped to one, two, three or four bytes, as needed:

Code points U+0000 to U+007E => 1 byte
Code points U+0080 to U+07FF => 2 bytes
Code points U+0800 to U+FFFF => 3 bytes
Code points U+10000 to U+10FFFF => 4 bytes

(Older versions of UTF-8 could go up to six bytes, but now that Unicode is officially limited to exactly 0x10FFFF code points, it now only goes up to four bytes.)



-- 
Steven

From alan.gauld at btinternet.com  Sat May 18 08:33:30 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 18 May 2013 07:33:30 +0100
Subject: [Tutor] Retrieving data from a web site
In-Reply-To: <5196C3F7.6030507@bigpond.com>
References: <5196C3F7.6030507@bigpond.com>
Message-ID: <kn77bl$c10$1@ger.gmane.org>

On 18/05/13 00:57, Phil wrote:
> I'd like to "download" eight digits from a web site where the digits are
> stored as individual graphics. Is this possible, using perhaps, one of
> the countless number of Python modules? Is this the function of a web
> scraper?

In addition to Dave's points there is also the legality to consider.
Images are often copyrighted (although images of digits are less 
likely!) and sites often have conditions of use that prohibit web 
scraping. Such sites often include scripts that analyze user activity 
and if they suspect you of being a robot may ban your computer from 
accessing the site - including by browser.

So be sure that you  are allowed to access the site robotically and that 
you are allowed to download the content or you could find yourself 
blacklisted and unable to access the site even with your browser.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From jjxu95 at gmail.com  Thu May 16 03:44:23 2013
From: jjxu95 at gmail.com (Jiajun Xu)
Date: Wed, 15 May 2013 20:44:23 -0500
Subject: [Tutor] use python to change the webpage content?
Message-ID: <CAEx-Hj4kj8qBpbe=VgFPMev3dDQVu3pjC3=BTqMSX3TW59dMLg@mail.gmail.com>

There is a online simulator about a physic project I'm doing and I want to
use the data the simulator generates on that website. I can get data using
urllib.request and regular expression but I also want to change some of the
input values and then get different sets of data. However, if I change the
inputs, the address of the webpage wouldn't change, so I couldn't get data
with different initial conditions.I'm wondering how I can implement this.

Thanks for your effort!!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130515/5944a20e/attachment.html>

From staffordbaines at yahoo.com  Thu May 16 18:58:10 2013
From: staffordbaines at yahoo.com (Stafford Baines)
Date: Thu, 16 May 2013 17:58:10 +0100
Subject: [Tutor] Unsubscribe
Message-ID: <66612899-0ACF-454B-B384-7310ADB29EB3@yahoo.com>

I only intend this to be temporary. I'm going away for a couple of weeks and don't want my mailbox overflowing when I return.? Thanks for all the help

Sent from my iPhone

From adindar at iku.edu.tr  Sat May 18 09:20:50 2013
From: adindar at iku.edu.tr (Ahmet Anil Dindar)
Date: Sat, 18 May 2013 10:20:50 +0300
Subject: [Tutor] Python web script to run a command line expression
Message-ID: <CAGf4weVWAGP0um9LWbkcYsvZQNCR8jNzfG7SaFg1GDea1CPTGQ@mail.gmail.com>

Hi,
I have a WAMP running in my office computer. I wonder how I can implement a
python script that runs within WAMP and execute a command line expression.
By this way, I will able to run my command line expressions through web
page in intranet.

I appreciate your suggestions.

++Ahmet
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130518/ccadea99/attachment.html>

From phil_lor at bigpond.com  Sat May 18 10:41:06 2013
From: phil_lor at bigpond.com (Phil)
Date: Sat, 18 May 2013 18:41:06 +1000
Subject: [Tutor] Retrieving data from a web site
In-Reply-To: <kn77bl$c10$1@ger.gmane.org>
References: <5196C3F7.6030507@bigpond.com> <kn77bl$c10$1@ger.gmane.org>
Message-ID: <51973EA2.6040007@bigpond.com>

On 18/05/13 16:33, Alan Gauld wrote:
> On 18/05/13 00:57, Phil wrote:
>> I'd like to "download" eight digits from a web site where the digits are
>> stored as individual graphics. Is this possible, using perhaps, one of
>> the countless number of Python modules? Is this the function of a web
>> scraper?
>
> In addition to Dave's points there is also the legality to consider.
> Images are often copyrighted (although images of digits are less
> likely!) and sites often have conditions of use that prohibit web
> scraping. Such sites often include scripts that analyze user activity
> and if they suspect you of being a robot may ban your computer from
> accessing the site - including by browser.
>
> So be sure that you  are allowed to access the site robotically and that
> you are allowed to download the content or you could find yourself
> blacklisted and unable to access the site even with your browser.
>

Thanks for the replies,

The site in question is the Lotto results page and the drawn numbers are 
not obscured. So I don't expect that there would be any legal or 
copyright problems.

I have written a simple program that checks the results, for an unlikely 
win, but I have to manually enter the drawn numbers. I thought the next 
step might be to automatically download the results.

I can see that this would be a relatively easy task if the digits were 
not displayed as graphics.

-- 
Regards,
Phil

From __peter__ at web.de  Sat May 18 11:25:03 2013
From: __peter__ at web.de (Peter Otten)
Date: Sat, 18 May 2013 11:25:03 +0200
Subject: [Tutor] Retrieving data from a web site
References: <5196C3F7.6030507@bigpond.com> <kn77bl$c10$1@ger.gmane.org>
	<51973EA2.6040007@bigpond.com>
Message-ID: <kn7hda$tr7$1@ger.gmane.org>

Phil wrote:

> On 18/05/13 16:33, Alan Gauld wrote:
>> On 18/05/13 00:57, Phil wrote:
>>> I'd like to "download" eight digits from a web site where the digits are
>>> stored as individual graphics. Is this possible, using perhaps, one of
>>> the countless number of Python modules? Is this the function of a web
>>> scraper?
>>
>> In addition to Dave's points there is also the legality to consider.
>> Images are often copyrighted (although images of digits are less
>> likely!) and sites often have conditions of use that prohibit web
>> scraping. Such sites often include scripts that analyze user activity
>> and if they suspect you of being a robot may ban your computer from
>> accessing the site - including by browser.
>>
>> So be sure that you  are allowed to access the site robotically and that
>> you are allowed to download the content or you could find yourself
>> blacklisted and unable to access the site even with your browser.
>>
> 
> Thanks for the replies,
> 
> The site in question is the Lotto results page and the drawn numbers are
> not obscured. So I don't expect that there would be any legal or
> copyright problems.
> 
> I have written a simple program that checks the results, for an unlikely
> win, but I have to manually enter the drawn numbers. I thought the next
> step might be to automatically download the results.
> 
> I can see that this would be a relatively easy task if the digits were
> not displayed as graphics.

What's the url of the page? 

Are there alternatives that give the number as plain text? 

If not, do the images have names like whatever0.jpg, whatever1.jpg, 
whatever2.jpg, ...? Then you could infer the value from the name. 

If not, is a digit always represented by the same image? Then you could map 
the image urls to the digits.



From fomcl at yahoo.com  Sat May 18 12:01:40 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sat, 18 May 2013 03:01:40 -0700 (PDT)
Subject: [Tutor] why is unichr(sys.maxunicode) blank?
In-Reply-To: <5196FA52.9090000@pearwood.info>
References: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<5196FA52.9090000@pearwood.info>
Message-ID: <1368871300.10705.YahooMailNeo@web163805.mail.gq1.yahoo.com>



>> I was curious what the "high" four-byte ut8 unicode characters look like.
>

>By the way, your sentence above reflects a misunderstanding. Unicode characters (strictly speaking, code points) are not "bytes", four or otherwise. They are abstract entities represented by a number between 0 and 1114111, or in hex, 0x10FFFF. Code points can represent characters, or parts of characters (e.g. accents, diacritics, combining characters and similar), or non-characters.



Thanks for all your replies. I knew about code points, but to represent the unicode string (code point) as a utf-8 byte string (bytes), characters 0-127 are 1 byte (of 8 bits), then 128-255 (accented chars) 
are 2 bytes, and so on up to 4 bytes for East Asian languages. But later on Joel Spolsky's "standard" page about unicode I read that it goes to 6 bytes. That's what I implied when I mentioned "utf8".



>Much confusion comes from conflating bytes and code points, or bytes and characters. The first step to being a Unicode wizard is to always keep them distinct in your mind. By analogy, the floating point number 23.42 is stored in memory or on disk as a bunch of bytes, but there is nothing to be gained from confusing the number 23.42 from the bytes 0xEC51B81E856B3740, which is how it is stored as a C double.
>
>Unicode code points are abstract entities, but in the real world, they have to be stored in a computer's memory, or written to disk, or transmitted over a wire, and that requires *bytes*. So there are three Unicode schemes for storing code points as bytes. These are called *encodings*. Only encodings involve bytes, so it is nonsense to talk about "four-byte" unicode characters, since it conflates the abstract Unicode character set with one of various concrete encodings.


I would admit it if otherwise, but that's what I meant ;-)



>There are three standard Unicode encodings. (These are not to be confused with the dozens of "legacy encodings", a.k.a. code pages, used prior to the Unicode standard. They do not cover the entire range of Unicode, and are not part of the Unicode standard.) These encodings are:



I always viewed the codepage as "the bunch of chars on top of ascii", e.g. cp1252 (latin-1) is ascii (0-127) +? another 128 characters that are used in Europe (euro sign, Scandinavian and Mediterranean (Spanish), but not Slavian chars). A certain locale implies a certain codepage (on Windows), but where does the locale category LC_CTYPE fit in this story?



>
>UTF-8
>UTF-16
>UTF-32 (also sometimes known as UCS-4)
>
>plus at least one older, obsolete encoding, UCS-2.

Isn't UCS-2 the internal unicode encoding for CPython (narrow builds)? Or maybe this is a different abbreviation. I read about bit multilingual plane (BMP) and surrogate pairs and all. The author suggested that messing with surrogate pairs is a topic to dive into in case one's nail bed is being derusted. I wholeheartedly agree.



>UTF-32 is the least common, but simplest. It simply maps every code point to four bytes. In the following, I will follow this convention:
>
>- code points are written using the standard Unicode notation, U+xxxx where the x's are hexadecimal digits;
>
>- bytes are written in hexadecimal, using a leading 0x.
>
>Code point U+0000 -> bytes 0x00000000
>Code point U+0001 -> bytes 0x00000001
>Code point U+0002 -> bytes 0x00000002
>...
>Code point U+10FFFF -> bytes 0x0010FFFF
>
>
>It is simple because the mapping is trivially simple, and uncommon because for typical English-language text, it wastes a lot of memory.
>
>The only complication is that UTF-32 depends on the endianess of your system. In the above examples I glossed over this factor. In fact, there are two common ways that bytes can be stored:
>
>- "big endian", where the most-significant (largest) byte is on the left (lowest address);
>- "little endian", where the most-significant (largest) byte is on the right.


Why is endianness relevant only for utf-32, but not for utf-8 and utf16? Is "utf-8" a shorthand for saying "utf-8 le"?



>So in a little-endian system, we have this instead:
>
>Code point U+0000 -> bytes 0x00000000
>Code point U+0001 -> bytes 0x01000000
>Code point U+0002 -> bytes 0x02000000
>...
>Code point U+10FFFF -> bytes 0xFFFF1000
>
>(Note that little-endian is not merely the reverse of big-endian. It is the order of bytes that is reversed, not the order of digits, or the order of bits within each byte.)
>
>So when you receive a bunch of bytes that you know represents text encoded using UTF-32, you can bunch the bytes in groups of four and convert them to Unicode code points. But you need to know the endianess. One way to do that is to add a Byte Order Mark at the beginning of the bytes. If you look at the first four bytes, and it looks like 0x0000FEFF, then you have big-endian UTF-32. But if it looks like 0xFFFE0000, then you have little-endian.

So each byte starts with a BOM? Or each file? I find utf-32 indeed the easiest to understand. In utf-8, how does a system "know" that the given octet of bits is to be interpreted as a single-byte character, or rather like "hold on, these eight bits are gibberish as they are right now, let's check what happens if we add the next eight bits", in other words a multibyte char (forgive me the naive phrasing ;-). Why I mention is in the context of BOM: why aren't these needed to indicate "mulitbyte char ahead!"?



>So that's UTF-32. UTF-16 is a little more complicated.
>
>UTF-16 divides the Unicode range into two groups:
>
>* The first (approximately) 65000 code points which are represented as two bytes;
>
>* Everything else, which are represented as a pair of double bytes, so-called "surrogate pairs".


Just as I thought I was starting to understand it.... Sorry. len(unichr(63000).encode("utf-8")) returns three bytes.
What should I do to arrive at two? Something like len(unichr(63000).encode("<internal unicode encoding that Python 2.7 uses>"))? 


>Last but not least, we have UTF-8. UTF-8 is slowly becoming the standard for storing Unicode on disk, because it is very compact for common English-language text, backwards-compatible with ASCII text files, and doesn't require a BOM. (Although Microsoft software sometimes adds a UTF-8 signature at the start of files, namely the three bytes 0xEFBBBF.)

Ah, ok, this answers one of my questions above.


Thanks again, all, it is much appreciated!


From fomcl at yahoo.com  Sat May 18 12:39:22 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sat, 18 May 2013 03:39:22 -0700 (PDT)
Subject: [Tutor] why is unichr(sys.maxunicode) blank?
In-Reply-To: <CACL+1asO=2GxSgz34JwFQqsewoBmhOpagkO7MRb+HLSk1oBewA@mail.gmail.com>
References: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<5196CF4B.20809@pearwood.info> <5196F02F.5000508@davea.name>
	<CACL+1asO=2GxSgz34JwFQqsewoBmhOpagkO7MRb+HLSk1oBewA@mail.gmail.com>
Message-ID: <1368873562.40750.YahooMailNeo@web163805.mail.gq1.yahoo.com>



----- Original Message -----

> From: eryksun <eryksun at gmail.com>
> To: tutor at python.org
> Cc: 
> Sent: Saturday, May 18, 2013 5:28 AM
> Subject: Re: [Tutor] why is unichr(sys.maxunicode) blank?
> 
> On Fri, May 17, 2013 at 11:06 PM, Dave Angel <davea at davea.name> wrote:
>>  One tool that can help is the name function in module unicodedata
>> 
>> ? >>> import unicodedata
>> ? >>> unicodedata.name(u'\xb0')
>>  'DEGREE SIGN'
>> 
>>  If you try that on the values near sys.maxunicode you get an exception:
>>  ValueError: no such name
> 
> There's no name since the code point isn't assigned, but the category
> is defined:
> 
> ? ? >>> unicodedata.category(u'\U0010FFFD')
> ? ? 'Co'
> ? ? >>> unicodedata.category(u'\U0010FFFE')
> ? ? 'Cn'
> ? ? >>> unicodedata.category(u'\U0010FFFF')
> ? ? 'Cn'
> 
> 'Co' is the private use category, and 'Cn' is for codes that 
> aren't assigned.

Thank you. That unicodedata module is very handy sometimes (and crucial for regexes, sometimes). I rarely use it but I should have remembered it.


From fomcl at yahoo.com  Sat May 18 12:42:44 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sat, 18 May 2013 03:42:44 -0700 (PDT)
Subject: [Tutor] use python to change the webpage content?
In-Reply-To: <CAEx-Hj4kj8qBpbe=VgFPMev3dDQVu3pjC3=BTqMSX3TW59dMLg@mail.gmail.com>
References: <CAEx-Hj4kj8qBpbe=VgFPMev3dDQVu3pjC3=BTqMSX3TW59dMLg@mail.gmail.com>
Message-ID: <1368873764.71085.YahooMailNeo@web163803.mail.gq1.yahoo.com>



>There is a online simulator about a physic project I'm doing and I want to use the data the simulator generates on that website. I can get data using urllib.request and regular expression but I also want to change some of the input values and then get different sets of data. However, if I change the inputs, the address of the webpage wouldn't change, so I couldn't get data with different initial conditions.I'm wondering how I can implement this.

Maybe this? http://www.pythonforbeginners.com/cheatsheet/python-mechanize-cheat-sheet/


From phil_lor at bigpond.com  Sat May 18 11:40:49 2013
From: phil_lor at bigpond.com (Phil)
Date: Sat, 18 May 2013 19:40:49 +1000
Subject: [Tutor] Retrieving data from a web site
In-Reply-To: <kn7hda$tr7$1@ger.gmane.org>
References: <5196C3F7.6030507@bigpond.com> <kn77bl$c10$1@ger.gmane.org>
	<51973EA2.6040007@bigpond.com> <kn7hda$tr7$1@ger.gmane.org>
Message-ID: <51974CA1.3020909@bigpond.com>

On 18/05/13 19:25, Peter Otten wrote:
>
> What's the url of the page?

http://tatts.com/goldencasket

> Are there alternatives that give the number as plain text?

Not that I can find. A Google search hasn't turned up anything.

> If not, do the images have names like whatever0.jpg, whatever1.jpg,
> whatever2.jpg, ...? Then you could infer the value from the name.
>
> If not, is a digit always represented by the same image? Then you could map
> the image urls to the digits.

Good point Peter, I'll investigate.

-- 
Regards,
Phil

From phil_lor at bigpond.com  Sat May 18 12:16:41 2013
From: phil_lor at bigpond.com (Phil)
Date: Sat, 18 May 2013 20:16:41 +1000
Subject: [Tutor] Retrieving data from a web site
In-Reply-To: <kn7hda$tr7$1@ger.gmane.org>
References: <5196C3F7.6030507@bigpond.com> <kn77bl$c10$1@ger.gmane.org>
	<51973EA2.6040007@bigpond.com> <kn7hda$tr7$1@ger.gmane.org>
Message-ID: <51975509.2020102@bigpond.com>

On 18/05/13 19:25, Peter Otten wrote:
>
> Are there alternatives that give the number as plain text?

Further investigation shows that the numbers are available if I view the 
source of the page. So, all I have to do is parse the page and extract 
the drawn numbers. I'm not sure, at the moment, how I might do that but 
I have something to work with.

-- 
Regards,
Phil

From davea at davea.name  Sat May 18 14:06:51 2013
From: davea at davea.name (Dave Angel)
Date: Sat, 18 May 2013 08:06:51 -0400
Subject: [Tutor] Unsubscribe
In-Reply-To: <66612899-0ACF-454B-B384-7310ADB29EB3@yahoo.com>
References: <66612899-0ACF-454B-B384-7310ADB29EB3@yahoo.com>
Message-ID: <51976EDB.5010407@davea.name>

On 05/16/2013 12:58 PM, Stafford Baines wrote:
> I only intend this to be temporary. I'm going away for a couple of weeks and don't want my mailbox overflowing when I return.? Thanks for all the help
>
> Sent from my iPhone
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

At the bottom of every message is a link to a web page to "change 
subscription options."  At the bottom of that page is a button that can 
unsubscribe you.

-- 
DaveA

From steve at pearwood.info  Sat May 18 14:12:16 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 18 May 2013 22:12:16 +1000
Subject: [Tutor] why is unichr(sys.maxunicode) blank?
In-Reply-To: <1368871300.10705.YahooMailNeo@web163805.mail.gq1.yahoo.com>
References: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<5196FA52.9090000@pearwood.info>
	<1368871300.10705.YahooMailNeo@web163805.mail.gq1.yahoo.com>
Message-ID: <51977020.9050008@pearwood.info>

On 18/05/13 20:01, Albert-Jan Roskam wrote:

> Thanks for all your replies. I knew about code points, but to represent the unicode string (code point) as a utf-8 byte string (bytes), characters 0-127 are 1 byte (of 8 bits), then 128-255 (accented chars)
> are 2 bytes, and so on up to 4 bytes for East Asian languages. But later on Joel Spolsky's "standard" page about unicode I read that it goes to 6 bytes. That's what I implied when I mentioned "utf8".

The UTF-8 data structure was originally designed to go up to 6 bytes, but since Unicode itself is limited to 1114111 code points, no more than 4 bytes are needed for UTF-8.

Also, it is wrong to say that the 4-byte UTF-8 values are "East Asian languages". The full Unicode range contains 17 "planes" of 65,536 code points. The first such plane is called the "Basic Multilingual Plane", and it includes all the code points that can be represented in 1 to 3 UTF-8 bytes. The BMP includes in excess of 13,000 East Asian code points, e.g.:


py> import unicodedata as ud
py> c = '\u3050'
py> print(c, ud.name(c), c.encode('utf-8'))
P HIRAGANA LETTER GU b'\xe3\x81\x90'


The 4-byte UTF-8 values are in the second and subsequent planes, called "Supplementary Multilingual Planes". They include historical character sets such as Egyptian hieroglyphs, cuneiform, musical and mathematical symbols, Emoji, gaming symbols, Ancient Arabic and Persian, and many others.

http://en.wikipedia.org/wiki/Plane_(Unicode)


> I always viewed the codepage as "the bunch of chars on top of ascii", e.g. cp1252 (latin-1) is ascii (0-127) +  another 128 characters that are used in Europe (euro sign, Scandinavian and Mediterranean (Spanish), but not Slavian chars).

Well, that's certainly common, but not all legacy encodings are supersets of ASCII. For example:

http://en.wikipedia.org/wiki/Big5

although I see that Python's implementation of Big5 is *technically* incorrect, although *practically* useful, as it does include ASCII.


> A certain locale implies a certain codepage (on Windows), but where does the locale category LC_CTYPE fit in this story?

No idea :-)




>> UTF-8
>> UTF-16
>> UTF-32 (also sometimes known as UCS-4)
>>
>> plus at least one older, obsolete encoding, UCS-2.
>
> Isn't UCS-2 the internal unicode encoding for CPython (narrow builds)? Or maybe this is a different abbreviation. I read about bit multilingual plane (BMP) and surrogate pairs and all. The author suggested that messing with surrogate pairs is a topic to dive into in case one's nail bed is being derusted. I wholeheartedly agree.

UCS-2 is a fixed-width encoding that is identical to UTF-16 for code points up to U+FFFF. It differs from UTF-16 in that it *cannot* encode code points U+10000 and higher, in other words, it does not support surrogate pairs. So UCS-2 is obsolete in the sense it doesn't include the whole set of Unicode characters.

In Python 3.2 and older, Python has a choice between a *narrow build* that uses UTF-16 (including surrogates) for strings in memory, or a *wide build* that uses UTF-32. The choice is made when you compile the Python interpreter. Other programming languages may use other systems.

Python 3.3 uses a different, more flexible scheme for keeping strings in memory. Depending on the largest code point in a string, the string will be stored in either Latin-1 (one byte per character), UCS-2 (two bytes per character, and no surrogates) or UTF-32 (four bytes per character). This means that there is no longer a need for surrogate pairs, but only strings that *need* four bytes per character will use four bytes.



>> - "big endian", where the most-significant (largest) byte is on the left (lowest address);
>> - "little endian", where the most-significant (largest) byte is on the right.
>
>
> Why is endianness relevant only for utf-32, but not for utf-8 and utf16? Is "utf-8" a shorthand for saying "utf-8 le"?

Endianness is relevant for UTF-16 too.

It is not relevant for UTF-8 because UTF-8 defines the order that multiple bytes must appear. UTF-8 is defined in terms of *bytes*, not multi-byte words. So the code point U+3050 is encoded into three bytes, *in this order*:

0xE3 0x81 0x90

There's no question about which byte comes first, because the order is set. But UTF-16 defines the encoding in terms of double-byte words, so the question of how words are stored becomes relevant. A 16-bit word can be laid out in memory in at least two ways:

[most significant byte] [least significant byte]

[least significant byte] [most significant byte]

so U+3050 could legitimately appear as bytes 0x3050 or 0x5030 depending on the machine you are using.

It's hard to talk about endianness without getting confused, or at least for me it is :-) Even though I've written down 0x3050 and 0x5030, it is important to understand that they both have the same numeric value of 12368 in decimal. The difference is just in how the bytes are laid out in memory. By analogy, Arabic numerals used in English and other Western languages are written in *big endian order*:

1234 means 1 THOUSAND 2 HUNDREDS 3 TENS 4 UNITS

Imagine a language that wrote numbers in *little endian order*, but using the same digits. You would count:

0
1
2
...
01  # no UNITS 1 TEN
11  # 1 UNITS 1 TEN
21  # 2 UNITS 1 TEN
...
4321  # 4 UNITS 3 TENS 2 HUNDREDS 1 THOUSAND


Since both UTF-16 and UTF-32 are defined in terms of 16 or 32 bit words, endianness is relevant; since UTF-8 is defined in terms of 8-bit bytes, it is not.

Fortunately, all(?) modern computing hardware has standardized on the same "endianness" of individual bytes. This was not always the case, but today if you receive a byte with bits:

0b00110000

then there is no(?) doubt that it represents decimal 48, not 12.



>> So when you receive a bunch of bytes that you know represents text encoded using UTF-32, you can bunch the bytes in groups of four and convert them to Unicode code points. But you need to know the endianess. One way to do that is to add a Byte Order Mark at the beginning of the bytes. If you look at the first four bytes, and it looks like 0x0000FEFF, then you have big-endian UTF-32. But if it looks like 0xFFFE0000, then you have little-endian.
>
> So each byte starts with a BOM? Or each file? I find utf-32 indeed the easiest to understand.

Certainly not each byte! That would be impossible, since the BOM itself is *two bytes* for UTF-16 and *four bytes* for UTF-32.

Remember, a BOM is not compulsory. If you decide before hand that you will always use big-endian UTF-16, say, there is no need to waste time with a BOM. But then you're responsible for producing big-endian words even if your hardware is little-endian.

A BOM is useful when you're transmitting a file to somebody else, and they *might* not have the same endianness as you. If you can pass a message on via some other channel, you can say "I'm about to send you a file in little-endian UTF-16" and all will be good. But since you normally can't, you just insert the BOM at the start of the file, and they can auto-detect the endianness.

How do they do that? Because they read the first two bytes. If they read it as 0xFFFE, that tells them that their byte-order and my byte-order are mismatched, and they should just use the opposite byte-order from what their system uses by default. If they read it as 0xFEFF, our endianness match, and we're right to go.

You can stick a BOM at the beginning of every string, but that's rather wasteful, and it leads to difficulty with string processing (especially concatenating strings), so it's best not to use BOMs except *at most* once per file.


> In utf-8, how does a system "know" that the given octet of bits is to be interpreted as a single-byte character, or rather like "hold on, these eight bits are gibberish as they are right now, let's check what happens if we add the next eight bits", in other words a multibyte char (forgive me the naive phrasing ;-). Why I mention is in the context of BOM: why aren't these needed to indicate "mulitbyte char ahead!"?

Because UTF-8 is a very cunning system that was designed by very clever people (Dave Prosser and Ken Thompson) to be unambiguous when read one byte at a time.

When reading a stream of UTF-8 bytes, you look at the first bit of the current byte. If it is a zero, then you have a single-byte code, so you can decode that byte and move on to the next byte. A single byte with a leading 0 gives you 127 possible different values. (If this sounds like ASCII, that's not a coincidence.)

But if the current byte starts with bits 110, then you throw those three bits away, and keep the next five bits. Then you read the next byte, check that it starts with bits 10, and keep the six bits following that. That gives you 5+6 = 11 useful bits in total, from two bytes read, which is enough to encode a further 2047 distinct values.

If the current byte starts with bits 1110, then you throw those four bits away and keep the next four. Then you read in two more bytes, check that they both start with bits 10, and keep the next six bits from each. This gives you 4+6+6 = 16 bits in total, which encodes a further 65535 values.

If the current byte starts with 11110, you throw away those five bits and read in the next three bytes. This gives you 3+6+6+6 = 21 bits, which is enough to encode 2097151 values. So in total, that gives you 127+2047+65535+2097151 = 2164860 distinct values, which is more than the number we actually need.

(Notice that the number of leading 1s in the first byte tells you how many bytes you need to read. Also note that not all byte sequences are valid UTF-8.) In summary:

U+0000 - U+007F => 0xxxxxxx
U+0080 - U+07FF => 110xxxxx 10xxxxxx
U+0800 - U+FFFF => 1110xxxx 10xxxxxx 10xxxxxx
U+10000 - U+1FFFFF => 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx



>> So that's UTF-32. UTF-16 is a little more complicated.
>>
>> UTF-16 divides the Unicode range into two groups:
>>
>> * The first (approximately) 65000 code points which are represented as two bytes;
>>
>> * Everything else, which are represented as a pair of double bytes, so-called "surrogate pairs".
>
>
> Just as I thought I was starting to understand it.... Sorry. len(unichr(63000).encode("utf-8")) returns three bytes.

You're using UTF-8. I'm talking about UTF-16.





-- 
Steven

From __peter__ at web.de  Sat May 18 14:44:45 2013
From: __peter__ at web.de (Peter Otten)
Date: Sat, 18 May 2013 14:44:45 +0200
Subject: [Tutor] Retrieving data from a web site
References: <5196C3F7.6030507@bigpond.com> <kn77bl$c10$1@ger.gmane.org>
	<51973EA2.6040007@bigpond.com> <kn7hda$tr7$1@ger.gmane.org>
	<51975509.2020102@bigpond.com>
Message-ID: <kn7t3n$1sr$1@ger.gmane.org>

Phil wrote:

> On 18/05/13 19:25, Peter Otten wrote:
>>
>> Are there alternatives that give the number as plain text?
> 
> Further investigation shows that the numbers are available if I view the
> source of the page. So, all I have to do is parse the page and extract
> the drawn numbers. I'm not sure, at the moment, how I might do that but
> I have something to work with.

You can use a tool like lxml that "understands" html (though in this case 
you'd need a javascript parser on top of that) -- or hack something together 
with string methods or regular expressions. For example:

import urllib2
import json

s = urllib2.urlopen("http://*********/goldencasket").read()
s = s.partition("latestResults_productResults")[2].lstrip(" =")
s = s.partition(";")[0]
data = json.loads(s)
lotto = data["GoldLottoSaturday"]

print lotto["drawDayDateNumber"]
print map(int, lotto["primaryNumbers"])
print map(int, lotto["secondaryNumbers"])

While this is brittle I've found that doing it "right" is usually not 
worthwhile as it won't survive the next website redesign eighter.

PS: <http://*********/goldencasket/results/download-results>
has links to zipped csv files with the results. Downloading, inflating and 
reading these should be the simplest and best way to get your data.


From eryksun at gmail.com  Sat May 18 16:23:45 2013
From: eryksun at gmail.com (eryksun)
Date: Sat, 18 May 2013 10:23:45 -0400
Subject: [Tutor] why is unichr(sys.maxunicode) blank?
In-Reply-To: <1368871300.10705.YahooMailNeo@web163805.mail.gq1.yahoo.com>
References: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<5196FA52.9090000@pearwood.info>
	<1368871300.10705.YahooMailNeo@web163805.mail.gq1.yahoo.com>
Message-ID: <CACL+1av_5Y8ZX1qdtdojmLRdbeLPNwO_cZ70c-yyD8t6sHbT0g@mail.gmail.com>

On Sat, May 18, 2013 at 6:01 AM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
>
> East Asian languages. But later on Joel Spolsky's "standard" page about unicode
> I read that it goes to 6 bytes. That's what I implied when I mentioned "utf8".

Each surrogate in a UTF-16 surrogate pair is 10 bits, for a total of
20-bits. Thus UTF-16 sets the upper bound on the number of code points
at 2**20 + 2**16 (BMP). UTF-8 only needs 4 bytes for this number of
codes.

> A certain locale implies a certain codepage (on Windows), but where does the locale
> category LC_CTYPE fit in this story?

LC_CTYPE is the locale category that classifies characters. In Debian
Linux, the English-language locales copy LC_CTYPE from the i18n
(internationalization) locale:

short: http://goo.gl/Hs8RD
http://www.eglibc.org/cgi-bin/viewvc.cgi/trunk/libc/localedata/locales/i18n?view=markup

Here's the mapping between the symbolic Unicode names in the latter
(e.g. <U0020>) and UTF-8:

short: http://goo.gl/cZ3dS
http://www.eglibc.org/cgi-bin/viewvc.cgi/trunk/libc/localedata/charmaps/UTF-8?view=markup

The i18n locale is defined by the ISO/IEC technical report 14652, as
an instance of an upward compatible extension to the POSIX locale
specification called the FDCC-set (i.e. Set of Formal Definitions of
Cultural Conventions). Here it is in all its glory, if you like
reading technical reports:

http://www.open-std.org/jtc1/sc22/wg20/docs/n972-14652ft.pdf

If that's not enough, here's the POSIX 1003.1 locale spec:

short: http://goo.gl/aOJUx
http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap07.html

> Isn't UCS-2 the internal unicode encoding for CPython (narrow builds)?

Narrow builds create UTF-16 surrogate pairs from \U literals, but
these aren't treated as an atomic unit for slicing, iteration, or
string length.

From fomcl at yahoo.com  Sat May 18 18:45:32 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sat, 18 May 2013 09:45:32 -0700 (PDT)
Subject: [Tutor] why is unichr(sys.maxunicode) blank?
In-Reply-To: <CACL+1av_5Y8ZX1qdtdojmLRdbeLPNwO_cZ70c-yyD8t6sHbT0g@mail.gmail.com>
References: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<5196FA52.9090000@pearwood.info>
	<1368871300.10705.YahooMailNeo@web163805.mail.gq1.yahoo.com>
	<CACL+1av_5Y8ZX1qdtdojmLRdbeLPNwO_cZ70c-yyD8t6sHbT0g@mail.gmail.com>
Message-ID: <1368895532.71831.YahooMailNeo@web163803.mail.gq1.yahoo.com>



> 
>>  East Asian languages. But later on Joel Spolsky's "standard" 
> page about unicode
>>  I read that it goes to 6 bytes. That's what I implied when I mentioned 
> "utf8".
> 
> Each surrogate in a UTF-16 surrogate pair is 10 bits, for a total of
> 20-bits. Thus UTF-16 sets the upper bound on the number of code points
> at 2**20 + 2**16 (BMP). UTF-8 only needs 4 bytes for this number of
> codes.
> 
>>  A certain locale implies a certain codepage (on Windows), but where does 
> the locale
>>  category LC_CTYPE fit in this story?
> 
> LC_CTYPE is the locale category that classifies characters. In Debian
> Linux, the English-language locales copy LC_CTYPE from the i18n
> (internationalization) locale:
?
Thanks for the links. Without examples it remains pretty abstract, but I think I know is meant by this locale category now.. "The LC_CTYPE category shall define character classification, case conversion, and other character attributes. So if you switch from one locale to another, certain attributes of a character set might change". A switch from locale A to locale B might affect an attribute "casing", therefore, the mapping from lower- to uppercase *might* differ by locale. In stupid country X? "a".upper() may return "B".

It seems that the result of str.isalpha() and str.isdigit() *might* be different depending on the setting of locale.C_CTYPE. 

It is pretty sick that all these things can be adjusted separately (what is the use of having: danish collation, russian case conversion, english decimal sign, japanese codepage ;-)

?
> The i18n locale is defined by the ISO/IEC technical report 14652, as
> an instance of an upward compatible extension to the POSIX locale
> specification called the FDCC-set (i.e. Set of Formal Definitions of
> Cultural Conventions). Here it is in all its glory, if you like
> reading technical reports:
> 
> http://www.open-std.org/jtc1/sc22/wg20/docs/n972-14652ft.pdf

> If that's not enough, here's the POSIX 1003.1 locale spec:
> 
> short: http://goo.gl/aOJUx
> http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap07.html


That one is the clearest IMHO. Oh no, now I see the possible impact on regexes. The meaning of e.g. "\s+"
might change depending on the locale.C_CTYPE setting!!


>>  Isn't UCS-2 the internal unicode encoding for CPython (narrow builds)?
> 
> Narrow builds create UTF-16 surrogate pairs from \U literals, but
> these aren't treated as an atomic unit for slicing, iteration, or
> string length.

That is a nice way of putting it. So if you slice a multibyte char "mb", mb[0] will return the first byte? That is annoying.


From wprins at gmail.com  Sat May 18 19:48:53 2013
From: wprins at gmail.com (Walter Prins)
Date: Sat, 18 May 2013 18:48:53 +0100
Subject: [Tutor] Retrieving data from a web site
In-Reply-To: <kn7t3n$1sr$1@ger.gmane.org>
References: <5196C3F7.6030507@bigpond.com> <kn77bl$c10$1@ger.gmane.org>
	<51973EA2.6040007@bigpond.com> <kn7hda$tr7$1@ger.gmane.org>
	<51975509.2020102@bigpond.com> <kn7t3n$1sr$1@ger.gmane.org>
Message-ID: <CANLXbfDHgz71_0C2uK=LGz46RqsPNfguN6svox=LpLaN+QnPLw@mail.gmail.com>

Hi

Just a minor observation:

On 18 May 2013 13:44, Peter Otten <__peter__ at web.de> wrote:

> Phil wrote:
>
> > On 18/05/13 19:25, Peter Otten wrote:
> >>
> >> Are there alternatives that give the number as plain text?
> >
> > Further investigation shows that the numbers are available if I view the
> > source of the page. So, all I have to do is parse the page and extract
> > the drawn numbers. I'm not sure, at the moment, how I might do that but
> > I have something to work with.
>
> You can use a tool like lxml that "understands" html (though in this case
> you'd need a javascript parser on top of that) -- or hack something
> together
> with string methods or regular expressions. For example:


You don't need javascript, in this case, assuming the reference is to the
UK lotto --  A simple curl test confirms that (for the UK lottery at least)
the numbers can be retrieved simply without the involvedment of javascript,
so Python will be able to do the same. (URL:
https://www.national-lottery.co.uk/player/p/results.ftl  Apologies if this
is about some other lottery and I've missed it...)

Best,

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130518/0c9d3ba9/attachment.html>

From eryksun at gmail.com  Sat May 18 21:15:07 2013
From: eryksun at gmail.com (eryksun)
Date: Sat, 18 May 2013 15:15:07 -0400
Subject: [Tutor] why is unichr(sys.maxunicode) blank?
In-Reply-To: <1368895532.71831.YahooMailNeo@web163803.mail.gq1.yahoo.com>
References: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<5196FA52.9090000@pearwood.info>
	<1368871300.10705.YahooMailNeo@web163805.mail.gq1.yahoo.com>
	<CACL+1av_5Y8ZX1qdtdojmLRdbeLPNwO_cZ70c-yyD8t6sHbT0g@mail.gmail.com>
	<1368895532.71831.YahooMailNeo@web163803.mail.gq1.yahoo.com>
Message-ID: <CACL+1atj7H8+WhjQspMy0zup6em+sZU+eL0hsWJ3TfnVr=G-Zg@mail.gmail.com>

On Sat, May 18, 2013 at 12:45 PM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
>
> It seems that the result of str.isalpha() and str.isdigit() *might* be different depending
> on the setting of locale.C_CTYPE.

Yes, str() in 2.x uses the locale predicates from <ctype.h>:

http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/ctype.h.html

However, 2.x bytearray uses the bytes_methods from 3.x, which use pyctype:

2.7.5 source:
http://hg.python.org/cpython/file/ab05e7dd2788/Include/pyctype.h
http://hg.python.org/cpython/file/ab05e7dd2788/Python/pyctype.c
http://hg.python.org/cpython/file/ab05e7dd2788/Include/bytes_methods.h
http://hg.python.org/cpython/file/ab05e7dd2788/Objects/stringlib/ctype.h

Note that the table in pyctype.c is only defined for ASCII.

> It is pretty sick that all these things can be adjusted separately (what is the use of having:
> danish collation, russian case conversion, english decimal sign, japanese codepage ;-)

Here's a non-sick example. A system in the US might customize
LC_MEASUREMENT to use SI units and LC_TIME to have Monday as the first
day of the week.

> That one is the clearest IMHO. Oh no, now I see the possible impact on regexes. The
> meaning of e.g. "\s+" might change depending on the locale.C_CTYPE setting!!

The re module has the re.L flag to enable limited locale support. It
only affects the alphanumeric category and word boundaries. You're
probably better off using re.U and the Unicode database.

>> Narrow builds create UTF-16 surrogate pairs from \U literals, but
>> these aren't treated as an atomic unit for slicing, iteration, or
>> string length.
>
> That is a nice way of putting it. So if you slice a multibyte char "mb", mb[0] will return the
> first byte? That is annoying.

It's 2 bytes, not one. If you use a non-BMP \U escape on a narrow
build it creates a surrogate pair.  Each surrogate has a 10-bit range
in a 2-byte code. The lead surrogate is in the range 0xD800-0xDBFF,
and the trail is in the range 0xDC00-0xDFFF.

From chigga101 at gmail.com  Sat May 18 21:16:27 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Sat, 18 May 2013 20:16:27 +0100
Subject: [Tutor] model methods in Django
Message-ID: <CACzNyA3zu32s88-gW8G4RcO+UoSUQ4nycDrYEMpD5rDGwdM8Bg@mail.gmail.com>

 im following the official docs and after learning Python im sure of
how methods work, but the model example on the beginners guide has me
really confused.

The model definition is omitted but can anyone explain how this methed
(was_published_recently) is given these attributes:

class Poll(models.Model):
    # ...
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

are the names of the attributes already attached to these
functions/methods, or are they being created on the fly with whatever
name you want? As i am unable to comprehend what is going on, i dont
really have a clue as to what each definition is doing and how it
affects the model, even after reading this section of the docs over
and over again im still lost.

From william at ranvaud.com  Sat May 18 22:23:04 2013
From: william at ranvaud.com (William Ranvaud)
Date: Sat, 18 May 2013 17:23:04 -0300
Subject: [Tutor] Python web script to run a command line expression
In-Reply-To: <CAGf4weVWAGP0um9LWbkcYsvZQNCR8jNzfG7SaFg1GDea1CPTGQ@mail.gmail.com>
References: <CAGf4weVWAGP0um9LWbkcYsvZQNCR8jNzfG7SaFg1GDea1CPTGQ@mail.gmail.com>
Message-ID: <5197E328.2070408@ranvaud.com>


I'm not sure if this is what you are looking for or if this will work on 
WAMP but python has a virtual terminal emulator called Vte or 
python-vte. I use it to display the terminal and run commands.
I'm using it on Linux by adding "from gi.repository import Vte".
Hope it helps.



On 18-05-2013 04:20, Ahmet Anil Dindar wrote:
>
> Hi,
> I have a WAMP running in my office computer. I wonder how I can 
> implement a python script that runs within WAMP and execute a command 
> line expression. By this way, I will able to run my command line 
> expressions through web page in intranet.
>
> I appreciate your suggestions.
>
> ++Ahmet
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130518/2a514e25/attachment.html>

From phil_lor at bigpond.com  Sun May 19 02:02:54 2013
From: phil_lor at bigpond.com (Phil)
Date: Sun, 19 May 2013 10:02:54 +1000
Subject: [Tutor] Retrieving data from a web site
In-Reply-To: <kn7t3n$1sr$1@ger.gmane.org>
References: <5196C3F7.6030507@bigpond.com> <kn77bl$c10$1@ger.gmane.org>
	<51973EA2.6040007@bigpond.com> <kn7hda$tr7$1@ger.gmane.org>
	<51975509.2020102@bigpond.com> <kn7t3n$1sr$1@ger.gmane.org>
Message-ID: <519816AE.4060800@bigpond.com>

On 18/05/13 22:44, Peter Otten wrote:
> You can use a tool like lxml that "understands" html (though in this case
> you'd need a javascript parser on top of that) -- or hack something together
> with string methods or regular expressions. For example:
>
> import urllib2
> import json
>
> s = urllib2.urlopen("http://*********/goldencasket").read()
> s = s.partition("latestResults_productResults")[2].lstrip(" =")
> s = s.partition(";")[0]
> data = json.loads(s)
> lotto = data["GoldLottoSaturday"]
>
> print lotto["drawDayDateNumber"]
> print map(int, lotto["primaryNumbers"])
> print map(int, lotto["secondaryNumbers"])
>
> While this is brittle I've found that doing it "right" is usually not
> worthwhile as it won't survive the next website redesign eighter.
>
> PS: <http://*********/goldencasket/results/download-results>
> has links to zipped csv files with the results. Downloading, inflating and
> reading these should be the simplest and best way to get your data.

Thanks again Peter and Walter,

The results download link points to a historical file of past results 
although the latest results are included at the bottom of the file. The 
file is quite large and it's zipped so I imagine unzipping would another 
problem. I've come across Beautiful Soup and it may also offer a simple 
solution.

Thanks for your response Walter, I'd like to download the Australian 
Lotto results and there isn't a simple way, as far as I can see, to do 
this. I'll read up on curl, maybe I can use it.

I'll experiment with the Peter's code and Beautiful Soup and see what I 
can come up with. Maybe unzipping the file could be the best solution, 
I'll experiment with that option as well.

-- 
Regards,
Phil

From steve at pearwood.info  Sun May 19 03:34:44 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 19 May 2013 11:34:44 +1000
Subject: [Tutor] why is unichr(sys.maxunicode) blank?
In-Reply-To: <1368895532.71831.YahooMailNeo@web163803.mail.gq1.yahoo.com>
References: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<5196FA52.9090000@pearwood.info>
	<1368871300.10705.YahooMailNeo@web163805.mail.gq1.yahoo.com>
	<CACL+1av_5Y8ZX1qdtdojmLRdbeLPNwO_cZ70c-yyD8t6sHbT0g@mail.gmail.com>
	<1368895532.71831.YahooMailNeo@web163803.mail.gq1.yahoo.com>
Message-ID: <51982C34.5010606@pearwood.info>

On 19/05/13 02:45, Albert-Jan Roskam wrote about locales:

> It is pretty sick that all these things can be adjusted separately (what is the use of having: danish collation, russian case conversion, english decimal sign, japanese codepage ;-)

Well obviously there is no point to such a mess, but the ability to make a mess comes from having the flexibility to have less silly combinations.

By the way, I'm not sure what you mean by "pretty sick", since in Australian slang "sick" can mean "fantastic, excellent", as in "Mate, that's a pretty sick sub-woofer!".

See http://www.youtube.com/watch?v=iRv7IE6T4gQ

(warning: ethnic stereotypes, low-brow humour)



[...]
>>>   Isn't UCS-2 the internal unicode encoding for CPython (narrow builds)?
>>
>> Narrow builds create UTF-16 surrogate pairs from \U literals, but
>> these aren't treated as an atomic unit for slicing, iteration, or
>> string length.
>
> That is a nice way of putting it. So if you slice a multibyte char "mb", mb[0] will return the first byte? That is annoying.

Correct. You can easily break apart surrogate pairs in Python narrow builds, which leads to invalid strings. The solution is to either use a wide build, or upgrade to Python 3.3 which no longer has this problem:


# Python 3.2, narrow build:
py> len(chr(0x101001))
2

# Python 3.3
py> len(chr(0x101001))
1


-- 
Steven

From davea at davea.name  Sun May 19 04:22:15 2013
From: davea at davea.name (Dave Angel)
Date: Sat, 18 May 2013 22:22:15 -0400
Subject: [Tutor] model methods in Django
In-Reply-To: <CACzNyA3zu32s88-gW8G4RcO+UoSUQ4nycDrYEMpD5rDGwdM8Bg@mail.gmail.com>
References: <CACzNyA3zu32s88-gW8G4RcO+UoSUQ4nycDrYEMpD5rDGwdM8Bg@mail.gmail.com>
Message-ID: <51983757.3020504@davea.name>

On 05/18/2013 03:16 PM, Matthew Ngaha wrote:
>   im following the official docs and after learning Python im sure of
> how methods work, but the model example on the beginners guide

which official docs?  URLs please?
which beginners guide?  URL please?

> has me
> really confused.
>

I don't know Django, so if this is really Django specific, I can't help.

> The model definition is omitted but can anyone explain how this methed
> (was_published_recently) is given these attributes:

Which attributes are you confused about?
The admin_order_field, boolean, ande short_description attributes of the 
method are bound in class code, immediately after the method is defined.

The pub_date is probably an instance attribute of either the Poll class 
or the models.Model class.  It should probably be defined in the 
appropriate __init__ method.  In any case it's not a method attribute.

>
> class Poll(models.Model):
>      # ...
>      def was_published_recently(self):
>          return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
>      was_published_recently.admin_order_field = 'pub_date'
>      was_published_recently.boolean = True
>      was_published_recently.short_description = 'Published recently?'
>
> are the names of the attributes already attached to these
> functions/methods, or are they being created on the fly with whatever
> name you want? As i am unable to comprehend what is going on, i dont
> really have a clue as to what each definition is doing and how it
> affects the model, even after reading this section of the docs over
> and over again im still lost.
>

This fragment isn't big enough for much else to be told.  But I don't 
really understand what aspect is confusing you.

Perhaps you didn't realize that a function can have attributes, and that 
they can be added to the function at any time after the function is 
created. Being a method doesn't change that.


-- 
DaveA

From cybervigilante at gmail.com  Sun May 19 05:29:38 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sat, 18 May 2013 20:29:38 -0700
Subject: [Tutor] WAMP stack
Message-ID: <CALRAYNXGvXhFKphvJtbsQagCrjB-CPn=dqjAxE9asaDm2z54bQ@mail.gmail.com>

I noticed someone mentioned WAMP stacks but didn't see the answer. I
use a WAMP stack a lot. It has PHP. But I used it mainly with PHP CMS.
How do I install Python into my WAMP stack, and does that make any
sense for just raw Python, or only if I want to load Django or
something web-oriented and test it? (Assume I know nothing about
Django other than it's a Py CMS, since I don't ;')

Jim Mooney

"Since True * True * True == True, what I tell you three times is
true." --The Hunting of the Snark

From cybervigilante at gmail.com  Sun May 19 06:08:17 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sat, 18 May 2013 21:08:17 -0700
Subject: [Tutor] creating import directories
Message-ID: <CALRAYNUUijtCFHxhb1Pj+_yvzdgLrb-sEMdB+_3H2GSz6zbsGw@mail.gmail.com>

I'm a bit unclear about creating import directories.

I can import something like the json directory from Lib with a simple
 import json

So I tried putting my own directory in Lib, called bagofries, as a
test, and put a simple printstuff.py program in it. But when I try to
import bagofries, I get "no module named bagofries"

Is there some reason I can put a program right under Lib and it
imports, which it does but not a directory?

Also, I noticed Wing 101 is sometimes creating a same-named pyc
program alongside my py program, but I don't see an option to do that.

-- 
Jim Mooney

Today is the day that would have been tomorrow if yesterday was today.

From steve at pearwood.info  Sun May 19 07:19:24 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 19 May 2013 15:19:24 +1000
Subject: [Tutor] creating import directories
In-Reply-To: <CALRAYNUUijtCFHxhb1Pj+_yvzdgLrb-sEMdB+_3H2GSz6zbsGw@mail.gmail.com>
References: <CALRAYNUUijtCFHxhb1Pj+_yvzdgLrb-sEMdB+_3H2GSz6zbsGw@mail.gmail.com>
Message-ID: <519860DC.4080402@pearwood.info>

On 19/05/13 14:08, Jim Mooney wrote:
> I'm a bit unclear about creating import directories.

The terminology you want here is "import packages". You cannot import directories. You can only import modules and packages.

"Module" in Python has two meanings:

1) a module is a file containing Python code, such as:

- source code in a .py file

- pre-compiled byte code in a .pyc file

- C libraries in a .dll or .so file

- and various others.

2) a module is an object that exists in memory, created by Python when you import a module as defined above, *or* a package as defined below.


A package, on the other hand, is a way of collecting multiple modules (definition 1 above) into a single directory, so that it becomes a self-contained group of files. The way to do this is by setting up the directory in a way that Python understands as a package:


1) The directory must be somewhere that Python will see it, no different from a single file module. That means, in the current directory, or your PYTHONPATH.

2) The directory name must be legal as a module name. That means, it must follow the same rules as names for modules, except without the .py extension.

"mymodule" is good
"my module" (note space) is bad

3) Inside the module, you MUST put in a special file called "__init__.py" for Python to recognise it as a package. This is critical. This file can be empty, or it can contain Python code, but it must exist.

4) Any other modules inside the package follow the usual naming rules.

5) Last, and optional, if you want to run the package as if it were a script, you give it a file called "__main__.py" containing the code to run.

So, if I create the following directory structure where Python can see it:


mypackage/
   +-- __init__.py
   +-- spam.py
   +-- eggs.py
   +-- math.py


then I can do this:

import mypackage

which will read the file mypackage/__init__.py and create a module object (definition 2 above) called "mypackage".


import mypackage.spam

will *first* read mypackage/__init__.py (if it hasn't already read it), and *then* read mypackage/spam.py. Once this has done, you can use:

result = mypackage.spam.function()

to call the function inside the spam module.

Similarly for mypackage.eggs and mypackage.math, which is especially interesting because it means you don't have to worry about your package's math.py module shadowing (hiding) the standard math module that Python uses.

You can learn more about packages from this historical document:

http://www.python.org/doc/essays/packages.html

Even though this goes back to the Dark Ages of Python 1.3 (!) most of the details of packages have not changed.


One more trick: starting from Python 2.7, or optionally in 2.5 and 2.6, there is a special form of the import statement that tells Python to only look inside the *current* package. If I write

import math

inside (say) mypackage.spam, I will get the standard math module. But if I write:

from . import math

I will get the custom math module inside the package. I can even get them both at the same time, with a bit of renaming:

import math
from . import math as mymaths

Google on "absolute and relative imports" for more information on that.



> Also, I noticed Wing 101 is sometimes creating a same-named pyc
> program alongside my py program, but I don't see an option to do that.


This is normal behaviour when you import a module.

When you import a module, Python performs two versions of caching:

import spam


will first look in sys.modules for an entry called "spam", and if found, it will use that. If there is no such entry, Python looks for a .py file called "spam". If it finds one, it compiles it to byte code. To speed up that process for the next time, it caches that byte code in the a file called spam.pyc.

Of course Python also checks the timestamps on the source file, and won't use old byte code when the source code has changed.

This only occurs when you import a module. Just running the module will not cache the byte code.



-- 
Steven

From eryksun at gmail.com  Sun May 19 08:03:22 2013
From: eryksun at gmail.com (eryksun)
Date: Sun, 19 May 2013 02:03:22 -0400
Subject: [Tutor] model methods in Django
In-Reply-To: <51983757.3020504@davea.name>
References: <CACzNyA3zu32s88-gW8G4RcO+UoSUQ4nycDrYEMpD5rDGwdM8Bg@mail.gmail.com>
	<51983757.3020504@davea.name>
Message-ID: <CACL+1ausZVbdkpTUR0HaRTsxLogSiPxk4ra1YsqvzwO8wGSYvA@mail.gmail.com>

On Sat, May 18, 2013 at 10:22 PM, Dave Angel <davea at davea.name> wrote:
> The pub_date is probably an instance attribute of either the Poll class or
> the models.Model class.  It should probably be defined in the appropriate
> __init__ method.  In any case it's not a method attribute.

Django uses function attributes as metadata. The names "boolean" and
"short_description" are self-documenting. "admin_order_field" is
explained here:

https://docs.djangoproject.com/en/dev/ref/contrib/admin/
#django.contrib.admin.ModelAdmin.list_display

    Usually, elements of list_display that aren?t actual database
    fields can?t be used in sorting (because Django does all the
    sorting at the database level). However, if an element of
    list_display represents a certain database field, you can
    indicate this fact by setting the admin_order_field attribute
    of the item.

The Poll model is part of the tutorial, "Writing your first Django app":

https://docs.djangoproject.com/en/1.5/intro

The function attributes are added in "Customize the admin change
list", in part 2.

> Perhaps you didn't realize that a function can have attributes, and that
> they can be added to the function at any time after the function is created.
> Being a method doesn't change that.

In a class definition, from a conceptual point of view, you're adding
a 'method'. But technically it's a function object. When accessed as
an attribute, the function's __get__ descriptor is used to create a
method on the fly.

The instancemethod type has a custom __getattribute__ that first
checks the method object's attributes such as __self__. If the lookup
on the method object fails, it proxies the __getattribute__ of the
wrapped __func__. For example:

    class Spam(object):
        def __repr__(self):
            return 'eggs'

    >>> meth = Spam().__repr__
    >>> type(meth)
    <type 'instancemethod'>
    >>> meth.__self__
    eggs

A method doesn't have a __dict__ for setting dynamic attributes:

    >>> meth.boolean = False
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'instancemethod' object has no attribute 'boolean'

But you can set attributes on the underlying function object:

    >>> type(meth.__func__)
    <type 'function'>
    >>> meth.__func__.boolean = False

The method will proxy them:

    >>> meth.boolean
    False

But not for assignment:

    >>> meth.boolean  = True
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'instancemethod' object has no attribute 'boolean'

From phil_lor at bigpond.com  Sun May 19 07:01:32 2013
From: phil_lor at bigpond.com (Phil)
Date: Sun, 19 May 2013 15:01:32 +1000
Subject: [Tutor] Retrieving data from a web site
In-Reply-To: <CANLXbfDHgz71_0C2uK=LGz46RqsPNfguN6svox=LpLaN+QnPLw@mail.gmail.com>
References: <5196C3F7.6030507@bigpond.com> <kn77bl$c10$1@ger.gmane.org>
	<51973EA2.6040007@bigpond.com> <kn7hda$tr7$1@ger.gmane.org>
	<51975509.2020102@bigpond.com> <kn7t3n$1sr$1@ger.gmane.org>
	<CANLXbfDHgz71_0C2uK=LGz46RqsPNfguN6svox=LpLaN+QnPLw@mail.gmail.com>
Message-ID: <51985CAC.2000908@bigpond.com>

My apatite having been whetted I'm now stymied because of a Ubuntu 
dependency problem during the installation of urllib3. This is listed as 
a bug. Has anyone overcome this problem?

Perhaps there's another library that I can use to download data from a 
web page?

-- 
Regards,
Phil

From cybervigilante at gmail.com  Sun May 19 09:37:36 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sun, 19 May 2013 00:37:36 -0700
Subject: [Tutor] Tutor Digest, Vol 111, Issue 61
In-Reply-To: <mailman.10592.1368944861.3113.tutor@python.org>
References: <mailman.10592.1368944861.3113.tutor@python.org>
Message-ID: <CALRAYNXVhHWHSc6BAKZna2pWPR=xDf=8W74r1c6E4ZA2etuVBw@mail.gmail.com>

> 1) The directory must be somewhere that Python will see it, no different from a single file module. That means, in the current directory, or your PYTHONPATH.


Since Python on Win 7 can already find modules in Lib (and in
site-packages, under Lib) can I assume that it will find any
directories fabricated as mentioned, that are put in Lib or one of its
subdirectories, without doing anything further?

Also, I didn't have a PYTHONPATH so I made one, but are you allowed
multiple directory entries separated by a semicolon, as in the plain
Windows Path?  And just how detailed must PYTHONPATH be? Can it just
be the PYTHON27 and PYTHON33 directories, or does it have to drill
down to Lib or directories beneath that? Since there was no PYTHONPATH
I figured the win path was enough, but I put one in anyway. Or does
Win 7 put something in the registry? (I'm not sure which I dislike
more - IE or the Registry ;')

Jim

From eryksun at gmail.com  Sun May 19 10:04:21 2013
From: eryksun at gmail.com (eryksun)
Date: Sun, 19 May 2013 04:04:21 -0400
Subject: [Tutor] Tutor Digest, Vol 111, Issue 61
In-Reply-To: <CALRAYNXVhHWHSc6BAKZna2pWPR=xDf=8W74r1c6E4ZA2etuVBw@mail.gmail.com>
References: <mailman.10592.1368944861.3113.tutor@python.org>
	<CALRAYNXVhHWHSc6BAKZna2pWPR=xDf=8W74r1c6E4ZA2etuVBw@mail.gmail.com>
Message-ID: <CACL+1av0D6ri3D=yG2K0j=MdUvg=F4EXD3nV=CQQKwWbe+QHow@mail.gmail.com>

On Sun, May 19, 2013 at 3:37 AM, Jim Mooney <cybervigilante at gmail.com> wrote:
>
> Since Python on Win 7 can already find modules in Lib (and in
> site-packages, under Lib) can I assume that it will find any
> directories fabricated as mentioned, that are put in Lib or one of its
> subdirectories, without doing anything further?
>
> Also, I didn't have a PYTHONPATH so I made one, but are you allowed
> multiple directory entries separated by a semicolon, as in the plain
> Windows Path?

Putting packages directly in the standard Lib isn't a good idea. Even
the main Lib/site-packages should be reserved for installed packages
(i.e. setup.py, pip, exe/msi). Use the environment variable PYTHONPATH
to add your own list of directories to sys.path. For NT the list is
delimited by a semicolon.

> And just how detailed must PYTHONPATH be? Can it just
> be the PYTHON27 and PYTHON33 directories, or does it have to drill
> down to Lib or directories beneath that? Since there was no PYTHONPATH

Those directories are already on sys.path. By the way Python's
sys.path for importing modules/packages isn't related to the PATH
environment variable. NT uses PATH to find and open files and DLLs,
e.g. to find python.exe, python33.dll, and your .py scripts run from
the command line.

> I figured the win path was enough, but I put one in anyway. Or does
> Win 7 put something in the registry? (I'm not sure which I dislike
> more - IE or the Registry ;')

Python does use NT's registry (either HKLM or HKCU, depending on how
you installed) for some for some of the base paths, but don't mess
with this:

    C:\>reg query hklm\software\python\pythoncore\2.7\PythonPath

    HKEY_LOCAL_MACHINE\software\python\pythoncore\2.7\PythonPath
        (Default)    REG_SZ
C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk

    C:\>reg query hklm\software\python\pythoncore\3.3\PythonPath

    HKEY_LOCAL_MACHINE\software\python\pythoncore\3.3\PythonPath
        (Default)    REG_SZ    C:\Python33\Lib;C:\Python33\DLLs


Alternatively you can use your user profile site-packages. On NT, this
defaults to "{userbase}/Python{py_version_nodot}/site-packages", where
userbase is "%appdata%\Python". You can change the latter by setting
the environment variable PYTHONUSERBASE. Check your current setup as
follows:

    userbase = sysconfig.get_config_var('userbase')
    usersite = sysconfig.get_path('purelib', '%s_user' % os.name)

This is the directory pip uses if you install --user.

From __peter__ at web.de  Sun May 19 10:05:57 2013
From: __peter__ at web.de (Peter Otten)
Date: Sun, 19 May 2013 10:05:57 +0200
Subject: [Tutor] Retrieving data from a web site
References: <5196C3F7.6030507@bigpond.com> <kn77bl$c10$1@ger.gmane.org>
	<51973EA2.6040007@bigpond.com> <kn7hda$tr7$1@ger.gmane.org>
	<51975509.2020102@bigpond.com> <kn7t3n$1sr$1@ger.gmane.org>
	<CANLXbfDHgz71_0C2uK=LGz46RqsPNfguN6svox=LpLaN+QnPLw@mail.gmail.com>
	<51985CAC.2000908@bigpond.com>
Message-ID: <kna14r$g3o$1@ger.gmane.org>

Phil wrote:

> My apatite having been whetted I'm now stymied because of a Ubuntu
> dependency problem during the installation of urllib3. This is listed as
> a bug. Has anyone overcome this problem?
> 
> Perhaps there's another library that I can use to download data from a
> web page?

You mean you are using Python 3? The replacement for urllib2 in Python 3 is 
urllib.request and a few others. There is a tool called 2to3 that can help 
you with the transition.

The original Python 2 code:

 $ cat parse.py 
import urllib2
import json

url = "http://*********/goldencasket"
s = urllib2.urlopen(url).read()

s = s.partition("latestResults_productResults")[2].lstrip(" =")
s = s.partition(";")[0]
data = json.loads(s)
lotto = data["GoldLottoSaturday"]
print lotto["drawDayDateNumber"]
print map(int, lotto["primaryNumbers"])
print map(int, lotto["secondaryNumbers"])
$ python parse.py 
Sat 18/May/13, Draw 3321
[14, 31, 16, 25, 6, 3]
[9, 35]

Now let's apply 2to3 (I'm using the version that comes with python3.3).
The -w option tells the script to overwrite the original source:

$ 2to3-3.3 parse.py -w
[noisy output omitted]

The script now looks like this:

$ cat parse.py
import urllib.request, urllib.error, urllib.parse
import json

url = "http://*********/goldencasket"
s = urllib.request.urlopen(url).read()

s = s.partition("latestResults_productResults")[2].lstrip(" =")
s = s.partition(";")[0]
data = json.loads(s)
lotto = data["GoldLottoSaturday"]
print(lotto["drawDayDateNumber"])
print(list(map(int, lotto["primaryNumbers"])))
print(list(map(int, lotto["secondaryNumbers"])))
$ python3.3 parse.py
Traceback (most recent call last):
  File "parse.py", line 7, in <module>
    s = s.partition("latestResults_productResults")[2].lstrip(" =")
TypeError: expected bytes, bytearray or buffer compatible object

After manually changing the line

s = urllib.request.urlopen(url).read()

to

s = urllib.request.urlopen(url).read().decode()

$ python3.3 parse.py
Sat 18/May/13, Draw 3321
[14, 31, 16, 25, 6, 3]
[9, 35]
$ 


From chigga101 at gmail.com  Sun May 19 12:35:56 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Sun, 19 May 2013 11:35:56 +0100
Subject: [Tutor] model methods in Django
In-Reply-To: <CACL+1ausZVbdkpTUR0HaRTsxLogSiPxk4ra1YsqvzwO8wGSYvA@mail.gmail.com>
References: <CACzNyA3zu32s88-gW8G4RcO+UoSUQ4nycDrYEMpD5rDGwdM8Bg@mail.gmail.com>
	<51983757.3020504@davea.name>
	<CACL+1ausZVbdkpTUR0HaRTsxLogSiPxk4ra1YsqvzwO8wGSYvA@mail.gmail.com>
Message-ID: <CACzNyA3M_zr5ykX11w+dRJtUaGcY-wEV7Ga_Bkr_aD_cEByh4w@mail.gmail.com>

Thanks guys i had no idea about these  method attributes and also
these underlying oop  __objects__

@ eryksun
i understand your explanation, im still having trouble figuring out
how django is being used in the tutorial.

class Poll(models.Model):
    # ...
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'
    list_filter = ['pub_date']
    search_fields = ['question']
    date_hierarchy = 'pub_date'


if you look at the diagram under that function, why is the value of
"was_published_recently.short_description" the title of that field?
replacing the old title? is a "short_desccription" attribute set
somewhere in django being inactive, but once you make use of this
attribute(or keyword), whatever the value is automatically becomes the
field title? is it the same for boolean being the value of the field
with the checked or unchecked symbol?

From fomcl at yahoo.com  Sun May 19 12:54:03 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sun, 19 May 2013 03:54:03 -0700 (PDT)
Subject: [Tutor] why is unichr(sys.maxunicode) blank?
In-Reply-To: <51982C34.5010606@pearwood.info>
References: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<5196FA52.9090000@pearwood.info>
	<1368871300.10705.YahooMailNeo@web163805.mail.gq1.yahoo.com>
	<CACL+1av_5Y8ZX1qdtdojmLRdbeLPNwO_cZ70c-yyD8t6sHbT0g@mail.gmail.com>
	<1368895532.71831.YahooMailNeo@web163803.mail.gq1.yahoo.com>
	<51982C34.5010606@pearwood.info>
Message-ID: <1368960843.38846.YahooMailNeo@web163803.mail.gq1.yahoo.com>



----- Original Message -----

> From: Steven D'Aprano <steve at pearwood.info>
> To: tutor at python.org
> Cc: 
> Sent: Sunday, May 19, 2013 3:34 AM
> Subject: Re: [Tutor] why is unichr(sys.maxunicode) blank?
> 
> On 19/05/13 02:45, Albert-Jan Roskam wrote about locales:
> 
>>  It is pretty sick that all these things can be adjusted separately (what is 
> the use of having: danish collation, russian case conversion, english decimal 
> sign, japanese codepage ;-)
> 
> Well obviously there is no point to such a mess, but the ability to make a mess 
> comes from having the flexibility to have less silly combinations.
> 
> By the way, I'm not sure what you mean by "pretty sick", since in 
> Australian slang "sick" can mean "fantastic, excellent", as 
> in "Mate, that's a pretty sick sub-woofer!".

I was under the impression that all these locale categories created a degree of flexibility that is far greater than one would need in daily practice. Eryksun's non-esoteric (note the lack of use of the term "sick" ;-) example convinced me that this is not the case. So all in all, the flexibility is sick after all, not in the literal sense, but in the Australian sense of the word.


From eryksun at gmail.com  Sun May 19 13:04:46 2013
From: eryksun at gmail.com (eryksun)
Date: Sun, 19 May 2013 07:04:46 -0400
Subject: [Tutor] model methods in Django
In-Reply-To: <CACzNyA3M_zr5ykX11w+dRJtUaGcY-wEV7Ga_Bkr_aD_cEByh4w@mail.gmail.com>
References: <CACzNyA3zu32s88-gW8G4RcO+UoSUQ4nycDrYEMpD5rDGwdM8Bg@mail.gmail.com>
	<51983757.3020504@davea.name>
	<CACL+1ausZVbdkpTUR0HaRTsxLogSiPxk4ra1YsqvzwO8wGSYvA@mail.gmail.com>
	<CACzNyA3M_zr5ykX11w+dRJtUaGcY-wEV7Ga_Bkr_aD_cEByh4w@mail.gmail.com>
Message-ID: <CACL+1atJPermoSUdBnvKEHmLnm1HCmfeAhrAjm3JWtLugg_Kdw@mail.gmail.com>

On Sun, May 19, 2013 at 6:35 AM, Matthew Ngaha <chigga101 at gmail.com> wrote:
>
> if you look at the diagram under that function, why is the value of
> "was_published_recently.short_description" the title of that field?
> replacing the old title? is a "short_desccription" attribute set
> somewhere in django being inactive, but once you make use of this
> attribute(or keyword), whatever the value is automatically becomes the
> field title? is it the same for boolean being the value of the field
> with the checked or unchecked symbol?

For example, see line 586 in admin/options.py:

https://github.com/django/django/blob/1.5.1/django/contrib/admin/options.py#L586

        # Gather actions from the admin site first
        for (name, func) in self.admin_site.actions:
            description = getattr(func, 'short_description',
name.replace('_', ' '))
            actions.append((func, name, description))

The default description is the name with underscores removed, unless
you set a custom description in the function's "short_description"
attribute. I'm not experienced with Django, so I can't ramble off lots
of examples, but hopefully you get the gist.

From chigga101 at gmail.com  Sun May 19 13:20:02 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Sun, 19 May 2013 12:20:02 +0100
Subject: [Tutor] model methods in Django
In-Reply-To: <CACL+1atJPermoSUdBnvKEHmLnm1HCmfeAhrAjm3JWtLugg_Kdw@mail.gmail.com>
References: <CACzNyA3zu32s88-gW8G4RcO+UoSUQ4nycDrYEMpD5rDGwdM8Bg@mail.gmail.com>
	<51983757.3020504@davea.name>
	<CACL+1ausZVbdkpTUR0HaRTsxLogSiPxk4ra1YsqvzwO8wGSYvA@mail.gmail.com>
	<CACzNyA3M_zr5ykX11w+dRJtUaGcY-wEV7Ga_Bkr_aD_cEByh4w@mail.gmail.com>
	<CACL+1atJPermoSUdBnvKEHmLnm1HCmfeAhrAjm3JWtLugg_Kdw@mail.gmail.com>
Message-ID: <CACzNyA2WXK-ExE15r8-33bEf3wtkUR7yn3FHjRDSc64NSSfXDQ@mail.gmail.com>

> The default description is the name with underscores removed, unless
> you set a custom description in the function's "short_description"
> attribute. I'm not experienced with Django, so I can't ramble off lots
> of examples, but hopefully you get the gist.

Thanks that does clear it up. Also thats a huge script you linked, can
i ask which framework you're coming from, and why you have decided to
try out django? When i asked around, people's opinions of it weren't
good and i was recommended to try flask but as i only use Python 3, i
won't be able to use Flask.

From phil_lor at bigpond.com  Sun May 19 13:30:05 2013
From: phil_lor at bigpond.com (Phil)
Date: Sun, 19 May 2013 21:30:05 +1000
Subject: [Tutor] Retrieving data from a web site
In-Reply-To: <kna14r$g3o$1@ger.gmane.org>
References: <5196C3F7.6030507@bigpond.com> <kn77bl$c10$1@ger.gmane.org>
	<51973EA2.6040007@bigpond.com> <kn7hda$tr7$1@ger.gmane.org>
	<51975509.2020102@bigpond.com> <kn7t3n$1sr$1@ger.gmane.org>
	<CANLXbfDHgz71_0C2uK=LGz46RqsPNfguN6svox=LpLaN+QnPLw@mail.gmail.com>
	<51985CAC.2000908@bigpond.com> <kna14r$g3o$1@ger.gmane.org>
Message-ID: <5198B7BD.60208@bigpond.com>

On 19/05/13 18:05, Peter Otten wrote:
> Phil wrote:
>
>> My apatite having been whetted I'm now stymied because of a Ubuntu
>> dependency problem during the installation of urllib3. This is listed as
>> a bug. Has anyone overcome this problem?
>>
>> Perhaps there's another library that I can use to download data from a
>> web page?
>
> You mean you are using Python 3? The replacement for urllib2 in Python 3 is
> urllib.request and a few others. There is a tool called 2to3 that can help
> you with the transition.
>

Thank you once again Peter for a very helpful reply.

Under Ubuntu (I'm actually using Kubuntu) the packages are 
python-urllib3 (for python 2) and python3-urllib3. Unfortunately neither 
will install because of a dependency issue with libbz2-1.0. So I'll have 
to put this project on hold until the bug is resolved.

-- 
Regards,
Phil

From davea at davea.name  Sun May 19 13:46:09 2013
From: davea at davea.name (Dave Angel)
Date: Sun, 19 May 2013 07:46:09 -0400
Subject: [Tutor] Retrieving data from a web site
In-Reply-To: <5198B7BD.60208@bigpond.com>
References: <5196C3F7.6030507@bigpond.com> <kn77bl$c10$1@ger.gmane.org>
	<51973EA2.6040007@bigpond.com> <kn7hda$tr7$1@ger.gmane.org>
	<51975509.2020102@bigpond.com> <kn7t3n$1sr$1@ger.gmane.org>
	<CANLXbfDHgz71_0C2uK=LGz46RqsPNfguN6svox=LpLaN+QnPLw@mail.gmail.com>
	<51985CAC.2000908@bigpond.com> <kna14r$g3o$1@ger.gmane.org>
	<5198B7BD.60208@bigpond.com>
Message-ID: <5198BB81.1040105@davea.name>

On 05/19/2013 07:30 AM, Phil wrote:
> On 19/05/13 18:05, Peter Otten wrote:
>> Phil wrote:
>>
>>> My apatite having been whetted I'm now stymied because of a Ubuntu
>>> dependency problem during the installation of urllib3. This is listed as
>>> a bug. Has anyone overcome this problem?
>>>
>>> Perhaps there's another library that I can use to download data from a
>>> web page?
>>
>> You mean you are using Python 3? The replacement for urllib2 in Python
>> 3 is
>> urllib.request and a few others. There is a tool called 2to3 that can
>> help
>> you with the transition.
>>
>
> Thank you once again Peter for a very helpful reply.
>
> Under Ubuntu (I'm actually using Kubuntu) the packages are
> python-urllib3 (for python 2) and python3-urllib3. Unfortunately neither
> will install because of a dependency issue with libbz2-1.0. So I'll have
> to put this project on hold until the bug is resolved.
>

Have you simply tried using urlib.request ?  That should be built into 
Python 3.3 without any outside packages from Kubuntu.  (I haven't used 
Kubuntu, just making some bald assumptions)


-- 
DaveA

From bgailer at gmail.com  Sun May 19 01:21:12 2013
From: bgailer at gmail.com (bob gailer)
Date: Sat, 18 May 2013 19:21:12 -0400
Subject: [Tutor] Fwd: spyder
In-Reply-To: <51980CAC.2080700@gmail.com>
References: <51980CAC.2080700@gmail.com>
Message-ID: <51980CE8.6000805@gmail.com>

-------- Original Message --------
Subject: 	spyder
Date: 	Sat, 18 May 2013 19:20:12 -0400
From: 	bob gailer <bgailer at gmail.com>
To: 	ricaraoz at gmail.com



Following your recommendation I installed spyder using the Windows
installer.

Now what do I do to run it. I found no useful guidance in the online
documentation.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC




From rafael.knuth at gmail.com  Sun May 19 15:04:32 2013
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Sun, 19 May 2013 15:04:32 +0200
Subject: [Tutor] Beginner level: Why doesn't my code work?
Message-ID: <CAM-E2X4iYCpRNm40UL7i=s6dz26sMcx=VKb2iAutSLLtJ7xHbw@mail.gmail.com>

Hello,

here's a tiny little program I wrote:

import random

print("""

This is a magic super computer.

He will ask you a couple of questions.

An ultra-complicated algorithm will then figure out what your favorite meal
is.

""")

name = str(input("What is your name? "))

age = int(input("How old are you? "))

birthplace = str(input("Where are you born? "))

meal = random.randint(1, 3)

if meal == 1:
    print("Well, " + name + " as a " + str(age) + " year old human being
born in " + birthplace + " you probably like hamburgers.")

elif meal == 2:
    print("Well, " + name + " as a " + str(age) + " year old human being
born in " + birthplace + " you probably like sushi.")

elif meal == 3:
    print("Well, " + name + " as a " + str(age) + " year old human being
born in " + birthplace + "you probably like pizza.")

Here's the error message I am getting:

Traceback (most recent call last):
  File "/home/rafael/Documents/3_Tufcik.py", line 13, in <module>
    name = str(input("What is your name? "))
  File "<string>", line 1, in <module>
NameError: name 'Rafael' is not defined


Can anyone help?
Thanks in advance!

Rafael
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130519/cbdb1c9e/attachment.html>

From phil_lor at bigpond.com  Sun May 19 14:08:02 2013
From: phil_lor at bigpond.com (Phil)
Date: Sun, 19 May 2013 22:08:02 +1000
Subject: [Tutor] Retrieving data from a web site
In-Reply-To: <5198BB81.1040105@davea.name>
References: <5196C3F7.6030507@bigpond.com> <kn77bl$c10$1@ger.gmane.org>
	<51973EA2.6040007@bigpond.com> <kn7hda$tr7$1@ger.gmane.org>
	<51975509.2020102@bigpond.com> <kn7t3n$1sr$1@ger.gmane.org>
	<CANLXbfDHgz71_0C2uK=LGz46RqsPNfguN6svox=LpLaN+QnPLw@mail.gmail.com>
	<51985CAC.2000908@bigpond.com> <kna14r$g3o$1@ger.gmane.org>
	<5198B7BD.60208@bigpond.com> <5198BB81.1040105@davea.name>
Message-ID: <5198C0A2.7040600@bigpond.com>

On 19/05/13 21:46, Dave Angel wrote:
>
> Have you simply tried using urlib.request ?  That should be built into
> Python 3.3 without any outside packages from Kubuntu.  (I haven't used
> Kubuntu, just making some bald assumptions)
Thanks Dave,

Thanks Dave,

The urllib.request package has the same dependency problem. I haven't 
checked to see if it's built into Python yet, it's getting a bit late 
here. A job for tomorrow.

-- 
Regards,
Phil

From oscar.j.benjamin at gmail.com  Sun May 19 15:16:31 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Sun, 19 May 2013 14:16:31 +0100
Subject: [Tutor] Beginner level: Why doesn't my code work?
In-Reply-To: <CAM-E2X4iYCpRNm40UL7i=s6dz26sMcx=VKb2iAutSLLtJ7xHbw@mail.gmail.com>
References: <CAM-E2X4iYCpRNm40UL7i=s6dz26sMcx=VKb2iAutSLLtJ7xHbw@mail.gmail.com>
Message-ID: <CAHVvXxSZXFfKgwVF44uTki-U6n7dQGLJqOiyewS9UgNdcyFYNg@mail.gmail.com>

On 19 May 2013 14:04, Rafael Knuth <rafael.knuth at gmail.com> wrote:
> Hello,

Hello, please post in plain text (not html) in future. Also you should
mention what version of Python you're using as it makes a dfference in
this case.

>
> here's a tiny little program I wrote:
>
> import random
>
> print("""
>
> This is a magic super computer.
>
> He will ask you a couple of questions.
>
> An ultra-complicated algorithm will then figure out what your favorite meal
> is.
>
> """)
>
> name = str(input("What is your name? "))

In Python 3 you should use input(). In Python 2 you should use
raw_input(). I'm guessing that you're using Python 2. In Python 2 the
input() function tries to evaluate whatever the user types in as if it
was Python code. Since Rafael is not a defined variable it fails. The
fix is to use raw_input() which just returns a string.

An alternative fix is to write

input = raw_input

at the top of your script. That way you won't need to change anything
else to have it work with Python 3. In fact if you write it like this

try:
    input = raw_input
except NameError:
    pass

then it will work in both Python 2 and 3.

> Here's the error message I am getting:
>
> Traceback (most recent call last):
>   File "/home/rafael/Documents/3_Tufcik.py", line 13, in <module>
>     name = str(input("What is your name? "))
>   File "<string>", line 1, in <module>
> NameError: name 'Rafael' is not defined


Oscar

From johnsteedman360 at gmail.com  Sun May 19 15:17:59 2013
From: johnsteedman360 at gmail.com (John Steedman)
Date: Sun, 19 May 2013 14:17:59 +0100
Subject: [Tutor] model methods in Django
In-Reply-To: <CACzNyA3zu32s88-gW8G4RcO+UoSUQ4nycDrYEMpD5rDGwdM8Bg@mail.gmail.com>
References: <CACzNyA3zu32s88-gW8G4RcO+UoSUQ4nycDrYEMpD5rDGwdM8Bg@mail.gmail.com>
Message-ID: <CAF50Yh_7_zsVHOPGk2dyDgcqrf+oo72i=rW1=OGZ0O_hegTWSg@mail.gmail.com>

For the benefit of others,I believe the full class (from the Django
Tutorial) is

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    #

    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'


Source:
https://docs.djangoproject.com/en/dev/intro/tutorial01/
https://docs.djangoproject.com/en/dev/intro/tutorial02/


I find the Django (and this fragment) very elegant UP TO the comment.


On Sat, May 18, 2013 at 8:16 PM, Matthew Ngaha <chigga101 at gmail.com> wrote:

>  im following the official docs and after learning Python im sure of
> how methods work, but the model example on the beginners guide has me
> really confused.
>
> The model definition is omitted but can anyone explain how this methed
> (was_published_recently) is given these attributes:
>
> class Poll(models.Model):
>     # ...
>     def was_published_recently(self):
>         return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
>     was_published_recently.admin_order_field = 'pub_date'
>     was_published_recently.boolean = True
>     was_published_recently.short_description = 'Published recently?'
>
> are the names of the attributes already attached to these
> functions/methods, or are they being created on the fly with whatever
> name you want? As i am unable to comprehend what is going on, i dont
> really have a clue as to what each definition is doing and how it
> affects the model, even after reading this section of the docs over
> and over again im still lost.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130519/d21821ac/attachment.html>

From rafael.knuth at gmail.com  Sun May 19 15:38:43 2013
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Sun, 19 May 2013 15:38:43 +0200
Subject: [Tutor] Beginner level: Why doesn't my code work?
In-Reply-To: <CAHVvXxSZXFfKgwVF44uTki-U6n7dQGLJqOiyewS9UgNdcyFYNg@mail.gmail.com>
References: <CAM-E2X4iYCpRNm40UL7i=s6dz26sMcx=VKb2iAutSLLtJ7xHbw@mail.gmail.com>
	<CAHVvXxSZXFfKgwVF44uTki-U6n7dQGLJqOiyewS9UgNdcyFYNg@mail.gmail.com>
Message-ID: <CAM-E2X4nM239G9Y-t5j2-u70CyRo6x7OwSXWCLtRVhkpDrnhQA@mail.gmail.com>

Hello, please post in plain text (not html) in future. Also you should
mention what version of Python you're using as it makes a dfference in
this case.

Thank you, I am using Python 3.3.0
As for the HTML ... I copied the code from the Python Shell - should I post
code as a screenshot?
Would that resolve that issue you mentioned?

In Python 3 you should use input(). In Python 2 you should use
raw_input(). I'm guessing that you're using Python 2. In Python 2 the
input() function tries to evaluate whatever the user types in as if it
was Python code. Since Rafael is not a defined variable it fails. The
fix is to use raw_input() which just returns a string.

I am not sure I understand.
"Rafael" is the user's in put, and that value is assigned to the variable
"name".
I made sure only a string is accepted as input

name = (str(input("What's your name?"))

Can you clarify? Thank you in advance.


On Sun, May 19, 2013 at 3:16 PM, Oscar Benjamin
<oscar.j.benjamin at gmail.com>wrote:

> On 19 May 2013 14:04, Rafael Knuth <rafael.knuth at gmail.com> wrote:
> > Hello,
>
> Hello, please post in plain text (not html) in future. Also you should
> mention what version of Python you're using as it makes a dfference in
> this case.
>
> >
> > here's a tiny little program I wrote:
> >
> > import random
> >
> > print("""
> >
> > This is a magic super computer.
> >
> > He will ask you a couple of questions.
> >
> > An ultra-complicated algorithm will then figure out what your favorite
> meal
> > is.
> >
> > """)
> >
> > name = str(input("What is your name? "))
>
> In Python 3 you should use input(). In Python 2 you should use
> raw_input(). I'm guessing that you're using Python 2. In Python 2 the
> input() function tries to evaluate whatever the user types in as if it
> was Python code. Since Rafael is not a defined variable it fails. The
> fix is to use raw_input() which just returns a string.
>
> An alternative fix is to write
>
> input = raw_input
>
> at the top of your script. That way you won't need to change anything
> else to have it work with Python 3. In fact if you write it like this
>
> try:
>     input = raw_input
> except NameError:
>     pass
>
> then it will work in both Python 2 and 3.
>
> > Here's the error message I am getting:
> >
> > Traceback (most recent call last):
> >   File "/home/rafael/Documents/3_Tufcik.py", line 13, in <module>
> >     name = str(input("What is your name? "))
> >   File "<string>", line 1, in <module>
> > NameError: name 'Rafael' is not defined
>
>
> Oscar
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130519/8a06e999/attachment-0001.html>

From eryksun at gmail.com  Sun May 19 15:55:48 2013
From: eryksun at gmail.com (eryksun)
Date: Sun, 19 May 2013 09:55:48 -0400
Subject: [Tutor] model methods in Django
In-Reply-To: <CACzNyA2WXK-ExE15r8-33bEf3wtkUR7yn3FHjRDSc64NSSfXDQ@mail.gmail.com>
References: <CACzNyA3zu32s88-gW8G4RcO+UoSUQ4nycDrYEMpD5rDGwdM8Bg@mail.gmail.com>
	<51983757.3020504@davea.name>
	<CACL+1ausZVbdkpTUR0HaRTsxLogSiPxk4ra1YsqvzwO8wGSYvA@mail.gmail.com>
	<CACzNyA3M_zr5ykX11w+dRJtUaGcY-wEV7Ga_Bkr_aD_cEByh4w@mail.gmail.com>
	<CACL+1atJPermoSUdBnvKEHmLnm1HCmfeAhrAjm3JWtLugg_Kdw@mail.gmail.com>
	<CACzNyA2WXK-ExE15r8-33bEf3wtkUR7yn3FHjRDSc64NSSfXDQ@mail.gmail.com>
Message-ID: <CACL+1atMFQdqDySQWBnxUXXLce+L3MwZ=cZxCDk32JTbJb4xcg@mail.gmail.com>

On Sun, May 19, 2013 at 7:20 AM, Matthew Ngaha <chigga101 at gmail.com> wrote:
> Thanks that does clear it up. Also thats a huge script you linked, can

options.py is the biggest module in the admin package. The link I
posted is to the get_actions method of ModelAdmin. In the tutorial,
PollAdmin extends this class.

> i ask which framework you're coming from, and why you have decided to
> try out django? When i asked around, people's opinions of it weren't
> good and i was recommended to try flask but as i only use Python 3, i
> won't be able to use Flask.

I'm not coming from any framework. My knowledge of web development is
scattered from bits learned here and there, out of curiosity rather
than necessity. With Python 3 you're a bit limited, but you still have
options. Obviously there's Django -- arguably the most popular,
batteries-included framework. Pyramid is a leaner alternative. Bottle
and CherryPy (also a WSGI server) are micro frameworks. There's also
Tornado if you want an asynchronous framework based on callbacks and
coroutines.

From chigga101 at gmail.com  Sun May 19 16:23:27 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Sun, 19 May 2013 15:23:27 +0100
Subject: [Tutor] model methods in Django
In-Reply-To: <CAF50Yh_7_zsVHOPGk2dyDgcqrf+oo72i=rW1=OGZ0O_hegTWSg@mail.gmail.com>
References: <CACzNyA3zu32s88-gW8G4RcO+UoSUQ4nycDrYEMpD5rDGwdM8Bg@mail.gmail.com>
	<CAF50Yh_7_zsVHOPGk2dyDgcqrf+oo72i=rW1=OGZ0O_hegTWSg@mail.gmail.com>
Message-ID: <CACzNyA0mXUFMOVCCaZ79VZVDX=ptpMCJQw59U2r95TH=1HFgsg@mail.gmail.com>

> class Poll(models.Model):
>
>     question = models.CharField(max_length=200)
>     pub_date = models.DateTimeField('date published')
>
>
>
>     def was_published_recently(self):
>         return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
>
>     #
>
>
>     was_published_recently.admin_order_field = 'pub_date'
>     was_published_recently.boolean = True
>     was_published_recently.short_description = 'Published recently?'
>
>
> Source:
> https://docs.djangoproject.com/en/dev/intro/tutorial01/
> https://docs.djangoproject.com/en/dev/intro/tutorial02/
>
>
> I find the Django (and this fragment) very elegant UP TO the comment.
>
is the dislike after the comment more to do with the python code
rather than django itself?

From chigga101 at gmail.com  Sun May 19 16:31:48 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Sun, 19 May 2013 15:31:48 +0100
Subject: [Tutor] model methods in Django
In-Reply-To: <CACL+1atMFQdqDySQWBnxUXXLce+L3MwZ=cZxCDk32JTbJb4xcg@mail.gmail.com>
References: <CACzNyA3zu32s88-gW8G4RcO+UoSUQ4nycDrYEMpD5rDGwdM8Bg@mail.gmail.com>
	<51983757.3020504@davea.name>
	<CACL+1ausZVbdkpTUR0HaRTsxLogSiPxk4ra1YsqvzwO8wGSYvA@mail.gmail.com>
	<CACzNyA3M_zr5ykX11w+dRJtUaGcY-wEV7Ga_Bkr_aD_cEByh4w@mail.gmail.com>
	<CACL+1atJPermoSUdBnvKEHmLnm1HCmfeAhrAjm3JWtLugg_Kdw@mail.gmail.com>
	<CACzNyA2WXK-ExE15r8-33bEf3wtkUR7yn3FHjRDSc64NSSfXDQ@mail.gmail.com>
	<CACL+1atMFQdqDySQWBnxUXXLce+L3MwZ=cZxCDk32JTbJb4xcg@mail.gmail.com>
Message-ID: <CACzNyA3JyTNi5ho4J+43B7F1kknh+-73i22pqTg7ZHcJ6rd9oA@mail.gmail.com>

 > options.py is the biggest module in the admin package. The link I
> posted is to the get_actions method of ModelAdmin. In the tutorial,
> PollAdmin extends this class.
>
oh ok thanks, yes i will definately look through it

> I'm not coming from any framework. My knowledge of web development is
> scattered from bits learned here and there, out of curiosity rather
> than necessity. With Python 3 you're a bit limited, but you still have
> options. Obviously there's Django -- arguably the most popular,
> batteries-included framework. Pyramid is a leaner alternative. Bottle
> and CherryPy (also a WSGI server) are micro frameworks. There's also
> Tornado if you want an asynchronous framework based on callbacks and
> coroutines.

As there are a lot more guides for Django i think i will stick with it
rather than Pyramid. Maybe after ive learnt it well i can pick up
Cherrypy as i like the sounds of a small framework with a server. But
Django will be my main focus. Thanks for detailing the options for
Python 3

From steve at pearwood.info  Sun May 19 16:31:59 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 20 May 2013 00:31:59 +1000
Subject: [Tutor] Beginner level: Why doesn't my code work?
In-Reply-To: <CAM-E2X4nM239G9Y-t5j2-u70CyRo6x7OwSXWCLtRVhkpDrnhQA@mail.gmail.com>
References: <CAM-E2X4iYCpRNm40UL7i=s6dz26sMcx=VKb2iAutSLLtJ7xHbw@mail.gmail.com>
	<CAHVvXxSZXFfKgwVF44uTki-U6n7dQGLJqOiyewS9UgNdcyFYNg@mail.gmail.com>
	<CAM-E2X4nM239G9Y-t5j2-u70CyRo6x7OwSXWCLtRVhkpDrnhQA@mail.gmail.com>
Message-ID: <5198E25F.1030608@pearwood.info>

On 19/05/13 23:38, Rafael Knuth wrote:

> Thank you, I am using Python 3.3.0

Based on the error you show, I doubt that very much.

> As for the HTML ... I copied the code from the Python Shell - should I post
> code as a screenshot?
> Would that resolve that issue you mentioned?

No. It has nothing to do with the Python shell, it has to do with your email program.

Your email program will probably have an option somewhere to send "Rich Text" or "Styled Text" or "HTML Text". Turn it off. There are many reasons to avoid it, but as far as this mailing list goes, the main one is that it mangles the code you send and makes it harder to answer your questions.



> "Rafael" is the user's in put, and that value is assigned to the variable
> "name".
> I made sure only a string is accepted as input
>
> name = (str(input("What's your name?"))

The call to str() is unnecessary.

In Python 3, this works as you would expect:

# Python 3.3
py> name = input("What's your name? ")
What's your name? Raphael
py> print(name)
Raphael


But when you run it, that's not the result you get. You get this result:

# Python 2.7
py> name = input("What's your name? ")
What's your name? Raphael
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<string>", line 1, in <module>
NameError: name 'Raphael' is not defined


This tells me very strongly that you are actually using Python 2, not Python 3.

Try this: at the very beginning of your file 3_Tufcik.py, put these two lines:

import sys
print(sys.version)


then run the file as you would normally, and see what it prints.



-- 
Steven

From steve at pearwood.info  Sun May 19 16:34:39 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 20 May 2013 00:34:39 +1000
Subject: [Tutor] model methods in Django
In-Reply-To: <CACzNyA0mXUFMOVCCaZ79VZVDX=ptpMCJQw59U2r95TH=1HFgsg@mail.gmail.com>
References: <CACzNyA3zu32s88-gW8G4RcO+UoSUQ4nycDrYEMpD5rDGwdM8Bg@mail.gmail.com>
	<CAF50Yh_7_zsVHOPGk2dyDgcqrf+oo72i=rW1=OGZ0O_hegTWSg@mail.gmail.com>
	<CACzNyA0mXUFMOVCCaZ79VZVDX=ptpMCJQw59U2r95TH=1HFgsg@mail.gmail.com>
Message-ID: <5198E2FF.6040600@pearwood.info>

Matthew, who are you quoting? Your email program should automatically insert an attribution line, such as the one just below. Without that attribution line, it is hard to follow the conversation, as we can't tell who you are quoting.

On 20/05/13 00:23, Matthew Ngaha wrote:
>> class Poll(models.Model):
[...]


-- 
Steven

From __peter__ at web.de  Sun May 19 16:54:28 2013
From: __peter__ at web.de (Peter Otten)
Date: Sun, 19 May 2013 16:54:28 +0200
Subject: [Tutor] Beginner level: Why doesn't my code work?
References: <CAM-E2X4iYCpRNm40UL7i=s6dz26sMcx=VKb2iAutSLLtJ7xHbw@mail.gmail.com>
	<CAHVvXxSZXFfKgwVF44uTki-U6n7dQGLJqOiyewS9UgNdcyFYNg@mail.gmail.com>
	<CAM-E2X4nM239G9Y-t5j2-u70CyRo6x7OwSXWCLtRVhkpDrnhQA@mail.gmail.com>
Message-ID: <knap2p$3ks$1@ger.gmane.org>

Rafael Knuth wrote:

> Thank you, I am using Python 3.3.0

[Oscar]
> In Python 3 you should use input(). In Python 2 you should use
> raw_input(). I'm guessing that you're using Python 2. In Python 2 the
> input() function tries to evaluate whatever the user types in as if it
> was Python code. Since Rafael is not a defined variable it fails. The
> fix is to use raw_input() which just returns a string.

 
[Rafael] 
> I am not sure I understand.
> "Rafael" is the user's in put, and that value is assigned to the variable
> "name".
> I made sure only a string is accepted as input
> 
> name = (str(input("What's your name?"))
> 
> Can you clarify? Thank you in advance.

As Oscar says you are invoking your script with Python 2. Python 2's input() 
function evals user input as a Python expression. For example if you run a 
script

print input("your input please: ")

and you type

1 + 1

the script will print

2

Likewise if you type

Rafael

the script will look up the value of a variable named Rafael. This doesn't 
exist and therefore you get an exception.

But this is all a distraction -- how exactly are you invoking what you think 
is Python 3.3.0? What is your operating system?

If you are using Linux or OSX open a terminal window and try to run your 
script from that terminal window with

python3.3 ~/Documents/3_Tufcik.py



From chigga101 at gmail.com  Sun May 19 16:49:54 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Sun, 19 May 2013 15:49:54 +0100
Subject: [Tutor] model methods in Django
In-Reply-To: <5198E2FF.6040600@pearwood.info>
References: <CACzNyA3zu32s88-gW8G4RcO+UoSUQ4nycDrYEMpD5rDGwdM8Bg@mail.gmail.com>
	<CAF50Yh_7_zsVHOPGk2dyDgcqrf+oo72i=rW1=OGZ0O_hegTWSg@mail.gmail.com>
	<CACzNyA0mXUFMOVCCaZ79VZVDX=ptpMCJQw59U2r95TH=1HFgsg@mail.gmail.com>
	<5198E2FF.6040600@pearwood.info>
Message-ID: <CACzNyA1LsD96ppao9FmRTFUci+aM8BZvNcXqudO8wC+2OEdsbg@mail.gmail.com>

On Sun, May 19, 2013 at 3:34 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> Matthew, who are you quoting? Your email program should automatically insert
> an attribution line, such as the one just below. Without that attribution
> line, it is hard to follow the conversation, as we can't tell who you are
> quoting.
>
> On 20/05/13 00:23, Matthew Ngaha wrote:

ok thanks i didnt think about that. I was quoting eryksun. I'll
includethat line from now on

From eryksun at gmail.com  Sun May 19 17:24:21 2013
From: eryksun at gmail.com (eryksun)
Date: Sun, 19 May 2013 11:24:21 -0400
Subject: [Tutor] model methods in Django
In-Reply-To: <CACzNyA1LsD96ppao9FmRTFUci+aM8BZvNcXqudO8wC+2OEdsbg@mail.gmail.com>
References: <CACzNyA3zu32s88-gW8G4RcO+UoSUQ4nycDrYEMpD5rDGwdM8Bg@mail.gmail.com>
	<CAF50Yh_7_zsVHOPGk2dyDgcqrf+oo72i=rW1=OGZ0O_hegTWSg@mail.gmail.com>
	<CACzNyA0mXUFMOVCCaZ79VZVDX=ptpMCJQw59U2r95TH=1HFgsg@mail.gmail.com>
	<5198E2FF.6040600@pearwood.info>
	<CACzNyA1LsD96ppao9FmRTFUci+aM8BZvNcXqudO8wC+2OEdsbg@mail.gmail.com>
Message-ID: <CACL+1auSjrpjvtMPrmVmqkXwW==mbXR=pw8nAfaOOm9hvn4Cig@mail.gmail.com>

On Sun, May 19, 2013 at 10:49 AM, Matthew Ngaha <chigga101 at gmail.com> wrote:
> On Sun, May 19, 2013 at 3:34 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> Matthew, who are you quoting? Your email program should automatically insert
>> an attribution line, such as the one just below. Without that attribution
>> line, it is hard to follow the conversation, as we can't tell who you are
>> quoting.
>
> ok thanks i didnt think about that. I was quoting eryksun. I'll
> includethat line from now on

I think this was in reference to your reply to John Steedman. Here's
the archive thread (based on the "In-Reply-To" header field):

http://mail.python.org/pipermail/tutor/2013-May/thread.html#95521

From cybervigilante at gmail.com  Mon May 20 03:30:58 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sun, 19 May 2013 18:30:58 -0700
Subject: [Tutor] from import works but I'm flubbing a package import
Message-ID: <CALRAYNVOqBUYx4DQ8Zam_jy1rcX9pXiRTsgR=gCKt3WEsgV1RQ@mail.gmail.com>

Still puzzling on imports.

I have the jimlib module in Lib with the proper __init__.py . Inside
it is the program bark.py, with data item zarf that contains string
'fraz'

It also contains the function barker.

def barker():
   print 'bark, bark'

If I do the below everything works:

from jimlib import bark

print bark.zarf

bark.barker()

But if I just do

import jimlib and chain the program and its functions or data

nothing works.

If I try jimlib.bark.barker() after importing jimlib or print
jimlib.bark.zarf I get the error that the module has no attribute
'bark'

I'm doing the from statement right but what am I doing wrong with just
importing the whole module and chaining out bark (for bark.py) and the
function or data following?

Using Py27 and Win 7

-- 
Jim Mooney

There is no such thing as a failed experiment

From davea at davea.name  Mon May 20 03:41:09 2013
From: davea at davea.name (Dave Angel)
Date: Sun, 19 May 2013 21:41:09 -0400
Subject: [Tutor] from import works but I'm flubbing a package import
In-Reply-To: <CALRAYNVOqBUYx4DQ8Zam_jy1rcX9pXiRTsgR=gCKt3WEsgV1RQ@mail.gmail.com>
References: <CALRAYNVOqBUYx4DQ8Zam_jy1rcX9pXiRTsgR=gCKt3WEsgV1RQ@mail.gmail.com>
Message-ID: <51997F35.2000500@davea.name>

On 05/19/2013 09:30 PM, Jim Mooney wrote:
> Still puzzling on imports.
>
> I have the jimlib module in Lib with the proper __init__.py . Inside
> it is the program bark.py, with data item zarf that contains string
> 'fraz'
>
> It also contains the function barker.
>
> def barker():
>     print 'bark, bark'
>
> If I do the below everything works:
>
> from jimlib import bark
>
> print bark.zarf
>
> bark.barker()
>
> But if I just do
>
> import jimlib and chain the program and its functions or data

Syntax error.  Be more specific, don't just paraphrase.

>
> nothing works.
>
> If I try jimlib.bark.barker() after importing jimlib or print
> jimlib.bark.zarf I get the error that the module has no attribute
> 'bark'

that's because you never imported jimlib.bark .

>
> I'm doing the from statement right but what am I doing wrong with just
> importing the whole module and chaining out bark (for bark.py) and the
> function or data following?
>
> Using Py27 and Win 7
>

Try:

import jimlib
import jimlib.bark



-- 
DaveA

From phil_lor at bigpond.com  Mon May 20 04:19:08 2013
From: phil_lor at bigpond.com (Phil)
Date: Mon, 20 May 2013 12:19:08 +1000
Subject: [Tutor] Retrieving data from a web site
In-Reply-To: <kna14r$g3o$1@ger.gmane.org>
References: <5196C3F7.6030507@bigpond.com> <kn77bl$c10$1@ger.gmane.org>
	<51973EA2.6040007@bigpond.com> <kn7hda$tr7$1@ger.gmane.org>
	<51975509.2020102@bigpond.com> <kn7t3n$1sr$1@ger.gmane.org>
	<CANLXbfDHgz71_0C2uK=LGz46RqsPNfguN6svox=LpLaN+QnPLw@mail.gmail.com>
	<51985CAC.2000908@bigpond.com> <kna14r$g3o$1@ger.gmane.org>
Message-ID: <5199881C.9080106@bigpond.com>

On 19/05/13 18:05, Peter Otten wrote:
>
> The original Python 2 code:
>
>   $ cat parse.py
> import urllib2
> import json
>
> url = "http://*********/goldencasket"
> s = urllib2.urlopen(url).read()
>
> s = s.partition("latestResults_productResults")[2].lstrip(" =")
> s = s.partition(";")[0]
> data = json.loads(s)
> lotto = data["GoldLottoSaturday"]
> print lotto["drawDayDateNumber"]
> print map(int, lotto["primaryNumbers"])
> print map(int, lotto["secondaryNumbers"])
> $ python parse.py
> Sat 18/May/13, Draw 3321
> [14, 31, 16, 25, 6, 3]
> [9, 35]
>

It turns out that urllib2 and 3 are both built into python so I didn't 
have to stress over the dependency error. However, I do have an error 
and I'm not completely certain that I understand how the code provided 
by Peter works. The following is the error message:

Traceback (most recent call last):
   File "/home/phil/Python/lotto.py", line 10, in <module>
     data = json.loads(s)
   File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
     return _default_decoder.decode(s)
   File "/usr/lib/python2.7/json/decoder.py", line 365, in decode
     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
   File "/usr/lib/python2.7/json/decoder.py", line 383, in raw_decode
     raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

-- 
Regards,
Phil

From bentbakwards at gmail.com  Mon May 20 08:31:32 2013
From: bentbakwards at gmail.com (spangled spanner)
Date: Mon, 20 May 2013 14:31:32 +0800
Subject: [Tutor] os.getcwd() confusion
Message-ID: <CAKq3qLVfRdhAc9383DDhC3C_2ML-yRoL4wZwva57jeaSntQoag@mail.gmail.com>

G'day,

I have a comprehension issue here! I have made two simple scripts:

## script1

import os

print os.getcwd()

-----------------------------
## script 2

import os

f = open('test', 'wb')
f.write(os.getcwd())
f.close()

_________________

Both scripts are in my home directory.
Using bash I cd to some other directory and call script 1:
> python ../../script1.py
and I get this result printed to the screen:
> users/scriptdir/dir1/dir2
i.e. the script returns the name of the directory that I'm currently
working in.

However if I call script2:
> python ../../script2.py
I get a result that to me seems inconsistent: the script writes the
directory
that IT is in (i.e., NOT the name of the directory I'm currently working
in),
to the file 'test' in the home directory.

I don't quite understand what is happening here! Any explanation would be
much appreciated.

Cheers,
CSS
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130520/cbe11ff1/attachment.html>

From __peter__ at web.de  Mon May 20 09:21:47 2013
From: __peter__ at web.de (Peter Otten)
Date: Mon, 20 May 2013 09:21:47 +0200
Subject: [Tutor] os.getcwd() confusion
References: <CAKq3qLVfRdhAc9383DDhC3C_2ML-yRoL4wZwva57jeaSntQoag@mail.gmail.com>
Message-ID: <kncitt$sph$1@ger.gmane.org>

spangled spanner wrote:

> G'day,
> 
> I have a comprehension issue here! I have made two simple scripts:
> 
> ## script1
> 
> import os
> 
> print os.getcwd()
> 
> -----------------------------
> ## script 2
> 
> import os
> 
> f = open('test', 'wb')
> f.write(os.getcwd())
> f.close()
> 
> _________________
> 
> Both scripts are in my home directory.
> Using bash I cd to some other directory and call script 1:
>> python ../../script1.py
> and I get this result printed to the screen:
>> users/scriptdir/dir1/dir2
> i.e. the script returns the name of the directory that I'm currently
> working in.
> 
> However if I call script2:
>> python ../../script2.py
> I get a result that to me seems inconsistent: the script writes the
> directory
> that IT is in (i.e., NOT the name of the directory I'm currently working
> in),
> to the file 'test' in the home directory.
> 
> I don't quite understand what is happening here! Any explanation would be
> much appreciated.

The test file will be written in the current working directory, too. You are 
looking into a leftover test file from a previous run.


From __peter__ at web.de  Mon May 20 09:55:14 2013
From: __peter__ at web.de (Peter Otten)
Date: Mon, 20 May 2013 09:55:14 +0200
Subject: [Tutor] Retrieving data from a web site
References: <5196C3F7.6030507@bigpond.com> <kn77bl$c10$1@ger.gmane.org>
	<51973EA2.6040007@bigpond.com> <kn7hda$tr7$1@ger.gmane.org>
	<51975509.2020102@bigpond.com> <kn7t3n$1sr$1@ger.gmane.org>
	<CANLXbfDHgz71_0C2uK=LGz46RqsPNfguN6svox=LpLaN+QnPLw@mail.gmail.com>
	<51985CAC.2000908@bigpond.com> <kna14r$g3o$1@ger.gmane.org>
	<5199881C.9080106@bigpond.com>
Message-ID: <kncksk$fqu$1@ger.gmane.org>

Phil wrote:

> On 19/05/13 18:05, Peter Otten wrote:
>>
>> The original Python 2 code:
>>
>>   $ cat parse.py
>> import urllib2
>> import json
>>
>> url = "http://*********/goldencasket"
>> s = urllib2.urlopen(url).read()
>>
>> s = s.partition("latestResults_productResults")[2].lstrip(" =")
>> s = s.partition(";")[0]
>> data = json.loads(s)
>> lotto = data["GoldLottoSaturday"]
>> print lotto["drawDayDateNumber"]
>> print map(int, lotto["primaryNumbers"])
>> print map(int, lotto["secondaryNumbers"])
>> $ python parse.py
>> Sat 18/May/13, Draw 3321
>> [14, 31, 16, 25, 6, 3]
>> [9, 35]
>>
> 
> It turns out that urllib2 and 3 are both built into python so I didn't

To make it crystal clear: despite the suggestive name urllib3 is an external 
library separate from urllib2. 

urllib2 is in the standard library of Python 2. In Python 3 the standard lib 
has been reorganized, and the functionality of urllib2 needed for the above 
script is now in urllib.request.

> have to stress over the dependency error. However, I do have an error
> and I'm not completely certain that I understand how the code provided
> by Peter works. The following is the error message:
> 
> Traceback (most recent call last):
>    File "/home/phil/Python/lotto.py", line 10, in <module>
>      data = json.loads(s)
>    File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
>      return _default_decoder.decode(s)
>    File "/usr/lib/python2.7/json/decoder.py", line 365, in decode
>      obj, end = self.raw_decode(s, idx=_w(s, 0).end())
>    File "/usr/lib/python2.7/json/decoder.py", line 383, in raw_decode
>      raise ValueError("No JSON object could be decoded")
> ValueError: No JSON object could be decoded

I've rerun the script and it still works over here. I'm in Germany, though, 
and therefore there's a small chance that I'm being served different data.
What does

import urllib2

url = "http://tatts.com/goldencasket"
s = urllib2.urlopen(url).read()

s = s.partition("latestResults_productResults")[2].lstrip(" =")
print s[:100]
s = s.partition(";")[0]
print s[-100:]

print?

> I'm not completely certain that I understand how the code provided
> by Peter works.

I've looked into the page source and found something like

<html>
...
<script type="text/javascript">
...
var latestResults_productResults = {"GoldLottoSaturday":
{"drawDayDateNumber":"Sat 18/May/13, Draw 3321","primaryNumbers":
["14","31","16","25","6","3"],"secondaryNumbers":
["9","35"],"hasDividends":true,"jurisdictionPath":"goldencasket","watchdrawUrl":"//media.tatts.com/Lotto/tattersalls/Draw 
videos/TattsLottodraw3321180513.flv"},"OZ7Lotto":{"drawDayDateNumber":"Tue 
14/May/13, Draw 1004","primaryNumbers":
["13","9","1","12","26","22","41"],"secondaryNumbers":
["34","39"],"hasDividends":true,"jurisdictionPath":"goldencasket","watchdrawUrl":"//media.tatts.com/Lotto/tattersalls/Draw 
videos/Super7sOzLottodraw1004140513.flv"},"QLDPowerball":
{"drawDayDateNumber":"Thu 16/May/13, Draw 887","primaryNumbers":
["24","26","31","23","40","4"],"secondaryNumbers":
["13"],"hasDividends":true,"jurisdictionPath":"goldencasket","watchdrawUrl":"//media.tatts.com/Lotto/tattersalls/Draw 
videos/Powerballdraw887160513.flv"},"WednesdayLotto":
{"drawDayDateNumber":"Wed 15/May/13, Draw 3320","primaryNumbers":
["26","3","27","24","17","33"],"secondaryNumbers":
["1","22"],"hasDividends":true,"jurisdictionPath":"goldencasket","watchdrawUrl":"//media.tatts.com/Lotto/goldencasket/Draw 
videos/WednesdayLottodraw3320150513.flv"},"QLDSuper66":
{"drawDayDateNumber":"Sat 18/May/13, Draw 3321","primaryNumbers":
["7","1","7","5","1","6"],"secondaryNumbers":
[],"hasDividends":true,"jurisdictionPath":"goldencasket","watchdrawUrl":""},"QLDPools":
{"drawDayDateNumber":"Sat 18/May/13, Draw 1451","primaryNumbers":
["1","2","24","27","28","35"],"secondaryNumbers":
["36"],"hasDividends":true,"jurisdictionPath":"goldencasket","watchdrawUrl":""}};
...


If all goes well, with 

s = s.partition("latestResults_productResults")[2]

everything before  " = {"GoldLottoSaturday":" is removed,
with s = s.lstrip(" =") the leading "=" and " " are removed, too.

s = s.partition(";")[0] removes everything after the nested dicts, so now we 
have

"""{"GoldLottoSaturday":{"drawDayDateNumber":"Sat 18/May/13, Draw 
3321","primaryNumbers":["14","31","16","25","6","3"],"secondaryNumbers":
["9","35"],"hasDividends":true,"jurisdictionPath":"goldencasket","watchdrawUrl":"//media.tatts.com/Lotto/tattersalls/Draw 
videos/TattsLottodraw3321180513.flv"},"OZ7Lotto":{"drawDayDateNumber":"Tue 
14/May/13, Draw 1004","primaryNumbers":
["13","9","1","12","26","22","41"],"secondaryNumbers":
["34","39"],"hasDividends":true,"jurisdictionPath":"goldencasket","watchdrawUrl":"//media.tatts.com/Lotto/tattersalls/Draw 
videos/Super7sOzLottodraw1004140513.flv"},"QLDPowerball":
{"drawDayDateNumber":"Thu 16/May/13, Draw 887","primaryNumbers":
["24","26","31","23","40","4"],"secondaryNumbers":
["13"],"hasDividends":true,"jurisdictionPath":"goldencasket","watchdrawUrl":"//media.tatts.com/Lotto/tattersalls/Draw 
videos/Powerballdraw887160513.flv"},"WednesdayLotto":
{"drawDayDateNumber":"Wed 15/May/13, Draw 3320","primaryNumbers":
["26","3","27","24","17","33"],"secondaryNumbers":
["1","22"],"hasDividends":true,"jurisdictionPath":"goldencasket","watchdrawUrl":"//media.tatts.com/Lotto/goldencasket/Draw 
videos/WednesdayLottodraw3320150513.flv"},"QLDSuper66":
{"drawDayDateNumber":"Sat 18/May/13, Draw 3321","primaryNumbers":
["7","1","7","5","1","6"],"secondaryNumbers":
[],"hasDividends":true,"jurisdictionPath":"goldencasket","watchdrawUrl":""},"QLDPools":
{"drawDayDateNumber":"Sat 18/May/13, Draw 1451","primaryNumbers":
["1","2","24","27","28","35"],"secondaryNumbers":
["36"],"hasDividends":true,"jurisdictionPath":"goldencasket","watchdrawUrl":""}}"""

a data structure of nested javascript dicts and lists. With 

data = json.loads(s)

this string is converted into a data structure of nested python dicts and 
lists. I've warned you before that this is brittle. For example if one of 
the strings in the data structure contains a ";" s. = s.partition(";")[0] 
will preserve only part of the structure.


From amalthomas111 at gmail.com  Mon May 20 11:59:49 2013
From: amalthomas111 at gmail.com (Amal Thomas)
Date: Mon, 20 May 2013 17:59:49 +0800
Subject: [Tutor] Which version of python should i use?
Message-ID: <CAGw83-gZqPNr-KwvJKvhiU4Egnz_c5p0vX5Y17N7ASeD6z3+Eg@mail.gmail.com>

hi,
   I am a beginner. I am using a unix sytem (ubuntu 12.10). Python 2.7.3
is installed in my system. I found out that Python has version upto 3.3.2.
Should I update my python version? Is the syntaxes of the each version
different?

Thanks,

Thomas
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130520/c4b99bc8/attachment.html>

From phil_lor at bigpond.com  Mon May 20 12:25:24 2013
From: phil_lor at bigpond.com (Phil)
Date: Mon, 20 May 2013 20:25:24 +1000
Subject: [Tutor] Retrieving data from a web site
In-Reply-To: <kncksk$fqu$1@ger.gmane.org>
References: <5196C3F7.6030507@bigpond.com> <kn77bl$c10$1@ger.gmane.org>
	<51973EA2.6040007@bigpond.com> <kn7hda$tr7$1@ger.gmane.org>
	<51975509.2020102@bigpond.com> <kn7t3n$1sr$1@ger.gmane.org>
	<CANLXbfDHgz71_0C2uK=LGz46RqsPNfguN6svox=LpLaN+QnPLw@mail.gmail.com>
	<51985CAC.2000908@bigpond.com> <kna14r$g3o$1@ger.gmane.org>
	<5199881C.9080106@bigpond.com> <kncksk$fqu$1@ger.gmane.org>
Message-ID: <5199FA14.4030509@bigpond.com>

On 20/05/13 17:55, Peter Otten wrote:
>
> I've rerun the script and it still works over here. I'm in Germany, though,
> and therefore there's a small chance that I'm being served different data.
> What does
>
> import urllib2
>

Thank you Peter for your detailed reply, I now have a better 
understanding of how json works.

I discovered my error just before receiving your reply. I'm a little 
embarrassed to admit that despite giving you the correct url I had 
attempted to get the results from another tatts page.

Thank you again, your help is greatly appreciated.

-- 
Regards,
Phil

From eryksun at gmail.com  Mon May 20 12:34:24 2013
From: eryksun at gmail.com (eryksun)
Date: Mon, 20 May 2013 06:34:24 -0400
Subject: [Tutor] Which version of python should i use?
In-Reply-To: <CAGw83-gZqPNr-KwvJKvhiU4Egnz_c5p0vX5Y17N7ASeD6z3+Eg@mail.gmail.com>
References: <CAGw83-gZqPNr-KwvJKvhiU4Egnz_c5p0vX5Y17N7ASeD6z3+Eg@mail.gmail.com>
Message-ID: <CACL+1atQxSM2MrP-zMOxRiCVne8ePbVSpS-F6UUfbQpkoGnwbw@mail.gmail.com>

On Mon, May 20, 2013 at 5:59 AM, Amal Thomas <amalthomas111 at gmail.com> wrote:
> I am a beginner. I am using a unix sytem (ubuntu 12.10). Python 2.7.3  is
> installed in my system. I found out that Python has version upto 3.3.2.
> Should I update my python version?

Ubuntu 12.10 should have 3.2.3 installed (the python3 package). The
command is "python3". There's also a python3.3 package, currently at
version 3.30. The command is "python3.3":

http://packages.ubuntu.com/quantal/python3
http://packages.ubuntu.com/quantal/python3.3

From davea at davea.name  Mon May 20 12:38:45 2013
From: davea at davea.name (Dave Angel)
Date: Mon, 20 May 2013 06:38:45 -0400
Subject: [Tutor] Which version of python should i use?
In-Reply-To: <CAGw83-gZqPNr-KwvJKvhiU4Egnz_c5p0vX5Y17N7ASeD6z3+Eg@mail.gmail.com>
References: <CAGw83-gZqPNr-KwvJKvhiU4Egnz_c5p0vX5Y17N7ASeD6z3+Eg@mail.gmail.com>
Message-ID: <5199FD35.4090409@davea.name>

On 05/20/2013 05:59 AM, Amal Thomas wrote:
> hi,
>     I am a beginner. I am using a unix sytem (ubuntu 12.10). Python 2.7.3
> is installed in my system. I found out that Python has version upto 3.3.2.

Welcome, and thanks for telling us your environment up front.


> Should I update my python version?

No.  Your OS has lots of dependencies on that installed Python, and if 
you remove that one (eg. replace it), many things will stop working.

HOWEVER, you can install a second Python, of whatever version, and use 
that for all your own experimenting and learning.  So the question is 
which one you should use for learning.  My comments at the end.

> Is the syntaxes of the each version
> different?
>

Yes.  Not only syntax but semantics as well.  Version 3.0 was 
deliberately a breaking update, where many of the painful gotchas in the 
language were fixed, even if it meant things were incompatible.  There 
is a 2to3 utility, but the transition can be painful for large programs.

Which one should you learn on?

#1 --- if you're committed to a particular tutorial, use the version 
that matches the tutorial.  At your stage, you don't want to have to 
convert every example in your head before getting it to work.

#2 --- If you have a particular library or libraries that you plan to 
use, and it's only currently available for one version, then use that 
version.

#3 --- If neither of the above apply, then use 3.3 or the soon-coming 3.4.

What's different?  For a beginner, the most noticeable different is that 
the print statement in 2.x was replaced by a print function in 3.x  For 
really simple cases, that just means slap a parentheses around the 
argument(s).  But the print statement has syntax for redirecting to a 
file, while the print function has a parameter.  And the technique for 
suppressing the trailing newline is different.  Etc.

The second most noticeable difference is that 3.x handles Unicode 
directly, so that a string is Unicode, and if you want bytes, those are 
different.




-- 
DaveA

From amalthomas111 at gmail.com  Mon May 20 15:24:08 2013
From: amalthomas111 at gmail.com (Amal Thomas)
Date: Mon, 20 May 2013 21:24:08 +0800
Subject: [Tutor] Which version of python should i use?
In-Reply-To: <5199FD35.4090409@davea.name>
References: <CAGw83-gZqPNr-KwvJKvhiU4Egnz_c5p0vX5Y17N7ASeD6z3+Eg@mail.gmail.com>
	<5199FD35.4090409@davea.name>
Message-ID: <CAGw83-hyDPV3jK=MFMoP8D2RYC5jE4EY5XkUcE19Kv1D8pFkQg@mail.gmail.com>

Thank you very much..!! I am starting to learn python for my Bioinformatics
work, so I would look for the version that has libraries helpful for me..


On Mon, May 20, 2013 at 6:38 PM, Dave Angel <davea at davea.name> wrote:

> On 05/20/2013 05:59 AM, Amal Thomas wrote:
>
>> hi,
>>     I am a beginner. I am using a unix sytem (ubuntu 12.10). Python 2.7.3
>> is installed in my system. I found out that Python has version upto 3.3.2.
>>
>
> Welcome, and thanks for telling us your environment up front.
>
>
>
>  Should I update my python version?
>>
>
> No.  Your OS has lots of dependencies on that installed Python, and if you
> remove that one (eg. replace it), many things will stop working.
>
> HOWEVER, you can install a second Python, of whatever version, and use
> that for all your own experimenting and learning.  So the question is which
> one you should use for learning.  My comments at the end.
>
>
>  Is the syntaxes of the each version
>> different?
>>
>>
> Yes.  Not only syntax but semantics as well.  Version 3.0 was deliberately
> a breaking update, where many of the painful gotchas in the language were
> fixed, even if it meant things were incompatible.  There is a 2to3 utility,
> but the transition can be painful for large programs.
>
> Which one should you learn on?
>
> #1 --- if you're committed to a particular tutorial, use the version that
> matches the tutorial.  At your stage, you don't want to have to convert
> every example in your head before getting it to work.
>
> #2 --- If you have a particular library or libraries that you plan to use,
> and it's only currently available for one version, then use that version.
>
> #3 --- If neither of the above apply, then use 3.3 or the soon-coming 3.4.
>
> What's different?  For a beginner, the most noticeable different is that
> the print statement in 2.x was replaced by a print function in 3.x  For
> really simple cases, that just means slap a parentheses around the
> argument(s).  But the print statement has syntax for redirecting to a file,
> while the print function has a parameter.  And the technique for
> suppressing the trailing newline is different.  Etc.
>
> The second most noticeable difference is that 3.x handles Unicode
> directly, so that a string is Unicode, and if you want bytes, those are
> different.
>
>
>
>
> --
> DaveA
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>



-- 
*AMAL THOMAS
Third Year Undergraduate Student
Department of Biotechnology
IIT KHARAGPUR-721302*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130520/ab34c493/attachment.html>

From fomcl at yahoo.com  Mon May 20 15:22:48 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Mon, 20 May 2013 06:22:48 -0700 (PDT)
Subject: [Tutor] Which version of python should i use?
In-Reply-To: <CACL+1atQxSM2MrP-zMOxRiCVne8ePbVSpS-F6UUfbQpkoGnwbw@mail.gmail.com>
References: <CAGw83-gZqPNr-KwvJKvhiU4Egnz_c5p0vX5Y17N7ASeD6z3+Eg@mail.gmail.com>
	<CACL+1atQxSM2MrP-zMOxRiCVne8ePbVSpS-F6UUfbQpkoGnwbw@mail.gmail.com>
Message-ID: <1369056168.17205.YahooMailNeo@web163804.mail.gq1.yahoo.com>



>On Mon, May 20, 2013 at 5:59 AM, Amal Thomas <amalthomas111 at gmail.com> wrote:
>> I am a beginner. I am using a unix sytem (ubuntu 12.10). Python 2.7.3? is
>> installed in my system. I found out that Python has version upto 3.3.2.
>> Should I update my python version?
>
>Ubuntu 12.10 should have 3.2.3 installed (the python3 package). The
>command is "python3". There's also a python3.3 package, currently at
>version 3.30. The command is "python3.3":

Nice, I never knew that this was already installed. To what extent is Ubuntu (I use Mint, but I think that's almost the same) already using Python 3.2 internally? I tried "sudo updatedb; locate python3". But probably I should scan inside files to see where python3 is used. 

From steve at pearwood.info  Mon May 20 17:41:27 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 21 May 2013 01:41:27 +1000
Subject: [Tutor] Which version of python should i use?
In-Reply-To: <1369056168.17205.YahooMailNeo@web163804.mail.gq1.yahoo.com>
References: <CAGw83-gZqPNr-KwvJKvhiU4Egnz_c5p0vX5Y17N7ASeD6z3+Eg@mail.gmail.com>
	<CACL+1atQxSM2MrP-zMOxRiCVne8ePbVSpS-F6UUfbQpkoGnwbw@mail.gmail.com>
	<1369056168.17205.YahooMailNeo@web163804.mail.gq1.yahoo.com>
Message-ID: <519A4427.9050806@pearwood.info>

On 20/05/13 23:22, Albert-Jan Roskam wrote:

>To what extent is Ubuntu (I use Mint, but I think that's almost the same) already using Python 3.2 internally?

Zero.

As far as I know, the only major Linux distro using Python 3 as the standard Python is Arch Linux, and they have a reputation for trail-blazing past the bleeding edge.

> I tried "sudo updatedb; locate python3".

That will only find files (or directories) with "python3" in the name, not those that rely on Python3.


-- 
Steven

From rafael.knuth at gmail.com  Mon May 20 18:31:47 2013
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Mon, 20 May 2013 18:31:47 +0200
Subject: [Tutor] Random Number Game: Returns always the same number - why?
Message-ID: <CAM-E2X71W6PVeOpRfrrvT8B9x8S-5Z-vG8XdFO8jY18bvUT_xA@mail.gmail.com>

Hello,

I wrote a simple program, and I was expecting that I would get 100
different random numbers. Instead, I am getting 100 times exactly the same
random number. Can anyone advise how I should alter my program?

Thank you!

All the best,

Rafael
PS. I am using Python 3.3.0

print ("""

This game will return 100 random numbers between 1 and 100.

""")

import random

Count = 0

Random_Number = random.randint(1, 100)

while Count <= 100:
    print (Random_Number)

    Count = Count + 1
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130520/201af5e5/attachment.html>

From robertvstepp at gmail.com  Mon May 20 18:37:45 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Mon, 20 May 2013 11:37:45 -0500
Subject: [Tutor] Random Number Game: Returns always the same number -
	why?
In-Reply-To: <CAM-E2X71W6PVeOpRfrrvT8B9x8S-5Z-vG8XdFO8jY18bvUT_xA@mail.gmail.com>
References: <CAM-E2X71W6PVeOpRfrrvT8B9x8S-5Z-vG8XdFO8jY18bvUT_xA@mail.gmail.com>
Message-ID: <CANDiX9+x0YHYL0avasZqhRRpyaGRaq8mroytABH0jon-v-3tSQ@mail.gmail.com>

On Mon, May 20, 2013 at 11:31 AM, Rafael Knuth <rafael.knuth at gmail.com> wrote:
>
> Hello,
>
> I wrote a simple program, and I was expecting that I would get 100 different random numbers. Instead, I am getting 100 times exactly the same random number. Can anyone advise how I should alter my program?
>
> Thank you!
>
> All the best,
>
> Rafael
> PS. I am using Python 3.3.0
>
> print ("""
>
> This game will return 100 random numbers between 1 and 100.
>
> """)
>
> import random
>
> Count = 0
>
> Random_Number = random.randint(1, 100)
>
> while Count <= 100:
>     print (Random_Number)
>
>     Count = Count + 1
>
Your variable assignment for Random_Number is outside of your while
loop. Therefore its value never changes. Put it inside the while loop
just before the print statement and I think you will get what you
wanted.

HTH,
boB

From n711az at gmail.com  Mon May 20 18:40:33 2013
From: n711az at gmail.com (John R Jones)
Date: Mon, 20 May 2013 09:40:33 -0700
Subject: [Tutor] Random Number Game: Returns always the same number -
	why?
In-Reply-To: <CAM-E2X71W6PVeOpRfrrvT8B9x8S-5Z-vG8XdFO8jY18bvUT_xA@mail.gmail.com>
References: <CAM-E2X71W6PVeOpRfrrvT8B9x8S-5Z-vG8XdFO8jY18bvUT_xA@mail.gmail.com>
Message-ID: <CANBmx3bORB7+F4F+t28f4yzvBOwYArriqSPp369-5pp2U3Up6Q@mail.gmail.com>

You need to move this line:

Random_Number = random.randint(1, 100)

into the loop body, like this:


while Count <= 100:
     Random_Number = random.randint(1, 100)
     print (Random_Number)
     Count = Count + 1

 Hope this helps.



On Mon, May 20, 2013 at 9:31 AM, Rafael Knuth <rafael.knuth at gmail.com>wrote:

> Hello,
>
> I wrote a simple program, and I was expecting that I would get 100
> different random numbers. Instead, I am getting 100 times exactly the same
> random number. Can anyone advise how I should alter my program?
>
> Thank you!
>
> All the best,
>
> Rafael
> PS. I am using Python 3.3.0
>
> print ("""
>
> This game will return 100 random numbers between 1 and 100.
>
> """)
>
> import random
>
> Count = 0
>
> Random_Number = random.randint(1, 100)
>
> while Count <= 100:
>     print (Random_Number)
>
>     Count = Count + 1
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
John R Jones   <n711az at gmail.com>
10814 Des Moines Ave,  Porter Ranch, CA 91326
818-378-6206 cell/text,  310-531-8300 work, 424-234-9213 voicemail
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130520/a638ab3f/attachment.html>

From msirenef at lightbird.net  Mon May 20 18:43:52 2013
From: msirenef at lightbird.net (Mitya Sirenef)
Date: Mon, 20 May 2013 12:43:52 -0400
Subject: [Tutor] Random Number Game: Returns always the same number -
 why?
In-Reply-To: <CAM-E2X71W6PVeOpRfrrvT8B9x8S-5Z-vG8XdFO8jY18bvUT_xA@mail.gmail.com>
References: <CAM-E2X71W6PVeOpRfrrvT8B9x8S-5Z-vG8XdFO8jY18bvUT_xA@mail.gmail.com>
Message-ID: <519A52C8.5000903@lightbird.net>

On 05/20/2013 12:31 PM, Rafael Knuth wrote:
> Hello,
 >
 > I wrote a simple program, and I was expecting that I would get 100 
different random numbers. Instead, I am getting 100 times exactly the 
same random number. Can anyone advise how I should alter my program?
 >
 > Thank you!
 >
 > All the best,
 >
 > Rafael
 > PS. I am using Python 3.3.0
 >
 > print ("""
 >
 > This game will return 100 random numbers between 1 and 100.
 >
 > """)
 >
 > import random
 >
 > Count = 0
 >
 > Random_Number = random.randint(1, 100)
 >
 > while Count <= 100:
 > print (Random_Number)
 >
 > Count = Count + 1
 >
 >
 >


There are a few issues here:
* variable names should be lower case
* for this case it's best to use for loop with range()
* you calculate random number only once, outside of loop

Try something like:

for count in range(100):
print random.randint(1, 100)


-m

-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/

?So many books, so little time.?
? Frank Zappa


From rafael.knuth at gmail.com  Mon May 20 18:47:04 2013
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Mon, 20 May 2013 18:47:04 +0200
Subject: [Tutor] Beginner level: Why doesn't my code work?
In-Reply-To: <knap2p$3ks$1@ger.gmane.org>
References: <CAM-E2X4iYCpRNm40UL7i=s6dz26sMcx=VKb2iAutSLLtJ7xHbw@mail.gmail.com>
	<CAHVvXxSZXFfKgwVF44uTki-U6n7dQGLJqOiyewS9UgNdcyFYNg@mail.gmail.com>
	<CAM-E2X4nM239G9Y-t5j2-u70CyRo6x7OwSXWCLtRVhkpDrnhQA@mail.gmail.com>
	<knap2p$3ks$1@ger.gmane.org>
Message-ID: <CAM-E2X4b91XrNob2J=9WkR372EmZuBDeOGjnEswUFW0wDpUkVw@mail.gmail.com>

But this is all a distraction -- how exactly are you invoking what you think
is Python 3.3.0? What is your operating system?

My mistake, I am using two laptops with different operating systems
(Windows 7 & SUSE 12.3). I am using Python 3.3.0 on the Windows laptop and
I was wrongly assuming that I am running the same version of Python on my
SUSE laptop. I simply forgot that I have a Python 2.x version on my SUSE
laptop. I tried that game on my Windows 7 laptop (where I have 3.3.0
installed) and it runs nicely.

Thank you for your support!

import random

print("""

This is a magic super computer.

He will ask you a couple of questions.

An ultra-complicated algorithm will then figure out what your favorite meal
is.

""")

name = input("What is your name? ")

age = int(input("How old are you? "))

birthplace = input("Where are you born? ")

meal = random.randint(1, 3)

if meal == 1:
    print("Well, " + name + " as a " + str(age) + " year old human being
born in " + birthplace + " you probably like hamburgers.")

elif meal == 2:
    print("Well, " + name + " as a " + str(age) + " year old human being
born in " + birthplace + " you probably like sushi.")

elif meal == 3:
    print("Well, " + name + " as a " + str(age) + " year old human being
born in " + birthplace + " you probably like pizza.")


On Sun, May 19, 2013 at 4:54 PM, Peter Otten <__peter__ at web.de> wrote:

> Rafael Knuth wrote:
>
> > Thank you, I am using Python 3.3.0
>
> [Oscar]
> > In Python 3 you should use input(). In Python 2 you should use
> > raw_input(). I'm guessing that you're using Python 2. In Python 2 the
> > input() function tries to evaluate whatever the user types in as if it
> > was Python code. Since Rafael is not a defined variable it fails. The
> > fix is to use raw_input() which just returns a string.
>
>
> [Rafael]
> > I am not sure I understand.
> > "Rafael" is the user's in put, and that value is assigned to the variable
> > "name".
> > I made sure only a string is accepted as input
> >
> > name = (str(input("What's your name?"))
> >
> > Can you clarify? Thank you in advance.
>
> As Oscar says you are invoking your script with Python 2. Python 2's
> input()
> function evals user input as a Python expression. For example if you run a
> script
>
> print input("your input please: ")
>
> and you type
>
> 1 + 1
>
> the script will print
>
> 2
>
> Likewise if you type
>
> Rafael
>
> the script will look up the value of a variable named Rafael. This doesn't
> exist and therefore you get an exception.
>
> But this is all a distraction -- how exactly are you invoking what you
> think
> is Python 3.3.0? What is your operating system?
>
> If you are using Linux or OSX open a terminal window and try to run your
> script from that terminal window with
>
> python3.3 ~/Documents/3_Tufcik.py
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130520/9e39ce5c/attachment-0001.html>

From rafael.knuth at gmail.com  Mon May 20 18:51:20 2013
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Mon, 20 May 2013 18:51:20 +0200
Subject: [Tutor] Random Number Game: Returns always the same number -
	why?
In-Reply-To: <CANDiX9+x0YHYL0avasZqhRRpyaGRaq8mroytABH0jon-v-3tSQ@mail.gmail.com>
References: <CAM-E2X71W6PVeOpRfrrvT8B9x8S-5Z-vG8XdFO8jY18bvUT_xA@mail.gmail.com>
	<CANDiX9+x0YHYL0avasZqhRRpyaGRaq8mroytABH0jon-v-3tSQ@mail.gmail.com>
Message-ID: <CAM-E2X4j60UuY4vwYmvWU6XPJfy5WR=Fc3UPkeJLG0G8kWLZoA@mail.gmail.com>

Your variable assignment for Random_Number is outside of your while
loop. Therefore its value never changes. Put it inside the while loop
just before the print statement and I think you will get what you

That was it! Thank you, you made my day, Bob :-)


On Mon, May 20, 2013 at 6:37 PM, boB Stepp <robertvstepp at gmail.com> wrote:
>
> On Mon, May 20, 2013 at 11:31 AM, Rafael Knuth <rafael.knuth at gmail.com>
wrote:
> >
> > Hello,
> >
> > I wrote a simple program, and I was expecting that I would get 100
different random numbers. Instead, I am getting 100 times exactly the same
random number. Can anyone advise how I should alter my program?
> >
> > Thank you!
> >
> > All the best,
> >
> > Rafael
> > PS. I am using Python 3.3.0
> >
> > print ("""
> >
> > This game will return 100 random numbers between 1 and 100.
> >
> > """)
> >
> > import random
> >
> > Count = 0
> >
> > Random_Number = random.randint(1, 100)
> >
> > while Count <= 100:
> >     print (Random_Number)
> >
> >     Count = Count + 1
> >
> Your variable assignment for Random_Number is outside of your while
> loop. Therefore its value never changes. Put it inside the while loop
> just before the print statement and I think you will get what you
> wanted.
>
> HTH,
> boB
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130520/53e75a72/attachment.html>

From thomasmurphymusic at gmail.com  Mon May 20 18:55:02 2013
From: thomasmurphymusic at gmail.com (Thomas Murphy)
Date: Mon, 20 May 2013 12:55:02 -0400
Subject: [Tutor] Random Number Game: Returns always the same number -
	why?
In-Reply-To: <519A52C8.5000903@lightbird.net>
References: <CAM-E2X71W6PVeOpRfrrvT8B9x8S-5Z-vG8XdFO8jY18bvUT_xA@mail.gmail.com>
	<519A52C8.5000903@lightbird.net>
Message-ID: <CAEcwjcyfJ4jweuG8oRBtZ6=ZUqdRquOzbF8_zyBwoHm=izbWSA@mail.gmail.com>

Mitya,
Why is it best in this situation to use range() rather than a while
loop? Curious about best practices for the various iterating
functions. Thanks!


> There are a few issues here:
> * variable names should be lower case
> * for this case it's best to use for loop with range()
> * you calculate random number only once, outside of loop
>
> Try something like:
>
> for count in range(100):
> print random.randint(1, 100)
>
>
> -m

From msirenef at lightbird.net  Mon May 20 19:13:43 2013
From: msirenef at lightbird.net (Mitya Sirenef)
Date: Mon, 20 May 2013 13:13:43 -0400
Subject: [Tutor] Random Number Game: Returns always the same number -
 why?
In-Reply-To: <CAEcwjcyfJ4jweuG8oRBtZ6=ZUqdRquOzbF8_zyBwoHm=izbWSA@mail.gmail.com>
References: <CAM-E2X71W6PVeOpRfrrvT8B9x8S-5Z-vG8XdFO8jY18bvUT_xA@mail.gmail.com>
	<519A52C8.5000903@lightbird.net>
	<CAEcwjcyfJ4jweuG8oRBtZ6=ZUqdRquOzbF8_zyBwoHm=izbWSA@mail.gmail.com>
Message-ID: <519A59C7.8020902@lightbird.net>

On 05/20/2013 12:55 PM, Thomas Murphy wrote:
> Mitya,
> Why is it best in this situation to use range() rather than a while
> loop? Curious about best practices for the various iterating
> functions. Thanks!
>
>
>> There are a few issues here:
>> * variable names should be lower case
>> * for this case it's best to use for loop with range()
>> * you calculate random number only once, outside of loop
>>
>> Try something like:
>>
>> for count in range(100):
>> print random.randint(1, 100)
>>
>>
>> -m

It's a simpler and more idiomatic approach, as you can
see, you don't need to initialize the counter and you don't
need to manually increment it.  -m


-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/


From cybervigilante at gmail.com  Mon May 20 19:22:22 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Mon, 20 May 2013 10:22:22 -0700
Subject: [Tutor] Tutor Digest, Vol 111, Issue 68
In-Reply-To: <mailman.10867.1369068426.3113.tutor@python.org>
References: <mailman.10867.1369068426.3113.tutor@python.org>
Message-ID: <CALRAYNVa7=uxeCSU3EpgJfDoVEOWpQM0SrgE0ZxunC7xghNBCg@mail.gmail.com>

>  > import random
>  >
>  > Count = 0
>  >
>  > Random_Number = random.randint(1, 100)
>  >
>  > while Count <= 100:
>  > print (Random_Number)
>  >
>  > Count = Count + 1

>
> There are a few issues here:
> * variable names should be lower case
> * for this case it's best to use for loop with range()
> * you calculate random number only once, outside of loop

This gave rise to an interesting behavior, though. I ran it with
random outside the loop and indeed got the same number. Except the
number Changed right toward the end to one other number. I got a lot
of 19s, then a 17. The third time I got a lot of 23s, then a lot of
70s. This was consistent. Then I scrolled the results more slowly and
realized the program ran over 25,000 times and the anomalous numbers
were toward the end.

So why did it run about 25,000 times and why the change in number?

Here's the prog so you can see the loopvar count does increment so it
Should stop at 100.

import random

Count = 0
Random_Number = random.randint(1, 100)

Count = 0

while Count <= 100:

    print (Random_Number)
    Count = Count + 1

I found the cause. If I just print Count it only goes to 100. If I
print Random_Number it goes to 25K. Is this consistent or a strange
flaw of Pyscripter?


Jim

From Robert.Treder at morganstanley.com  Tue May 21 00:49:08 2013
From: Robert.Treder at morganstanley.com (Treder, Robert)
Date: Mon, 20 May 2013 18:49:08 -0400
Subject: [Tutor] reducing lists within list to their set of unique values
Message-ID: <E84A3AA0F1F20E41953E8486223DD65057F543FE30@NYWEXMBX2130.msad.ms.com>

Hi python folks,
 
I have a list of lists that looks something like this: 
 
tst = [ [], ['test'], ['t1', 't2'], ['t1', 't1', 't2'] ]
 
I want to change the empty sets to a blank string, i.e., '' and the lists with repeat values to the unique set of values. So I have done the following: 
 
>>> for t in tst:
	if len(t) == 0:
		tst.__setitem__(tst.index(t), '')
	else:
		tst.__setitem__(tst.index(t), set(t))

What I get in return is 

>>> tst
['', set(['test']), set(['t2', 't1']), set(['t2', 't1'])]

The empty list is fine but the other lists seem to be expressions rather than values. What do I need to do to simply get the values back liike the following? 

['', ['test'], ['t2', 't1'], ['t2', 't1']]


Thanks, 
Bob
 



--------------------------------------------------------------------------------

NOTICE: Morgan Stanley is not acting as a municipal advisor and the opinions or views contained herein are not intended to be, and do not constitute, advice within the meaning of Section 975 of the Dodd-Frank Wall Street Reform and Consumer Protection Act. If you have received this communication in error, please destroy all electronic and paper copies and notify the sender immediately. Mistransmission is not intended to waive confidentiality or privilege. Morgan Stanley reserves the right, to the extent permitted under applicable law, to monitor electronic communications. This message is subject to terms available at the following link: http://www.morganstanley.com/disclaimers. If you cannot access these links, please notify us by reply message and we will send the contents to you. By messaging with Morgan Stanley you consent to the foregoing.

From steve at pearwood.info  Tue May 21 01:45:17 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 21 May 2013 09:45:17 +1000
Subject: [Tutor] reducing lists within list to their set of unique values
In-Reply-To: <E84A3AA0F1F20E41953E8486223DD65057F543FE30@NYWEXMBX2130.msad.ms.com>
References: <E84A3AA0F1F20E41953E8486223DD65057F543FE30@NYWEXMBX2130.msad.ms.com>
Message-ID: <519AB58D.9020206@pearwood.info>

On 21/05/13 08:49, Treder, Robert wrote:
> Hi python folks,
>
> I have a list of lists that looks something like this:
>
> tst = [ [], ['test'], ['t1', 't2'], ['t1', 't1', 't2'] ]
>
> I want to change the empty sets to a blank string, i.e., '' and the lists with repeat values to the unique set of values. So I have done the following:
>
>>>> for t in tst:
> 	if len(t) == 0:
> 		tst.__setitem__(tst.index(t), '')
> 	else:
> 		tst.__setitem__(tst.index(t), set(t))


As a general rule, if you are writing double-underscore special methods like __setitem__ directly, you're doing it wrong. (There are exceptions, but consider them "for experts".)

So instead of tst.__setitem__(a, b) you should write tst[a] = b.

But that's still the wrong way to do this! You're doing a lot of extra work with the calls to tst.index. You won't notice for a short list like the example above, but for a long list, this will get really, really slow.

The way to do this is to keep track of the index as you walk over the list, and not recalculate it by searching the list:


for index, item in enumerate(tst):
     if item == []:
         item = ""
     else:
         item = list(set(item))
     tst[index] = item


Notice that I call set() to get the unique values, then list() again to turn it back into a list. This does the job you want, but it is not guaranteed to keep the order:

py> L = ['b', 'd', 'c', 'a', 'b']
py> list(set(L))
['a', 'c', 'b', 'd']


If keeping the order is important, you cannot use set, and you'll need another way to extract only the unique values. Ask if you need help on that.



> What I get in return is
>
>>>> tst
> ['', set(['test']), set(['t2', 't1']), set(['t2', 't1'])]
>
> The empty list is fine but the other lists seem to be expressions rather than values. What do I need to do to simply get the values back liike the following?
>
> ['', ['test'], ['t2', 't1'], ['t2', 't1']]


They are values. It is just that they are *sets* rather than *lists*. When printed, lists have a nice compact representation using square brackets [], but unfortunately sets do not. However, if you upgrade to Python 3, they have been upgraded to look a little nicer:


# Python 2:
set(['a', 'c', 'b', 'd'])

# Python 3
{'d', 'b', 'c', 'a'}


Notice that the order of the items is not guaranteed, but apart from that, the two versions are the same despite the difference in print representation.



-- 
Steven

From cybervigilante at gmail.com  Tue May 21 03:43:04 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Mon, 20 May 2013 18:43:04 -0700
Subject: [Tutor] still clarifying imorting
Message-ID: <CALRAYNWJs4-L_JKN8gEHSCbrdD8N+kXxjq5tLe68gPE3P-jEbg@mail.gmail.com>

If I make a package called jimlib with __init__.py in it, and a
program called bark.py in it, and even put it in site packages, I
still have to import the program with   import jimlib.bark

But I noticed that the pygraphics package is in site packages, and has
media.py in it, and all I have to do with that is import media,
without qualifying it with pygraphics, as in import pygraphics.media

Why don't I have to drill down for media.py as I do with jimlib?

-- 
Jim Mooney

"And as he walked along he carried some things in his small sack. Some
were useless and some were not. But the useless things he prized most
of all."  --The Story of Dirtville

From amitsaha.in at gmail.com  Tue May 21 03:54:15 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Tue, 21 May 2013 11:54:15 +1000
Subject: [Tutor] Random Number Game: Returns always the same number -
	why?
In-Reply-To: <CAM-E2X4j60UuY4vwYmvWU6XPJfy5WR=Fc3UPkeJLG0G8kWLZoA@mail.gmail.com>
References: <CAM-E2X71W6PVeOpRfrrvT8B9x8S-5Z-vG8XdFO8jY18bvUT_xA@mail.gmail.com>
	<CANDiX9+x0YHYL0avasZqhRRpyaGRaq8mroytABH0jon-v-3tSQ@mail.gmail.com>
	<CAM-E2X4j60UuY4vwYmvWU6XPJfy5WR=Fc3UPkeJLG0G8kWLZoA@mail.gmail.com>
Message-ID: <CANODV3kAKzfizmUazPomb7-k6KKjeRjPnT5q3hUZaUuPA9H0ZQ@mail.gmail.com>

Hi Rafael,


On Tue, May 21, 2013 at 2:51 AM, Rafael Knuth <rafael.knuth at gmail.com> wrote:
>
> Your variable assignment for Random_Number is outside of your while
> loop. Therefore its value never changes. Put it inside the while loop
> just before the print statement and I think you will get what you
>
> That was it! Thank you, you made my day, Bob :-)


Here is a visualization of how the lines of your original code are
executed: http://goo.gl/uRRTu.  Click on the "Forward" button there to
see the next line of code that is executed. You will see that in your
original code, the statement: "Random_Number = random.randint(1, 100)"
which actually generates your random numbers is executed only once.

Hope that helps your understanding.

Best,
Amit.

--
http://echorand.me

From amitsaha.in at gmail.com  Tue May 21 04:03:41 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Tue, 21 May 2013 12:03:41 +1000
Subject: [Tutor] Which version of python should i use?
In-Reply-To: <CAGw83-hyDPV3jK=MFMoP8D2RYC5jE4EY5XkUcE19Kv1D8pFkQg@mail.gmail.com>
References: <CAGw83-gZqPNr-KwvJKvhiU4Egnz_c5p0vX5Y17N7ASeD6z3+Eg@mail.gmail.com>
	<5199FD35.4090409@davea.name>
	<CAGw83-hyDPV3jK=MFMoP8D2RYC5jE4EY5XkUcE19Kv1D8pFkQg@mail.gmail.com>
Message-ID: <CANODV3=nKkTLbmKdZOv6q1_=q9sVgD=kAWNRoLo=Z9A2gja24g@mail.gmail.com>

Hello Amal,

On Mon, May 20, 2013 at 11:24 PM, Amal Thomas <amalthomas111 at gmail.com> wrote:
> Thank you very much..!! I am starting to learn python for my Bioinformatics
> work, so I would look for the version that has libraries helpful for me..

Do you already have any libraries in mind (or aware of) that  you
would want to use? I came across this link:
http://intro-prog-bioinfo-2012.wikispaces.com/, which doesn't seem to
use any specific tools other than the "generic" libraries that are
pretty much common in any scientific work involving Python: SciPy,
Numpy, etc.

The rule of thumb would probably be "If you don't have any particular
library that you are looking to use and it doesn't yet support Python
3, then you may as well learn Python 3", since that is the future. I
think you may need to spend some time deciding this one. However that
said, why not start with Python 3? The programming language syntax and
style won't be different if you need to go by chance and use Python 2
at some other point of time.


Hope that helps.
-Amit.


>
>
> On Mon, May 20, 2013 at 6:38 PM, Dave Angel <davea at davea.name> wrote:
>>
>> On 05/20/2013 05:59 AM, Amal Thomas wrote:
>>>
>>> hi,
>>>     I am a beginner. I am using a unix sytem (ubuntu 12.10). Python 2.7.3
>>> is installed in my system. I found out that Python has version upto
>>> 3.3.2.
>>
>>
>> Welcome, and thanks for telling us your environment up front.
>>
>>
>>
>>> Should I update my python version?
>>
>>
>> No.  Your OS has lots of dependencies on that installed Python, and if you
>> remove that one (eg. replace it), many things will stop working.
>>
>> HOWEVER, you can install a second Python, of whatever version, and use
>> that for all your own experimenting and learning.  So the question is which
>> one you should use for learning.  My comments at the end.
>>
>>
>>> Is the syntaxes of the each version
>>> different?
>>>
>>
>> Yes.  Not only syntax but semantics as well.  Version 3.0 was deliberately
>> a breaking update, where many of the painful gotchas in the language were
>> fixed, even if it meant things were incompatible.  There is a 2to3 utility,
>> but the transition can be painful for large programs.
>>
>> Which one should you learn on?
>>
>> #1 --- if you're committed to a particular tutorial, use the version that
>> matches the tutorial.  At your stage, you don't want to have to convert
>> every example in your head before getting it to work.
>>
>> #2 --- If you have a particular library or libraries that you plan to use,
>> and it's only currently available for one version, then use that version.
>>
>> #3 --- If neither of the above apply, then use 3.3 or the soon-coming 3.4.
>>
>> What's different?  For a beginner, the most noticeable different is that
>> the print statement in 2.x was replaced by a print function in 3.x  For
>> really simple cases, that just means slap a parentheses around the
>> argument(s).  But the print statement has syntax for redirecting to a file,
>> while the print function has a parameter.  And the technique for suppressing
>> the trailing newline is different.  Etc.
>>
>> The second most noticeable difference is that 3.x handles Unicode
>> directly, so that a string is Unicode, and if you want bytes, those are
>> different.
>>
>>
>>
>>
>> --
>> DaveA
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
>
>
>
> --
> AMAL THOMAS
> Third Year Undergraduate Student
> Department of Biotechnology
> IIT KHARAGPUR-721302
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



--
http://echorand.me

From davea at davea.name  Tue May 21 04:05:18 2013
From: davea at davea.name (Dave Angel)
Date: Mon, 20 May 2013 22:05:18 -0400
Subject: [Tutor] still clarifying imorting
In-Reply-To: <CALRAYNWJs4-L_JKN8gEHSCbrdD8N+kXxjq5tLe68gPE3P-jEbg@mail.gmail.com>
References: <CALRAYNWJs4-L_JKN8gEHSCbrdD8N+kXxjq5tLe68gPE3P-jEbg@mail.gmail.com>
Message-ID: <519AD65E.5050805@davea.name>

On 05/20/2013 09:43 PM, Jim Mooney wrote:
> If I make a package called jimlib with __init__.py in it, and a
> program called bark.py in it, and even put it in site packages, I
> still have to import the program with   import jimlib.bark
>
> But I noticed that the pygraphics package is in site packages, and has
> media.py in it, and all I have to do with that is import media,
> without qualifying it with pygraphics, as in import pygraphics.media
>
> Why don't I have to drill down for media.py as I do with jimlib?
>

I'd guess that pygraphics has some content in their __init__.py.  That 
content gets executed when you import it.

-- 
DaveA

From eryksun at gmail.com  Tue May 21 04:44:03 2013
From: eryksun at gmail.com (eryksun)
Date: Mon, 20 May 2013 22:44:03 -0400
Subject: [Tutor] still clarifying imorting
In-Reply-To: <CALRAYNWJs4-L_JKN8gEHSCbrdD8N+kXxjq5tLe68gPE3P-jEbg@mail.gmail.com>
References: <CALRAYNWJs4-L_JKN8gEHSCbrdD8N+kXxjq5tLe68gPE3P-jEbg@mail.gmail.com>
Message-ID: <CACL+1avbnj44et+c7sueBpYM=jP47Kh6mhAM3QyE34PmoQk5_Q@mail.gmail.com>

On Mon, May 20, 2013 at 9:43 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> If I make a package called jimlib with __init__.py in it, and a
> program called bark.py in it, and even put it in site packages, I
> still have to import the program with   import jimlib.bark
>
> But I noticed that the pygraphics package is in site packages, and has
> media.py in it, and all I have to do with that is import media,
> without qualifying it with pygraphics, as in import pygraphics.media
>
> Why don't I have to drill down for media.py as I do with jimlib?

It's using a .pth file named "pygraphics.pth", which should be in your
Lib\site-packages directory on NT. The first and only line is
"pygraphics". This subdirectory is added to sys.path.

Specifically, in the setup.py for PyGraphics, it's using the
"extra_path" argument:

http://code.google.com/p/pygraphics/source/browse/trunk/setup.py#24

This argument is actually undocumented:

http://bugs.python.org/issue901727

To document this a bit, here's a snippet from the distutils source:

            if len(self.extra_path) == 1:
                path_file = extra_dirs = self.extra_path[0]
            elif len(self.extra_path) == 2:
                (path_file, extra_dirs) = self.extra_path
            else:
                raise DistutilsOptionError, \
                      ("'extra_path' option must be a list, tuple, or "
                      "comma-separated string with 1 or 2 elements")

And the function that creates the file:

    def create_path_file (self):
        filename = os.path.join(self.install_libbase,
                                self.path_file + ".pth")
        if self.install_path_file:
            self.execute(write_file,
                         (filename, [self.extra_dirs]),
                         "creating %s" % filename)
        else:
            self.warn("path file '%s' not created" % filename)

From fomcl at yahoo.com  Tue May 21 10:14:34 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Tue, 21 May 2013 01:14:34 -0700 (PDT)
Subject: [Tutor] Which version of python should i use?
In-Reply-To: <CANODV3=nKkTLbmKdZOv6q1_=q9sVgD=kAWNRoLo=Z9A2gja24g@mail.gmail.com>
References: <CAGw83-gZqPNr-KwvJKvhiU4Egnz_c5p0vX5Y17N7ASeD6z3+Eg@mail.gmail.com>
	<5199FD35.4090409@davea.name>
	<CAGw83-hyDPV3jK=MFMoP8D2RYC5jE4EY5XkUcE19Kv1D8pFkQg@mail.gmail.com>
	<CANODV3=nKkTLbmKdZOv6q1_=q9sVgD=kAWNRoLo=Z9A2gja24g@mail.gmail.com>
Message-ID: <1369124074.84923.YahooMailNeo@web163803.mail.gq1.yahoo.com>

> Subject: Re: [Tutor] Which version of python should i use?

> 
> Hello Amal,
> 
> On Mon, May 20, 2013 at 11:24 PM, Amal Thomas <amalthomas111 at gmail.com> 
> wrote:
>>  Thank you very much..!! I am starting to learn python for my Bioinformatics
>>  work, so I would look for the version that has libraries helpful for me..
> 
> Do you already have any libraries in mind (or aware of) that? you
> would want to use? I came across this link:
> http://intro-prog-bioinfo-2012.wikispaces.com/, which doesn't seem to
> use any specific tools other than the "generic" libraries that are
> pretty much common in any scientific work involving Python: SciPy,
> Numpy, etc.


Also check out Python(x, y) (http://code.google.com/p/pythonxy/): "Python(x,y) is a free scientific and engineering development software for numerical computations, data analysis and data visualization based on Python programming language, Qt graphical user interfaces and Spyder interactive scientific development environment."


From Robert.Treder at morganstanley.com  Tue May 21 15:31:08 2013
From: Robert.Treder at morganstanley.com (Treder, Robert)
Date: Tue, 21 May 2013 09:31:08 -0400
Subject: [Tutor] reducing lists within list to their set of unique values
In-Reply-To: <mailman.10940.1369093529.3113.tutor@python.org>
References: <mailman.10940.1369093529.3113.tutor@python.org>
Message-ID: <E84A3AA0F1F20E41953E8486223DD65057F543FE54@NYWEXMBX2130.msad.ms.com>

> Message: 6
> Date: Tue, 21 May 2013 09:45:17 +1000
> From: Steven D'Aprano <steve at pearwood.info>
> To: tutor at python.org
> Subject: Re: [Tutor] reducing lists within list to their set of unique
>	values
> Message-ID: <519AB58D.9020206 at pearwood.info>
> Content-Type: text/plain; charset=UTF-8; format=flowed
>
> On 21/05/13 08:49, Treder, Robert wrote:
>> Hi python folks,
>>
>> I have a list of lists that looks something like this:
>>
>> tst = [ [], ['test'], ['t1', 't2'], ['t1', 't1', 't2'] ]
>>
>> I want to change the empty sets to a blank string, i.e., '' and the lists with repeat values to the unique set of values. So I have done the >> following:
>>
>>>>> for t in tst:
>> 	if len(t) == 0:
>> 		tst.__setitem__(tst.index(t), '')
>> 	else:
>> 		tst.__setitem__(tst.index(t), set(t))
>
>
> As a general rule, if you are writing double-underscore special methods like __setitem__ directly, you're doing it wrong. (There are
> exceptions, but consider them "for experts".)
>
> So instead of tst.__setitem__(a, b) you should write tst[a] = b.
>
> But that's still the wrong way to do this! You're doing a lot of extra work with the calls to tst.index. You won't notice for a short list like > the example above, but for a long list, this will get really, really slow.
>
> The way to do this is to keep track of the index as you walk over the list, and not recalculate it by searching the list:
>
>
> for index, item in enumerate(tst):
>     if item == []:
>         item = ""
>     else:
>         item = list(set(item))
>     tst[index] = item
>
>
> Notice that I call set() to get the unique values, then list() again to turn it back into a list. This does the job you want, but it is not 
> guaranteed to keep the order:
>
> py> L = ['b', 'd', 'c', 'a', 'b']
> py> list(set(L))
> ['a', 'c', 'b', 'd']
>
>
> If keeping the order is important, you cannot use set, and you'll need another way to extract only the unique values. Ask if you need help on 
> that.

Thanks, Steven. Very helpful. It looks like the order is only changed on the inner list that set() is applied to, not on the outer list since the outer list order is controlled by index. For this application I don't care about the order of the inner lists. However there are other applications where that will be import. Can you please describe the alternate method for extracting the unique values that maintains order. 

Thanks, 
Bob

>
>
>
>> What I get in return is
>>
>>>>> tst
>> ['', set(['test']), set(['t2', 't1']), set(['t2', 't1'])]
>>
>> The empty list is fine but the other lists seem to be expressions rather than values. What do I need to do to simply get the values back 
>> liike the following?
>>
>> ['', ['test'], ['t2', 't1'], ['t2', 't1']]
>
>
> They are values. It is just that they are *sets* rather than *lists*. When printed, lists have a nice compact representation using square 
> brackets [], but unfortunately sets do not. However, if you upgrade to Python 3, they have been upgraded to look a little nicer:
>
>
> # Python 2:
> set(['a', 'c', 'b', 'd'])
> 
> # Python 3
> {'d', 'b', 'c', 'a'}
>
>
> Notice that the order of the items is not guaranteed, but apart from that, the two versions are the same despite the difference in print 
> representation.
>
> -- 
> Steven




--------------------------------------------------------------------------------

NOTICE: Morgan Stanley is not acting as a municipal advisor and the opinions or views contained herein are not intended to be, and do not constitute, advice within the meaning of Section 975 of the Dodd-Frank Wall Street Reform and Consumer Protection Act. If you have received this communication in error, please destroy all electronic and paper copies and notify the sender immediately. Mistransmission is not intended to waive confidentiality or privilege. Morgan Stanley reserves the right, to the extent permitted under applicable law, to monitor electronic communications. This message is subject to terms available at the following link: http://www.morganstanley.com/disclaimers. If you cannot access these links, please notify us by reply message and we will send the contents to you. By messaging with Morgan Stanley you consent to the foregoing.

From oscar.j.benjamin at gmail.com  Tue May 21 17:12:03 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Tue, 21 May 2013 16:12:03 +0100
Subject: [Tutor] reducing lists within list to their set of unique values
In-Reply-To: <E84A3AA0F1F20E41953E8486223DD65057F543FE54@NYWEXMBX2130.msad.ms.com>
References: <mailman.10940.1369093529.3113.tutor@python.org>
	<E84A3AA0F1F20E41953E8486223DD65057F543FE54@NYWEXMBX2130.msad.ms.com>
Message-ID: <CAHVvXxSkgQMijLcE9tkpvaN8BYQWUQY9+euD5hjrhHk_MkRwjw@mail.gmail.com>

On 21 May 2013 14:31, Treder, Robert <Robert.Treder at morganstanley.com> wrote:
> Steven wrote:
>>
>> py> L = ['b', 'd', 'c', 'a', 'b']
>> py> list(set(L))
>> ['a', 'c', 'b', 'd']
>>
>>
>> If keeping the order is important, you cannot use set, and you'll need another way to extract only the unique values. Ask if you need help on
>> that.
>
> Thanks, Steven. Very helpful. It looks like the order is only changed on the inner list that
> set() is applied to, not on the outer list since the outer list order is controlled by index.
> For this application I don't care about the order of the inner lists. However there are other
> applications where that will be import. Can you please describe the alternate method for
> extracting the unique values that maintains order.

There isn't necessarily a uniquely defined ordering. Here's a function
that preserves the order of the first occurrences of each element in
each list:

def uniquify(original):
    new = []
    seen = set()
    for item in original:
        if item not in seen:
            new.append(item)
            seen.add(item)
    return new

>>> uniquify([1, 2, 3, 1, 2, 5])
[1, 2, 3, 5]


Oscar

From spiff007 at gmail.com  Tue May 21 17:52:35 2013
From: spiff007 at gmail.com (spiff007)
Date: Tue, 21 May 2013 21:22:35 +0530
Subject: [Tutor] Hi Folks...Need help with a modified version of the Subset
	sum problem.
Message-ID: <CADqYtOtCHUn6qtnBuCwsoXMB-Wg72QW+TK6r1=btx=S7Fm4_LA@mail.gmail.com>

Hi there Tutor folks

I need your help with a modified version of the subset sum problem [
http://en.wikipedia.org/wiki/Subset_sum_problem].

The problem i am facing is a bit hard to describe (as most complex problem
always are :D ), so please bear with my longish articulation :)

Here it goes :

After scrubbing some input data, i have two lists 'minutes' (elements are
positive integers) & 'names' (elements are strings). They are the exact
same length and each element of one corresponds exactly with the respective
element of the other.

The elements in the minutes list are not unique; a sample list is :
minutes = [60, 45, 30, 45, 45, 5, 60, 45, 30, 30, 45, 60, 60, 45, 30, 30,
60, 30, 30 ]
names = ['abc', 'ghi', 'jkl', 'def', 'zab', 'wux', ........... ]

Now i need to pick some elements from the 'minutes' list (i.e. a subset of
minutes) which add up to a certain sum ('target_sum1').
I have to then do some processing with the *respective elements from the
'names' list, corresponding to, the elements i just picked from the
'minutes' list which sum upto target_sum1.*

I now have to remove these elements i picked (which add up to 'target_sum1'
) from the 'minutes' list, and essentially do a second pass, picking some
elements, which add up to a certain other sum ('target_sum2'). Again, *retrieve
the elements from the 'names' list*, *corresponding to the elements i just
picked which sum upto 'target_sum2'*,  & do some processing on them.  And
so  on.

Picking a subset of numbers, which add up to a certain target sum, is a
well-known problem[1] & i have found the following code for it [2] :

I also have the code on a github gist
https://gist.github.com/anonymous/5620886

def subset_sum_recursive(numbers,target,partial):
    s = sum(partial)

    #check if the partial sum is equals to target
    if s == target:
        print "sum(%s)=%s"%(partial,target)
    if s >= target:
        return # if we reach the number why bother to continue

    for i in range(len(numbers)):
        n = numbers[i]
        remaining = numbers[i+1:]
        subset_sum_recursive(remaining,target,partial + [n])

def subset_sum(numbers,target):
    #we need an intermediate function to start the recursion.
    #the recursion starts with an empty list  as partial solution.
    subset_sum_recursive(numbers,target,list())

if __name__ == "__main__":
    minutes = [3,9,8,4,5,7,10]
    target_sum = 15
    subset_sum(minutes,target_sum)

    #Outputs:
    #sum([3, 8, 4])=15
    #sum([3, 5, 7])=15
    #sum([8, 7])=15
    #sum([5, 10])=15


This above code returns the elements of the 'minutes' list(subset of the
'minutes' list)  which add up to 'target_sum'.

*I am stuck on this point : *
*I am unable to determine the list indices, of the elements of 'minutes'
which add upto 'target_sum1', so i can retrieve the corresponding elements
from the 'names' list, & do my processing on them.*
*
*
*I also need the list indices to remove the elements which add upto
target_sum1, and then run a "second pass", to determine the elements which
add upto 'target_sum2'.*

Any & all explanations/links/code
snippets/thoughts/ideas/suggestions/feedback/comments/ of the Python tutor
community would be greatly appreciated.

Thanks a ton,
calvin
spiff007 at gmail.com



References

1. http://en.wikipedia.org/wiki/Subset_sum_problem
2. http://stackoverflow.com/a/4633515/559456
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130521/ab8675b8/attachment.html>

From __peter__ at web.de  Tue May 21 19:59:03 2013
From: __peter__ at web.de (Peter Otten)
Date: Tue, 21 May 2013 19:59:03 +0200
Subject: [Tutor] Hi Folks...Need help with a modified version of the
	Subset sum problem.
References: <CADqYtOtCHUn6qtnBuCwsoXMB-Wg72QW+TK6r1=btx=S7Fm4_LA@mail.gmail.com>
Message-ID: <kngckh$7md$1@ger.gmane.org>

spiff007 wrote:

> Hi there Tutor folks
> 
> I need your help with a modified version of the subset sum problem [
> http://en.wikipedia.org/wiki/Subset_sum_problem].
> 
> The problem i am facing is a bit hard to describe (as most complex problem
> always are :D ), so please bear with my longish articulation :)
> 
> Here it goes :
> 
> After scrubbing some input data, i have two lists 'minutes' (elements are
> positive integers) & 'names' (elements are strings). They are the exact
> same length and each element of one corresponds exactly with the
> respective element of the other.
> 
> The elements in the minutes list are not unique; a sample list is :
> minutes = [60, 45, 30, 45, 45, 5, 60, 45, 30, 30, 45, 60, 60, 45, 30, 30,
> 60, 30, 30 ]
> names = ['abc', 'ghi', 'jkl', 'def', 'zab', 'wux', ........... ]
> 
> Now i need to pick some elements from the 'minutes' list (i.e. a subset of
> minutes) which add up to a certain sum ('target_sum1').
> I have to then do some processing with the *respective elements from the
> 'names' list, corresponding to, the elements i just picked from the
> 'minutes' list which sum upto target_sum1.*
> 
> I now have to remove these elements i picked (which add up to
> 'target_sum1' ) from the 'minutes' list, and essentially do a second pass,
> picking some elements, which add up to a certain other sum
> ('target_sum2'). Again, *retrieve the elements from the 'names' list*,
> *corresponding to the elements i just
> picked which sum upto 'target_sum2'*,  & do some processing on them.  And
> so  on.
> 
> Picking a subset of numbers, which add up to a certain target sum, is a
> well-known problem[1] & i have found the following code for it [2] :
> 
> I also have the code on a github gist
> https://gist.github.com/anonymous/5620886
> 
> def subset_sum_recursive(numbers,target,partial):
>     s = sum(partial)
> 
>     #check if the partial sum is equals to target
>     if s == target:
>         print "sum(%s)=%s"%(partial,target)
>     if s >= target:
>         return # if we reach the number why bother to continue
> 
>     for i in range(len(numbers)):
>         n = numbers[i]
>         remaining = numbers[i+1:]
>         subset_sum_recursive(remaining,target,partial + [n])
> 
> def subset_sum(numbers,target):
>     #we need an intermediate function to start the recursion.
>     #the recursion starts with an empty list  as partial solution.
>     subset_sum_recursive(numbers,target,list())
> 
> if __name__ == "__main__":
>     minutes = [3,9,8,4,5,7,10]
>     target_sum = 15
>     subset_sum(minutes,target_sum)
> 
>     #Outputs:
>     #sum([3, 8, 4])=15
>     #sum([3, 5, 7])=15
>     #sum([8, 7])=15
>     #sum([5, 10])=15
> 
> 
> This above code returns the elements of the 'minutes' list(subset of the
> 'minutes' list)  which add up to 'target_sum'.
> 
> *I am stuck on this point : *
> *I am unable to determine the list indices, of the elements of 'minutes'
> which add upto 'target_sum1', so i can retrieve the corresponding elements
> from the 'names' list, & do my processing on them.*

I think the easiest approach is to combine the two lists into a single one

pairs = zip(names, minutes)

or, if you really need the indices

pairs = list(enumerate(minutes))

and invoke subset_sum() with these pairs instead of minutes alone.
Of course you have to modify the sum() call to unpack the pairs:

s = sum(value for index, value in partial)

> *I also need the list indices to remove the elements which add upto
> target_sum1, and then run a "second pass", to determine the elements which
> add upto 'target_sum2'.*
> 
> Any & all explanations/links/code
> snippets/thoughts/ideas/suggestions/feedback/comments/ of the Python tutor
> community would be greatly appreciated.
> 
> Thanks a ton,
> calvin
> spiff007 at gmail.com
> 
> 
> 
> References
> 
> 1. http://en.wikipedia.org/wiki/Subset_sum_problem
> 2. http://stackoverflow.com/a/4633515/559456



From robertvstepp at gmail.com  Tue May 21 20:18:43 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Tue, 21 May 2013 13:18:43 -0500
Subject: [Tutor] Configuring Emacs for Python development?
Message-ID: <CANDiX9Ktv36VS-R66BTTTu3gY9pg=9TNd4=dX6Pktakepw0N2g@mail.gmail.com>

Okay. Since I first joined this list I have played around (as time
permitted) with these editors/IDEs: PyCharm, Eclipse with PyDev,
Notepad++, Emacs, IDLE, PyScripter, IdleX, Sublime Text, and possibly
others. Of course, I have far from mastered any of them, but I think
that I have a sense of what each is capable of plus an idea of their
quirks/bugs. I have found that I do not entirely like any of them. I
suppose that is normal. Of the above list I like Notepad++, PyCharm
and Emacs the best. I have decided to eliminate Notepad++ due to it
being tied entirely to Windows and that it does not have the power of
Emacs. I liked PyCharm enough that when a special Earth Day sale came
out, I purchased a license for it. Eventually, I think that I will
gravitate to this if I start creating truly large projects, but I
cannot use it at work. And it seems to be overkill for just beginning
in Python. And I don't like the idea of creating a project for what
amounts to one-off scripts.

So I am led to Emacs. I like the ability to keep my fingers on the
keyboard for almost everything I might want to do. And PyCharm has an
ever-improving Emacs keybinding mode for when I do start using it. It
SHOULD be available at work on the two Solaris 10 systems I do most of
my work on, but I found out today that while the binary for Emacs
exists on both systems, not all of the dependencies are installed.
However, I am hoping to get permission to install a fresh, latest,
greatest version of Emacs on these systems, but even if I don't
Googling has revealed that Emacs can edit remote files via something
called Tramp. So it looks like I could install Emacs on my Windows PC
at work and edit from there. Likewise at home I am on Windows 7-64 bit
Pro and have already installed GNU Emacs 24.3.

When I last mentioned Emacs there was at least one offer to help me
optimally configure Emacs for Python development on Windows. I am
currently using version 3.3. This does not appear straightforward to
me. When I Google for this topic, people have taken different
approaches and I do not have the background or experience to judge
which would work best for me. Additionally this latest version of
Emacs apparently has made some improvements to the Python.el mode and
it is not clear to me what suggestions will or will not work with
this.

Anyone care to help me with this?

As always, thanks!
boB

From cybervigilante at gmail.com  Wed May 22 02:09:33 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Tue, 21 May 2013 17:09:33 -0700
Subject: [Tutor] nose error
Message-ID: <CALRAYNVqPjA2i=609m9MRNy5f8-H+oM=wnYD-a_NsaqwMcdoMQ@mail.gmail.com>

I'm trying a nose test on a simple prog. Once I got past the huge
traceback in Wing that made me think nose didn't work I realized the
prog tested okay. But I noticed at the end of the traceback nose says
this:

"c:\Python27\Lib\site-packages\nose-1.3.0-py2.7.egg\nose\core.py",
line 200, in runTests
    sys.exit(not self.success)
SystemExit: False

As i said, nose works and says Okay on the asserts (or not if I give
things a bad value). I was just wondering what they SystemExit: False
meant, or is that standard?

Jim

"When I got to high school I realized my name would always present
problems." --Dick Hertz

From cybervigilante at gmail.com  Wed May 22 02:25:37 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Tue, 21 May 2013 17:25:37 -0700
Subject: [Tutor] still nosing around
Message-ID: <CALRAYNUdsT5Pb5QA91fJ+zB_qFcy9-EmWUttSCb1AY6F_dB2tg@mail.gmail.com>

Okay, why is nose saying this run is OK when I purposely screwed it up?

import nose

def stand_and_deliver():
    return 52

def stupid_error():
    '''This is my stupid error'''
    assert stand_and_deliver() == 17

if __name__ == '__main__':
    nose.runmodule()

nose result:

Ran 0 tests in 0.000s

OK


-- 
Jim Mooney

"When I got to high school I realized my name would always present
problems." --Dick Hertz

From breamoreboy at yahoo.co.uk  Wed May 22 02:50:53 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Wed, 22 May 2013 01:50:53 +0100
Subject: [Tutor] still nosing around
In-Reply-To: <CALRAYNUdsT5Pb5QA91fJ+zB_qFcy9-EmWUttSCb1AY6F_dB2tg@mail.gmail.com>
References: <CALRAYNUdsT5Pb5QA91fJ+zB_qFcy9-EmWUttSCb1AY6F_dB2tg@mail.gmail.com>
Message-ID: <knh4om$1kd$1@ger.gmane.org>

On 22/05/2013 01:25, Jim Mooney wrote:
> Okay, why is nose saying this run is OK when I purposely screwed it up?
>
> import nose
>
> def stand_and_deliver():
>      return 52
>
> def stupid_error():
>      '''This is my stupid error'''
>      assert stand_and_deliver() == 17
>
> if __name__ == '__main__':
>      nose.runmodule()
>
> nose result:
>
> Ran 0 tests in 0.000s
>
> OK
>
>

Do you ever bother to investigate anything before posing a question?  I 
know nothing about nose, but when I see output telling me that precisely 
nothing has been run, I'd hazard a guess that stupid_error has to be 
called test_stupid_error or similar.  I'll leave you to check the nose 
docs to confirm whether or not my guess is correct.

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From steve at pearwood.info  Wed May 22 02:53:54 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 22 May 2013 10:53:54 +1000
Subject: [Tutor] still nosing around
In-Reply-To: <CALRAYNUdsT5Pb5QA91fJ+zB_qFcy9-EmWUttSCb1AY6F_dB2tg@mail.gmail.com>
References: <CALRAYNUdsT5Pb5QA91fJ+zB_qFcy9-EmWUttSCb1AY6F_dB2tg@mail.gmail.com>
Message-ID: <519C1722.1060201@pearwood.info>

On 22/05/13 10:25, Jim Mooney wrote:
> Okay, why is nose saying this run is OK when I purposely screwed it up?
>
> import nose
>
> def stand_and_deliver():
>      return 52
>
> def stupid_error():
>      '''This is my stupid error'''
>      assert stand_and_deliver() == 17
>
> if __name__ == '__main__':
>      nose.runmodule()
>
> nose result:
>
> Ran 0 tests in 0.000s
>
> OK


"Ran 0 tests" -- does that give you a clue? Nose is not running any tests. I have never used nose, so I don't know how you write tests for it, but whatever you are supposed to do, you haven't done it.

Let's see what Google has to say... this looks promising.

http://nose.readthedocs.org/en/latest/testing.html


As far as I can tell from about 30 seconds reading that page, your tests have to inherit from unittest.TestCase, or they have to be in a function, class or module called TestMatch.

(There must be something useful about nose, but frankly I don't see the benefit of running it instead of just using unittest directly.)


Personally, I recommend you start with doctests rather than nose or unittest. Change your module to this:

=== cut ===

def stand_and_deliver():
     """Always returns 52.

     >>> stand_and_deliver()
     52

     """
     return 52


def stupid_error():
     """This is my stupid error.

     >>> stupid_error()
     17

     """
     return stand_and_deliver() + 1000


if __name__ == '__main__':
     import doctest
     failed, run = doctest.testmod()
     if failed == 0:
         print("Successfully ran %d doc tests." % run)


=== cut ===



Run that file, and you should get 1 failed test out of 2, and a description of how it failed.





-- 
Steven

From eryksun at gmail.com  Wed May 22 03:16:15 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 21 May 2013 21:16:15 -0400
Subject: [Tutor] nose error
In-Reply-To: <CALRAYNVqPjA2i=609m9MRNy5f8-H+oM=wnYD-a_NsaqwMcdoMQ@mail.gmail.com>
References: <CALRAYNVqPjA2i=609m9MRNy5f8-H+oM=wnYD-a_NsaqwMcdoMQ@mail.gmail.com>
Message-ID: <CACL+1avGBBUf-iCCnvhVpc-Xph8XHWr2VcUJ=0v+CUfqxX+F8w@mail.gmail.com>

On Tue, May 21, 2013 at 8:09 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
>
> "c:\Python27\Lib\site-packages\nose-1.3.0-py2.7.egg\nose\core.py",
> line 200, in runTests
>     sys.exit(not self.success)
> SystemExit: False
>
> As i said, nose works and says Okay on the asserts (or not if I give
> things a bad value). I was just wondering what they SystemExit: False
> meant, or is that standard?

Python's bool type is a subclass of int, so the function that handles
system exit converts False to 0. In terms of process exit codes, 0
means success. On Windows the exit code is set in "errorlevel":

    >>> raise SystemExit(False)

    C:\>echo %errorlevel%
    0

    >>> raise SystemExit(True)

    C:\>if errorlevel 1 echo spam
    spam

From steve at pearwood.info  Wed May 22 05:03:13 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 22 May 2013 13:03:13 +1000
Subject: [Tutor] still nosing around
In-Reply-To: <knh4om$1kd$1@ger.gmane.org>
References: <CALRAYNUdsT5Pb5QA91fJ+zB_qFcy9-EmWUttSCb1AY6F_dB2tg@mail.gmail.com>
	<knh4om$1kd$1@ger.gmane.org>
Message-ID: <519C3571.1000400@pearwood.info>

On 22/05/13 10:50, Mark Lawrence wrote:

> Do you ever bother to investigate anything before posing a question?


That's rather harsh. The OP is doing a fine job at investigating new tools, and he's far more adventurous than I was at his level of expertise. (Or now, for that matter...) I think we can forgive him the occasional "whoops" moment.



-- 
Steven

From cybervigilante at gmail.com  Wed May 22 06:26:56 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Tue, 21 May 2013 21:26:56 -0700
Subject: [Tutor] Tutor Digest, Vol 111, Issue 72
In-Reply-To: <mailman.11186.1369191815.3113.tutor@python.org>
References: <mailman.11186.1369191815.3113.tutor@python.org>
Message-ID: <CALRAYNWcgjpARRiDJKZ=NhqjkuK-un12-zhC0hit2B=yKej=og@mail.gmail.com>

> Do you ever bother to investigate anything before posing a question?

Actually, I did notice that tests were zero, but the book I am using
does not mention needing the word 'test' as part of the regex. There
is only so much time in a day and so many books I can buy (and not all
comprehensive, apparently.)

That is why this list is an excellent ancillary to save me time.
Otherwise, learning Py will take me a lot more time than I can budget.
I'm not reading all the docs right now - which I used to and may in
the future - because I'm trying a different method of just running a
lot of progs to get up to speed. I figure once I "grok" the language,
docs will be a lot easier. There is a certain logic to every language
so you can anticipate what is right, but I'm not there yet.

But that brings up a point. Does this mean that if I have to test a
module with a lot of subroutines I have to rename every subroutine
with 'test' appended?

Try replying with a bit less emotion ;')

Jim

From andrew139668 at yahoo.com  Wed May 22 07:02:59 2013
From: andrew139668 at yahoo.com (Andrew Triplett)
Date: Tue, 21 May 2013 22:02:59 -0700 (PDT)
Subject: [Tutor] challenge-chapter 2
Message-ID: <1369198979.77301.YahooMailNeo@web122003.mail.ne1.yahoo.com>

I am on chapter two for Python Programming working on the challenges and the question is:

1. Create a list of legal and illegal variable names. Describe why each is either legal or illegal. Next, create a list of "good" and "bad" legal variable names. Describe why each is either a good or bad choice for a variable name.

Can you help me solve this problem?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130521/d5dcfbff/attachment.html>

From cybervigilante at gmail.com  Wed May 22 07:46:06 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Tue, 21 May 2013 22:46:06 -0700
Subject: [Tutor] try..except - what about that ton of **Error statements?
Message-ID: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>

I'm looking at Try..Except

Try:
     <some statements>
Except SomethingError as err:
    <other statements>

The list of error statements is huge. How do I know which error
statement to put in place of SomethingError (or multiple errors for
that matter)? Or is it best to just leave SomethingError blank until I
know more? ( I have an asymptotic learning curve, so I go off on a lot
of confused tangents, but I find it makes things go a lot faster after
a certain point.)

-- 
Jim Mooney

"When I got to high school I realized my name would always present
problems." --Dick Hertz

From cybervigilante at gmail.com  Wed May 22 08:20:29 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Tue, 21 May 2013 23:20:29 -0700
Subject: [Tutor] try..except - what about that ton of **Error statements?
In-Reply-To: <CAG6Bxkck58SvaSh522947dJM5TiAyACTNqj0xutFywOYRnyzPg@mail.gmail.com>
References: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>
	<CAG6Bxkck58SvaSh522947dJM5TiAyACTNqj0xutFywOYRnyzPg@mail.gmail.com>
Message-ID: <CALRAYNXKMuLqg=spN2A25evurvoJYva2zQj+6m2Sd1+AfaA+Ow@mail.gmail.com>

> Keep the try block small. For example if it's for a call to
> open(filename, "r") the only possible errors (assuming correct syntax)
> are NameError for using an undefined variable and IOError for
> specifying a file which doesnt exist.

Thanks. Since I'm new at this the error lists I saw just had the bald
names, which didn't tell me much. But I found a concise and basic
explanation of each error at
http://python.about.com/od/pythonstandardlibrary/a/lib_exceptions.htm

Although it's still a bit circular at my level. I won't be sure what
errors to raise until I see enough errors, but that will come with
experience, I guess. Now I just have to figure how to print the list
out without the ads ;')

Jim

From bodsda at googlemail.com  Wed May 22 08:25:52 2013
From: bodsda at googlemail.com (Bod Soutar)
Date: Wed, 22 May 2013 07:25:52 +0100
Subject: [Tutor] try..except - what about that ton of **Error statements?
In-Reply-To: <CALRAYNXKMuLqg=spN2A25evurvoJYva2zQj+6m2Sd1+AfaA+Ow@mail.gmail.com>
References: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>
	<CAG6Bxkck58SvaSh522947dJM5TiAyACTNqj0xutFywOYRnyzPg@mail.gmail.com>
	<CALRAYNXKMuLqg=spN2A25evurvoJYva2zQj+6m2Sd1+AfaA+Ow@mail.gmail.com>
Message-ID: <CAG6Bxkc4mFkkKudqt6Jfz-iHdUarBLDkrwoaa_eSGQC0nuaddg@mail.gmail.com>

On 22 May 2013 07:20, Jim Mooney <cybervigilante at gmail.com> wrote:
>> Keep the try block small. For example if it's for a call to
>> open(filename, "r") the only possible errors (assuming correct syntax)
>> are NameError for using an undefined variable and IOError for
>> specifying a file which doesnt exist.
>
> Thanks. Since I'm new at this the error lists I saw just had the bald
> names, which didn't tell me much. But I found a concise and basic
> explanation of each error at
> http://python.about.com/od/pythonstandardlibrary/a/lib_exceptions.htm
>
> Although it's still a bit circular at my level. I won't be sure what
> errors to raise until I see enough errors, but that will come with
> experience, I guess. Now I just have to figure how to print the list
> out without the ads ;')
>
> Jim
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

One thing I tend to do is fire up the interpreter and deliberately
write something that should fail, then I can see what error is raised.
For example, when I suggested the open() test, I fired up the
interpreter and tried

>>> open(dave, "r")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'dave' is not defined

>>> open("dave2", "r")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'dave2'

From fomcl at yahoo.com  Wed May 22 09:18:10 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Wed, 22 May 2013 00:18:10 -0700 (PDT)
Subject: [Tutor] still nosing around
In-Reply-To: <519C1722.1060201@pearwood.info>
References: <CALRAYNUdsT5Pb5QA91fJ+zB_qFcy9-EmWUttSCb1AY6F_dB2tg@mail.gmail.com>
	<519C1722.1060201@pearwood.info>
Message-ID: <1369207090.11040.YahooMailNeo@web163805.mail.gq1.yahoo.com>



?

<snip>
> Personally, I recommend you start with doctests rather than nose or unittest. 


Doctests can also be run using nose, maybe that's also an idea? Nose does doctest, unittest, and its own tests. By default, test files need to have a prefix "test_". Unless you specify this either as a commanline switch or in the .cfg file, nose won't do doctests. 

<snip>


From marc.tompkins at gmail.com  Wed May 22 09:21:45 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 22 May 2013 00:21:45 -0700
Subject: [Tutor] try..except - what about that ton of **Error statements?
In-Reply-To: <CAG6Bxkc4mFkkKudqt6Jfz-iHdUarBLDkrwoaa_eSGQC0nuaddg@mail.gmail.com>
References: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>
	<CAG6Bxkck58SvaSh522947dJM5TiAyACTNqj0xutFywOYRnyzPg@mail.gmail.com>
	<CALRAYNXKMuLqg=spN2A25evurvoJYva2zQj+6m2Sd1+AfaA+Ow@mail.gmail.com>
	<CAG6Bxkc4mFkkKudqt6Jfz-iHdUarBLDkrwoaa_eSGQC0nuaddg@mail.gmail.com>
Message-ID: <CAKK8jXaapsXKvc4Fyv7_5Bo3hNJk3oy05fbeatGA_cKSD1aOLA@mail.gmail.com>

On Tue, May 21, 2013 at 11:25 PM, Bod Soutar <bodsda at googlemail.com> wrote:

> On 22 May 2013 07:20, Jim Mooney <cybervigilante at gmail.com> wrote:
> >> Keep the try block small. For example if it's for a call to
> >> open(filename, "r") the only possible errors (assuming correct syntax)
> >> are NameError for using an undefined variable and IOError for
> >> specifying a file which doesnt exist.
> >
> > Thanks. Since I'm new at this the error lists I saw just had the bald
> > names, which didn't tell me much. But I found a concise and basic
> > explanation of each error at
> > http://python.about.com/od/pythonstandardlibrary/a/lib_exceptions.htm
> >
> > Although it's still a bit circular at my level. I won't be sure what
> > errors to raise until I see enough errors, but that will come with
> > experience, I guess. Now I just have to figure how to print the list
> > out without the ads ;')
> >
> > Jim
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
>
> One thing I tend to do is fire up the interpreter and deliberately
> write something that should fail, then I can see what error is raised.
> For example, when I suggested the open() test, I fired up the
> interpreter and tried
>
> >>> open(dave, "r")
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> NameError: name 'dave' is not defined
>
> >>> open("dave2", "r")
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> IOError: [Errno 2] No such file or directory: 'dave2'
>

I would just like to contribute my $.02 worth here and say: be VERY
conservative about assuming that you know what the error was/what caused
it.  As a user, and as support for users, nothing irritates me more than a
program that lies to me (unintentionally, of course) about what's wrong.
Case in point: back in the 80s and early 90s, "out of memory" errors were
extremely common - not necessarily because memory was actually scarce (it
WAS, but we knew how to deal with that) but because that was the default
error code if nothing else matched.  The actual error was sometimes "file
not found", or "printer not plugged in", or something else equally
unrelated to an actual shortage of memory - but because the programmer had
1) not foreseen the particular problem and 2) put in a catch-all that
assumed that "all errors not otherwise specified" were "out of memory",
troubleshooting was much harder than it should have been.

In short: if you're going to take the "catch all errors" approach (instead
of simply predicting what the most common errors might be), always let the
default be either to display the error and a traceback (in a dialog box,
for example) or to actually let the program crash and display the error on
stdout.  If you try to be too clever, your users will end up hating you for
it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130522/7be76fa9/attachment.html>

From stutozer at gmail.com  Wed May 22 09:49:07 2013
From: stutozer at gmail.com (Stuart Tozer)
Date: Wed, 22 May 2013 10:49:07 +0300
Subject: [Tutor] trying to split or rpartition the contents of a list
Message-ID: <CA+pweXvAGMit3eaOHAm3-6AJSNwoD5Ki4nVYSXXFc1k0tKu8Pw@mail.gmail.com>

Hi everyone.

I'm stuck on a problem while developing a small tool for Maya. Basically, I
have a folder with some filenames in it which have been returned by
os.listdir().
These filenames look something like...


apple_d.jpg
apple_si.jpg
apple_sg.jpg
box_d.jpg
box_si.jpg
pumpkin_d.jpg


Right now, I'm using os.listdir to get the filenames, and then each
filename becomes a selectable option in an option menu in maya. The code
is...

objects = os.listdir(dir)





    for object in objects:
        cmds.menuItem(label = object, parent = "objectMenu")



My problem is that I don't want duplicates of the same object in the menu
and I also want to truncate everything past and including the underscore.
So for eg, if my filenames are the same as the example above, I want to
change the list so I have this instead...

apple
box
pumpkin


I have tried splitting the filenames, but so far haven't had any luck.

for object in objects:
        sorted(set(object.split('_', 1)[0]))
        cmds.menuItem(label = object, parent = "objectMenu")



Also, I tried .rpartition but also no luck. I'm very new to python and this
has me stumped.
Any suggestions would be most welcome! ;)

Cheers,
S Tozer




-- 
http://stutozer.elementfx.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130522/05a5c87a/attachment.html>

From __peter__ at web.de  Wed May 22 09:59:46 2013
From: __peter__ at web.de (Peter Otten)
Date: Wed, 22 May 2013 09:59:46 +0200
Subject: [Tutor] challenge-chapter 2
References: <1369198979.77301.YahooMailNeo@web122003.mail.ne1.yahoo.com>
Message-ID: <knhtsq$27u$1@ger.gmane.org>

Andrew Triplett wrote:

> I am on chapter two for Python Programming working on the challenges and
> the question is:
> 
> 1. Create a list of legal and illegal variable names. Describe why each is
> either legal or illegal. Next, create a list of "good" and "bad" legal
> variable names. Describe why each is either a good or bad choice for a
> variable name.
> 
> Can you help me solve this problem?

i
n
foo
1timepad
with
__
_name
__name
row1
row2
row3
question
length
x
bottles
number_of_bottles
number_of_bottles_of_beer_on_the_wall
seperate_concerns
next_KindOfQuestion
it's_about_time
Animal
animal
ANIMAL
HttpServer
HTTPServer
bin2hex
bin_to_hex
childs
intNumber
strValue

So here's your lists, but they got totally mixed up. Also, while it's easy 
to separate the legal from the illegal names (by typing them into the 
interpreter) the distinction between good and bad is not so clear-cut.
You really have to think about it and form an opinion. Write it down in a 
sentence or two and post it here.

Hint: Often a name may even be good or bad depending on the context.
For example

for x, y in points:
    r = math.sqrt(x*x + y*y)
    print x, y, "-->", r

Here x is a fine name because if follows a well-known mathematical 
convention...

with open(datafile, "rb") as f:
    x = pickle.load(f)

...whereas this x leaves you totally clueless about what x could contain.


Another hint: One criterium to decide whether a name is "good" is its 
compliance with PEP 8 
<http://www.python.org/dev/peps/pep-0008/#naming-conventions>



From amitsaha.in at gmail.com  Wed May 22 09:55:30 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Wed, 22 May 2013 17:55:30 +1000
Subject: [Tutor] trying to split or rpartition the contents of a list
In-Reply-To: <CA+pweXvAGMit3eaOHAm3-6AJSNwoD5Ki4nVYSXXFc1k0tKu8Pw@mail.gmail.com>
References: <CA+pweXvAGMit3eaOHAm3-6AJSNwoD5Ki4nVYSXXFc1k0tKu8Pw@mail.gmail.com>
Message-ID: <CANODV3msku5omE93-bLkPsa8BDakg9KToeSWuHnwcVNABbu+4Q@mail.gmail.com>

Hello,

On Wed, May 22, 2013 at 5:49 PM, Stuart Tozer <stutozer at gmail.com> wrote:
> Hi everyone.
>
> I'm stuck on a problem while developing a small tool for Maya. Basically, I
> have a folder with some filenames in it which have been returned by
> os.listdir(). These filenames look something like...
>
>
> apple_d.jpg
> apple_si.jpg
> apple_sg.jpg
> box_d.jpg
> box_si.jpg
> pumpkin_d.jpg
>
>
> Right now, I'm using os.listdir to get the filenames, and then each filename
> becomes a selectable option in an option menu in maya. The code is...
>
> objects = os.listdir(dir)
>
>
>
>
>
>     for object in objects:
>         cmds.menuItem(label = object, parent = "objectMenu")
>
>
>
> My problem is that I don't want duplicates of the same object in the menu
> and I also want to truncate everything past and including the underscore. So
> for eg, if my filenames are the same as the example above, I want to change
> the list so I have this instead...
>
> apple
> box
> pumpkin
>
>
> I have tried splitting the filenames, but so far haven't had any luck.
>
> for object in objects:
>         sorted(set(object.split('_', 1)[0]))
>         cmds.menuItem(label = object, parent = "objectMenu")

You are almost there.

Something like this should work:

>>> labels = ['apple_d.jpg','apple_si.jpg','apple_sg.jpg','box_si.jpg']

Now, create a list of only the names (upto _):

>>> labels_processed=[ ]
>>> for label in labels:
...     labels_processed.append(label.split('_')[0])
...

Remove the duplicates:

>>> set(labels_processed)
set(['box', 'apple'])

If you have any doubts about this, please ask.

Best,
Amit.



--
http://echorand.me

From fomcl at yahoo.com  Wed May 22 10:06:09 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Wed, 22 May 2013 01:06:09 -0700 (PDT)
Subject: [Tutor] trying to split or rpartition the contents of a list
In-Reply-To: <CA+pweXvAGMit3eaOHAm3-6AJSNwoD5Ki4nVYSXXFc1k0tKu8Pw@mail.gmail.com>
References: <CA+pweXvAGMit3eaOHAm3-6AJSNwoD5Ki4nVYSXXFc1k0tKu8Pw@mail.gmail.com>
Message-ID: <1369209969.43785.YahooMailNeo@web163804.mail.gq1.yahoo.com>

>

>forobjectinobjects:sorted(set(object.split('_',1)[0]))cmds.menuItem(label =object,parent ="objectMenu")


"sorted" returns the sorted list but you don't assign anything to it. You can either assign it to a variable, or use the .sort method instead. Also, you don't need to specify the maxsplit argument (1) in .split. Also, you used 'object' as a loop index but this is a reserved word. Why not use the more descriptive "for filename in filenames"?

From stutozer at gmail.com  Wed May 22 10:39:03 2013
From: stutozer at gmail.com (Stuart Tozer)
Date: Wed, 22 May 2013 11:39:03 +0300
Subject: [Tutor] trying to split or rpartition the contents of a list
In-Reply-To: <1369209969.43785.YahooMailNeo@web163804.mail.gq1.yahoo.com>
References: <CA+pweXvAGMit3eaOHAm3-6AJSNwoD5Ki4nVYSXXFc1k0tKu8Pw@mail.gmail.com>
	<1369209969.43785.YahooMailNeo@web163804.mail.gq1.yahoo.com>
Message-ID: <CA+pweXvug6NjxQs3VUXm0rqmRuTph2YtB_uM=nkxk41a99Tn8Q@mail.gmail.com>

Thanks very much guys- I'll get back to this when I have a spare moment and
let you know how I get on.

Cheers,
Stu



On Wed, May 22, 2013 at 11:06 AM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:

> >
>
> >forobjectinobjects:sorted(set(object.split('_',1)[0]))cmds.menuItem(label
> =object,parent ="objectMenu")
>
>
> "sorted" returns the sorted list but you don't assign anything to it. You
> can either assign it to a variable, or use the .sort method instead. Also,
> you don't need to specify the maxsplit argument (1) in .split. Also, you
> used 'object' as a loop index but this is a reserved word. Why not use the
> more descriptive "for filename in filenames"?
>



-- 
http://stutozer.elementfx.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130522/63ddc59c/attachment.html>

From chigga101 at gmail.com  Wed May 22 11:52:39 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Wed, 22 May 2013 10:52:39 +0100
Subject: [Tutor] challenge-chapter 2
In-Reply-To: <1369198979.77301.YahooMailNeo@web122003.mail.ne1.yahoo.com>
References: <1369198979.77301.YahooMailNeo@web122003.mail.ne1.yahoo.com>
Message-ID: <CACzNyA0QBxdzPawxWreaEDjYo5EoF9O3e-F+qH2Ao+Xgk+nrQQ@mail.gmail.com>

On Wed, May 22, 2013 at 6:02 AM, Andrew Triplett <andrew139668 at yahoo.com> wrote:
> I am on chapter two for Python Programming working on the challenges and the
> question is:
>
> 1. Create a list of legal and illegal variable names. Describe why each is
> either legal or illegal. Next, create a list of "good" and "bad" legal
> variable names. Describe why each is either a good or bad choice for a
> variable name.
>

The title is a bit ambigious. Just incase anyone likes the sound of
the challenge, the book is:
Python Programming For The Absolute Beginner
i also used it and would recommend it to anyone trying to learn Python

From eryksun at gmail.com  Wed May 22 12:10:31 2013
From: eryksun at gmail.com (eryksun)
Date: Wed, 22 May 2013 06:10:31 -0400
Subject: [Tutor] Tutor Digest, Vol 111, Issue 72
In-Reply-To: <CALRAYNWcgjpARRiDJKZ=NhqjkuK-un12-zhC0hit2B=yKej=og@mail.gmail.com>
References: <mailman.11186.1369191815.3113.tutor@python.org>
	<CALRAYNWcgjpARRiDJKZ=NhqjkuK-un12-zhC0hit2B=yKej=og@mail.gmail.com>
Message-ID: <CACL+1aux5LNKP4QVenrMRZaWKFXVRYQD+cFD3=7Mh+d9h9Sr_Q@mail.gmail.com>

On Wed, May 22, 2013 at 12:26 AM, Jim Mooney <cybervigilante at gmail.com> wrote:
>
> Actually, I did notice that tests were zero, but the book I am using
> does not mention needing the word 'test' as part of the regex. There
> is only so much time in a day and so many books I can buy (and not all
> comprehensive, apparently.)

Please don't reply to digests. Each message has a Message-ID, and
replies have an IN-REPLY-TO field that references the ID of the
previous message in the thread. By replying to the digest your message
has no meaningful Subject, and even if you change the Subject field,
it still won't be threaded properly. See for yourself:

http://mail.python.org/pipermail/tutor/2013-May/thread.html#95572

From wprins at gmail.com  Wed May 22 13:37:34 2013
From: wprins at gmail.com (Walter Prins)
Date: Wed, 22 May 2013 12:37:34 +0100
Subject: [Tutor] still nosing around
In-Reply-To: <CALRAYNUdsT5Pb5QA91fJ+zB_qFcy9-EmWUttSCb1AY6F_dB2tg@mail.gmail.com>
References: <CALRAYNUdsT5Pb5QA91fJ+zB_qFcy9-EmWUttSCb1AY6F_dB2tg@mail.gmail.com>
Message-ID: <CANLXbfDZcLNwYLR30EXBcPU+6H71ErK5yRco_rd=DcdOgq1Rbw@mail.gmail.com>

Hi,

On 22 May 2013 05:26, Jim Mooney <cybervigilante at gmail.com> wrote:

> But that brings up a point. Does this mean that if I have to test a
> module with a lot of subroutines I have to rename every subroutine
> with 'test' appended?
>

Some quick comments for what it's worth: (One of) the points about nose is
to make lessen the overhead needed to write tests.  With unittest, you have
to create a subclass of unittest.Testcase in order to identify and package
tests for the test framework, and  manually organise them into suites.
 This is fine, but slightly burdensome if all you want is to write a
function or functions that tests another function or functions (maybe
working still in just one single file at that point, as it were, on a
single function or so.)

Nose allows you to do this, e.g. just start writing tests with as little
friction/resistance as possible.  But there's a question:  How is the test
runner now supposed to "know" whether an arbitrary function in a module is
in fact a test?  With unittest, the test framework "knows" (get it) by the
fact that tests are descended from a common base class.  But with an
arbitrary function, how should the test framework know?

So to answer your question: In short, yes, you have to let nose know
whether a given piece of code is a test.  Either include the word "test" in
the function name either prefixed or postfixed as "_test" as you asked Or
you can do it like unittest requires, e.g. create a test class descended
from unittest.Testcase, in which case your method names then don't matter
IIRC.  You may have read this already, but the relevant documentation page:
https://nose.readthedocs.org/en/latest/writing_tests.html

Aside, doctest answers/approaches this same question by reading IIRC
docstring entries for classes, methods or modules (?) and assumes that text
that looks like  python interpreter styled input/output sequences defines
test input/output sequences.

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130522/011a57ce/attachment.html>

From davea at davea.name  Wed May 22 14:01:30 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 22 May 2013 08:01:30 -0400
Subject: [Tutor] still nosing around
In-Reply-To: <CALRAYNUdsT5Pb5QA91fJ+zB_qFcy9-EmWUttSCb1AY6F_dB2tg@mail.gmail.com>
References: <CALRAYNUdsT5Pb5QA91fJ+zB_qFcy9-EmWUttSCb1AY6F_dB2tg@mail.gmail.com>
Message-ID: <519CB39A.1040100@davea.name>


On 22 May 2013 05:26, Jim Mooney <cybervigilante at gmail.com> wrote:

 > But that brings up a point. Does this mean that if I have to test a
 > module with a lot of subroutines I have to rename every subroutine
 > with 'test' appended?
 >

No, you don't rename the existing functions.  But the testing functions 
need to be identifiable, in one of several ways.


-- 
DaveA

From steve at pearwood.info  Wed May 22 14:50:33 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 22 May 2013 22:50:33 +1000
Subject: [Tutor] try..except - what about that ton of **Error statements?
In-Reply-To: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>
References: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>
Message-ID: <519CBF19.108@pearwood.info>

On 22/05/13 15:46, Jim Mooney wrote:
> I'm looking at Try..Except
>
> Try:
>       <some statements>
> Except SomethingError as err:
>      <other statements>
>
> The list of error statements is huge. How do I know which error
> statement to put in place of SomethingError (or multiple errors for
> that matter)? Or is it best to just leave SomethingError blank until I
> know more?



For playing around at the interactive interpreter, leaving the except clause blank is fine.

try:
     something()
except:
     pass


But don't do this in real code! In real code, the rules you should apply are:


1) never hide programming errors by catching exceptions;

2) errors should only be caught if you can recover from them;

3) your job as a programmer is *not* to stop your program from raising an error, but to make it behave correctly -- sometimes an error is the right thing to do;

4) catch the fewest possible errors that make sense;

5) nearly always, "the fewest" will mean *zero* -- 99% of your code should not be inside a try...except block;

6) you should put the least amount of code as possible inside each try block -- as a general rule, that doesn't just mean "one line of code", but *one operation*.



Unfortunately there is no hard rule about what exceptions Python will raise. Some things are obvious: if you mistype a name, you'll probably get a NameError. Some things are documented: if you look up an item in a dict, and it is not there, you will get KeyError. Some things are not. E.g. there's pretty much no limit to the exceptions you *might* (but probably never will!) get from some of the more complex modules.

In general, once I have decided that I need a try...except block around a certain operation, I look up what exceptions it is documented to produce (if any!). Then I decide, if such-and-such an exception occurs, can I recover from it? If not, I don't catch it. If so, then I do. Then, I wait to see if the operation produces some other undocumented exception. If so, then I repeat the process.



-- 
Steven

From steve at pearwood.info  Wed May 22 15:07:53 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 22 May 2013 23:07:53 +1000
Subject: [Tutor] try..except - what about that ton of **Error statements?
In-Reply-To: <CALRAYNXKMuLqg=spN2A25evurvoJYva2zQj+6m2Sd1+AfaA+Ow@mail.gmail.com>
References: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>
	<CAG6Bxkck58SvaSh522947dJM5TiAyACTNqj0xutFywOYRnyzPg@mail.gmail.com>
	<CALRAYNXKMuLqg=spN2A25evurvoJYva2zQj+6m2Sd1+AfaA+Ow@mail.gmail.com>
Message-ID: <519CC329.7010203@pearwood.info>

On 22/05/13 16:20, Jim Mooney wrote:
>> Keep the try block small. For example if it's for a call to
>> open(filename, "r") the only possible errors (assuming correct syntax)
>> are NameError for using an undefined variable and IOError for
>> specifying a file which doesnt exist.


Jim, I don't know who you are replying to here. You have quoted somebody, but not included an attribution. Whoever it was that replied to you, I don't seem to have their email (maybe they sent it direct to you, not to the list?) so I have no idea who it was.

However, let me say that under normal circumstances, you should not catch NameError. A NameError is almost always a programming error: you have made a typo, or tried using a variable that doesn't exist. You need to see that error, so you can fix it, not just hide it with a try...except.

A very important quote from Chris Smith:

"I find it amusing when novice programmers believe their main job is preventing programs from crashing. ... More experienced programmers realize that correct code is great, code that crashes could use improvement, but incorrect code that doesn't crash is a horrible nightmare."

In the specific case of the open command, there are many other errors that can occur:

IOError, if the file doesn't exist, or is unreadable, or if you do not have read permission, or any one of a number of rarer file-system errors;

TypeError, if the file name contains an ASCII NULL character, or if you pass something other than a file name;

TypeError again, if you pass too few, or too many, arguments;

ValueError, if you provide an illegal mode argument (e.g. 'x' instead of 'r' or 'w');

to mention only a few. But nearly all of them are programming errors, and should not be caught, they should be fixed. E.g. if you get a NameError, *fix the typo*. If you get ValueError, *use a legal mode*. And so forth. IOError is probably the only one you might legitimately want to catch, and even then only if you can recover from the error.


-- 
Steven

From robertvstepp at gmail.com  Wed May 22 15:31:08 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Wed, 22 May 2013 08:31:08 -0500
Subject: [Tutor] try..except - what about that ton of **Error statements?
In-Reply-To: <519CBF19.108@pearwood.info>
References: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>
	<519CBF19.108@pearwood.info>
Message-ID: <CANDiX9Ly7xvEiGY1UHM+510tC_UOCHNOURzuhpejbehZ=HhkWQ@mail.gmail.com>

On Wed, May 22, 2013 at 7:50 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On 22/05/13 15:46, Jim Mooney wrote:
>>

[...]

>
> But don't do this in real code! In real code, the rules you should apply
> are:
>
>
> 1) never hide programming errors by catching exceptions;
>
> 2) errors should only be caught if you can recover from them;
>

I have not made it to the point of catching errors. I am still at the
stage of doing my best to prevent them from occurring. However, I try
to follow all of the posts as best I can and I am not sure I
understand what you mean here. You seem to be saying that there may be
errors that you cannot eliminate, but also cannot do anything about if
they happen to occur. Am I interpreting this correctly? Please
clarify.

> 3) your job as a programmer is *not* to stop your program from raising an
> error, but to make it behave correctly -- sometimes an error is the right
> thing to do;
>

Also, can you clarify this point as well? When would you want your
program to crash?

> 4) catch the fewest possible errors that make sense;
>
> 5) nearly always, "the fewest" will mean *zero* -- 99% of your code should
> not be inside a try...except block;
>
> 6) you should put the least amount of code as possible inside each try block
> -- as a general rule, that doesn't just mean "one line of code", but *one
> operation*.
>

Here by "one operation" do you mean the most efficient means to deal
with that particular error condition?

[...]

> In general, once I have decided that I need a try...except block around a
> certain operation, I look up what exceptions it is documented to produce (if
> any!). Then I decide, if such-and-such an exception occurs, can I recover
> from it? If not, I don't catch it. If so, then I do. Then, I wait to see if
> the operation produces some other undocumented exception. If so, then I
> repeat the process.
>
Maybe I have been totally misunderstanding your comments. Is what you
are saying above referring strictly to while you are still debugging
the program? Or do the above comments that I asked for clarification
refer to the finished product?

Thanks!
boB

From robertvstepp at gmail.com  Wed May 22 15:37:04 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Wed, 22 May 2013 08:37:04 -0500
Subject: [Tutor] try..except - what about that ton of **Error statements?
In-Reply-To: <519CC329.7010203@pearwood.info>
References: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>
	<CAG6Bxkck58SvaSh522947dJM5TiAyACTNqj0xutFywOYRnyzPg@mail.gmail.com>
	<CALRAYNXKMuLqg=spN2A25evurvoJYva2zQj+6m2Sd1+AfaA+Ow@mail.gmail.com>
	<519CC329.7010203@pearwood.info>
Message-ID: <CANDiX9LR4i0bFC4Bpnc7HcLro=tZPqWrFN+Xn0GBgqML0SWQoQ@mail.gmail.com>

On Wed, May 22, 2013 at 8:07 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On 22/05/13 16:20, Jim Mooney wrote:
>>>

[...}

> A very important quote from Chris Smith:
>
> "I find it amusing when novice programmers believe their main job is
> preventing programs from crashing. ... More experienced programmers realize
> that correct code is great, code that crashes could use improvement, but
> incorrect code that doesn't crash is a horrible nightmare."
>

Being a novice programmer, I am interpreting this to mean that a) I
complete a program. b) I believe it to be correct and bug-free. c) I
should make sure I do NOT try to catch errors just to keep the program
running from things I failed to anticipate (Probably from being a
novice programmer!). So the conclusion I am drawing is that I WANT my
program to crash if something I did not anticipate/plan for happens.
Am I understanding this correctly?

boB

From steve at pearwood.info  Wed May 22 16:45:23 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 23 May 2013 00:45:23 +1000
Subject: [Tutor] try..except - what about that ton of **Error statements?
In-Reply-To: <CANDiX9Ly7xvEiGY1UHM+510tC_UOCHNOURzuhpejbehZ=HhkWQ@mail.gmail.com>
References: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>
	<519CBF19.108@pearwood.info>
	<CANDiX9Ly7xvEiGY1UHM+510tC_UOCHNOURzuhpejbehZ=HhkWQ@mail.gmail.com>
Message-ID: <519CDA03.7070206@pearwood.info>

On 22/05/13 23:31, boB Stepp wrote:
> On Wed, May 22, 2013 at 7:50 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>> On 22/05/13 15:46, Jim Mooney wrote:
>>>
>
> [...]
>
>>
>> But don't do this in real code! In real code, the rules you should apply
>> are:
>>
>>
>> 1) never hide programming errors by catching exceptions;
>>
>> 2) errors should only be caught if you can recover from them;
>>
>
> I have not made it to the point of catching errors. I am still at the
> stage of doing my best to prevent them from occurring. However, I try
> to follow all of the posts as best I can and I am not sure I
> understand what you mean here. You seem to be saying that there may be
> errors that you cannot eliminate, but also cannot do anything about if
> they happen to occur. Am I interpreting this correctly? Please
> clarify.


Correct. Some errors can be recovered from, e.g. if a website is not available, you can wait a few seconds and try again; if a file cannot be read, you can ask the user for a different file name. Some errors cannot reasonably be recovered from. If you ask the user for a number between 1 and 10, and they enter "hello", what are you going to do?

If your program is interactive, you can ask them again. But if it is non-interactive, you have no choice but to fail gracefully and display an error.

Some errors are *expected* -- users make mistakes, they don't read instructions, or misunderstand them, they enter garbage, make typos, etc. Web sites and networks go down temporarily, or respond slowly; disks fill up; etc. Good programs should deal with them gracefully.

Some errors are *unexpected*, in which case they should be identified as either a bug that needs to be fixed, or as an error condition which *should have been expected* but wasn't. If you catch every exception in sight, you will never be able to identify those unexpected errors and fix them.



>> 3) your job as a programmer is *not* to stop your program from raising an
>> error, but to make it behave correctly -- sometimes an error is the right
>> thing to do;
>>
>
> Also, can you clarify this point as well? When would you want your
> program to crash?

You don't *want* it to crash, you would rather it exit gracefully. But a crash is better than silently doing the wrong thing.

Some years ago there was a very unfortunate incident where a computer-controlled medical x-ray irradiated a large number of people with fatal doses of radiation. The machine should have halted with an error, but due to a combination of bad design, operator error, and programming bugs, instead it blasted the poor doomed patients with thousands of times the safe limit of radiation.

That's an extreme example, but the same principle applies in general. Your program has a job to do. If it cannot do that job correctly, it should own up to it rather than do something else. If you tell your program to save your work to a file, and the disk is full, what would you rather happen?

- You get an error message, so you can make some space and try again.

- The program silently discards your data, so it is not saved but you don't know it.

- The program deletes other files at random until it has freed up enough space to save your data.


Pick one.


>> 4) catch the fewest possible errors that make sense;
>>
>> 5) nearly always, "the fewest" will mean *zero* -- 99% of your code should
>> not be inside a try...except block;
>>
>> 6) you should put the least amount of code as possible inside each try block
>> -- as a general rule, that doesn't just mean "one line of code", but *one
>> operation*.
>>
>
> Here by "one operation" do you mean the most efficient means to deal
> with that particular error condition?

No. I mean that you should identify (if you can) the smallest thing that can go wrong in the way you expect, and deal with it.

For example, suppose you are looking up a key in a dict, and process it in some way. If the key is not in the dict, you can deal with it quite easily:


try:
     value = my_dict[key]
     result = process(value)
except KeyError:
     result = something_else()


Looks reasonable, yes?

No. You're guarding too much with the try block. The problem is, there are two places where you *might* get a KeyError:

- when you call my_dict[key]

- inside process(value) -- who knows what is happening in there? You have to assume that it *could* raise KeyError.

But only the first case can be legitimately handled by the except clause. A KeyError in process(value) needs to be treated as a bug, and fixed, not covered up. So the above is better written as:

try:
     value = my_dict[key]
except KeyError:
     result = something_else()
else:
     # No exception occurred.
     result = process(value)


Now if you get KeyError inside the call to process(), you will see it, and can fix it.



>> In general, once I have decided that I need a try...except block around a
>> certain operation, I look up what exceptions it is documented to produce (if
>> any!). Then I decide, if such-and-such an exception occurs, can I recover
>> from it? If not, I don't catch it. If so, then I do. Then, I wait to see if
>> the operation produces some other undocumented exception. If so, then I
>> repeat the process.
>>
> Maybe I have been totally misunderstanding your comments. Is what you
> are saying above referring strictly to while you are still debugging
> the program? Or do the above comments that I asked for clarification
> refer to the finished product?

The non-trivial program that is 100% bug-free has never been written yet. Even those that are "finished" probably have bugs, it may be that they are so obscure that nobody has discovered them yet. In practice, programs will be available for use long before they are bug-free, but the rate at which bugs are reported will get slower. At first, you'll be discovering bugs all the time. Then only occasionally. Then rarely. Eventually, you will get to the point that the bugs that remain are so rare, or minor, or so hard to reproduce, that you will decide not to bother fixing them.

This is why pieces of software that are really old and stable will still occasionally get a new version.


-- 
Steven

From steve at pearwood.info  Wed May 22 16:49:32 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 23 May 2013 00:49:32 +1000
Subject: [Tutor] try..except - what about that ton of **Error statements?
In-Reply-To: <CANDiX9LR4i0bFC4Bpnc7HcLro=tZPqWrFN+Xn0GBgqML0SWQoQ@mail.gmail.com>
References: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>
	<CAG6Bxkck58SvaSh522947dJM5TiAyACTNqj0xutFywOYRnyzPg@mail.gmail.com>
	<CALRAYNXKMuLqg=spN2A25evurvoJYva2zQj+6m2Sd1+AfaA+Ow@mail.gmail.com>
	<519CC329.7010203@pearwood.info>
	<CANDiX9LR4i0bFC4Bpnc7HcLro=tZPqWrFN+Xn0GBgqML0SWQoQ@mail.gmail.com>
Message-ID: <519CDAFC.8070502@pearwood.info>

On 22/05/13 23:37, boB Stepp wrote:
> On Wed, May 22, 2013 at 8:07 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>> On 22/05/13 16:20, Jim Mooney wrote:
>>>>
>
> [...}
>
>> A very important quote from Chris Smith:
>>
>> "I find it amusing when novice programmers believe their main job is
>> preventing programs from crashing. ... More experienced programmers realize
>> that correct code is great, code that crashes could use improvement, but
>> incorrect code that doesn't crash is a horrible nightmare."
>>
>
> Being a novice programmer, I am interpreting this to mean that a) I
> complete a program. b) I believe it to be correct and bug-free. c) I
> should make sure I do NOT try to catch errors just to keep the program
> running from things I failed to anticipate (Probably from being a
> novice programmer!). So the conclusion I am drawing is that I WANT my
> program to crash if something I did not anticipate/plan for happens.
> Am I understanding this correctly?


Yes!


Well, within reason. If you are programming in C, a crash can be a nasty thing to deal with. It could cause memory corruption, leading to a Blue Screen of Death or equivalent. In the absolute worst case, low-level C or assembly bugs can actually cause hardware damage! So you don't want to be writing low-level code like that if you can avoid it.

But in a high-level language like Python, exceptions are not to be feared. They are perfectly safe, and should be welcomed, since they show you where your code needs to be improved.


-- 
Steven

From robertvstepp at gmail.com  Wed May 22 18:09:14 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Wed, 22 May 2013 11:09:14 -0500
Subject: [Tutor] try..except - what about that ton of **Error statements?
In-Reply-To: <519CDAFC.8070502@pearwood.info>
References: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>
	<CAG6Bxkck58SvaSh522947dJM5TiAyACTNqj0xutFywOYRnyzPg@mail.gmail.com>
	<CALRAYNXKMuLqg=spN2A25evurvoJYva2zQj+6m2Sd1+AfaA+Ow@mail.gmail.com>
	<519CC329.7010203@pearwood.info>
	<CANDiX9LR4i0bFC4Bpnc7HcLro=tZPqWrFN+Xn0GBgqML0SWQoQ@mail.gmail.com>
	<519CDAFC.8070502@pearwood.info>
Message-ID: <CANDiX9+_g+9x6vizMFausuQrfbia9raA4V+E74CTjiQjDkSe=w@mail.gmail.com>

Thanks, Steve, for your last two posts. You have made things much
clearer for me.

On Wed, May 22, 2013 at 9:49 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On 22/05/13 23:37, boB Stepp wrote:
>>
>> On Wed, May 22, 2013 at 8:07 AM, Steven D'Aprano <steve at pearwood.info>
>> wrote:
>>>

[...]

>>
>> Being a novice programmer, I am interpreting this to mean that a) I
>> complete a program. b) I believe it to be correct and bug-free. c) I
>> should make sure I do NOT try to catch errors just to keep the program
>> running from things I failed to anticipate (Probably from being a
>> novice programmer!). So the conclusion I am drawing is that I WANT my
>> program to crash if something I did not anticipate/plan for happens.
>> Am I understanding this correctly?
>
>
>
> Yes!
>
>
> Well, within reason. If you are programming in C, a crash can be a nasty
> thing to deal with. It could cause memory corruption, leading to a Blue
> Screen of Death or equivalent. In the absolute worst case, low-level C or
> assembly bugs can actually cause hardware damage! So you don't want to be
> writing low-level code like that if you can avoid it.
>

I was not aware that hardware damage could be caused by poor
programming. I am curious; can you give some examples of how this
might occur?

> But in a high-level language like Python, exceptions are not to be feared.
> They are perfectly safe, and should be welcomed, since they show you where
> your code needs to be improved.
>
I would like to ask some general questions here. Problems can arise
from bugs in the operating system, bugs in the programming language(s)
being used, bugs in packages/modules being used, bugs in any third
party packages being used, etc. Also, whenever any one of these things
is updated/upgraded, it can introduce new issues. What strategies can
one use to deal with these possibilities that seem entirely out of the
programmer's control?

boB

From onyxtic at gmail.com  Wed May 22 18:11:06 2013
From: onyxtic at gmail.com (Evans Anyokwu)
Date: Wed, 22 May 2013 17:11:06 +0100
Subject: [Tutor] challenge-chapter 2
In-Reply-To: <1369198979.77301.YahooMailNeo@web122003.mail.ne1.yahoo.com>
References: <1369198979.77301.YahooMailNeo@web122003.mail.ne1.yahoo.com>
Message-ID: <CAAXVmZPc87utp16-bY7Wv3LOvzrMnT7rKo_cqQRj+Py88AqO_g@mail.gmail.com>

Hi Andrew,

I'm sure the exercises at the end of the each chapters are there for you to
attempt. Asking for help here without attempting it is not the best way to
learn.
If however, you've tried something - and it didn't work, by all means ask
for help.

In the mean time show us what you have so far.


Good luck,
Evans


On Wed, May 22, 2013 at 6:02 AM, Andrew Triplett <andrew139668 at yahoo.com>wrote:

> I am on chapter two for Python Programming working on the challenges and
> the question is:
>
> 1. Create a list of legal and illegal variable names. Describe why each is
> either legal or illegal. Next, create a list of "good" and "bad" legal
> variable names. Describe why each is either a good or bad choice for a
> variable name.
>
> Can you help me solve this problem?
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130522/9a614a52/attachment-0001.html>

From cybervigilante at gmail.com  Wed May 22 18:13:51 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Wed, 22 May 2013 09:13:51 -0700
Subject: [Tutor] Tutor Digest, Vol 111, Issue 72
In-Reply-To: <CACL+1aux5LNKP4QVenrMRZaWKFXVRYQD+cFD3=7Mh+d9h9Sr_Q@mail.gmail.com>
References: <mailman.11186.1369191815.3113.tutor@python.org>
	<CALRAYNWcgjpARRiDJKZ=NhqjkuK-un12-zhC0hit2B=yKej=og@mail.gmail.com>
	<CACL+1aux5LNKP4QVenrMRZaWKFXVRYQD+cFD3=7Mh+d9h9Sr_Q@mail.gmail.com>
Message-ID: <CALRAYNV0d3eqoyRz2CBkPnpbcNrw6WzXHV7jmE5Pw4+=yLLcCA@mail.gmail.com>

> Please don't reply to digests. Each message has a Message-ID, and
> replies have an IN-REPLY-TO field that references the ID of the
> previous message in the thread. By replying to the digest your message
> has no meaningful Subject, and even if you change the Subject field,
> it still won't be threaded properly. See for yourself:
>
> http://mail.python.org/pipermail/tutor/2013-May/thread.html#95572

So is Reply to All the way to go? For some odd reason Gmail won't
always Reply to All. I'll have to figure out why.

Jim

From steve at pearwood.info  Wed May 22 18:24:52 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 23 May 2013 02:24:52 +1000
Subject: [Tutor] Tutor Digest, Vol 111, Issue 72
In-Reply-To: <CALRAYNV0d3eqoyRz2CBkPnpbcNrw6WzXHV7jmE5Pw4+=yLLcCA@mail.gmail.com>
References: <mailman.11186.1369191815.3113.tutor@python.org>
	<CALRAYNWcgjpARRiDJKZ=NhqjkuK-un12-zhC0hit2B=yKej=og@mail.gmail.com>
	<CACL+1aux5LNKP4QVenrMRZaWKFXVRYQD+cFD3=7Mh+d9h9Sr_Q@mail.gmail.com>
	<CALRAYNV0d3eqoyRz2CBkPnpbcNrw6WzXHV7jmE5Pw4+=yLLcCA@mail.gmail.com>
Message-ID: <519CF154.4010401@pearwood.info>

On 23/05/13 02:13, Jim Mooney wrote:
>> Please don't reply to digests. Each message has a Message-ID, and
>> replies have an IN-REPLY-TO field that references the ID of the
>> previous message in the thread. By replying to the digest your message
>> has no meaningful Subject, and even if you change the Subject field,
>> it still won't be threaded properly. See for yourself:
>>
>> http://mail.python.org/pipermail/tutor/2013-May/thread.html#95572
>
> So is Reply to All the way to go? For some odd reason Gmail won't
> always Reply to All. I'll have to figure out why.


If you look at your subscription options:

http://mail.python.org/mailman/listinfo/tutor


you have an option to receive a digest containing many posts in a single email, or to receive individual emails. If you are going to reply to messages, please pick individual emails. Then when you wish to respond to one email, you hit "Reply To List" (if your email program has that option) or "Reply All" (if it doesn't), edit your reply, and send.

If you are planning to be busy or away, and still wish to receive the emails, but not reply to them, some people like to go onto digest mode. I've tried that, and would not bother.




-- 
Steven

From cybervigilante at gmail.com  Wed May 22 18:27:59 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Wed, 22 May 2013 09:27:59 -0700
Subject: [Tutor] To error statement or not to error statement
Message-ID: <CALRAYNVz7n+Gx37AL19aXHnfLfO0gBwyrUuJS7721vfGAcSbZg@mail.gmail.com>

>> "I find it amusing when novice programmers believe their main job is
>> preventing programs from crashing. ... More experienced programmers realize
>> that correct code is great, code that crashes could use improvement, but
>> incorrect code that doesn't crash is a horrible nightmare."

Then am I right to assume that rather than put in error statements I
barely understand at this point, the best thing would be to work the
hell out of the program in hope of seeing an error?  Does Python have
something that would do this automatically since I can't see running a
program a hundred times by hand?

Mainly, I'm just learning all this stuff for future reference. I
really doubt I'll need to use nose to find errors in twenty-line
programs. Print, assert, and staring at it for a long time should be
enough for now - and the Wing debugger now and then.

>From the varied replies so far, it sounds to me that debugging is more
of an art than a science. So far the books I've looked at just mention
the basics but don't get into the philosophy of when and how.

Jim

From eryksun at gmail.com  Wed May 22 18:45:32 2013
From: eryksun at gmail.com (eryksun)
Date: Wed, 22 May 2013 12:45:32 -0400
Subject: [Tutor] Tutor Digest, Vol 111, Issue 72
In-Reply-To: <CALRAYNV0d3eqoyRz2CBkPnpbcNrw6WzXHV7jmE5Pw4+=yLLcCA@mail.gmail.com>
References: <mailman.11186.1369191815.3113.tutor@python.org>
	<CALRAYNWcgjpARRiDJKZ=NhqjkuK-un12-zhC0hit2B=yKej=og@mail.gmail.com>
	<CACL+1aux5LNKP4QVenrMRZaWKFXVRYQD+cFD3=7Mh+d9h9Sr_Q@mail.gmail.com>
	<CALRAYNV0d3eqoyRz2CBkPnpbcNrw6WzXHV7jmE5Pw4+=yLLcCA@mail.gmail.com>
Message-ID: <CACL+1avOceTW=S8gtPB9JS+m4wspaT=9pz4=9HrMWw6vfxsgNA@mail.gmail.com>

On Wed, May 22, 2013 at 12:13 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
>> Please don't reply to digests. Each message has a Message-ID, and
>> replies have an IN-REPLY-TO field that references the ID of the
>> previous message in the thread. By replying to the digest your message
>> has no meaningful Subject, and even if you change the Subject field,
>> it still won't be threaded properly. See for yourself:
>>
>> http://mail.python.org/pipermail/tutor/2013-May/thread.html#95572
>
> So is Reply to All the way to go? For some odd reason Gmail won't
> always Reply to All. I'll have to figure out why.

You can configure Gmail to default to reply all in the general
settings. Of course that's of no use if you're replying to a digest,
so switch to receiving individual messages. Receiving the list as a
digest is unnecessary with Gmail. Just create a label for the list,
and use a filter to automatically label and archive messages from the
list out of your inbox.

From robertvstepp at gmail.com  Wed May 22 18:50:34 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Wed, 22 May 2013 11:50:34 -0500
Subject: [Tutor] try..except - what about that ton of **Error statements?
In-Reply-To: <519CDA03.7070206@pearwood.info>
References: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>
	<519CBF19.108@pearwood.info>
	<CANDiX9Ly7xvEiGY1UHM+510tC_UOCHNOURzuhpejbehZ=HhkWQ@mail.gmail.com>
	<519CDA03.7070206@pearwood.info>
Message-ID: <CANDiX9+yKaQdxe0d6DvqYZDA7Y61=7i_m_Q=A=oi5vSbjnmGqw@mail.gmail.com>

On Wed, May 22, 2013 at 9:45 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On 22/05/13 23:31, boB Stepp wrote:
>>
>> On Wed, May 22, 2013 at 7:50 AM, Steven D'Aprano <steve at pearwood.info>
>> wrote:

[...]

>>> 3) your job as a programmer is *not* to stop your program from raising an
>>> error, but to make it behave correctly -- sometimes an error is the right
>>> thing to do;
>>>
>>
>> Also, can you clarify this point as well? When would you want your
>> program to crash?
>
>
> You don't *want* it to crash, you would rather it exit gracefully. But a
> crash is better than silently doing the wrong thing.
>

Would you define "exiting gracefully"? It appears you mean a
controlled (by the programmer's code) exit that gives a meaningful (to
the user or the programmer?) error message instead of in an
uncontrolled manner where the only available information would be
whatever the OS generates.

> Some years ago there was a very unfortunate incident where a
> computer-controlled medical x-ray irradiated a large number of people with
> fatal doses of radiation. The machine should have halted with an error, but
> due to a combination of bad design, operator error, and programming bugs,
> instead it blasted the poor doomed patients with thousands of times the safe
> limit of radiation.
>

Thanks for the example! Unfortunately these devastating errors
continue. The New York Times has reported on some radiation therapy
incidents in the past few years, some of which were caused by
programming errors (along with the usual errors by the people using
the software).

> That's an extreme example, but the same principle applies in general. Your
> program has a job to do. If it cannot do that job correctly, it should own
> up to it rather than do something else. If you tell your program to save
> your work to a file, and the disk is full, what would you rather happen?
>

I like very much how you put this. Integrity in programming!

> - You get an error message, so you can make some space and try again.
>
> - The program silently discards your data, so it is not saved but you don't
> know it.
>
> - The program deletes other files at random until it has freed up enough
> space to save your data.
>
>
> Pick one.
>

I guess I'll pick the first alternative. However, this brings to mind
my biggest gripe as a user of software, particularly here at work
where the programmer obviously has no medical background: cryptic
error messages that might be meaningful to the programmer, but are
totally unhelpful to me, the user, who has to figure out what to do
next.

[...]

Thanks for the clarifications!

boB

From steve at pearwood.info  Wed May 22 19:20:19 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 23 May 2013 03:20:19 +1000
Subject: [Tutor] try..except - what about that ton of **Error statements?
In-Reply-To: <CANDiX9+_g+9x6vizMFausuQrfbia9raA4V+E74CTjiQjDkSe=w@mail.gmail.com>
References: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>
	<CAG6Bxkck58SvaSh522947dJM5TiAyACTNqj0xutFywOYRnyzPg@mail.gmail.com>
	<CALRAYNXKMuLqg=spN2A25evurvoJYva2zQj+6m2Sd1+AfaA+Ow@mail.gmail.com>
	<519CC329.7010203@pearwood.info>
	<CANDiX9LR4i0bFC4Bpnc7HcLro=tZPqWrFN+Xn0GBgqML0SWQoQ@mail.gmail.com>
	<519CDAFC.8070502@pearwood.info>
	<CANDiX9+_g+9x6vizMFausuQrfbia9raA4V+E74CTjiQjDkSe=w@mail.gmail.com>
Message-ID: <519CFE53.3010904@pearwood.info>

On 23/05/13 02:09, boB Stepp wrote:

> I was not aware that hardware damage could be caused by poor
> programming. I am curious; can you give some examples of how this
> might occur?

Does your computer have a DVD drive? Or Blu-Ray? Is it region-locked? Some region-locked drives let you change the region up to a maximum of (say) 3 times. A malicious or unlucky program may "accidentally" change the region 3 times, then you are locked for good. If you're locked in the wrong region, the drive might as well be dead.

Some DVD burners are capable of operating at speeds faster than low-quality discs can stand. DVDs have been known to shatter inside the drive, destroying both the disk and the drive. If a program runs the DVD at excessively high speed, not only do the mechanical parts wear faster, but cheap disks could shatter.

(I never shattered a DVD or CD, but I went through about 50 blank CDs, back when they were about two dollars each, making "coasters" from them because I was trying to burn data to them faster than the disc was capable of dealing with. I will never forgot the moment I realised why four out of five of my burns were failing: it was when I reached for the SECOND LAST DISC in the pack.)

You can destroy old CRT monitors by running them at the wrong frequency. I don't think LCD monitors are subject to that particular flaw, but they may have their own flaws.

Many computer components are running firmware from flash memory, and you can update the firmware. If you update it with garbage instead of code, your device will be bricked. Flash memory can only be written to so many times. If your code "accidentally" writes to flash memory, over and over again, eventually it will get corrupted or die, and your device is bricked.

The Stuxnet computer virus was designed to physically break centrifuges.

http://arstechnica.com/tech-policy/2011/07/how-digital-detectives-deciphered-stuxnet-the-most-menacing-malware-in-history/

See also:

http://en.wikipedia.org/wiki/Killer_poke
http://en.wikipedia.org/wiki/Halt_and_Catch_Fire
http://superuser.com/questions/313850/can-some-software-physically-damage-hardware

and of course, always mount a scratch monkey before performing hardware tests:

http://edp.org/monkey.htm


[...]
> I would like to ask some general questions here.

I'd love to answer, but it's past 3am here and I must get some sleep eventually, so I'll try to return to this topic tomorrow.



-- 
Steven

From marc.tompkins at gmail.com  Wed May 22 19:23:11 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 22 May 2013 10:23:11 -0700
Subject: [Tutor] try..except - what about that ton of **Error statements?
In-Reply-To: <CANDiX9+yKaQdxe0d6DvqYZDA7Y61=7i_m_Q=A=oi5vSbjnmGqw@mail.gmail.com>
References: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>
	<519CBF19.108@pearwood.info>
	<CANDiX9Ly7xvEiGY1UHM+510tC_UOCHNOURzuhpejbehZ=HhkWQ@mail.gmail.com>
	<519CDA03.7070206@pearwood.info>
	<CANDiX9+yKaQdxe0d6DvqYZDA7Y61=7i_m_Q=A=oi5vSbjnmGqw@mail.gmail.com>
Message-ID: <CAKK8jXbWyYE2UXf6hxG3z1wSpHeeW_zSJgSSC4cDmECD3ftcoQ@mail.gmail.com>

On Wed, May 22, 2013 at 9:50 AM, boB Stepp <robertvstepp at gmail.com> wrote:

> I guess I'll pick the first alternative. However, this brings to mind
> my biggest gripe as a user of software, particularly here at work
> where the programmer obviously has no medical background: cryptic
> error messages that might be meaningful to the programmer, but are
> totally unhelpful to me, the user, who has to figure out what to do
> next.
>

I agree with you a LOT more strongly in the case of compiled languages,
where the error dump amounts to a memory location and a blob of
hexadecimal.  When that happens, nobody but the original programmer (or
software company) is likely to find out the cause, and even then not
without a symbolic debugger.  But in Python, the error messages/tracebacks
are fairly self-explanatory (to someone familiar with Python) and even
include the actual line number where the error occurred.  It's true that
the average end-user won't be able to fix it, but the pool of potential
help is actually quite wide.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130522/62e320c2/attachment.html>

From citizenkant at gmail.com  Wed May 22 20:14:55 2013
From: citizenkant at gmail.com (Citizen Kant)
Date: Wed, 22 May 2013 20:14:55 +0200
Subject: [Tutor] Available characters
Message-ID: <CAMbF=C-Wcu5unwQ5cn=cSqsPJCRnQOqzbDeSKE0DU+-=Ndhp_A@mail.gmail.com>

Does anybody know if there's a Python method that gives or stores the
complete list of ascii characters or unicode characters? The list of every
single character available would be perfect.

Thanks.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130522/86cab3f4/attachment.html>

From eryksun at gmail.com  Wed May 22 20:26:18 2013
From: eryksun at gmail.com (eryksun)
Date: Wed, 22 May 2013 14:26:18 -0400
Subject: [Tutor] Available characters
In-Reply-To: <CAMbF=C-Wcu5unwQ5cn=cSqsPJCRnQOqzbDeSKE0DU+-=Ndhp_A@mail.gmail.com>
References: <CAMbF=C-Wcu5unwQ5cn=cSqsPJCRnQOqzbDeSKE0DU+-=Ndhp_A@mail.gmail.com>
Message-ID: <CACL+1atyaYDcNTo69riRbw41icC1kT0Mw9fxfvUpbKaWSPV0dA@mail.gmail.com>

On Wed, May 22, 2013 at 2:14 PM, Citizen Kant <citizenkant at gmail.com> wrote:
> Does anybody know if there's a Python method that gives or stores the
> complete list of ascii characters or unicode characters? The list of every
> single character available would be perfect.

The unicodedata module provides access to the Unicode database that Python uses:

http://docs.python.org/2/library/unicodedata#unicodedata.unidata_version

Here are the versions of the database for Python 2.6.8, 2.7.3, 3.2.3, and 3.3.1:

    >>> unicodedata.unidata_version # 2.6.8
    '5.1.0'
    >>> unicodedata.unidata_version # 2.7.3
    '5.2.0'
    >>> unicodedata.unidata_version # 3.2.3
    '6.0.0'
    >>> unicodedata.unidata_version # 3.3.1
    '6.1.0'

From fomcl at yahoo.com  Wed May 22 21:03:14 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Wed, 22 May 2013 12:03:14 -0700 (PDT)
Subject: [Tutor] try..except - what about that ton of **Error statements?
In-Reply-To: <519CFE53.3010904@pearwood.info>
References: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>
	<CAG6Bxkck58SvaSh522947dJM5TiAyACTNqj0xutFywOYRnyzPg@mail.gmail.com>
	<CALRAYNXKMuLqg=spN2A25evurvoJYva2zQj+6m2Sd1+AfaA+Ow@mail.gmail.com>
	<519CC329.7010203@pearwood.info>
	<CANDiX9LR4i0bFC4Bpnc7HcLro=tZPqWrFN+Xn0GBgqML0SWQoQ@mail.gmail.com>
	<519CDAFC.8070502@pearwood.info>
	<CANDiX9+_g+9x6vizMFausuQrfbia9raA4V+E74CTjiQjDkSe=w@mail.gmail.com>
	<519CFE53.3010904@pearwood.info>
Message-ID: <1369249394.60516.YahooMailNeo@web163801.mail.gq1.yahoo.com>



> Subject: Re: [Tutor] try..except - what about that ton of **Error statements?
> 
> On 23/05/13 02:09, boB Stepp wrote:
> 
>>  I was not aware that hardware damage could be caused by poor
>>  programming. I am curious; can you give some examples of how this
>>  might occur?

There used to be a program that would let your harddisk "sing" a melody by letting it frantically spin. I always thought this was *not* a good idea, though I have never heard of accidents with it. ;-)


From citizenkant at gmail.com  Wed May 22 21:12:35 2013
From: citizenkant at gmail.com (Citizen Kant)
Date: Wed, 22 May 2013 21:12:35 +0200
Subject: [Tutor] Fwd:  Available characters
In-Reply-To: <CACL+1atyaYDcNTo69riRbw41icC1kT0Mw9fxfvUpbKaWSPV0dA@mail.gmail.com>
References: <CAMbF=C-Wcu5unwQ5cn=cSqsPJCRnQOqzbDeSKE0DU+-=Ndhp_A@mail.gmail.com>
	<CACL+1atyaYDcNTo69riRbw41icC1kT0Mw9fxfvUpbKaWSPV0dA@mail.gmail.com>
Message-ID: <CAMbF=C8ZgXmPgqGL-8zdERpYZpp3XSJcPdLFzrG7eeinwaYBsQ@mail.gmail.com>

On Wed, May 22, 2013 at 2:14 PM, Citizen Kant <citizenkant at gmail.com> wrote:
> Does anybody know if there's a Python method that gives or stores the
> complete list of ascii characters or unicode characters? The list of every
> single character available would be perfect.

The unicodedata module provides access to the Unicode database that Python
uses:

http://docs.python.org/2/library/unicodedata#unicodedata.unidata_version

Here are the versions of the database for Python 2.6.8, 2.7.3, 3.2.3, and
3.3.1:

    >>> unicodedata.unidata_version # 2.6.8
    '5.1.0'
    >>> unicodedata.unidata_version # 2.7.3
    '5.2.0'
    >>> unicodedata.unidata_version # 3.2.3
    '6.0.0'
    >>> unicodedata.unidata_version # 3.3.1
    '6.1.0'


Thanks! This is perfect.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130522/9f90c41c/attachment.html>

From cybervigilante at gmail.com  Wed May 22 21:29:28 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Wed, 22 May 2013 12:29:28 -0700
Subject: [Tutor] Fwd: Available characters
In-Reply-To: <CAMbF=C8ZgXmPgqGL-8zdERpYZpp3XSJcPdLFzrG7eeinwaYBsQ@mail.gmail.com>
References: <CAMbF=C-Wcu5unwQ5cn=cSqsPJCRnQOqzbDeSKE0DU+-=Ndhp_A@mail.gmail.com>
	<CACL+1atyaYDcNTo69riRbw41icC1kT0Mw9fxfvUpbKaWSPV0dA@mail.gmail.com>
	<CAMbF=C8ZgXmPgqGL-8zdERpYZpp3XSJcPdLFzrG7eeinwaYBsQ@mail.gmail.com>
Message-ID: <CALRAYNXN8W4cEQrD_iBGuAr-DhshpGJYNZn3gut6HED2M0N53g@mail.gmail.com>

> The unicodedata module provides access to the Unicode database that Python
> uses:
>
> http://docs.python.org/2/library/unicodedata#unicodedata.unidata_version

That was really useful for another reason. After I checked and saw it
was in DLLs, I investigated the other Python DLLs  - which had
heretofore seemed mysterious - and found winsound. I happen to be
interested in frequency generation.

Jim

From cybervigilante at gmail.com  Wed May 22 21:47:17 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Wed, 22 May 2013 12:47:17 -0700
Subject: [Tutor] keyboard interrupt
Message-ID: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>

I made a simple ear frequency-tester, but I don't want it to go on
forever, so I tried stopping it when I  pressed a key, as below, but
that doesn't work. I did check out keyboard interrupts but they seem
unnecessarily complex just to stop a program. I'm not passing keys. Is
there something simple I'm missing?

import winsound

try:
    for freq in range(100,32000,100):
        winsound.Beep(freq, 1000)
except KeyboardInterrupt:
    pass

-- 
Jim Mooney

From marc.tompkins at gmail.com  Wed May 22 22:10:28 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 22 May 2013 13:10:28 -0700
Subject: [Tutor] keyboard interrupt
In-Reply-To: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
Message-ID: <CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>

On Wed, May 22, 2013 at 12:47 PM, Jim Mooney <cybervigilante at gmail.com>wrote:

> I made a simple ear frequency-tester, but I don't want it to go on
> forever, so I tried stopping it when I  pressed a key, as below, but
> that doesn't work. I did check out keyboard interrupts but they seem
> unnecessarily complex just to stop a program. I'm not passing keys. Is
> there something simple I'm missing?
>
> import winsound
>
> try:
>     for freq in range(100,32000,100):
>         winsound.Beep(freq, 1000)
> except KeyboardInterrupt:
>     pass
>
>
I've not used it myself, but I believe the KeyboadInterrupt is only
generated by one _specific_ keypress.  You mentioned that you pressed a key
- did you try Control-C?

http://effbot.org/zone/stupid-exceptions-keyboardinterrupt.htm
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130522/ba4db613/attachment.html>

From malaclypse2 at gmail.com  Wed May 22 22:11:01 2013
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Wed, 22 May 2013 16:11:01 -0400
Subject: [Tutor] keyboard interrupt
In-Reply-To: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
Message-ID: <CADwdpybuGAhue-SYnLKY+nA2ssvFetmAZ-q=7zWFd7RLxXiqvg@mail.gmail.com>

On Wed, May 22, 2013 at 3:47 PM, Jim Mooney <cybervigilante at gmail.com>wrote:

> I made a simple ear frequency-tester, but I don't want it to go on
> forever, so I tried stopping it when I  pressed a key, as below, but
> that doesn't work. I did check out keyboard interrupts but they seem
> unnecessarily complex just to stop a program. I'm not passing keys. Is
> there something simple I'm missing?
>
> import winsound
>
> try:
>     for freq in range(100,32000,100):
>         winsound.Beep(freq, 1000)
> except KeyboardInterrupt:
>     pass
>
>
The KeyboardInterrupt ?exception is raised when someone presses Ctrl-C.  If
you catch it, and ignore it (which is what your code above is doing), then
pressing Ctrl-C doesn't do anything.  If you just take out the try/except,
then you can hit Ctrl-C and interrupt your program as normal.

-- 
Jerry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130522/8f2fcc31/attachment.html>

From cybervigilante at gmail.com  Wed May 22 22:24:02 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Wed, 22 May 2013 13:24:02 -0700
Subject: [Tutor] keyboard interrupt
In-Reply-To: <CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
Message-ID: <CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>

> I've not used it myself, but I believe the KeyboadInterrupt is only
> generated by one _specific_ keypress.  You mentioned that you pressed a key
> - did you try Control-C?

Actually, I did, using Win 7 - and I put exit() in place of pass. I
tried ctrl-c, ctrl-x, esc, and del. Windows doesn't seem to respond to
anything. The prog just goes to the end

Jim

From davea at davea.name  Wed May 22 22:31:50 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 22 May 2013 16:31:50 -0400
Subject: [Tutor] try..except - what about that ton of **Error statements?
In-Reply-To: <1369249394.60516.YahooMailNeo@web163801.mail.gq1.yahoo.com>
References: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>
	<CAG6Bxkck58SvaSh522947dJM5TiAyACTNqj0xutFywOYRnyzPg@mail.gmail.com>
	<CALRAYNXKMuLqg=spN2A25evurvoJYva2zQj+6m2Sd1+AfaA+Ow@mail.gmail.com>
	<519CC329.7010203@pearwood.info>
	<CANDiX9LR4i0bFC4Bpnc7HcLro=tZPqWrFN+Xn0GBgqML0SWQoQ@mail.gmail.com>
	<519CDAFC.8070502@pearwood.info>
	<CANDiX9+_g+9x6vizMFausuQrfbia9raA4V+E74CTjiQjDkSe=w@mail.gmail.com>
	<519CFE53.3010904@pearwood.info>
	<1369249394.60516.YahooMailNeo@web163801.mail.gq1.yahoo.com>
Message-ID: <519D2B36.1050406@davea.name>

On 05/22/2013 03:03 PM, Albert-Jan Roskam wrote:
>
>
>> Subject: Re: [Tutor] try..except - what about that ton of **Error statements?
>>
>> On 23/05/13 02:09, boB Stepp wrote:
>>
>>>   I was not aware that hardware damage could be caused by poor
>>>   programming. I am curious; can you give some examples of how this
>>>   might occur?
>
> There used to be a program that would let your harddisk "sing" a melody by letting it frantically spin. I always thought this was *not* a good idea, though I have never heard of accidents with it. ;-)
>

I had a young lady working for me that was writing a printer driver, the 
kind that these days would be embedded inside the printer.  I believe it 
was a daisy-wheel printer.  It used a stepper motor which was stepped up 
gradually from zero to full speed and back again.  Anyway, she put a 
breakpoint in the code at the point where the carriage was ramped up, 
and the code stopped, but the carriage kept going, It almost made it 
through the outer wall of the printer - totalled.


-- 
DaveA

From cybervigilante at gmail.com  Wed May 22 22:30:29 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Wed, 22 May 2013 13:30:29 -0700
Subject: [Tutor] keyboard interrupt
In-Reply-To: <CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
	<CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
Message-ID: <CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>

On 22 May 2013 13:24, Jim Mooney <cybervigilante at gmail.com> wrote:
>> I've not used it myself, but I believe the KeyboadInterrupt is only
>> generated by one _specific_ keypress.  You mentioned that you pressed a key
>> - did you try Control-C?
>
> Actually, I did, using Win 7 - and I put exit() in place of pass. I
> tried ctrl-c, ctrl-x, esc, and del. Windows doesn't seem to respond to
> anything. The prog just goes to the end
>
> Jim

Figured it out. Ctrl-C only works in the Windows Command window, not
in an editor.

Jim



-- 
Jim Mooney

"When I got to high school I realized my name would always present
problems." --Dick Hertz

From marc.tompkins at gmail.com  Wed May 22 23:21:38 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 22 May 2013 14:21:38 -0700
Subject: [Tutor] keyboard interrupt
In-Reply-To: <CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
	<CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
	<CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
Message-ID: <CAKK8jXZ-UNnj+FMRe3bEOtY3D+U9rZ-3dB18YZoENAZXVffgUw@mail.gmail.com>

On Wed, May 22, 2013 at 1:30 PM, Jim Mooney <cybervigilante at gmail.com>wrote:

> On 22 May 2013 13:24, Jim Mooney <cybervigilante at gmail.com> wrote:
> >> I've not used it myself, but I believe the KeyboadInterrupt is only
> >> generated by one _specific_ keypress.  You mentioned that you pressed a
> key
> >> - did you try Control-C?
> >
> > Actually, I did, using Win 7 - and I put exit() in place of pass. I
> > tried ctrl-c, ctrl-x, esc, and del. Windows doesn't seem to respond to
> > anything. The prog just goes to the end
> >
> > Jim
>
> Figured it out. Ctrl-C only works in the Windows Command window, not
> in an editor.
>

That makes a lot of sense.  And should be added to the list of responses
_next_ time somebody asks "Why shouldn't I run production code in IDLE?"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130522/ad0582f3/attachment-0001.html>

From eryksun at gmail.com  Thu May 23 00:05:49 2013
From: eryksun at gmail.com (eryksun)
Date: Wed, 22 May 2013 18:05:49 -0400
Subject: [Tutor] keyboard interrupt
In-Reply-To: <CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
	<CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
	<CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
Message-ID: <CACL+1avQpoAHPVj-nMCGmJ_4QvEhSXTK3KeEJwMkPCSdQhsi6g@mail.gmail.com>

On Wed, May 22, 2013 at 4:30 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
>
> Figured it out. Ctrl-C only works in the Windows Command window, not
> in an editor.

Which IDE?

In IDLE, your code runs in the main thread of a subprocess (unless
IDLE is started with the -n option). A second thread ("SockThread") is
started to communicate with PyShell over a socket. When you press
ctrl-c, PyShell executes an interprocess call to
interrupt_the_server(), which simply executes thread.interrupt_main()
-- i.e. interrupt the main thread with a KeyboardInterrupt:

    >>> import thread
    >>> thread.interrupt_main()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyboardInterrupt

Almost certainly your IDE supports interrupting the execution of code.
You just need to configure the key binding. The default binding for
ctrl-c on Windows is to copy the selection to the clipboard.

From cybervigilante at gmail.com  Thu May 23 02:56:06 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Wed, 22 May 2013 17:56:06 -0700
Subject: [Tutor] keyboard interrupt
In-Reply-To: <CACL+1avQpoAHPVj-nMCGmJ_4QvEhSXTK3KeEJwMkPCSdQhsi6g@mail.gmail.com>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
	<CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
	<CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
	<CACL+1avQpoAHPVj-nMCGmJ_4QvEhSXTK3KeEJwMkPCSdQhsi6g@mail.gmail.com>
Message-ID: <CALRAYNUphqUGCtSbfa3G-m=Gm8=3bALuD7Uz+nE9oH8O3L9BhQ@mail.gmail.com>

On 22 May 2013 15:05, eryksun <eryksun at gmail.com> wrote:
> On Wed, May 22, 2013 at 4:30 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
>>
>> Figured it out. Ctrl-C only works in the Windows Command window, not
>> in an editor.
>
> Which IDE?

Wing. But not being able to abort out of a Windows program is a
feature. You don't want to lose seven hours of spreadsheet work
because you forgot and hit ctrl-C. (I just hit Ctrl-C. Nothing, which
is as it should be ;')

Well, it's good to be reminded that an editor does funny stuff as
opposed to command line.

Jim

From steve at pearwood.info  Thu May 23 03:06:48 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 23 May 2013 11:06:48 +1000
Subject: [Tutor] Available characters
In-Reply-To: <CAMbF=C-Wcu5unwQ5cn=cSqsPJCRnQOqzbDeSKE0DU+-=Ndhp_A@mail.gmail.com>
References: <CAMbF=C-Wcu5unwQ5cn=cSqsPJCRnQOqzbDeSKE0DU+-=Ndhp_A@mail.gmail.com>
Message-ID: <519D6BA8.6060004@pearwood.info>

On 23/05/13 04:14, Citizen Kant wrote:
> Does anybody know if there's a Python method that gives or stores the
> complete list of ascii characters or unicode characters? The list of every
> single character available would be perfect.


There are only 127 ASCII characters, so getting a list of them is trivial:

ascii = map(chr, range(128))  # Python 2
ascii = list(map(chr, range(128)))  # Python 3


or if you prefer a string:

ascii = ''.join(map(chr, range(128)))


If you don't like map(), you can use a list comprehension:

[chr(i) for i in range(128)]

The string module already defines some useful subsets of them:

py> import string
py> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'


There are 1114111 (hexadecimal 0x10FFFF) possible Unicode code-points, but most of them are currently unassigned. Of those that are assigned, many of them are reserved as non-characters or for special purposes, and even those which are assigned, most fonts do not display anything even close to the full range of Unicode characters.

If you spend some time on the Unicode web site, you will find lists of characters which are defined:

www.unicode.org

but beware, it is relatively heavy going. Wikipedia has a page showing all currently assigned characters, but font support is still lousy and many of them display as boxes:

http://en.wikipedia.org/wiki/List_of_Unicode_characters

You can generate the entire list yourself, using the same technique as for ASCII above:


# Python 2:
unicode = ''.join(map(unichr, xrange(1114112)))

# Python3:
unicode = ''.join(map(chr, range(1114112)))


although it will take a few seconds to generate the entire range. You can then get the name for each one using something like this:

import unicodedata
for c in unicode:
     try:
         print(c, unicodedata.name(c))
     except ValueError:
         # unassigned, or a reserved non-character
         pass


but remember that there are currently almost 100,000 defined characters in Unicode, and your terminal will probably not be able to print most of them. Expect to see a lot of boxes.




-- 
Steven

From davea at davea.name  Thu May 23 03:25:57 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 22 May 2013 21:25:57 -0400
Subject: [Tutor] keyboard interrupt
In-Reply-To: <CADwdpybuGAhue-SYnLKY+nA2ssvFetmAZ-q=7zWFd7RLxXiqvg@mail.gmail.com>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CADwdpybuGAhue-SYnLKY+nA2ssvFetmAZ-q=7zWFd7RLxXiqvg@mail.gmail.com>
Message-ID: <519D7025.8030108@davea.name>

On 05/22/2013 04:11 PM, Jerry Hill wrote:
> On Wed, May 22, 2013 at 3:47 PM, Jim Mooney <cybervigilante at gmail.com>wrote:
>
>> I made a simple ear frequency-tester, but I don't want it to go on
>> forever, so I tried stopping it when I  pressed a key, as below, but
>> that doesn't work. I did check out keyboard interrupts but they seem
>> unnecessarily complex just to stop a program. I'm not passing keys. Is
>> there something simple I'm missing?
>>
>> import winsound
>>
>> try:
>>      for freq in range(100,32000,100):
>>          winsound.Beep(freq, 1000)
>> except KeyboardInterrupt:
>>      pass
>>
>>
> The KeyboardInterrupt ?exception is raised when someone presses Ctrl-C.  If
> you catch it, and ignore it (which is what your code above is doing), then
> pressing Ctrl-C doesn't do anything.  If you just take out the try/except,
> then you can hit Ctrl-C and interrupt your program as normal.
>

What do you mean "doesn't do anything" ?  It certainly terminates the 
loop, which was the intent.  Provided of course that something else 
isn't trapping the Ctrl-C first.






-- 
DaveA

From cybervigilante at gmail.com  Thu May 23 03:46:21 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Wed, 22 May 2013 18:46:21 -0700
Subject: [Tutor] keyboard interrupt
In-Reply-To: <519D7025.8030108@davea.name>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CADwdpybuGAhue-SYnLKY+nA2ssvFetmAZ-q=7zWFd7RLxXiqvg@mail.gmail.com>
	<519D7025.8030108@davea.name>
Message-ID: <CALRAYNU4WMGCFkVNTB1jhh=Rw0qBvDSTV1Ety5hRyOyZEQk99A@mail.gmail.com>

> What do you mean "doesn't do anything" ?  It certainly terminates the loop,
> which was the intent.  Provided of course that something else isn't trapping
> the Ctrl-C first.

It doesn't in Windows proper, using Wing 101. It does exit in the
Windows command console. For some reason I forgot ctrl-C is Copy in
windows. I tried Ctrl-X but I was again confusing the old DOS abort
with Windows Cut. I've been enslaved by the GUI ;')

I'm using Wing 101, which doesn't have a feature set for altering that
behavior. It's probably in the professional version. If I scrape up
spare cash I may go for PyCharm or Wing Pro, but I don't need them on
the low end of the learning curve. I'd just waste time fooling with
them.

The program does exit in Idle, although Idle throws up a Tk screen
asking if you want to abort the program, so it's not a clean exit.

Jim

From steve at pearwood.info  Thu May 23 03:47:36 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 23 May 2013 11:47:36 +1000
Subject: [Tutor] try..except - what about that ton of **Error statements?
In-Reply-To: <CANDiX9+_g+9x6vizMFausuQrfbia9raA4V+E74CTjiQjDkSe=w@mail.gmail.com>
References: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>
	<CAG6Bxkck58SvaSh522947dJM5TiAyACTNqj0xutFywOYRnyzPg@mail.gmail.com>
	<CALRAYNXKMuLqg=spN2A25evurvoJYva2zQj+6m2Sd1+AfaA+Ow@mail.gmail.com>
	<519CC329.7010203@pearwood.info>
	<CANDiX9LR4i0bFC4Bpnc7HcLro=tZPqWrFN+Xn0GBgqML0SWQoQ@mail.gmail.com>
	<519CDAFC.8070502@pearwood.info>
	<CANDiX9+_g+9x6vizMFausuQrfbia9raA4V+E74CTjiQjDkSe=w@mail.gmail.com>
Message-ID: <519D7538.4010908@pearwood.info>

On 23/05/13 02:09, boB Stepp wrote:

> I would like to ask some general questions here. Problems can arise
> from bugs in the operating system, bugs in the programming language(s)
> being used, bugs in packages/modules being used, bugs in any third
> party packages being used, etc. Also, whenever any one of these things
> is updated/upgraded, it can introduce new issues. What strategies can
> one use to deal with these possibilities that seem entirely out of the
> programmer's control?


They're not really out of your control though. You can always write code
to work around them.

For instance, a long time ago I was using a programming language that had a bug that caused the program to crash if you tried to display the string "0^0". If this was Python, I might do something like this:

def my_print(astring):
     if astring == '0^0':
         # Avoid the system bug.
         astring = '0 ^ 0'  # Close enough...
     print astring


and then make sure I always call my_print instead of print directly.

Sometimes it is sufficient to just avoid triggering the bug. Sometimes you might need use a different tool. For instance, in Python, print is not "thread safe" -- if you have two different threads trying to print at the same time, their output may interleave.

# Thread 1:
print "Hello world!"

# Thread 2:
print "Goodbye cruel world :-("

# Output might look like this:
HelGoodblo ye crue l worworldld :-(!



Is this a bug in print? No, not really, but it is a limitation, it is not designed to be thread safe. So when using threads, you can:

- always make sure only one thread is responsible for doing any printing;

- if you must have multiple threads printing at the same time, use sys.stdout.write instead of print, because it is thread-safe.


So working around bugs is, in general, possible, even if sometimes it is hard.

A general technique when programming is to always have a good, solid test suite. This will detect any change in behaviour, whether due to your own programming errors, on bugs in the language or operating system. What you do is as you develop your own code, in parallel you also develop a second program that tests as much of your code as you can.

For instance, suppose you have a (trivial) function that doubles a number and adds one:

def double_plus_one(x):
     return 2*x + 1

So you have a second file open that tests it:


from my_app import *

def test_double_plus_one():
     assert double_plus_one(5) == 11
     assert double_plus_one(100.25) == 201.5
     assert double_plus_one(-0.5) == 0


test_double_plus_one()



(Or you can use a test frame work like unittest or doctest or both.) Now, whenever you change something, say you upgrade to a new version of the language, or change your code, you run the test file and see what tests start failing. Each failed test indicates a bug that needs to be fixed, although it doesn't tell you what introduced the bug.



-- 
Steven

From davea at davea.name  Thu May 23 03:58:22 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 22 May 2013 21:58:22 -0400
Subject: [Tutor] keyboard interrupt
In-Reply-To: <CALRAYNU4WMGCFkVNTB1jhh=Rw0qBvDSTV1Ety5hRyOyZEQk99A@mail.gmail.com>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CADwdpybuGAhue-SYnLKY+nA2ssvFetmAZ-q=7zWFd7RLxXiqvg@mail.gmail.com>
	<519D7025.8030108@davea.name>
	<CALRAYNU4WMGCFkVNTB1jhh=Rw0qBvDSTV1Ety5hRyOyZEQk99A@mail.gmail.com>
Message-ID: <519D77BE.9090506@davea.name>

On 05/22/2013 09:46 PM, Jim Mooney wrote:
>> What do you mean "doesn't do anything" ?  It certainly terminates the loop,
>> which was the intent.  Provided of course that something else isn't trapping
>> the Ctrl-C first.
>
> It doesn't in Windows proper, using Wing 101.

Then Wing is changing the behavior, trapping the Ctrl-C.  Not sure why 
you would call Wing the "proper Windows".

> It does exit in the
> Windows command console.

Of course.

> For some reason I forgot ctrl-C is Copy in
> windows.

Only to programs that have a GUI event loop which happens to trap the 
event.  That's common in Windows, and is required by the CUA standard 
(apparently defunct), but it's not the default behavior of a Windows 
executable.

> I tried Ctrl-X but I was again confusing the old DOS abort
> with Windows Cut. I've been enslaved by the GUI ;')
>
> I'm using Wing 101, which doesn't have a feature set for altering that
> behavior. It's probably in the professional version. If I scrape up
> spare cash I may go for PyCharm or Wing Pro, but I don't need them on
> the low end of the learning curve. I'd just waste time fooling with
> them.
>
> The program does exit in Idle, although Idle throws up a Tk screen
> asking if you want to abort the program, so it's not a clean exit.
>
> Jim
>
>


-- 
DaveA

From eryksun at gmail.com  Thu May 23 08:56:35 2013
From: eryksun at gmail.com (eryksun)
Date: Thu, 23 May 2013 02:56:35 -0400
Subject: [Tutor] keyboard interrupt
In-Reply-To: <CALRAYNUphqUGCtSbfa3G-m=Gm8=3bALuD7Uz+nE9oH8O3L9BhQ@mail.gmail.com>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
	<CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
	<CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
	<CACL+1avQpoAHPVj-nMCGmJ_4QvEhSXTK3KeEJwMkPCSdQhsi6g@mail.gmail.com>
	<CALRAYNUphqUGCtSbfa3G-m=Gm8=3bALuD7Uz+nE9oH8O3L9BhQ@mail.gmail.com>
Message-ID: <CACL+1avETMJq1R5qdcwbN_+mbPpc5Q4zNuonBtM5BKDF2w2tFg@mail.gmail.com>

On Wed, May 22, 2013 at 8:56 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> On 22 May 2013 15:05, eryksun <eryksun at gmail.com> wrote:
>> On Wed, May 22, 2013 at 4:30 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
>>>
>>> Figured it out. Ctrl-C only works in the Windows Command window, not
>>> in an editor.
>>
>> Which IDE?
>
> Wing. But not being able to abort out of a Windows program is a
> feature. You don't want to lose seven hours of spreadsheet work
> because you forgot and hit ctrl-C. (I just hit Ctrl-C. Nothing, which
> is as it should be ;')
>
> Well, it's good to be reminded that an editor does funny stuff as
> opposed to command line.

Apparently Wing isn't as savvy as IDLE when it comes to communicating
with the subprocess. I've only searched for about a minute, but
apparently the way this works in Wing is to "Restart Shell":

http://stackoverflow.com/a/10360503/205580
http://www.wingware.com/doc/debug/interactive-python-shell

This kills the suprocess and starts a new interpreter. Crude, but it
should get the job done.

From stutozer at gmail.com  Thu May 23 14:57:42 2013
From: stutozer at gmail.com (Stuart Tozer)
Date: Thu, 23 May 2013 15:57:42 +0300
Subject: [Tutor] trying to split or rpartition the contents of a list
In-Reply-To: <CA+pweXvug6NjxQs3VUXm0rqmRuTph2YtB_uM=nkxk41a99Tn8Q@mail.gmail.com>
References: <CA+pweXvAGMit3eaOHAm3-6AJSNwoD5Ki4nVYSXXFc1k0tKu8Pw@mail.gmail.com>
	<1369209969.43785.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<CA+pweXvug6NjxQs3VUXm0rqmRuTph2YtB_uM=nkxk41a99Tn8Q@mail.gmail.com>
Message-ID: <CA+pweXtTDQvEbJ9b1eXYeETf=SJP2DMQO_=gqdBD8O8XLoxEKw@mail.gmail.com>

Hello Amit- your solution works very well. Thanks very much!

Best regards,
Stu


On Wed, May 22, 2013 at 11:39 AM, Stuart Tozer <stutozer at gmail.com> wrote:

> Thanks very much guys- I'll get back to this when I have a spare moment
> and let you know how I get on.
>
> Cheers,
> Stu
>
>
>
> On Wed, May 22, 2013 at 11:06 AM, Albert-Jan Roskam <fomcl at yahoo.com>wrote:
>
>> >
>>
>> >forobjectinobjects:sorted(set(object.split('_',1)[0]))cmds.menuItem(label
>> =object,parent ="objectMenu")
>>
>>
>> "sorted" returns the sorted list but you don't assign anything to it. You
>> can either assign it to a variable, or use the .sort method instead. Also,
>> you don't need to specify the maxsplit argument (1) in .split. Also, you
>> used 'object' as a loop index but this is a reserved word. Why not use the
>> more descriptive "for filename in filenames"?
>>
>
>
>
> --
> http://stutozer.elementfx.com/
>
>
>


-- 
http://stutozer.elementfx.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130523/7c327ab6/attachment.html>

From amitsaha.in at gmail.com  Thu May 23 15:00:22 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Thu, 23 May 2013 23:00:22 +1000
Subject: [Tutor] trying to split or rpartition the contents of a list
In-Reply-To: <CA+pweXtTDQvEbJ9b1eXYeETf=SJP2DMQO_=gqdBD8O8XLoxEKw@mail.gmail.com>
References: <CA+pweXvAGMit3eaOHAm3-6AJSNwoD5Ki4nVYSXXFc1k0tKu8Pw@mail.gmail.com>
	<1369209969.43785.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<CA+pweXvug6NjxQs3VUXm0rqmRuTph2YtB_uM=nkxk41a99Tn8Q@mail.gmail.com>
	<CA+pweXtTDQvEbJ9b1eXYeETf=SJP2DMQO_=gqdBD8O8XLoxEKw@mail.gmail.com>
Message-ID: <CANODV3npzq7Uhi=zDaT3YukXL3TZw2a=FvgNV7fPVBBGOtRGXg@mail.gmail.com>

Hi Stuart,

On Thu, May 23, 2013 at 10:57 PM, Stuart Tozer <stutozer at gmail.com> wrote:
> Hello Amit- your solution works very well. Thanks very much!

Good to know that! Hope it was clear.

All the best.
-Amit

>
> Best regards,
> Stu
>
>
> On Wed, May 22, 2013 at 11:39 AM, Stuart Tozer <stutozer at gmail.com> wrote:
>>
>> Thanks very much guys- I'll get back to this when I have a spare moment
>> and let you know how I get on.
>>
>> Cheers,
>> Stu
>>
>>
>>
>> On Wed, May 22, 2013 at 11:06 AM, Albert-Jan Roskam <fomcl at yahoo.com>
>> wrote:
>>>
>>> >
>>>
>>>
>>> > >forobjectinobjects:sorted(set(object.split('_',1)[0]))cmds.menuItem(label
>>> > =object,parent ="objectMenu")
>>>
>>>
>>> "sorted" returns the sorted list but you don't assign anything to it. You
>>> can either assign it to a variable, or use the .sort method instead. Also,
>>> you don't need to specify the maxsplit argument (1) in .split. Also, you
>>> used 'object' as a loop index but this is a reserved word. Why not use the
>>> more descriptive "for filename in filenames"?
>>
>>
>>
>>
>> --
>> http://stutozer.elementfx.com/
>>
>>
>
>
>
> --
> http://stutozer.elementfx.com/
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



--
http://echorand.me

From malaclypse2 at gmail.com  Thu May 23 15:38:46 2013
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Thu, 23 May 2013 09:38:46 -0400
Subject: [Tutor] keyboard interrupt
In-Reply-To: <519D7025.8030108@davea.name>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CADwdpybuGAhue-SYnLKY+nA2ssvFetmAZ-q=7zWFd7RLxXiqvg@mail.gmail.com>
	<519D7025.8030108@davea.name>
Message-ID: <CADwdpybP6SPSt6BuCvZzTX-B8bSjE534kDyT2Yohaqgxm2zU7g@mail.gmail.com>

On Wed, May 22, 2013 at 9:25 PM, Dave Angel <davea at davea.name> wrote:

> On 05/22/2013 04:11 PM, Jerry Hill wrote:
>
>> The KeyboardInterrupt ?exception is raised when someone presses Ctrl-C.
>>  If
>> you catch it, and ignore it (which is what your code above is doing), then
>> pressing Ctrl-C doesn't do anything.  If you just take out the try/except,
>> then you can hit Ctrl-C and interrupt your program as normal.
>>
>>
> What do you mean "doesn't do anything" ?  It certainly terminates the
> loop, which was the intent.  Provided of course that something else isn't
> trapping the Ctrl-C first.
>

?You're quite right.  I mis-read the original code as having the try/except
inside the loop.  ?The way Jim wrote it was correct.

-- 
Jerry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130523/fc765d10/attachment.html>

From robertvstepp at gmail.com  Thu May 23 18:39:23 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Thu, 23 May 2013 11:39:23 -0500
Subject: [Tutor] try..except - what about that ton of **Error statements?
In-Reply-To: <519D7538.4010908@pearwood.info>
References: <CALRAYNUAgDRFPCaU+7uA6FgG0c9bCo3PDemD9z0Ka02rPud-og@mail.gmail.com>
	<CAG6Bxkck58SvaSh522947dJM5TiAyACTNqj0xutFywOYRnyzPg@mail.gmail.com>
	<CALRAYNXKMuLqg=spN2A25evurvoJYva2zQj+6m2Sd1+AfaA+Ow@mail.gmail.com>
	<519CC329.7010203@pearwood.info>
	<CANDiX9LR4i0bFC4Bpnc7HcLro=tZPqWrFN+Xn0GBgqML0SWQoQ@mail.gmail.com>
	<519CDAFC.8070502@pearwood.info>
	<CANDiX9+_g+9x6vizMFausuQrfbia9raA4V+E74CTjiQjDkSe=w@mail.gmail.com>
	<519D7538.4010908@pearwood.info>
Message-ID: <CANDiX9J0QfzUhQDueN0TXabYuMVrHhAK0_x5Zhza0oVK0QzHJA@mail.gmail.com>

On Wed, May 22, 2013 at 8:47 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On 23/05/13 02:09, boB Stepp wrote:
>
>> I would like to ask some general questions here. Problems can arise
>> from bugs in the operating system, bugs in the programming language(s)
>> being used, bugs in packages/modules being used, bugs in any third
>> party packages being used, etc. Also, whenever any one of these things
>> is updated/upgraded, it can introduce new issues. What strategies can
>> one use to deal with these possibilities that seem entirely out of the
>> programmer's control?
>
>
>
> They're not really out of your control though. You can always write code
> to work around them.
>

I have found myself having to do this when I write scripts for my
radiation planning software at work. There are frequently rather
quirky behaviors in this software that I have to work around. And
there seems to be a different set of quirky behaviors every time the
software is upgraded.

[...]

>
> Sometimes it is sufficient to just avoid triggering the bug. Sometimes you
> might need use a different tool. For instance, in Python, print is not
> "thread safe" -- if you have two different threads trying to print at the
> same time, their output may interleave.
>

I did not know this.

[...]

>
> So working around bugs is, in general, possible, even if sometimes it is
> hard.
>
> A general technique when programming is to always have a good, solid test
> suite. This will detect any change in behaviour, whether due to your own
> programming errors, on bugs in the language or operating system. What you do
> is as you develop your own code, in parallel you also develop a second
> program that tests as much of your code as you can.
>

I guess this is the test driven development I have heard about.

[...]

>
> (Or you can use a test frame work like unittest or doctest or both.) Now,
> whenever you change something, say you upgrade to a new version of the
> language, or change your code, you run the test file and see what tests
> start failing. Each failed test indicates a bug that needs to be fixed,
> although it doesn't tell you what introduced the bug.
>
So this method of development is a good friend that keeps on giving! ~(:>))

More general questions: How do you keep up with the ongoing changes in
your development languages? One thing I have found frustrating in
learning Python at my rather slow pace (Due to limited time.) is that
the versions keep changing! Worse, at least in the case of Windows, is
there is a constant deluge of security updates, etc. Are you
constantly reading release notes to keep up? Is there a more efficient
way? It seems that if one has written a significant program for
Windows one would have to run one's automated test suite every time
there are updates. I wonder how often problems arise that have to be
dealt with? At least with Solaris at work, they only update the OS
when they update the hardware.

This has been very informative! I have so much to learn...

Thanks!
boB

From rohitha_h at yahoo.co.uk  Thu May 23 18:58:18 2013
From: rohitha_h at yahoo.co.uk (Robert R)
Date: Thu, 23 May 2013 17:58:18 +0100 (BST)
Subject: [Tutor] installing old versions of python on Mac OS X
Message-ID: <1369328298.9422.YahooMailClassic@web171406.mail.ir2.yahoo.com>

Hi,

I have Mac OS X 10.7.5 and would like to install < = python 2.3 on it.

I need it as one of the s/w I would like to try is based on an older version and does not seem to work with the new ones.
I am not sure if the s/w is wrong (doesn't seem like it) or is it really the python version that is messing it up.

I tried 2.4 (using mac ports) but thats not it so I want to go further back but I cannot do it with fink or mac ports.

Any other suggestions ? I tried to install using a tar file but that gave errors.
I am sorry for the dumb question. Thank you for the help

From andrew139668 at yahoo.com  Thu May 23 19:31:44 2013
From: andrew139668 at yahoo.com (Andrew Triplett)
Date: Thu, 23 May 2013 10:31:44 -0700 (PDT)
Subject: [Tutor] Presenting text in different ways by using quotes!
Message-ID: <1369330304.94450.YahooMailNeo@web122001.mail.ne1.yahoo.com>

I am asked to present text in different ways by using quotes in strings. for example:

print("Program "Game Over" 2.0")

print("same", "message", "as before")

print("just", 

?? ???? "a bit", 

??????? "bigger")

print("Here", end=" ")
print("it is...")

print(

????????? """





??? """
)

I can't however seem to input the text GAME OVER in giant text as it says in the book. Any help for this would be appreciated.

-Mitch Stevens
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130523/06352ea3/attachment.html>

From davea at davea.name  Thu May 23 20:27:23 2013
From: davea at davea.name (Dave Angel)
Date: Thu, 23 May 2013 14:27:23 -0400
Subject: [Tutor] Presenting text in different ways by using quotes!
In-Reply-To: <1369330304.94450.YahooMailNeo@web122001.mail.ne1.yahoo.com>
References: <1369330304.94450.YahooMailNeo@web122001.mail.ne1.yahoo.com>
Message-ID: <519E5F8B.2020806@davea.name>

On 05/23/2013 01:31 PM, Andrew Triplett wrote:
> I am asked to present text in different ways by using quotes in strings. for example:
>
> print("Program "Game Over" 2.0")

syntax error.  If you need quotes inside quotes, you probably want to 
use single-quotes for one type.  For example,

print('Program "Game Over" 2.0')

>
> print("same", "message", "as before")
>
> print("just",
>
>          "a bit",
>
>          "bigger")
>
> print("Here", end=" ")
> print("it is...")
>
> print(
>
>            """
>
>
>
>
>
>      """
> )
>
> I can't however seem to input

I suppose you mean "output"

> the text GAME OVER in giant text as it says in the book. Any help for this would be appreciated.
>

How does the book suggest you get text to be "giant" ?  If you write a 
console app, you're out of luck.  And I doubt if you're learning to 
program a GUI quite yet.


-- 
DaveA

From citizenkant at gmail.com  Thu May 23 21:38:08 2013
From: citizenkant at gmail.com (Citizen Kant)
Date: Thu, 23 May 2013 21:38:08 +0200
Subject: [Tutor] Fwd:  Available characters
In-Reply-To: <519D6BA8.6060004@pearwood.info>
References: <CAMbF=C-Wcu5unwQ5cn=cSqsPJCRnQOqzbDeSKE0DU+-=Ndhp_A@mail.gmail.com>
	<519D6BA8.6060004@pearwood.info>
Message-ID: <CAMbF=C_RdAP_FwzO0GD1X73AtAZZq_a22cOcfnDTMUO1XOugAw@mail.gmail.com>

Thanks!

There are only 127 ASCII characters, so getting a list of them is trivial:

ascii = map(chr, range(128))  # Python 2
ascii = list(map(chr, range(128)))  # Python 3


or if you prefer a string:

ascii = ''.join(map(chr, range(128)))


If you don't like map(), you can use a list comprehension:

[chr(i) for i in range(128)]

The string module already defines some useful subsets of them:

py> import string
py> string.printable
'**0123456789abcdefghijklmnopqrst**uvwxyzABCDEFGHIJKLMNOPQRSTUVWX**
YZ!"#$%&\'()*+,-./:;<=>?@[\\]^**_`{|}~ \t\n\r\x0b\x0c'


There are 1114111 (hexadecimal 0x10FFFF) possible Unicode code-points, but
most of them are currently unassigned. Of those that are assigned, many of
them are reserved as non-characters or for special purposes, and even those
which are assigned, most fonts do not display anything even close to the
full range of Unicode characters.

If you spend some time on the Unicode web site, you will find lists of
characters which are defined:

www.unicode.org

but beware, it is relatively heavy going. Wikipedia has a page showing all
currently assigned characters, but font support is still lousy and many of
them display as boxes:

http://en.wikipedia.org/wiki/**List_of_Unicode_characters<http://en.wikipedia.org/wiki/List_of_Unicode_characters>

You can generate the entire list yourself, using the same technique as for
ASCII above:


# Python 2:
unicode = ''.join(map(unichr, xrange(1114112)))

# Python3:
unicode = ''.join(map(chr, range(1114112)))


although it will take a few seconds to generate the entire range. You can
then get the name for each one using something like this:

import unicodedata
for c in unicode:
    try:
        print(c, unicodedata.name(c))
    except ValueError:
        # unassigned, or a reserved non-character
        pass


but remember that there are currently almost 100,000 defined characters in
Unicode, and your terminal will probably not be able to print most of them.
Expect to see a lot of boxes
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130523/4505f51a/attachment.html>

From robertvstepp at gmail.com  Thu May 23 21:49:17 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Thu, 23 May 2013 14:49:17 -0500
Subject: [Tutor] Presenting text in different ways by using quotes!
In-Reply-To: <1369330304.94450.YahooMailNeo@web122001.mail.ne1.yahoo.com>
References: <1369330304.94450.YahooMailNeo@web122001.mail.ne1.yahoo.com>
Message-ID: <CANDiX9JoZS-iiQB454pDN89+eTauJr88_1MKCUQ+VE35Dn_gFQ@mail.gmail.com>

On Thu, May 23, 2013 at 12:31 PM, Andrew Triplett
<andrew139668 at yahoo.com> wrote:
> I am asked to present text in different ways by using quotes in strings. for
> example:
>

[...]

> I can't however seem to input the text GAME OVER in giant text as it says in
> the book. Any help for this would be appreciated.
>
I'm taking a wild guess here, but is the books author(s) wanting you
to use forward slashes, back slashes, underscores and spaces as the
components of your print functions to form a mosaic which looks like
an enlarged GAME OVER ? If you line up everything correctly this can
be done. You just have to play around with the spacing, both
horizontally and vertically.

HTH,
boB

From citizenkant at gmail.com  Thu May 23 21:57:03 2013
From: citizenkant at gmail.com (Citizen Kant)
Date: Thu, 23 May 2013 21:57:03 +0200
Subject: [Tutor] Difference between types
Message-ID: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>

I guess I'm understanding that, in Python, if something belongs to a type,
must also be a value.

I guess I'm understanding that the reason why 9 is considered a value, is
since it's a normal form*,* an element of the system that cannot be
rewritten and reduced any further.

I also guess I'm understanding that the same goes somehow for the letter A
for example, since it cannot be rewritten or reduced any further, so it's a
value too.

type('A')
<type 'str'>

The question is, in order to understand: does this apostrophes thing has a
more profound reason to be attached to the letters or it's just a
conventional way to set a difference between letters and numbers? Do I must
observe this apostrophes thing like the symbol of the type itself inside
which one can put any character, setting it as type str?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130523/565a26a2/attachment-0001.html>

From chigga101 at gmail.com  Thu May 23 22:12:28 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Thu, 23 May 2013 21:12:28 +0100
Subject: [Tutor] Difference between types
In-Reply-To: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
Message-ID: <CACzNyA0-jOdoWLpD+Ezssj72tA9X95wet_=CEUf5zd-yu0W7LA@mail.gmail.com>

wait for someone more knowledgeable to answer, but from what i know,
Yes it does have a profound meaning.  Strings consist of character
sets. Something that was here way before Python

Like i said my experience is limited so i too would like to hear some reponses

From robertvstepp at gmail.com  Thu May 23 22:27:18 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Thu, 23 May 2013 15:27:18 -0500
Subject: [Tutor] Difference between types
In-Reply-To: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
Message-ID: <CANDiX9JsnrvpgiykcwWJU9bN+9XukSpUtftrG63PQciDa+HqEQ@mail.gmail.com>

On Thu, May 23, 2013 at 2:57 PM, Citizen Kant <citizenkant at gmail.com> wrote:
> I guess I'm understanding that, in Python, if something belongs to a type,
> must also be a value.
>
> I guess I'm understanding that the reason why 9 is considered a value, is
> since it's a normal form, an element of the system that cannot be rewritten
> and reduced any further.
>
> I also guess I'm understanding that the same goes somehow for the letter A
> for example, since it cannot be rewritten or reduced any further, so it's a
> value too.
>
> type('A')
> <type 'str'>
>
> The question is, in order to understand: does this apostrophes thing has a
> more profound reason to be attached to the letters or it's just a
> conventional way to set a difference between letters and numbers? Do I must
> observe this apostrophes thing like the symbol of the type itself inside
> which one can put any character, setting it as type str?
>
I asked a similar question a while back. Here is a link to my original
question in the ActiveState Tutor archives:

http://code.activestate.com/lists/python-tutor/91223/

If you look at the bottom it shows all of the links to answers offered.

HTH,
boB

From cybervigilante at gmail.com  Thu May 23 22:37:38 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Thu, 23 May 2013 13:37:38 -0700
Subject: [Tutor] keyboard interrupt
In-Reply-To: <CACL+1avETMJq1R5qdcwbN_+mbPpc5Q4zNuonBtM5BKDF2w2tFg@mail.gmail.com>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
	<CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
	<CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
	<CACL+1avQpoAHPVj-nMCGmJ_4QvEhSXTK3KeEJwMkPCSdQhsi6g@mail.gmail.com>
	<CALRAYNUphqUGCtSbfa3G-m=Gm8=3bALuD7Uz+nE9oH8O3L9BhQ@mail.gmail.com>
	<CACL+1avETMJq1R5qdcwbN_+mbPpc5Q4zNuonBtM5BKDF2w2tFg@mail.gmail.com>
Message-ID: <CALRAYNVQt7a+QUzHhBQRcf=H5KPmG866bAE8LnshF791BMroPA@mail.gmail.com>

> Apparently Wing isn't as savvy as IDLE when it comes to communicating
> with the subprocess. I've only searched for about a minute, but
> apparently the way this works in Wing is to "Restart Shell":
>
> http://stackoverflow.com/a/10360503/205580
> http://www.wingware.com/doc/debug/interactive-python-shell
>
> This kills the suprocess and starts a new interpreter. Crude, but it
> should get the job done.

Thanks. I'll put stackoverflow on my bookmarks. There is still a
difference, though. The program (as corrected below) prints out the
last sound heard as a hearing test, if you press Ctrl-C in Idle or the
Windows Command Console, but prints nothing if you use Option >
Restart Shell in Wing 101. Here's the corrected program if anyone
wants to test their hearing ;')

Oh, as a tip for winusers who have avoided the Win command console, I
also did because I thought you had to type in one line at a time. I
just found I can right-click > paste an entire Py program in (after
you start Python). The prog then starts after you hit Enter twice.
This is Win 7.

import winsound

try:
    for freq in range(100,32000,100):
        winsound.Beep(freq, 1000)
except KeyboardInterrupt:
    print 'last frequency heard was', freq - 100
    exit(0)

-- 
Jim Mooney

From steve at pearwood.info  Fri May 24 00:52:34 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 24 May 2013 08:52:34 +1000
Subject: [Tutor] keyboard interrupt
In-Reply-To: <CALRAYNVQt7a+QUzHhBQRcf=H5KPmG866bAE8LnshF791BMroPA@mail.gmail.com>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
	<CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
	<CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
	<CACL+1avQpoAHPVj-nMCGmJ_4QvEhSXTK3KeEJwMkPCSdQhsi6g@mail.gmail.com>
	<CALRAYNUphqUGCtSbfa3G-m=Gm8=3bALuD7Uz+nE9oH8O3L9BhQ@mail.gmail.com>
	<CACL+1avETMJq1R5qdcwbN_+mbPpc5Q4zNuonBtM5BKDF2w2tFg@mail.gmail.com>
	<CALRAYNVQt7a+QUzHhBQRcf=H5KPmG866bAE8LnshF791BMroPA@mail.gmail.com>
Message-ID: <519E9DB2.5000205@pearwood.info>

On 24/05/13 06:37, Jim Mooney wrote:
>> Apparently Wing isn't as savvy as IDLE when it comes to communicating
>> with the subprocess. I've only searched for about a minute, but
>> apparently the way this works in Wing is to "Restart Shell":
>>
>> http://stackoverflow.com/a/10360503/205580
>> http://www.wingware.com/doc/debug/interactive-python-shell
>>
>> This kills the suprocess and starts a new interpreter. Crude, but it
>> should get the job done.
>
> Thanks. I'll put stackoverflow on my bookmarks.

Beware though, while there are often some very good answers on Stackoverflow, there are also very many people who are nowhere near as knowledgeable as they think, giving terrible answers, and still having large scores. (One particular person comes to mind, I forget his name but he has a *very* high score which means lots of people are voting for his answers, and yet every time without exception I've seen him reply to someone he has been rude, missed the entire point of their question, or given them bad advice. Or all three at once.)

Personally, I think Stackoverflow is a great resource for experienced Python programmers who can separate the wheat from the chaff, but only a moderately okay resource for beginners :-)




-- 
Steven

From davea at davea.name  Fri May 24 03:34:56 2013
From: davea at davea.name (Dave Angel)
Date: Thu, 23 May 2013 21:34:56 -0400
Subject: [Tutor] Difference between types
In-Reply-To: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
Message-ID: <519EC3C0.1040800@davea.name>

On 05/23/2013 03:57 PM, Citizen Kant wrote:

It's quite hard to believe that you're not just trolling.  Little that 
you say below makes any sense with regards to Python.


> I guess I'm understanding that, in Python, if something belongs to a type,
> must also be a value.
>

Nothing belongs to a type.  Objects created during the running of a 
program do have a definite type, and a definite value.  Some are 
immutable, meaning they cannot change.  Others are mutable. Examples are 
int and list, respectively.

> I guess I'm understanding that the reason why 9 is considered a value, is
> since it's a normal form*,* an element of the system that cannot be
> rewritten and reduced any further.

9 is a numeric literal in your source code that describes the integer 
nine.  Since it starts with a digit, and does not have quotes around it, 
it will be represented in the virtual machine as an integer object.

>
> I also guess I'm understanding that the same goes somehow for the letter A
> for example, since it cannot be rewritten or reduced any further, so it's a
> value too.
>

The letter A in your source code might be almost anything.  If it stands 
by itself, or is surrounded just by letters and digits, then it's a 
name, or identifier, presumably defined in some namespace.

That same A in the source code could be part of a string literal, if 
it's between quote marks.  The quote marks are not part of the string, 
they're merely part of the literal representation.  The language parser 
has to have some way of deciding whether you meant it as a name, or as a 
string.  The quotes define that.

> type('A')
> <type 'str'>
>
> The question is, in order to understand: does this apostrophes thing has a
> more profound reason to be attached to the letters or it's just a
> conventional way to set a difference between letters and numbers?

Letters and numbers can both be used inside a string literal.  What 
makes it a string literal is the presence of quote marks.

> Do I must
> observe this apostrophes thing like the symbol of the type itself inside
> which one can put any character, setting it as type str?
>

No clue what that's supposed to mean.

When the compiler processes your source file, it tokenizes it into some 
byte code.  When that byte code executes, objects are created, 
identifiers are bound and unbound to those objects, expressions are 
evaluated, functions are called, and possibly external devices are 
spoken to.

A string object has no quote marks around it (unless you go out of your 
way to add them to the string explicitly), and an int object has no 
definite format that is defined in the language.  They both have values, 
and sometimes its convenient to describe those values in the terms of 
source code.   But an int object for example is unlikely to be in base ten.

-- 
DaveA

From cybervigilante at gmail.com  Fri May 24 04:39:33 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Thu, 23 May 2013 19:39:33 -0700
Subject: [Tutor] making a random list, then naming it
Message-ID: <CALRAYNVxxmHYbWHPBgsPcwwHNNL0Wpw72N73Zzwx3P8Bd4p1qw@mail.gmail.com>

I keep needing random lists of integers for trying things, so I wrote
a small prog I'll import as randlist. The user enters the length and
max val, but then I want the actual data name of the random list
created, to be   list_(length entered)_(max value entered)  as an easy
mnemonic.

I got as far as making the list, but my brain is fozzled on changing
the numbers entered into part of a data name. Feels like I have to go
outside the program to do it:

import random
random.seed

listparameters = raw_input('\nEnter two numbers, space separated, for
the length and largest value of a zero-starting random list, which can
be used as variable name:  randlist.list_len_max , where len is the
list length you entered, and max is the largest value\n')

listargs = listparameters.split()
rlist = []
length = int(listargs[0])
maxval = int(listargs[1])
for r in range(0,length):
    rlist.append(random.randint(0,maxval))

listlenmax = 'list' + '_' + str(length) + '_' + str(maxval)   # just
the name of a string, not the data name I want

#just printing the below as a test - they'll be removed when the import works

print
print rlist
print
print listlenmax

-- 
Jim Mooney

From steve at pearwood.info  Fri May 24 06:45:39 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 24 May 2013 14:45:39 +1000
Subject: [Tutor] Difference between types
In-Reply-To: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
Message-ID: <519EF073.2070207@pearwood.info>

On 24/05/13 05:57, Citizen Kant wrote:
> I guess I'm understanding that, in Python, if something belongs to a type,
> must also be a value.

Everything in Python is a value, and everything belongs to a type. Including other types. Yes, types are values too, and types have types of their own. There is no infinite regress, because ultimately everything ends at the "magic" type called "type", which is its own type:


py> type(42)  # 42 is an instance of int
<class 'int'>
py> type(int)  # int is an instance of type
<class 'type'>
py> type(type)  # type is an instance of itself!
<class 'type'>


> I guess I'm understanding that the reason why 9 is considered a value, is
> since it's a normal form*,* an element of the system that cannot be
> rewritten and reduced any further.

Are you referring to this definition?

http://en.wikipedia.org/wiki/Value_%28computer_science%29

As far as it goes, that's not an unreasonable rule of thumb, but it isn't bullet-proof. What, for example, do you make of this:

0x09

Is that a value? I say yes, because that is a literal expression for the natural number 9. It merely happens to use hexadecimal notation instead of decimal notation. Another language might define keywords one, two, three ... nine, ten which are also literal expressions for the same natural number, only using English words instead of numerals.

But let's not worry about hypothetical languages with such keywords. Even in Python, each of these represent the exact same value:

9 0x09 0o10 0b1001

They are the same value, using different notation.


> I also guess I'm understanding that the same goes somehow for the letter A
> for example, since it cannot be rewritten or reduced any further, so it's a
> value too.

Likewise for every object. Compound objects are also values:

iter([12, 3, None, "hello world!", 4.5, ('a', 'b', 3), {}])


but the fact that it is a value is not really captured by the definition given above. The definition is true so far as it goes, but it doesn't go far enough.


> type('A')
> <type 'str'>
>
> The question is, in order to understand: does this apostrophes thing has a
> more profound reason to be attached to the letters or it's just a
> conventional way to set a difference between letters and numbers?

The later. It is a long standing tradition in computer programming that so-called "strings" (ordered sequences of letters, digits and other characters) are defined using a notation that includes quotation marks as delimiters. In contrast, numbers are written in straight numeric form, usually in base-10 but sometimes in other bases.

This is not a hard rule, but it is a strong tradition, and any language which did differently would be considered strange. Some languages give '' and "" different meanings, but Python does not.


>  Do I must
> observe this apostrophes thing like the symbol of the type itself inside
> which one can put any character, setting it as type str?

I'm afraid that I don't understand the question.


-- 
Steven

From davea at davea.name  Fri May 24 07:24:11 2013
From: davea at davea.name (Dave Angel)
Date: Fri, 24 May 2013 01:24:11 -0400
Subject: [Tutor] making a random list, then naming it
In-Reply-To: <CALRAYNVxxmHYbWHPBgsPcwwHNNL0Wpw72N73Zzwx3P8Bd4p1qw@mail.gmail.com>
References: <CALRAYNVxxmHYbWHPBgsPcwwHNNL0Wpw72N73Zzwx3P8Bd4p1qw@mail.gmail.com>
Message-ID: <519EF97B.3060109@davea.name>

On 05/23/2013 10:39 PM, Jim Mooney wrote:
> I keep needing random lists of integers for trying things, so I wrote
> a small prog I'll import as randlist. The user enters the length and
> max val, but then I want the actual data name of the random list
> created, to be   list_(length entered)_(max value entered)  as an easy
> mnemonic.

<snip>

 > print
 > print rlist
 > print
 > print listlenmax
 >

By "name of the list" do you mean like the names rlist and listlenmax 
above?  In other words, you want to define an identifier at run time, 
and bind it to the list object that you have calculated.

And just how would you know you succeeded, unless you already had code 
that happened to use that same identifier?

The short answer is that Python is not designed to be able to do such a 
thing.  You're advised instead to make a dictionary, where the key is 
the name you generate

lists = {}


for .....
     key = 'list' + '_' + str(length) + '_' + str(maxval)
     lists[key] = buildlist(length, maxval)
-- 
DaveA

From rafael.knuth at gmail.com  Fri May 24 13:01:55 2013
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Fri, 24 May 2013 13:01:55 +0200
Subject: [Tutor] Issue w/ program: Flip a coin and count heads and tails
Message-ID: <CAM-E2X5vA5YCLb4LQhqk8U1mTczE042YuQNvRHGELeL4nxE4KQ@mail.gmail.com>

Hello,

I am writing a program in Python 3.3.0 which flips a coin 10 x times and
then counts the number of heads and tails. It obviously does something else
than I intended, and I am wondering what I did wrong:

import random

print ("""

This program flips a coin 10 times.

It then counts the number of heads and tails.

""")

flips = 0

heads = 0

tails = 0

while flips < 10:

    flips = flips + 1

    if random.randint(1,2) == 1:

        heads = heads + 1

        print("We've got " + str(heads) + " heads here."

    if random.randint(1,2) == 2:

        tails = tails + 1

        print("We've got " + str(tails) + " tails here.")

This is what I get as output:

This program flips a coin 10 times.

It then counts the number of heads and tails.

We've got 1 tails here.

We've got 1 heads here.

We've got 2 tails here.

We've got 2 heads here.

We've got 3 tails here.

We've got 3 heads here.

We've got 4 tails here.

We've got 5 tails here.

We've got 4 heads here.

We've got 6 tails here.

We've got 7 tails here.

We've got 5 heads here.

Can anyone help?

Thank you so much!

All the best,



Rafael
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130524/d4dd3b60/attachment.html>

From citizenkant at gmail.com  Fri May 24 13:04:45 2013
From: citizenkant at gmail.com (Citizen Kant)
Date: Fri, 24 May 2013 13:04:45 +0200
Subject: [Tutor] Fwd:  Difference between types
In-Reply-To: <519EF073.2070207@pearwood.info>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
Message-ID: <CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>

Are you referring to this definition?

http://en.wikipedia.org/wiki/**Value_%28computer_science%29<http://en.wikipedia.org/wiki/Value_%28computer_science%29>

As far as it goes, that's not an unreasonable rule of thumb, but it isn't
bullet-proof. What, for example, do you make of this:

0x09

Is that a value? I say yes, because that is a literal expression for the
natural number 9. It merely happens to use hexadecimal notation instead of
decimal notation. Another language might define keywords one, two, three
... nine, ten which are also literal expressions for the same natural
number, only using English words instead of numerals.

But let's not worry about hypothetical languages with such keywords. Even
in Python, each of these represent the exact same value:

9 0x09 0o10 0b1001

They are the same value, using different notation.

I'm referring to that definition. I've found out that, unless for me, it's
useful to think Python in this line. That leads me to think, first, that
every single character is in itself a value, any single thing that one can
find inside a Python script is somehow value, all are characters. So, since
Python only (is this correct?) works with values, then came the question
about how to create different kinds of value, so to speak more complex,
that respond to value's definition. The answer I've managed to give to
myself is that this could be accomplished by: setting a rule that makes
whatever to "have the shape" of a value. That's to say, for example:
'apostrophes' act as the shape of a value named string, no matter what one
puts inside it. So 'apostrophes' are just a label that Python considers the
shape of a value. Same happens with the tuple (100, 'value', 2);  where
parenthesis and semi colon work as a rule, setting the shape of a value
named tuple that's different to the shape of a value named list. At the
same time both shapes are equal (since both are value).

As far as I can think, the same must happen with all the other types of
value in Python.

Then, something like my_variable doesn't respond to value's definition
(even if no one can say that doesn't "look like" a normal form) until a
value it's assigned to it. Then
if my_variable = 9
<type 'int'>
if my_variable = 'A'
the <type 'str'>

I'm not very strong in maths, so I can't tell what's going on with 0x09.
Could it be that simple as that anything between integers is int, and
that's why one cannot start a variable name with a number since a
variable's name starting with a number could be perfectly confused with
some integer?

The point is, given this Python environment, would it be correct to look
for some truth, asking to myself "in which way every single thing in Python
comes to be a value (following value's wikipedia definition)?

Anyway, this line of thinking doesn't lead me to understand where's the
label for a value (acting as operator) like + or - or * for example. I
simply tend to think that maybe the difference is so to speak built-in in
Python.


Likewise for every object. Compound objects are also values:

iter([12, 3, None, "hello world!", 4.5, ('a', 'b', 3), {}])

It looks that your example match with the idea I've presented above. Am I
right? The fact that you wrote {} , looks like the pair of { } itself is
the value that one can always fill with some other proper value if it's
necessary.

 type('A')
> <type 'str'>
>
> The question is, in order to understand: does this apostrophes thing has a
> more profound reason to be attached to the letters or it's just a
> conventional way to set a difference between letters and numbers?
>

The later. It is a long standing tradition in computer programming that
so-called "strings" (ordered sequences of letters, digits and other
characters) are defined using a notation that includes quotation marks as
delimiters. In contrast, numbers are written in straight numeric form,
usually in base-10 but sometimes in other bases.

I guess that "delimiter" sound perfect to name what I use to see as the
shape or skin of values: 'delimiters' [delimiters] {delimiters}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130524/8c4e211f/attachment.html>

From bodsda at googlemail.com  Fri May 24 13:07:00 2013
From: bodsda at googlemail.com (Bod Soutar)
Date: Fri, 24 May 2013 12:07:00 +0100
Subject: [Tutor] Issue w/ program: Flip a coin and count heads and tails
In-Reply-To: <CAM-E2X5vA5YCLb4LQhqk8U1mTczE042YuQNvRHGELeL4nxE4KQ@mail.gmail.com>
References: <CAM-E2X5vA5YCLb4LQhqk8U1mTczE042YuQNvRHGELeL4nxE4KQ@mail.gmail.com>
Message-ID: <CAG6BxkcC3AiTaT-miDZfwyCdosCaHxng7PqqEpqkwn=qpjHBLg@mail.gmail.com>

On 24 May 2013 12:01, Rafael Knuth <rafael.knuth at gmail.com> wrote:
> Hello,
>
> I am writing a program in Python 3.3.0 which flips a coin 10 x times and
> then counts the number of heads and tails. It obviously does something else
> than I intended, and I am wondering what I did wrong:
>
> import random
>
> print ("""
>
> This program flips a coin 10 times.
>
> It then counts the number of heads and tails.
>
> """)
>
> flips = 0
>
> heads = 0
>
> tails = 0
>
> while flips < 10:
>
>     flips = flips + 1
>
>     if random.randint(1,2) == 1:
>
>         heads = heads + 1
>
>         print("We've got " + str(heads) + " heads here."
>
>     if random.randint(1,2) == 2:
>
>         tails = tails + 1
>
>         print("We've got " + str(tails) + " tails here.")
>
> This is what I get as output:
>
> This program flips a coin 10 times.
>
> It then counts the number of heads and tails.
>
> We've got 1 tails here.
>
> We've got 1 heads here.
>
> We've got 2 tails here.
>
> We've got 2 heads here.
>
> We've got 3 tails here.
>
> We've got 3 heads here.
>
> We've got 4 tails here.
>
> We've got 5 tails here.
>
> We've got 4 heads here.
>
> We've got 6 tails here.
>
> We've got 7 tails here.
>
> We've got 5 heads here.
>
> Can anyone help?
>
> Thank you so much!
>
> All the best,
>
>
>
> Rafael
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Hint: Look at your second if statement

Bodsda

From pasokan at talentsprint.com  Fri May 24 13:08:59 2013
From: pasokan at talentsprint.com (Asokan Pichai)
Date: Fri, 24 May 2013 16:38:59 +0530
Subject: [Tutor] Issue w/ program: Flip a coin and count heads and tails
In-Reply-To: <CAM-E2X5vA5YCLb4LQhqk8U1mTczE042YuQNvRHGELeL4nxE4KQ@mail.gmail.com>
References: <CAM-E2X5vA5YCLb4LQhqk8U1mTczE042YuQNvRHGELeL4nxE4KQ@mail.gmail.com>
Message-ID: <CAJAvg=EAk9DC-s=+LtQ1hKdE2v1fy+mUwW-UpvWpGRnJXCSjZg@mail.gmail.com>

On Fri, May 24, 2013 at 4:31 PM, Rafael Knuth <rafael.knuth at gmail.com>wrote:

> Hello,
>
> I am writing a program in Python 3.3.0 which flips a coin 10 x times and
> then counts the number of heads and tails. It obviously does something else
> than I intended, and I am wondering what I did wrong:
>

What is that you intended?
Please explain that.

>
> import random
>
> print ("""
>
> This program flips a coin 10 times.
>
Actually this is wrong. The program does something else.


>
> It then counts the number of heads and tails.
>
> """)
>
> flips = 0
>
> heads = 0
>
> tails = 0
>
> while flips < 10:
>
>     flips = flips + 1
>
>     if random.randint(1,2) == 1:
>
>         heads = heads + 1
>
>         print("We've got " + str(heads) + " heads here."
>
>     if random.randint(1,2) == 2:
>
>         tails = tails + 1
>
>         print("We've got " + str(tails) + " tails here.")
>

> This is what I get as output:
>
> This program flips a coin 10 times.
>
> It then counts the number of heads and tails.
>
> We've got 1 tails here.
>
> We've got 1 heads here.
>
> We've got 2 tails here.
>
> We've got 2 heads here.
>
> We've got 3 tails here.
>
> We've got 3 heads here.
>
> We've got 4 tails here.
>
> We've got 5 tails here.
>
> We've got 4 heads here.
>
> We've got 6 tails here.
>
> We've got 7 tails here.
>
> We've got 5 heads here.
>
Is this an actual output??? Did the program stop here at 5 heads and 7
tails?


>
> Can anyone help?
>
> Thank you so much!
>
> All the best,
>
> Rafael
>

Asokan Pichai

"Expecting the world to treat you fairly because you are a good person is a
little like expecting the bull to not attack you because you are a
vegetarian"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130524/cb997444/attachment-0001.html>

From rafael.knuth at gmail.com  Fri May 24 13:24:37 2013
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Fri, 24 May 2013 13:24:37 +0200
Subject: [Tutor] Issue w/ program: Flip a coin and count heads and tails
In-Reply-To: <CAJAvg=EAk9DC-s=+LtQ1hKdE2v1fy+mUwW-UpvWpGRnJXCSjZg@mail.gmail.com>
References: <CAM-E2X5vA5YCLb4LQhqk8U1mTczE042YuQNvRHGELeL4nxE4KQ@mail.gmail.com>
	<CAJAvg=EAk9DC-s=+LtQ1hKdE2v1fy+mUwW-UpvWpGRnJXCSjZg@mail.gmail.com>
Message-ID: <CAM-E2X5WOtjK0cGbMY=yvciKiFBbzRffRGSm+QkCCPcpQfr1qg@mail.gmail.com>

>
> I am writing a program in Python 3.3.0 which flips a coin 10 x times and
> then counts the number of heads and tails. It obviously does something else
> than I intended, and I am wondering what I did wrong:
>

What is that you intended?
Please explain that.

I want that program to flip a coin 10 x times and then count the number of
heads and tails.
That's very much it.


On Fri, May 24, 2013 at 1:08 PM, Asokan Pichai <pasokan at talentsprint.com>wrote:

>
>
> On Fri, May 24, 2013 at 4:31 PM, Rafael Knuth <rafael.knuth at gmail.com>wrote:
>
>> Hello,
>>
>> I am writing a program in Python 3.3.0 which flips a coin 10 x times and
>> then counts the number of heads and tails. It obviously does something else
>> than I intended, and I am wondering what I did wrong:
>>
>
> What is that you intended?
> Please explain that.
>
>>
>> import random
>>
>> print ("""
>>
>> This program flips a coin 10 times.
>>
> Actually this is wrong. The program does something else.
>
>
>>
>> It then counts the number of heads and tails.
>>
>> """)
>>
>> flips = 0
>>
>> heads = 0
>>
>> tails = 0
>>
>> while flips < 10:
>>
>>     flips = flips + 1
>>
>>     if random.randint(1,2) == 1:
>>
>>         heads = heads + 1
>>
>>         print("We've got " + str(heads) + " heads here."
>>
>>     if random.randint(1,2) == 2:
>>
>>         tails = tails + 1
>>
>>         print("We've got " + str(tails) + " tails here.")
>>
>
>> This is what I get as output:
>>
>> This program flips a coin 10 times.
>>
>> It then counts the number of heads and tails.
>>
>> We've got 1 tails here.
>>
>> We've got 1 heads here.
>>
>> We've got 2 tails here.
>>
>> We've got 2 heads here.
>>
>> We've got 3 tails here.
>>
>> We've got 3 heads here.
>>
>> We've got 4 tails here.
>>
>> We've got 5 tails here.
>>
>> We've got 4 heads here.
>>
>> We've got 6 tails here.
>>
>> We've got 7 tails here.
>>
>> We've got 5 heads here.
>>
> Is this an actual output??? Did the program stop here at 5 heads and 7
> tails?
>
>
>>
>> Can anyone help?
>>
>> Thank you so much!
>>
>> All the best,
>>
>> Rafael
>>
>
> Asokan Pichai
>
> "Expecting the world to treat you fairly because you are a good person is
> a little like expecting the bull to not attack you because you are a
> vegetarian"
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130524/91c73a3d/attachment.html>

From omar.aboumrad at gmail.com  Fri May 24 13:27:32 2013
From: omar.aboumrad at gmail.com (Omar Abou Mrad)
Date: Fri, 24 May 2013 14:27:32 +0300
Subject: [Tutor] Issue w/ program: Flip a coin and count heads and tails
In-Reply-To: <CAJAvg=EAk9DC-s=+LtQ1hKdE2v1fy+mUwW-UpvWpGRnJXCSjZg@mail.gmail.com>
References: <CAM-E2X5vA5YCLb4LQhqk8U1mTczE042YuQNvRHGELeL4nxE4KQ@mail.gmail.com>
	<CAJAvg=EAk9DC-s=+LtQ1hKdE2v1fy+mUwW-UpvWpGRnJXCSjZg@mail.gmail.com>
Message-ID: <CAFwtXp3-mkVSW_=Ju07F6xTcnQB1_KMku9S+4emHb8jfHWmQbQ@mail.gmail.com>

On Fri, May 24, 2013 at 2:08 PM, Asokan Pichai <pasokan at talentsprint.com>wrote:

>
> <snip>
> Is this an actual output??? Did the program stop here at 5 heads and 7
> tails?
> <snip>
> Asokan Pichai
>
>
Adding fuel to fire.

He actually got 12 Tails and 8 Heads!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130524/b21e22f7/attachment.html>

From wolfgang.maier at biologie.uni-freiburg.de  Fri May 24 13:52:05 2013
From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier)
Date: Fri, 24 May 2013 11:52:05 +0000 (UTC)
Subject: [Tutor] Issue w/ program: Flip a coin and count heads and tails
References: <CAM-E2X5vA5YCLb4LQhqk8U1mTczE042YuQNvRHGELeL4nxE4KQ@mail.gmail.com>
Message-ID: <loom.20130524T133815-501@post.gmane.org>

On 24 May 2013 12:01, Rafael Knuth <rafael.knuth <at> gmail.com> wrote:
> Hello,
>
> I am writing a program in Python 3.3.0 which flips a coin 10 x times and
> then counts the number of heads and tails. It obviously does something else
> than I intended, and I am wondering what I did wrong:
>
> import random
>
> print ("""
>
> This program flips a coin 10 times.
>
> It then counts the number of heads and tails.
>
> """)
>
> flips = 0
>
> heads = 0
>
> tails = 0
>
> while flips < 10:
>
>     flips = flips + 1
>
>     if random.randint(1,2) == 1:
>
>         heads = heads + 1
>
>         print("We've got " + str(heads) + " heads here."
>
>     if random.randint(1,2) == 2:
>
>         tails = tails + 1
>
>         print("We've got " + str(tails) + " tails here.")
>
> This is what I get as output:
>
> This program flips a coin 10 times.
>
> It then counts the number of heads and tails.
>
> We've got 1 tails here.
>
> We've got 1 heads here.
>
> We've got 2 tails here.
>
> We've got 2 heads here.
>
> We've got 3 tails here.
>
> We've got 3 heads here.
>
> We've got 4 tails here.
>
> We've got 5 tails here.
>
> We've got 4 heads here.
>
> We've got 6 tails here.
>
> We've got 7 tails here.
>
> We've got 5 heads here.
>

You're printing from within your while loop, so *everytime* through it, your
program prints either the heads or the tails message.
In addition, your throwing the coin twice during each run of the loop:
if random.randint(1,2) == 1   # that's one
if random.randint(1,2) == 2   # that's another one

flip the coin once instead and store the outcome in a variable, like:
result = random.randint(1,2)

if result == 1:
   # do head stuff here
else:
   # do tail stuff here

That should fix the unexpected behavior. However, if all you want to do is,
as you say, count the total numbers of head and tail results, this is an
incredibly complicated way to do it.
This short form suffices:

import random

flips = 10
s = sum(random.randint(0,1) for flip in range(flips))

print ("We've got " + str(flips-s) + " heads and " + str(s) + " tails here.")

Read about range, comprehensions and generator expressions if you have
trouble understanding the third line.
Best,
Wolfgang




From davea at davea.name  Fri May 24 14:24:22 2013
From: davea at davea.name (Dave Angel)
Date: Fri, 24 May 2013 08:24:22 -0400
Subject: [Tutor] Fwd:  Difference between types
In-Reply-To: <CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
Message-ID: <519F5BF6.9060408@davea.name>

On 05/24/2013 07:04 AM, Citizen Kant wrote:
> Are you referring to this definition?
>
> http://en.wikipedia.org/wiki/**Value_%28computer_science%29<http://en.wikipedia.org/wiki/Value_%28computer_science%29>
>

Any chance you can fix your use of gmail to conform to the usual 
standards?  It does it right by default.  We have lots of gmail users on 
here, but you're almost the only one who doesn't have the quote marks on 
the stuff you're quoting from earlier messages, nor the attribution.  So 
by breaking those conventions, you imply that you wrote the above text, 
when really you're
quoting Steven anonymoously.  Worse, then when you start your own text, 
there's no distinguishing them, unless a reader happens to have read the 
other message recently enough to remember.

      <SNIP>
>
>
> I'm referring to that definition. I've found out that, unless for me, it's
> useful to think Python in this line.

But that page is mostly wrong or misleading for Python.  And it assumes 
you already know what an expression is, so it's the wrong definition for 
you as well.

That page refers to another page:
    http://en.wikipedia.org/wiki/Expression_(computer_science)

to try to define expression.  But since that one says that an expression 
is a combination of many things, including value, it still doesn't help 
you much, because it's circular.

You concluded for example that A is a value, which of course it's not, 
in source code.  It might be a variable (or the Python approximation to 
variable), but only if it's a token within the source code.

Tell me, when you learned to drive, did you start by defining what a 
thread was?  After all, an engine would fall apart without threaded 
bolts, and without an engine there's no point in driving.


-- 
DaveA

From pasokan at talentsprint.com  Fri May 24 14:55:51 2013
From: pasokan at talentsprint.com (Asokan Pichai)
Date: Fri, 24 May 2013 18:25:51 +0530
Subject: [Tutor] Issue w/ program: Flip a coin and count heads and tails
In-Reply-To: <CAM-E2X5WOtjK0cGbMY=yvciKiFBbzRffRGSm+QkCCPcpQfr1qg@mail.gmail.com>
References: <CAM-E2X5vA5YCLb4LQhqk8U1mTczE042YuQNvRHGELeL4nxE4KQ@mail.gmail.com>
	<CAJAvg=EAk9DC-s=+LtQ1hKdE2v1fy+mUwW-UpvWpGRnJXCSjZg@mail.gmail.com>
	<CAM-E2X5WOtjK0cGbMY=yvciKiFBbzRffRGSm+QkCCPcpQfr1qg@mail.gmail.com>
Message-ID: <CAJAvg=G-+otnZvF61jdB6ug1pmrAQcqxEN3dHqf7DtPig3k90g@mail.gmail.com>

On Fri, May 24, 2013 at 4:54 PM, Rafael Knuth <rafael.knuth at gmail.com>wrote:

>  I am writing a program in Python 3.3.0 which flips a coin 10 x times and
>> then counts the number of heads and tails. It obviously does something else
>> than I intended, and I am wondering what I did wrong:
>>
>
> What is that you intended?
> Please explain that.
>
> I want that program to flip a coin 10 x times and then count the number of
> heads and tails.
> That's very much it.
>

Then you have set up the while loop right. It loops 10 times.
But if it is a head you are counting heads. Now if it is a tail
you are discarding and tossing again!

That is the effect of
while flips < 10:
    flips = flips + 1
    if random.randint(1,2) == 1:
#### - if it is not head?
        heads = heads + 1
        print("We've got " + str(heads) + " heads here."
    if random.randint(1,2) == 2:
#### - this is the second toss I am talking about
        tails = tails + 1

Now if you replace the second toss by an "else" and count it as a tail
you should go towards the code you are looking for. Try it and tell us
how it goes. All the best

Asokan Pichai
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130524/7491078c/attachment-0001.html>

From steve at pearwood.info  Fri May 24 15:17:01 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 24 May 2013 23:17:01 +1000
Subject: [Tutor] Fwd:  Difference between types
In-Reply-To: <CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
Message-ID: <519F684D.9080106@pearwood.info>

Citizen Kant,

will you please fix your email quoting? As it is, you are plagiarizing me, by quoting me word for word without attribution or any hint that you are quoting me.

Do you notice that everyone else quotes people by name, and prefixes their words with > quote marks? This is the normal standard on email. If you are using something that breaks that standard (possibly Gmail?) and cannot set it to follow the normal rules for quoting, then you are going to frustrate and annoy people, possibly to the point that they banish your emails to the "kill-file" and stop answering your questions. Harsh, but a fact of life.

If you ask, I'm sure people who know more about Gmail will help you fix your settings.

Thanks,



-- 
Steven


From citizenkant at gmail.com  Fri May 24 15:31:43 2013
From: citizenkant at gmail.com (Citizen Kant)
Date: Fri, 24 May 2013 15:31:43 +0200
Subject: [Tutor] Fwd: Difference between types
In-Reply-To: <519F684D.9080106@pearwood.info>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
	<519F684D.9080106@pearwood.info>
Message-ID: <CAMbF=C99UDAQgMsLDTf5E1EfCkbsvFYtRfhK8MBrS8Wqrwvd4g@mail.gmail.com>

Sorry. I'm not doing this on purpose, but I'm doing it anyway, so I'll
check how to fix it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130524/33bf0774/attachment.html>

From eryksun at gmail.com  Fri May 24 16:51:01 2013
From: eryksun at gmail.com (eryksun)
Date: Fri, 24 May 2013 10:51:01 -0400
Subject: [Tutor] Fwd: Difference between types
In-Reply-To: <CAMbF=C99UDAQgMsLDTf5E1EfCkbsvFYtRfhK8MBrS8Wqrwvd4g@mail.gmail.com>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
	<519F684D.9080106@pearwood.info>
	<CAMbF=C99UDAQgMsLDTf5E1EfCkbsvFYtRfhK8MBrS8Wqrwvd4g@mail.gmail.com>
Message-ID: <CACL+1avbMc9Fp662Vx-hG3miqDurZxCjK88iHdGQXT=g-df9qQ@mail.gmail.com>

On Fri, May 24, 2013 at 9:31 AM, Citizen Kant <citizenkant at gmail.com> wrote:
> Sorry. I'm not doing this on purpose, but I'm doing it anyway, so I'll check
> how to fix it.

You're replying with rich text, for which Gmail has a lot of its own
custom CSS (e.g. the gmail_quote class). In Gmail I see the quoted
text as a purplish color, but it looks like you're editing out the
block quotes on parts. This prevents the normal '>' quote indicator
from being inserted in the auto-generated plain text.

Just reply-all in plain text mode and follow the conventions you see
in other people's replies.

Personally, reading and editing plain text with a proportional font
annoys me -- a lot. Here's a Greasemonkey script to use a monospace
font for plain text in Gmail:

http://userscripts.org/scripts/show/17869

Also, when you post code remember to use less than 70 characters per
line. Gmail has a 'feature' to automatically hard wrap plain-text
messages at about 70 characters, which it applies *after* you send
(i.e. there's no indicator in the composer... brilliant).

From marc.tompkins at gmail.com  Fri May 24 17:11:08 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Fri, 24 May 2013 08:11:08 -0700
Subject: [Tutor] keyboard interrupt
In-Reply-To: <519E9DB2.5000205@pearwood.info>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
	<CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
	<CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
	<CACL+1avQpoAHPVj-nMCGmJ_4QvEhSXTK3KeEJwMkPCSdQhsi6g@mail.gmail.com>
	<CALRAYNUphqUGCtSbfa3G-m=Gm8=3bALuD7Uz+nE9oH8O3L9BhQ@mail.gmail.com>
	<CACL+1avETMJq1R5qdcwbN_+mbPpc5Q4zNuonBtM5BKDF2w2tFg@mail.gmail.com>
	<CALRAYNVQt7a+QUzHhBQRcf=H5KPmG866bAE8LnshF791BMroPA@mail.gmail.com>
	<519E9DB2.5000205@pearwood.info>
Message-ID: <CAKK8jXYVqC68O3yyxd3DpjiGn0iyb_PquVgV8=hj3Vt6OthKxw@mail.gmail.com>

On Thu, May 23, 2013 at 3:52 PM, Steven D'Aprano <steve at pearwood.info>wrote:

> On 24/05/13 06:37, Jim Mooney wrote:
>
>> Apparently Wing isn't as savvy as IDLE when it comes to communicating
>>> with the subprocess. I've only searched for about a minute, but
>>> apparently the way this works in Wing is to "Restart Shell":
>>>
>>> http://stackoverflow.com/a/**10360503/205580<http://stackoverflow.com/a/10360503/205580>
>>> http://www.wingware.com/doc/**debug/interactive-python-shell<http://www.wingware.com/doc/debug/interactive-python-shell>
>>>
>>> This kills the suprocess and starts a new interpreter. Crude, but it
>>> should get the job done.
>>>
>>
>> Thanks. I'll put stackoverflow on my bookmarks.
>>
>
> Beware though, while there are often some very good answers on
> Stackoverflow, there are also very many people who are nowhere near as
> knowledgeable as they think, giving terrible answers, and still having
> large scores. (One particular person comes to mind, I forget his name but
> he has a *very* high score which means lots of people are voting for his
> answers, and yet every time without exception I've seen him reply to
> someone he has been rude, missed the entire point of their question, or
> given them bad advice. Or all three at once.)
>

I love, love, love StackOverflow (and the whole StackExchange ecosystem),
but it's unfortunately susceptible to being gamed.  Anyone can edit a
question (or an answer), and if the edit is allowed to stand the editor
gets 2 points.  There are millions of questions, so this process can be
repeated ad nauseam.  I used to spend a lot of time on
english.stackexchange.com, and one of the reasons I got fed up with it is
exactly that: unhelpful, opinionated users whose scores were inflated to
make them seem authoritative.  One of them edited several of my answers,
making no change except to turn dashes into Unicode em dashes - and his
score was four times higher than mine, despite hardly having any answers
accepted (due to being a rude, ignorant loudmouth).  I have no problem at
all with true experts having higher scores than mine (especially if they
answer more questions than I, and do it beautifully) but I came to resent
being ranked behind jerks.

The system still _mostly_ works, though, and it sure beats the hell out of
ExpertSexChange or whatever they're calling it these days...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130524/f4cc6d5b/attachment.html>

From citizenkant at gmail.com  Fri May 24 18:52:59 2013
From: citizenkant at gmail.com (Citizen Kant)
Date: Fri, 24 May 2013 18:52:59 +0200
Subject: [Tutor] Fwd: Difference between types
In-Reply-To: <519F684D.9080106@pearwood.info>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
	<519F684D.9080106@pearwood.info>
Message-ID: <CAMbF=C_-zCSG=FJaOWdx9rd0VSDsA94QwiS0w_5skVcxQ-L0Fg@mail.gmail.com>

When I say "coding", anyone can think about what coding is
in his own daily work, but that's not my way.
I'll try to refine the concept: right now I'm learning,
if I say "coding" I refer to what I type inside
my file named learningpythoncode.py that,
believe it or not, starts with:

# """After the hash can go my comment.
That's the first thing I've learned, and it's useful since
this way I don't feel like as don't knowing any language
at all. This is part of the code that Python doesn't
compute, but this isn't less code.

Since I am using the triple quotation, I can continue:
On the left side of the hash will go some code, not like
this one, but one that Python can in fact compute.
It seems useful to know first what am I trying to accomplish,
so first I must find out what does Python is expecting from me.
I understand that Python works with values,
so on the left side of the hash, whatever one codes, must be VALUE.

Writing code that Python can compute depends entire on:
VALUE having a somehow useful definition.
This definition will help me to look at my own code, recognize
the value in it (correctness), and let me know that I'm doing well.
I can always rely on Python spiting an error message but I
prefer the understanding way.

I think I've found a definition for value and it seems to say
that is a *normal form* or element of the system which cannot be
reduced by rewriting any further."""

9 # """ Is my first attempt on the left side of the hash. 9 is a value
since it cannot be reduced by rewriting any further.
Same goes for the other integers 0 1 2 3 4 5 6 7 8.
They are values since they cannot be reduced by rewriting any further.
Then I consider to code another value, like A, that looks like if
cannot be reduced by rewriting any further but I arrived
to the fact that Python doesn't consider those characters like A
as able to take part in its computations until I put them between
apostrophes or quotation marks."""

'A' # """ I put A between apostrophes and it suddenly turned to something
that cannot be reduced by rewriting any further,
or unless that seems to me.
I thought: if one can turn to value anything by putting it between
apostrophes or quotation marks, then the trick must be in the
pair of apostrophes or quotation marks.

That's how I came to the conclusion that the pair of apostrophes
are, in fact, the value, and that Python treats that kind of delimiter
"" as a value, no matter what one puts inside it.

Seems like if 0 1 2 3 4 5 6 7 8 9 were values which cannot be
reduced by rewriting any further.

And that "" was another type of value since cannot be
reduced by rewriting any further

This [] is value since cannot be reduced by rewriting any further.

This {} is value since cannot be reduced by rewriting any further.

This """"""  is another value is value since cannot be reduced
by rewriting any further.

Then seem that those customized and customizable
delimited values were like a bunch of new numbers with
a void that one can fill if necessary.

Then seems that there are some other cases of value
that doesn't match with those above.

Cases like my_variable (not int, nor str) maybe values
only if they are assigned to one of the above values,
or assigned to a name that was previously assigned
to one of the above values.

Then True and False as bool, are somehow names that are
assigned to a value like the ones above.

Then any other Python keyword, (def for example) comes to be a
built-in value since it's (so to speak) built-in
assigned to one of the above values, or assigned to a name
that was previously assigned to one of the above values.

This way, everything one can code in Python remains
value and Python doesn't spit its error messages.

Then remains the fact that I have + - * / and other values that "act" as
operators.
According to Python they don't have a defined type, since if I type

type(+)

leads to an error."""

Is it possible to draw a line like this (that goes all along Python)
and grasp at least "one complete aspect" of the language?



2013/5/24 Steven D'Aprano <steve at pearwood.info>

> Citizen Kant,
>
> will you please fix your email quoting? As it is, you are plagiarizing me,
> by quoting me word for word without attribution or any hint that you are
> quoting me.
>
> Do you notice that everyone else quotes people by name, and prefixes their
> words with > quote marks? This is the normal standard on email. If you are
> using something that breaks that standard (possibly Gmail?) and cannot set
> it to follow the normal rules for quoting, then you are going to frustrate
> and annoy people, possibly to the point that they banish your emails to the
> "kill-file" and stop answering your questions. Harsh, but a fact of life.
>
> If you ask, I'm sure people who know more about Gmail will help you fix
> your settings.
>
> Thanks,
>
>
>
>
> --
> Steven
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130524/d451a663/attachment-0001.html>

From eryksun at gmail.com  Fri May 24 19:13:51 2013
From: eryksun at gmail.com (eryksun)
Date: Fri, 24 May 2013 13:13:51 -0400
Subject: [Tutor] Fwd: Difference between types
In-Reply-To: <CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
Message-ID: <CACL+1auT4ZKdY+zZRu_Mbv2yQ33u2tsvmw9eEe-+8NKZYQuPdQ@mail.gmail.com>

On Fri, May 24, 2013 at 7:04 AM, Citizen Kant <citizenkant at gmail.com> wrote:
> Same happens with the tuple (100, 'value', 2);  where parenthesis and semi
> colon work as a rule, setting the shape of a value named tuple that's
> different to the shape of a value named list. At the same time both shapes
> are equal (since both are value).

A semicolon is an optional way to delimit statements in Python. It's
rarely used since stacking multiple statements on a single line gets
ugly fast.

A tuple is defined by commas, depending on context. However,
parentheses are typically required because commas have low precedence.

    >>> 1, 2 + 3, 4
    (1, 5, 4)

    >>> (1, 2) + (3, 4)
    (1, 2, 3, 4)

An empty tuple is a special case:

    >>> x = ()
    >>> type(x)
    <type 'tuple'>

From eryksun at gmail.com  Fri May 24 19:39:21 2013
From: eryksun at gmail.com (eryksun)
Date: Fri, 24 May 2013 13:39:21 -0400
Subject: [Tutor] Fwd: Difference between types
In-Reply-To: <CAMbF=C_-zCSG=FJaOWdx9rd0VSDsA94QwiS0w_5skVcxQ-L0Fg@mail.gmail.com>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
	<519F684D.9080106@pearwood.info>
	<CAMbF=C_-zCSG=FJaOWdx9rd0VSDsA94QwiS0w_5skVcxQ-L0Fg@mail.gmail.com>
Message-ID: <CACL+1asC+W4zyF_ip1YNADY_QGU9_2fkZLWSEzKjSOis88ipvA@mail.gmail.com>

On Fri, May 24, 2013 at 12:52 PM, Citizen Kant <citizenkant at gmail.com> wrote:
> They are values since they cannot be reduced by rewriting any further.

You seem to be talking about the "atoms" of the language: identifiers,
literals, parenthesized forms, displays, and so on. Please read
sections 2.3 (identifiers), 2.4 (literals), and 6.2 (atoms) in the
language reference:

http://docs.python.org/3/reference

It may not answer all of your questions, but it's at least a common
reference for discussion.

From citizenkant at gmail.com  Fri May 24 20:08:57 2013
From: citizenkant at gmail.com (Citizen Kant)
Date: Fri, 24 May 2013 20:08:57 +0200
Subject: [Tutor] Fwd: Difference between types
In-Reply-To: <CACL+1asC+W4zyF_ip1YNADY_QGU9_2fkZLWSEzKjSOis88ipvA@mail.gmail.com>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
	<519F684D.9080106@pearwood.info>
	<CAMbF=C_-zCSG=FJaOWdx9rd0VSDsA94QwiS0w_5skVcxQ-L0Fg@mail.gmail.com>
	<CACL+1asC+W4zyF_ip1YNADY_QGU9_2fkZLWSEzKjSOis88ipvA@mail.gmail.com>
Message-ID: <CAMbF=C-GHfMkhm0XWEry3rNDnxV3KTOW+aTw=k5gY_Y6j_0ekQ@mail.gmail.com>

It's perfect, even if I'm not able to understand everything that's
stated there. Then 2.5 is Operators, and 2.6 is Delimiters,
that also goes in the line of what I'm thinking about.

Thanks for the "you seem to be talking about", coz
I'm learning not by memory but trying to understand,
and sometimes I have the idea but don't have the knowledge
to communicate the doubt properly.

Thanks again.



2013/5/24 eryksun <eryksun at gmail.com>

> On Fri, May 24, 2013 at 12:52 PM, Citizen Kant <citizenkant at gmail.com>
> wrote:
> > They are values since they cannot be reduced by rewriting any further.
>
> You seem to be talking about the "atoms" of the language: identifiers,
> literals, parenthesized forms, displays, and so on. Please read
> sections 2.3 (identifiers), 2.4 (literals), and 6.2 (atoms) in the
> language reference:
>
> http://docs.python.org/3/reference
>
> It may not answer all of your questions, but it's at least a common
> reference for discussion.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130524/568d6185/attachment.html>

From fomcl at yahoo.com  Fri May 24 20:53:33 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Fri, 24 May 2013 11:53:33 -0700 (PDT)
Subject: [Tutor] Fwd: Difference between types
In-Reply-To: <CACL+1auT4ZKdY+zZRu_Mbv2yQ33u2tsvmw9eEe-+8NKZYQuPdQ@mail.gmail.com>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
	<CACL+1auT4ZKdY+zZRu_Mbv2yQ33u2tsvmw9eEe-+8NKZYQuPdQ@mail.gmail.com>
Message-ID: <1369421613.60441.YahooMailNeo@web163804.mail.gq1.yahoo.com>

<snip>

> A tuple is defined by commas, depending on context. However,
> parentheses are typically required because commas have low precedence.
> 
> ? ? >>> 1, 2 + 3, 4
> ? ? (1, 5, 4)
> 
> ? ? >>> (1, 2) + (3, 4)
> ? ? (1, 2, 3, 4)
> 
> An empty tuple is a special case:
> 
> ? ? >>> x = ()
> ? ? >>> type(x)
> ? ? <type 'tuple'>

Why do I need to use a trailing comma to create a singleton tuple? Without a comma it seems to mean "parenthesized single object", ie the parentheses are basically not there.
>>> type((0,))
<type 'tuple'>
>>> type((0))
<type 'int'>
>>> (0)
0
>>> x = (,)
SyntaxError: invalid syntax

>>> (0,0)
(0, 0)


From davea at davea.name  Fri May 24 21:10:59 2013
From: davea at davea.name (Dave Angel)
Date: Fri, 24 May 2013 15:10:59 -0400
Subject: [Tutor] Fwd: Difference between types
In-Reply-To: <1369421613.60441.YahooMailNeo@web163804.mail.gq1.yahoo.com>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
	<CACL+1auT4ZKdY+zZRu_Mbv2yQ33u2tsvmw9eEe-+8NKZYQuPdQ@mail.gmail.com>
	<1369421613.60441.YahooMailNeo@web163804.mail.gq1.yahoo.com>
Message-ID: <519FBB43.8040501@davea.name>

On 05/24/2013 02:53 PM, Albert-Jan Roskam wrote:
> <snip>
>
>> A tuple is defined by commas, depending on context. However,
>> parentheses are typically required because commas have low precedence.
>>
>>      >>> 1, 2 + 3, 4
>>      (1, 5, 4)
>>
>>      >>> (1, 2) + (3, 4)
>>      (1, 2, 3, 4)
>>
>> An empty tuple is a special case:
>>
>>      >>> x = ()
>>      >>> type(x)
>>      <type 'tuple'>
>
> Why do I need to use a trailing comma to create a singleton tuple? Without a comma it seems to mean "parenthesized single object", ie the parentheses are basically not there.
>>>> type((0,))
> <type 'tuple'>
>>>> type((0))
> <type 'int'>
>>>> (0)
> 0
>>>> x = (,)
> SyntaxError: invalid syntax
>
>>>> (0,0)
> (0, 0)
>

Your answer is right above your question, in the part you quoted 
(without attribution) from eryksun.

The empty tuple is specified with ().  But for any tuple with one or 
more members, it's the commas that turn it into a tuple.  The parens are 
not necessarily needed unless the statement is complex enough that we 
need them for precedence.

So   x = 3,4

makes a one-tuple out of 3 and 4.  If you want a one-tuple (which is NOT 
a singleton), you need a silly-looking comma to specify it:
      x = 5,

In other words, comma is the operator, not parentheses.  Parentheses are 
used to change precedence (as well as for function parameters and 
arguments.)

Note that one thing that confuses newcomers is the dual use of commas 
and parens for functions.  If you need a literal tuple as a function 
argument, you will need extra parens so the comma aimed at the tuple 
doesn't get confused with the comma used to separate arguments.

-- 
DaveA

From bgailer at gmail.com  Sat May 25 01:41:01 2013
From: bgailer at gmail.com (bob gailer)
Date: Fri, 24 May 2013 19:41:01 -0400
Subject: [Tutor] challenge-chapter 2
In-Reply-To: <1369198979.77301.YahooMailNeo@web122003.mail.ne1.yahoo.com>
References: <1369198979.77301.YahooMailNeo@web122003.mail.ne1.yahoo.com>
Message-ID: <519FFA8D.8010804@gmail.com>

On 5/22/2013 1:02 AM, Andrew Triplett wrote:
> ... illegal variable names ...
That is a very poor description. Something can either be used as a 
variable name or not.

abc can be used as a variable name, if can't.

I defy you to give me a variable name that is illegal! Anything you 
attempt to give in that category is not a variable name.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130524/42d1d90b/attachment-0001.html>

From cybervigilante at gmail.com  Sat May 25 02:04:32 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Fri, 24 May 2013 17:04:32 -0700
Subject: [Tutor] making a random list, then naming it
In-Reply-To: <519EF97B.3060109@davea.name>
References: <CALRAYNVxxmHYbWHPBgsPcwwHNNL0Wpw72N73Zzwx3P8Bd4p1qw@mail.gmail.com>
	<519EF97B.3060109@davea.name>
Message-ID: <CALRAYNUFQJZh10eCSBoORWAard5_3FewyHTLbHJDyXM32o1jZw@mail.gmail.com>

> The short answer is that Python is not designed to be able to do such a
> thing.  You're advised instead to make a dictionary, where the key is the
> name you generate


I was probably unclear what I wanted to do. Basically, enter a string of
number pairs of lengths and maxvals to create and print multiple lists, and
name them, so I could fool around with them and not have to remember each
one. I noodled around google and found something to do that.

I haven't done the multiple lists or listing those lists, or input
filtering yet, but I named one list, tested it as a real int list, and it
seems to work. Unless I'm confused ;')

import random
random.seed

listparameters = raw_input('\nEnter two numbers, space separated, for the
length and largest value of a zero-starting random list, which can be used
as variable name: randlist.list_len_max , where len is the list length you
entered, and max is the largest value\n')

listargs = listparameters.split()
rlist = []
length = int(listargs[0])
maxval = int(listargs[1])
for r in range(0,length):
    rlist.append(random.randint(0,maxval))

listlenmax = 'list' + '_' + str(length) + '_' + str(maxval) + ' = rlist'

exec listlenmax

#I entered 20 and 120 just as a test, but any ints will work. The program
will be   changed to list the data names and lists created, accept more
than one number pair so I have multiple lists, and I'll add some input
filters, then put it in jimports

list_20_120[0] += 10042
# test to see if it's a real int list by adding a large number to element
zero

print list_20_120
#this is hard coded but I'll make a list of names taken from input, that I
can use

#result from one run was:
[10095, 98, 110, 89, 86, 2, 51, 88, 36, 20, 85, 84, 98, 20, 11, 64, 17,
111, 22, 5]

#The first number is bigger than the 120 max so it must work.

#the docs on exec were kind of inscrutable. I think some of the docs expect
you to know what you're doing before you read them ;')  But I found some
examples and ran a bunch of monkey-see, monkey-do progs. I haven't really
gotten to dictionaries yet, but this seems to work.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130524/de5da878/attachment.html>

From davea at davea.name  Sat May 25 03:10:22 2013
From: davea at davea.name (Dave Angel)
Date: Fri, 24 May 2013 21:10:22 -0400
Subject: [Tutor] making a random list, then naming it
In-Reply-To: <CALRAYNUFQJZh10eCSBoORWAard5_3FewyHTLbHJDyXM32o1jZw@mail.gmail.com>
References: <CALRAYNVxxmHYbWHPBgsPcwwHNNL0Wpw72N73Zzwx3P8Bd4p1qw@mail.gmail.com>
	<519EF97B.3060109@davea.name>
	<CALRAYNUFQJZh10eCSBoORWAard5_3FewyHTLbHJDyXM32o1jZw@mail.gmail.com>
Message-ID: <51A00F7E.8050400@davea.name>

On 05/24/2013 08:04 PM, Jim Mooney wrote:

You forgot to give the author attribution on the following paragraph.  I 
happen to recognize my own text, but that's not a nice thing to do. 
Notice above where it says  "Jim Mooney wrote" ?

>> The short answer is that Python is not designed to be able to do such a
>> thing.  You're advised instead to make a dictionary, where the key is the
>> name you generate
>
>
> I was probably unclear what I wanted to do. Basically, enter a string of
> number pairs of lengths and maxvals to create and print multiple lists, and
> name them, so I could fool around with them and not have to remember each
> one. I noodled around google and found something to do that.

exec and eval can do all sorts of magic.  When there's a different 
answer, that other answer is nearly always preferable.  The problem is 
that once you play this trick to save yourself some keystrokes while 
debugging, you may think you understand the functionality and the risks 
it involves, and use it on code that matters.

As I said, you should make a dictionary.  You can then give names to 
each item in the dictionary, and those names may or may not actually be 
valid identifiers.

Is lists[(3,8)]  really so much harder to type than
     list_3_8  ?

-- 
DaveA

From cybervigilante at gmail.com  Sat May 25 03:35:23 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Fri, 24 May 2013 18:35:23 -0700
Subject: [Tutor] making a random list, then naming it
In-Reply-To: <51A00F7E.8050400@davea.name>
References: <CALRAYNVxxmHYbWHPBgsPcwwHNNL0Wpw72N73Zzwx3P8Bd4p1qw@mail.gmail.com>
	<519EF97B.3060109@davea.name>
	<CALRAYNUFQJZh10eCSBoORWAard5_3FewyHTLbHJDyXM32o1jZw@mail.gmail.com>
	<51A00F7E.8050400@davea.name>
Message-ID: <CALRAYNVD+FiG=czFdnNa708RcRFoKWPGQ-Obnu2pGQBBe71yHA@mail.gmail.com>

On 24 May 2013 18:10, Dave Angel <davea at davea.name> wrote:

> Is lists[(3,8)]  really so much harder to type than
>     list_3_8  ?
>

You have a point. I hate underlines - my finger always misses them.
Keyboards were not designed for programming ;')

Anyway, I just thought I'd try exec, but it's giving me fits putting it in
a function so I can do multiple lists. A dictionary looks more manageable.

Jim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130524/561c6116/attachment.html>

From davea at davea.name  Sat May 25 03:44:10 2013
From: davea at davea.name (Dave Angel)
Date: Fri, 24 May 2013 21:44:10 -0400
Subject: [Tutor] making a random list, then naming it
In-Reply-To: <CALRAYNVD+FiG=czFdnNa708RcRFoKWPGQ-Obnu2pGQBBe71yHA@mail.gmail.com>
References: <CALRAYNVxxmHYbWHPBgsPcwwHNNL0Wpw72N73Zzwx3P8Bd4p1qw@mail.gmail.com>
	<519EF97B.3060109@davea.name>
	<CALRAYNUFQJZh10eCSBoORWAard5_3FewyHTLbHJDyXM32o1jZw@mail.gmail.com>
	<51A00F7E.8050400@davea.name>
	<CALRAYNVD+FiG=czFdnNa708RcRFoKWPGQ-Obnu2pGQBBe71yHA@mail.gmail.com>
Message-ID: <51A0176A.4010905@davea.name>

On 05/24/2013 09:35 PM, Jim Mooney wrote:
> On 24 May 2013 18:10, Dave Angel <davea at davea.name> wrote:
>
>> Is lists[(3,8)]  really so much harder to type than
>>      list_3_8  ?
>>
>
> You have a point. I hate underlines - my finger always misses them.
> Keyboards were not designed for programming ;')
>
> Anyway, I just thought I'd try exec, but it's giving me fits putting it in
> a function so I can do multiple lists. A dictionary looks more manageable.
>
> Jim
>

Just to save you further frustration, CPython compiles a function in 
such a way that adding new local identifiers to the function is 
effectively impossible.  The compiler decided long before the function 
is run how many locals there are, and what they're called.

So some sneaky tricks that work at global level won't work inside a 
function.

Other Python implementations may have other gotchas.  But a dict is 
legal in all of them.

-- 
DaveA

From eryksun at gmail.com  Sat May 25 03:51:19 2013
From: eryksun at gmail.com (eryksun)
Date: Fri, 24 May 2013 21:51:19 -0400
Subject: [Tutor] making a random list, then naming it
In-Reply-To: <51A00F7E.8050400@davea.name>
References: <CALRAYNVxxmHYbWHPBgsPcwwHNNL0Wpw72N73Zzwx3P8Bd4p1qw@mail.gmail.com>
	<519EF97B.3060109@davea.name>
	<CALRAYNUFQJZh10eCSBoORWAard5_3FewyHTLbHJDyXM32o1jZw@mail.gmail.com>
	<51A00F7E.8050400@davea.name>
Message-ID: <CACL+1asW-XoDF__5eqw4NF0qfVeOEFetobEHB=+=+s9U5JOS=Q@mail.gmail.com>

On Fri, May 24, 2013 at 9:10 PM, Dave Angel <davea at davea.name> wrote:
>
> Is lists[(3,8)]  really so much harder to type than
>     list_3_8  ?

Since a comma creates a tuple, in this context you can just use
lists[3,8] to save a couple more keystrokes.

    >>> from random import Random
    >>> randint = Random(42).randint

    >>> lists = {}
    >>> lists[3,8] = [randint(0,8) for i in range(3)]
    >>> lists
    {(3, 8): [1, 0, 4]}

From steve at pearwood.info  Sat May 25 04:19:48 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 25 May 2013 12:19:48 +1000
Subject: [Tutor] keyboard interrupt
In-Reply-To: <CAKK8jXYVqC68O3yyxd3DpjiGn0iyb_PquVgV8=hj3Vt6OthKxw@mail.gmail.com>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
	<CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
	<CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
	<CACL+1avQpoAHPVj-nMCGmJ_4QvEhSXTK3KeEJwMkPCSdQhsi6g@mail.gmail.com>
	<CALRAYNUphqUGCtSbfa3G-m=Gm8=3bALuD7Uz+nE9oH8O3L9BhQ@mail.gmail.com>
	<CACL+1avETMJq1R5qdcwbN_+mbPpc5Q4zNuonBtM5BKDF2w2tFg@mail.gmail.com>
	<CALRAYNVQt7a+QUzHhBQRcf=H5KPmG866bAE8LnshF791BMroPA@mail.gmail.com>
	<519E9DB2.5000205@pearwood.info>
	<CAKK8jXYVqC68O3yyxd3DpjiGn0iyb_PquVgV8=hj3Vt6OthKxw@mail.gmail.com>
Message-ID: <51A01FC4.8050104@pearwood.info>

On 25/05/13 01:11, Marc Tompkins wrote:

> I love, love, love StackOverflow (and the whole StackExchange ecosystem),
> but it's unfortunately susceptible to being gamed.  Anyone can edit a
> question (or an answer), and if the edit is allowed to stand the editor
> gets 2 points.


You can edit *other* people's questions and answers??!??!??

What. The. Hell.



-- 
Steven

From robert.sjoblom at gmail.com  Sat May 25 04:27:34 2013
From: robert.sjoblom at gmail.com (Robert Sjoblom)
Date: Sat, 25 May 2013 04:27:34 +0200
Subject: [Tutor] keyboard interrupt
In-Reply-To: <51A01FC4.8050104@pearwood.info>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
	<CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
	<CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
	<CACL+1avQpoAHPVj-nMCGmJ_4QvEhSXTK3KeEJwMkPCSdQhsi6g@mail.gmail.com>
	<CALRAYNUphqUGCtSbfa3G-m=Gm8=3bALuD7Uz+nE9oH8O3L9BhQ@mail.gmail.com>
	<CACL+1avETMJq1R5qdcwbN_+mbPpc5Q4zNuonBtM5BKDF2w2tFg@mail.gmail.com>
	<CALRAYNVQt7a+QUzHhBQRcf=H5KPmG866bAE8LnshF791BMroPA@mail.gmail.com>
	<519E9DB2.5000205@pearwood.info>
	<CAKK8jXYVqC68O3yyxd3DpjiGn0iyb_PquVgV8=hj3Vt6OthKxw@mail.gmail.com>
	<51A01FC4.8050104@pearwood.info>
Message-ID: <CAJKU7g19X34G4ypas8yxWcQe-ZwaS=Jo_5+bSQtHRP_J+XSs8Q@mail.gmail.com>

On 25 May 2013 04:19, Steven D'Aprano <steve at pearwood.info> wrote:
> You can edit *other* people's questions and answers??!??!??
>
> What. The. Hell.

Yes; I think that the idea is that it allows people to fix spelling
errors and/or reference mistakes, or maybe add things to clarify
something that the answer glossed over to begin with. I'm not entirely
sure how it works other than that you can edit answers and it's then
moderated by someone -- maybe the person who initially wrote the
answer? Or maybe you get moderator rights when reach a certain score.
--
best regards,
Robert S.

From eryksun at gmail.com  Sat May 25 04:27:13 2013
From: eryksun at gmail.com (eryksun)
Date: Fri, 24 May 2013 22:27:13 -0400
Subject: [Tutor] keyboard interrupt
In-Reply-To: <51A01FC4.8050104@pearwood.info>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
	<CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
	<CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
	<CACL+1avQpoAHPVj-nMCGmJ_4QvEhSXTK3KeEJwMkPCSdQhsi6g@mail.gmail.com>
	<CALRAYNUphqUGCtSbfa3G-m=Gm8=3bALuD7Uz+nE9oH8O3L9BhQ@mail.gmail.com>
	<CACL+1avETMJq1R5qdcwbN_+mbPpc5Q4zNuonBtM5BKDF2w2tFg@mail.gmail.com>
	<CALRAYNVQt7a+QUzHhBQRcf=H5KPmG866bAE8LnshF791BMroPA@mail.gmail.com>
	<519E9DB2.5000205@pearwood.info>
	<CAKK8jXYVqC68O3yyxd3DpjiGn0iyb_PquVgV8=hj3Vt6OthKxw@mail.gmail.com>
	<51A01FC4.8050104@pearwood.info>
Message-ID: <CACL+1auAkmt0X+6ZOUYVt9WviRAjjpvKhgNzHcFJgcv2SVsKdQ@mail.gmail.com>

On Fri, May 24, 2013 at 10:19 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>
> You can edit *other* people's questions and answers??!??!??
>
> What. The. Hell.

This should be done sparingly for answers. But it's very common for
questions since inexperienced users almost always get the markdown
wrong.

From steve at pearwood.info  Sat May 25 04:35:37 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 25 May 2013 12:35:37 +1000
Subject: [Tutor] Parentheses and tuples [was Re: Fwd: Difference between
	types]
In-Reply-To: <1369421613.60441.YahooMailNeo@web163804.mail.gq1.yahoo.com>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
	<CACL+1auT4ZKdY+zZRu_Mbv2yQ33u2tsvmw9eEe-+8NKZYQuPdQ@mail.gmail.com>
	<1369421613.60441.YahooMailNeo@web163804.mail.gq1.yahoo.com>
Message-ID: <51A02379.4060107@pearwood.info>

On 25/05/13 04:53, Albert-Jan Roskam wrote:

> Why do I need to use a trailing comma to create a singleton tuple? Without a comma it seems to mean "parenthesized single object", ie the parentheses are basically not there.


Because round brackets are also used for grouping. You can group any expression:

z = (x+1)*y


Even an expression consisting of a single element:

z = (x+1)*(y)


That might not be a sensible thing to do, but it's not worth special-casing the parser to reject parentheses in this case. Now bring in tuples. Tuples are created by the comma operator, NOT the parentheses:

a = 23, 42, None

creates a tuple. At least one comma is necessary to distinguish an element from a tuple of one element:

a = 23  # a is the int 23
a = 23,  # a is a one-item tuple containing 23

Sometimes you use round brackets to group the tuple item, either because you need to change the precedence:

a = 23, (2, 4, 8), None

groups the three elements 2, 4, 8 into a tuple, which in turn is in a tuple:

print a
=> (23, (2, 4, 8), None)


Or we use round brackets to make a tuple just because it looks better, and matches the display of them:

a = (23, 42, None)
print a
=> (23, 42, None)

But make no mistake: it is the comma, not the brackets, that makes the tuple.

So single-item tuples are not special. They just follow the rules for multiple-item tuples, except that you only have item. That does leave the question of how to specify an empty tuple. And that is special:

a = ()

however it does match the display of empty tuples, and looks rather similar to empty lists [] and empty dicts {}.



-- 
Steven

From jeanpierreda at gmail.com  Sat May 25 04:49:12 2013
From: jeanpierreda at gmail.com (Devin Jeanpierre)
Date: Fri, 24 May 2013 22:49:12 -0400
Subject: [Tutor] Parentheses and tuples [was Re: Fwd: Difference between
	types]
In-Reply-To: <51A02379.4060107@pearwood.info>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
	<CACL+1auT4ZKdY+zZRu_Mbv2yQ33u2tsvmw9eEe-+8NKZYQuPdQ@mail.gmail.com>
	<1369421613.60441.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<51A02379.4060107@pearwood.info>
Message-ID: <CABicbJ+kfY2BJGZvSuxr1YLFLj7s6uP8LAeVDPLHKEbaQzaEmA@mail.gmail.com>

On Fri, May 24, 2013 at 10:35 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> So single-item tuples are not special. They just follow the rules for
> multiple-item tuples, except that you only have item.

And except that the trailing comma is not optional. So, they are
special after all.

-- Devin

From steve at pearwood.info  Sat May 25 04:57:30 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 25 May 2013 12:57:30 +1000
Subject: [Tutor] challenge-chapter 2
In-Reply-To: <519FFA8D.8010804@gmail.com>
References: <1369198979.77301.YahooMailNeo@web122003.mail.ne1.yahoo.com>
	<519FFA8D.8010804@gmail.com>
Message-ID: <51A0289A.2060006@pearwood.info>

On 25/05/13 09:41, bob gailer wrote:
> On 5/22/2013 1:02 AM, Andrew Triplett wrote:
>> ... illegal variable names ...
> That is a very poor description. Something can either be used as a variable name or not.
>
> abc can be used as a variable name, if can't.

But it can be used as a variable name in some languages. "if" is at least *potentially* a variable name, in the sense that somebody might try to use it as a name.


> I defy you to give me a variable name that is illegal! Anything you attempt to give in that category is not a variable name.

While you are strictly correct, you are missing the point of the exercise, which is to distinguish between strings which can be used as variable names:

pedant
variable
constant
this_is_not_a_variable
pi
tau
alpha1234


and those that can't:

1234alpha
*$%^
for
return
this-is-a-variable


A better name for this is "identifier" rather than "variable name", and Python 3 defines a string method to test whether or not something is a valid identifier:

http://docs.python.org/3/library/stdtypes.html#str.isidentifier


-- 
Steven

From jiangtaoshengpython at gmail.com  Sat May 25 08:34:58 2013
From: jiangtaoshengpython at gmail.com (jiangtao sheng)
Date: Sat, 25 May 2013 14:34:58 +0800
Subject: [Tutor] Jion list!
Message-ID: <CABCZcn08z=tY3UfXfqtzZo=5Rp6jVw4s9mHnEPHsveNoXNH6fw@mail.gmail.com>

Hi,i am JiangtaoSheng!!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130525/6b0ebbb5/attachment.html>

From rafael.knuth at gmail.com  Sat May 25 11:25:13 2013
From: rafael.knuth at gmail.com (Rafael Knuth)
Date: Sat, 25 May 2013 11:25:13 +0200
Subject: [Tutor] Flip the coin 10x and count heads and tails: It works now!
Message-ID: <CAM-E2X6k+H4=6XcUMLXzpRsEM2Pc0YacTPMK30TOwnLtHZWyPQ@mail.gmail.com>

Gents,

thank you all for your help. One of you guys asked me to try out your
suggestions and then tell you how it goes. Here we go! First, let me
recap briefly what the expected outcome of my program was and which
difficulties I encountered at the beginning. I was writing a program
in Python 3.3.0 which flips a coin 10 x times and then counts the
number of heads and tails. It obviously did something else than I
intended:

import random

print ("""

This program flips a coin 10 times.
It then counts the number of heads and tails.

""")

flips = 0
heads = 0
tails = 0

while flips < 10:
    flips = flips + 1
    if random.randint(1,2) == 1:
        heads = heads + 1
        print("We've got " + str(heads) + " heads here."
    if random.randint(1,2) == 2:
        tails = tails + 1
        print("We've got " + str(tails) + " tails here.")

This is what I got as output:

This program flips a coin 10 times.
It then counts the number of heads and tails.

We've got 1 tails here.
We've got 1 heads here.
We've got 2 tails here.
We've got 2 heads here.
We've got 3 tails here.
We've got 3 heads here.
We've got 4 tails here.
We've got 5 tails here.
We've got 4 heads here.
We've got 6 tails here.
We've got 7 tails here.
We've got 5 heads here.

As it turned out, each of your answers was *partially* correct, so I
played around with your suggestions until I got my code up and
running. Frankly, I did two mistakes: First, I placed the print
statement inside the loop instead of outside of it. And second, I
mistakenly called the random function two times inside the loop. In
order to resolve that issue, I had to modify the heads and tails
variables and then add another variable and put it inside the loop:

result = random.randint(1,2)

Lastly, I figured out that counting the results can be done in a more
elegant fashion. Instead of:

variable_XYZ = variable_XYZ + 1

? it can be done this way:

variable_XYZ += 1

I got so excited when I saw my program run properly that I decided to
pimp it a little bit by printing each head and tail with a time delay
while the coin got flipped during the run. Here?s what my code looks
like now:

import random
import time

print ("""

This program flips a coin 10 times.
It then counts the number of heads and tails.

""")
time.sleep(1)

flips = 0
heads = 0
tails = 0

while flips < 10:
    result = random.randint(1,2)
    if result == 1:
        heads += 1
        print("head")
        time.sleep(1)
    elif result == 2:
        tails += 1
        print("tail")
        time.sleep(1)
    flips += 1
print ("\nYou've got " + str(heads) + " heads and " + str(tails) + " tails.")

I have one last question to you: I explained twice in my initial mail
what I expect my program to do (?I am writing a program in Python
3.3.0 which flips a coin 10 x times and then counts the number of
heads and tails.?). I did that the introduction as well as inside my
code. However, almost each of you asked me what I expect my program to
do. I was confused about that and I am wondering if any of you can
clarify? I just want to make sure I avoid misunderstandings like these
in the future.

Thank you all again!

All the best,



Rafael

From beachkidken at gmail.com  Sat May 25 14:42:54 2013
From: beachkidken at gmail.com (Ken G.)
Date: Sat, 25 May 2013 08:42:54 -0400
Subject: [Tutor] Flip the coin 10x and count heads and tails: It works
 now!
In-Reply-To: <CAM-E2X6k+H4=6XcUMLXzpRsEM2Pc0YacTPMK30TOwnLtHZWyPQ@mail.gmail.com>
References: <CAM-E2X6k+H4=6XcUMLXzpRsEM2Pc0YacTPMK30TOwnLtHZWyPQ@mail.gmail.com>
Message-ID: <51A0B1CE.7030502@gmail.com>


On 05/25/2013 05:25 AM, Rafael Knuth wrote:
> Gents,
>
> thank you all for your help. One of you guys asked me to try out your
> suggestions and then tell you how it goes. Here we go! First, let me
> recap briefly what the expected outcome of my program was and which
> difficulties I encountered at the beginning. I was writing a program
> in Python 3.3.0 which flips a coin 10 x times and then counts the
> number of heads and tails. It obviously did something else than I
> intended:
>
> import random
>
> print ("""
>
> This program flips a coin 10 times.
> It then counts the number of heads and tails.
>
> """)
>
> flips = 0
> heads = 0
> tails = 0
>
> while flips < 10:
>      flips = flips + 1
>      if random.randint(1,2) == 1:
>          heads = heads + 1
>          print("We've got " + str(heads) + " heads here."
>      if random.randint(1,2) == 2:
>          tails = tails + 1
>          print("We've got " + str(tails) + " tails here.")
>
> This is what I got as output:
>
> This program flips a coin 10 times.
> It then counts the number of heads and tails.
>
> We've got 1 tails here.
> We've got 1 heads here.
> We've got 2 tails here.
> We've got 2 heads here.
> We've got 3 tails here.
> We've got 3 heads here.
> We've got 4 tails here.
> We've got 5 tails here.
> We've got 4 heads here.
> We've got 6 tails here.
> We've got 7 tails here.
> We've got 5 heads here.
>
> As it turned out, each of your answers was *partially* correct, so I
> played around with your suggestions until I got my code up and
> running. Frankly, I did two mistakes: First, I placed the print
> statement inside the loop instead of outside of it. And second, I
> mistakenly called the random function two times inside the loop. In
> order to resolve that issue, I had to modify the heads and tails
> variables and then add another variable and put it inside the loop:
>
> result = random.randint(1,2)
>
> Lastly, I figured out that counting the results can be done in a more
> elegant fashion. Instead of:
>
> variable_XYZ = variable_XYZ + 1
>
> ? it can be done this way:
>
> variable_XYZ += 1
>
> I got so excited when I saw my program run properly that I decided to
> pimp it a little bit by printing each head and tail with a time delay
> while the coin got flipped during the run. Here?s what my code looks
> like now:
>
> import random
> import time
>
> print ("""
>
> This program flips a coin 10 times.
> It then counts the number of heads and tails.
>
> """)
> time.sleep(1)
>
> flips = 0
> heads = 0
> tails = 0
>
> while flips < 10:
>      result = random.randint(1,2)
>      if result == 1:
>          heads += 1
>          print("head")
>          time.sleep(1)
>      elif result == 2:
>          tails += 1
>          print("tail")
>          time.sleep(1)
>      flips += 1
> print ("\nYou've got " + str(heads) + " heads and " + str(tails) + " tails.")
>
> I have one last question to you: I explained twice in my initial mail
> what I expect my program to do (?I am writing a program in Python
> 3.3.0 which flips a coin 10 x times and then counts the number of
> heads and tails.?). I did that the introduction as well as inside my
> code. However, almost each of you asked me what I expect my program to
> do. I was confused about that and I am wondering if any of you can
> clarify? I just want to make sure I avoid misunderstandings like these
> in the future.
>
> Thank you all again!
>
> All the best,
>
>
>
> Rafael
May I suggest that instead of:

flips = 0
heads = 0
tails = 0

how about:

flips = heads = tails = 0

Ken


From robert.sjoblom at gmail.com  Sat May 25 14:50:28 2013
From: robert.sjoblom at gmail.com (Robert Sjoblom)
Date: Sat, 25 May 2013 14:50:28 +0200
Subject: [Tutor] Flip the coin 10x and count heads and tails: It works
	now!
In-Reply-To: <51A0B1CE.7030502@gmail.com>
References: <CAM-E2X6k+H4=6XcUMLXzpRsEM2Pc0YacTPMK30TOwnLtHZWyPQ@mail.gmail.com>
	<51A0B1CE.7030502@gmail.com>
Message-ID: <CAJKU7g2uepGf3zHANcq547Ru0du1jMuj-PcNQ0v_JYDCtYm4eA@mail.gmail.com>

On 25 May 2013 14:42, Ken G. <beachkidken at gmail.com> wrote:
> May I suggest that instead of:
> how about:
>
> flips = heads = tails = 0
>
> Ken

How about flips = heads = 0
tails can then be calculated from flips - heads.
--
best regards,
Robert S.

From fomcl at yahoo.com  Sat May 25 14:54:18 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sat, 25 May 2013 05:54:18 -0700 (PDT)
Subject: [Tutor] Fwd: Difference between types
In-Reply-To: <519FBB43.8040501@davea.name>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
	<CACL+1auT4ZKdY+zZRu_Mbv2yQ33u2tsvmw9eEe-+8NKZYQuPdQ@mail.gmail.com>
	<1369421613.60441.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<519FBB43.8040501@davea.name>
Message-ID: <1369486458.39725.YahooMailNeo@web163801.mail.gq1.yahoo.com>



> From: Dave Angel <davea at davea.name>
>To: tutor at python.org 
>Sent: Friday, May 24, 2013 9:10 PM
>Subject: Re: [Tutor] Fwd: Difference between types
> 
>
>On 05/24/2013 02:53 PM, Albert-Jan Roskam wrote:
>> <snip>
>>
>>> A tuple is defined by commas, depending on context. However,
>>> parentheses are typically required because commas have low precedence.
>>>
>>>? ? ? >>> 1, 2 + 3, 4
>>>? ? ? (1, 5, 4)
>>>
>>>? ? ? >>> (1, 2) + (3, 4)
>>>? ? ? (1, 2, 3, 4)
>>>
>>> An empty tuple is a special case:
>>>
>>>? ? ? >>> x = ()
>>>? ? ? >>> type(x)
>>>? ? ? <type 'tuple'>
>>
>> Why do I need to use a trailing comma to create a singleton tuple? Without a comma it seems to mean "parenthesized single object", ie the parentheses are basically not there.
>>>>> type((0,))
>> <type 'tuple'>
>>>>> type((0))
>> <type 'int'>
>>>>> (0)
>> 0
>>>>> x = (,)
>> SyntaxError: invalid syntax
>>
>>>>> (0,0)
>> (0, 0)
>>
>
>Your answer is right above your question, in the part you quoted 
>(without attribution) from eryksun.
>
>The empty tuple is specified with ().? But for any tuple with one or 
>more members, it's the commas that turn it into a tuple.? The parens are 
>not necessarily needed unless the statement is complex enough that we 
>need them for precedence.
>
>So???x = 3,4
>
>makes a one-tuple out of 3 and 4.? If you want a one-tuple (which is NOT 
>a singleton), you need a silly-looking comma to specify it:

So you say the term singleton is reserved to one-item sets? I looked it up and: "In mathematics, a singleton, also known as a unit set, is a set with exactly one element. For example, the set {0} is a singleton.The term is also used for a 1-tuple (a sequence with one element)".(http://en.wikipedia.org/wiki/Singleton_%28mathematics%29).

<snip>

From steve at pearwood.info  Sat May 25 15:13:38 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 25 May 2013 23:13:38 +1000
Subject: [Tutor] Flip the coin 10x and count heads and tails: It works
 now!
In-Reply-To: <CAM-E2X6k+H4=6XcUMLXzpRsEM2Pc0YacTPMK30TOwnLtHZWyPQ@mail.gmail.com>
References: <CAM-E2X6k+H4=6XcUMLXzpRsEM2Pc0YacTPMK30TOwnLtHZWyPQ@mail.gmail.com>
Message-ID: <51A0B902.8030903@pearwood.info>

On 25/05/13 19:25, Rafael Knuth wrote:

> flips = 0
> heads = 0
> tails = 0
>
> while flips < 10:
>      flips = flips + 1

Don't do this. It's not 1971 any more, we've had for loops for forty years :-)

Use while loops when you don't know how many loops you need. When you know how many loops you will have, use a for loop.

for flip in range(10):
     print(flip)

will print 0 1 2 3 ... 9 which makes ten loops altogether. If you want to start counting at 1 instead of 0, use:

for flip in range(1, 11):
     print(flip)

which will print 1 2 3 ... 9 10.


There's no need to count the number of heads and tails separately, since every loop is guaranteed to give either head or tails. So just count the number of heads, then the number of tails will be ten less the number of heads.




-- 
Steven

From steve at pearwood.info  Sat May 25 15:24:46 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 25 May 2013 23:24:46 +1000
Subject: [Tutor] Fwd: Difference between types
In-Reply-To: <1369486458.39725.YahooMailNeo@web163801.mail.gq1.yahoo.com>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
	<CACL+1auT4ZKdY+zZRu_Mbv2yQ33u2tsvmw9eEe-+8NKZYQuPdQ@mail.gmail.com>
	<1369421613.60441.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<519FBB43.8040501@davea.name>
	<1369486458.39725.YahooMailNeo@web163801.mail.gq1.yahoo.com>
Message-ID: <51A0BB9E.2060600@pearwood.info>

On 25/05/13 22:54, Albert-Jan Roskam wrote:
>
>
>> From: Dave Angel <davea at davea.name>

>> So   x = 3,4
>>
>> makes a one-tuple out of 3 and 4.

Dave means a two-tuple here.


>> If you want a one-tuple (which is NOT
>> a singleton), you need a silly-looking comma to specify it:
>
> So you say the term singleton is reserved to one-item sets?


Nope. "Singleton" has various meanings.

1) A singleton tuple (or set, or list) is a tuple with a single item in it. This is a fairly unusual definition in Object Oriented programming circles, since it clashes with the next definition, but it's more common in functional programming and the more heavily mathematical end of computer science theory.

2a) A singleton is a class that only allows a single instance to be created.

2b) The lone instance of a singleton class is also called a singleton. E.g. None is a singleton.

3) (Informal) A class that only allows a fixed, and small, number of instances to be created, where there is exactly one instance for each possible value. E.g. sometimes people will call True and False singletons, even though there are two of them, because Python guarantees that there will be exactly one True instance, and exactly one False instance.


Dave is, I think, referring to the common use in programming circles of "singleton" to refer to a class with exactly one instance, like None. This is very widespread, but not all programming languages have a concept of instances, so it is not a universal definition.



-- 
Steven

From davea at davea.name  Sat May 25 16:56:35 2013
From: davea at davea.name (Dave Angel)
Date: Sat, 25 May 2013 10:56:35 -0400
Subject: [Tutor] Fwd: Difference between types
In-Reply-To: <1369486458.39725.YahooMailNeo@web163801.mail.gq1.yahoo.com>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
	<CACL+1auT4ZKdY+zZRu_Mbv2yQ33u2tsvmw9eEe-+8NKZYQuPdQ@mail.gmail.com>
	<1369421613.60441.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<519FBB43.8040501@davea.name>
	<1369486458.39725.YahooMailNeo@web163801.mail.gq1.yahoo.com>
Message-ID: <51A0D123.2090903@davea.name>

On 05/25/2013 08:54 AM, Albert-Jan Roskam wrote:
>
>
>> From: Dave Angel <davea at davea.name>
>>
      <SNIP>
>>
>> The empty tuple is specified with ().  But for any tuple with one or
>> more members, it's the commas that turn it into a tuple.  The parens are
>> not necessarily needed unless the statement is complex enough that we
>> need them for precedence.
>>
>> So   x = 3,4
>>
>> makes a one-tuple out of 3 and 4.  If you want a one-tuple (which is NOT
>> a singleton), you need a silly-looking comma to specify it:
>
> So you say the term singleton is reserved to one-item sets? I looked it up and: "In mathematics, a singleton, also known as a unit set, is a set with exactly one element. For example, the set {0} is a singleton.The term is also used for a 1-tuple (a sequence with one element)".(http://en.wikipedia.org/wiki/Singleton_%28mathematics%29).
>
> <snip>
>
>

Thanks for that reference.  I had forgotten the usage of singleton in 
pure mathematics.  In computer software the only way I can recall it 
used (in about 45 years) is the design pattern singleton.  For example 
None is a singleton.  You cannot create another instance of NoneType.

http://en.wikipedia.org/wiki/Singleton_pattern

Now even that is a little different than I've seen used.  I've seen True 
and False considered singletons, even though they're the same class. 
But each value (of two legal values) of that class can only be 
instantiated once.

If the term is also used to represent one-tuples or one-item sets in 
software, that seems to me to be very confusing and misleading.  So I'm 
not saying you're wrong, only that I hope you are.

(Flash:) I just spotted Steven's post.  Thanks for the correction about 
3,4  which was just a typo.  And yes, I was referring to meanings two 
and three in your list.  And indirectly to the Gang of Four book,
     http://en.wikipedia.org/wiki/Design_Patterns


-- 
DaveA

From breamoreboy at yahoo.co.uk  Sat May 25 17:09:01 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 25 May 2013 16:09:01 +0100
Subject: [Tutor] Fwd: Difference between types
In-Reply-To: <51A0D123.2090903@davea.name>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
	<CACL+1auT4ZKdY+zZRu_Mbv2yQ33u2tsvmw9eEe-+8NKZYQuPdQ@mail.gmail.com>
	<1369421613.60441.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<519FBB43.8040501@davea.name>
	<1369486458.39725.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<51A0D123.2090903@davea.name>
Message-ID: <knqk5n$nep$2@ger.gmane.org>

On 25/05/2013 15:56, Dave Angel wrote:
> On 05/25/2013 08:54 AM, Albert-Jan Roskam wrote:
>>
>>
>>> From: Dave Angel <davea at davea.name>
>>>
>       <SNIP>
>>>
>>> The empty tuple is specified with ().  But for any tuple with one or
>>> more members, it's the commas that turn it into a tuple.  The parens are
>>> not necessarily needed unless the statement is complex enough that we
>>> need them for precedence.
>>>
>>> So   x = 3,4
>>>
>>> makes a one-tuple out of 3 and 4.  If you want a one-tuple (which is NOT
>>> a singleton), you need a silly-looking comma to specify it:
>>
>> So you say the term singleton is reserved to one-item sets? I looked
>> it up and: "In mathematics, a singleton, also known as a unit set, is
>> a set with exactly one element. For example, the set {0} is a
>> singleton.The term is also used for a 1-tuple (a sequence with one
>> element)".(http://en.wikipedia.org/wiki/Singleton_%28mathematics%29).
>>
>> <snip>
>>
>>
>
> Thanks for that reference.  I had forgotten the usage of singleton in
> pure mathematics.  In computer software the only way I can recall it
> used (in about 45 years) is the design pattern singleton.  For example
> None is a singleton.  You cannot create another instance of NoneType.
>
> http://en.wikipedia.org/wiki/Singleton_pattern
>
> Now even that is a little different than I've seen used.  I've seen True
> and False considered singletons, even though they're the same class. But
> each value (of two legal values) of that class can only be instantiated
> once.
>
> If the term is also used to represent one-tuples or one-item sets in
> software, that seems to me to be very confusing and misleading.  So I'm
> not saying you're wrong, only that I hope you are.
>
> (Flash:) I just spotted Steven's post.  Thanks for the correction about
> 3,4  which was just a typo.  And yes, I was referring to meanings two
> and three in your list.  And indirectly to the Gang of Four book,
>      http://en.wikipedia.org/wiki/Design_Patterns
>
>

IIRC Alex Martelli argued that you don't need a singleton, you need a 
borg.  I'll leave those interested to look this up :)

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From cybervigilante at gmail.com  Sat May 25 20:56:51 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sat, 25 May 2013 11:56:51 -0700
Subject: [Tutor] why can you swap an immutable tuple?
Message-ID: <CALRAYNVpWXTxSQZ+bswrSjY0oVxiuoLFBEX0mAHMQrB45P-7TQ@mail.gmail.com>

I thought tuples were immutable but it seems you can swap them, so I'm
confused:

a,b = 5,8

print a  # result 5

a,b = b,a

print a  # result 8, so they swapped

# but if I test the type of a,b I get a tuple

testit = a,b
print type(testit)  #comes out as a tuple

print testit, # result is (8,5)

# So how am I swapping elements of a tuple when a tuple is immutable?

#t rying so change a tuple since I just did it

testit[1] = 14  #program crashes - *TypeError: 'tuple' object does not
support item assignment *so the tuple I just changed is indeed immutable

-- 
Jim Mooney

"Coding? You can get a woman to do that!" he said with a sneer. --heard
from a physics professor in 1969
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130525/bcf045bf/attachment.html>

From breamoreboy at yahoo.co.uk  Sat May 25 21:23:39 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 25 May 2013 20:23:39 +0100
Subject: [Tutor] why can you swap an immutable tuple?
In-Reply-To: <CALRAYNVpWXTxSQZ+bswrSjY0oVxiuoLFBEX0mAHMQrB45P-7TQ@mail.gmail.com>
References: <CALRAYNVpWXTxSQZ+bswrSjY0oVxiuoLFBEX0mAHMQrB45P-7TQ@mail.gmail.com>
Message-ID: <knr338$7lr$1@ger.gmane.org>

On 25/05/2013 19:56, Jim Mooney wrote:
> I thought tuples were immutable but it seems you can swap them, so I'm
> confused:
>
> a,b = 5,8

You've defined two names a and b so where's the tuple?

>
> print a  # result 5
>
> a,b = b,a

You've redefined two names a and b to take the values that were held in 
b and a so still no tuple.

>
> print a  # result 8, so they swapped
>
> # but if I test the type of a,b I get a tuple
>
> testit = a,b

Finally a tuple.

> print type(testit)  #comes out as a tuple
>
> print testit, # result is (8,5)
>
> # So how am I swapping elements of a tuple when a tuple is immutable?
>
> #t rying so change a tuple since I just did it
>
> testit[1] = 14  #program crashes - *TypeError: 'tuple' object does not
> support item assignment *so the tuple I just changed is indeed immutable

Exactly as expected.  So what precisely don't you understand?

>
> --
> Jim Mooney
>
> "Coding? You can get a woman to do that!" he said with a sneer. --heard
> from a physics professor in 1969
>
-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From oscar.j.benjamin at gmail.com  Sat May 25 21:27:36 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Sat, 25 May 2013 20:27:36 +0100
Subject: [Tutor] making a random list, then naming it
In-Reply-To: <CACL+1asW-XoDF__5eqw4NF0qfVeOEFetobEHB=+=+s9U5JOS=Q@mail.gmail.com>
References: <CALRAYNVxxmHYbWHPBgsPcwwHNNL0Wpw72N73Zzwx3P8Bd4p1qw@mail.gmail.com>
	<519EF97B.3060109@davea.name>
	<CALRAYNUFQJZh10eCSBoORWAard5_3FewyHTLbHJDyXM32o1jZw@mail.gmail.com>
	<51A00F7E.8050400@davea.name>
	<CACL+1asW-XoDF__5eqw4NF0qfVeOEFetobEHB=+=+s9U5JOS=Q@mail.gmail.com>
Message-ID: <CAHVvXxTuXdXXQG9Zwt3jJufOzzJQpj=+YGOgOQad50e=zUqrbQ@mail.gmail.com>

On 25 May 2013 02:51, eryksun <eryksun at gmail.com> wrote:
> On Fri, May 24, 2013 at 9:10 PM, Dave Angel <davea at davea.name> wrote:
>>
>> Is lists[(3,8)]  really so much harder to type than
>>     list_3_8  ?
>
> Since a comma creates a tuple, in this context you can just use
> lists[3,8] to save a couple more keystrokes.

Or even lists(3, 8) if lists is a function.

From steve at alchemy.com  Sat May 25 21:29:48 2013
From: steve at alchemy.com (Steve Willoughby)
Date: Sat, 25 May 2013 12:29:48 -0700
Subject: [Tutor] why can you swap an immutable tuple?
In-Reply-To: <CALRAYNVpWXTxSQZ+bswrSjY0oVxiuoLFBEX0mAHMQrB45P-7TQ@mail.gmail.com>
References: <CALRAYNVpWXTxSQZ+bswrSjY0oVxiuoLFBEX0mAHMQrB45P-7TQ@mail.gmail.com>
Message-ID: <88751E34-0B50-496F-BEF5-F2FB15783352@alchemy.com>


On 2013-5?-25, at ??11:56, Jim Mooney wrote:

> I thought tuples were immutable but it seems you can swap them, so I'm confused:
> 
> a,b = 5,8
> 


I think you're confusing mutating the tuples with assigning the immutable tuples different names.  The variable names are just labels you attach to them.  The tuple values themselves cannot change.  

That said, your example here isn't a tuple but a pair of singleton values. 

If you said 
tuple1 = 1,2,3,4
tuple2 = 5,6,7,8

you create two tuples which are, yes, immutable.  They happen to be called tuple1 and tuple2 but that's beside the point of immutability.  If you pass them to a function, they'll be known locally there under different names but they're still immutable tuples.

Does that help?
--steve

From davea at davea.name  Sat May 25 22:52:04 2013
From: davea at davea.name (Dave Angel)
Date: Sat, 25 May 2013 16:52:04 -0400
Subject: [Tutor] why can you swap an immutable tuple?
In-Reply-To: <CALRAYNVpWXTxSQZ+bswrSjY0oVxiuoLFBEX0mAHMQrB45P-7TQ@mail.gmail.com>
References: <CALRAYNVpWXTxSQZ+bswrSjY0oVxiuoLFBEX0mAHMQrB45P-7TQ@mail.gmail.com>
Message-ID: <51A12474.9030106@davea.name>

On 05/25/2013 02:56 PM, Jim Mooney wrote:
> I thought tuples were immutable but it seems you can swap them, so I'm
> confused:
>

The anonymous tuple object is immutable, but you just build one 
temporarily, extract both items from it, and destroy it.

> a,b = 5,8
>

The a,b on the left hand side is a tuple-unpacking-syntax, where it 
takes whatever tuple (or list, or whatever else supports the protocol), 
and extracts the elements in order.  a,b are not tied together in any sense.

> print a  # result 5
>
> a,b = b,a
>

Here you build another anonymous tuple that happens to be in the reverse 
order as the earlier one.  Then you unpack it into two arbitrary 
variables, that only happen to be the same ones as you used before, and 
only happens to be the same ones as used on the right side.

> print a  # result 8, so they swapped
>
> # but if I test the type of a,b I get a tuple
>
> testit = a,b
> print type(testit)  #comes out as a tuple

Now you're building yet another tuple, and actually binding a name to 
it.  So it won't go away at the end of the statement.

>
> print testit, # result is (8,5)
>
> # So how am I swapping elements of a tuple when a tuple is immutable?
>
> #t rying so change a tuple since I just did it
>
> testit[1] = 14  #program crashes - *TypeError: 'tuple' object does not
> support item assignment *so the tuple I just changed is indeed immutable
>

This time you ARE trying to change a tuple, for the first time.


-- 
DaveA

From bouncingcats at gmail.com  Sun May 26 03:34:38 2013
From: bouncingcats at gmail.com (David)
Date: Sun, 26 May 2013 11:34:38 +1000
Subject: [Tutor] why can you swap an immutable tuple?
In-Reply-To: <CALRAYNVpWXTxSQZ+bswrSjY0oVxiuoLFBEX0mAHMQrB45P-7TQ@mail.gmail.com>
References: <CALRAYNVpWXTxSQZ+bswrSjY0oVxiuoLFBEX0mAHMQrB45P-7TQ@mail.gmail.com>
Message-ID: <CAMPXz=pEMCYvhgh+c-aXrVJCkONX+9+13W5s7X-+12u2snuyjA@mail.gmail.com>

On 26/05/2013, Jim Mooney <cybervigilante at gmail.com> wrote:
> I thought tuples were immutable but it seems you can swap them, so I'm
> confused:
>
> a,b = 5,8

I think your confusion might arise from not understanding that the
meaning of the comma differs depending on whether it is on the left or
the right side of an equals sign.

On the right: it combines the 5 and the 8 to create a tuple, as yet un-named.

On the left: it says to unpack the tuple-on-the-right into two
independent values and assign them to the names a and b. So here it is
effectively a=5 and b=8.

So, there is no tuple on the left hand side. The statement does not
create a tuple, because the comma on the left side means "unpack the
tuple-on-the-right".

To assign a name to a tuple, there must be no comma on the left side, like this:
name_of_tuple = 5, 8

From steve at pearwood.info  Sun May 26 04:38:19 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 26 May 2013 12:38:19 +1000
Subject: [Tutor] why can you swap an immutable tuple?
In-Reply-To: <knr338$7lr$1@ger.gmane.org>
References: <CALRAYNVpWXTxSQZ+bswrSjY0oVxiuoLFBEX0mAHMQrB45P-7TQ@mail.gmail.com>
	<knr338$7lr$1@ger.gmane.org>
Message-ID: <51A1759B.9010808@pearwood.info>

On 26/05/13 05:23, Mark Lawrence wrote:
> On 25/05/2013 19:56, Jim Mooney wrote:
>> I thought tuples were immutable but it seems you can swap them, so I'm
>> confused:
>>
>> a,b = 5,8
>
> You've defined two names a and b so where's the tuple?

On the right hand side, 5,8 creates a tuple, which is then immediately unpacked to two individual values. You can see this by disassembling the code. In 2.7, you get this:

py> from dis import dis
py> code = compile("a, b = 5, 8", "", "exec")
py> dis(code)
   1           0 LOAD_CONST               3 ((5, 8))
               3 UNPACK_SEQUENCE          2
               6 STORE_NAME               0 (a)
               9 STORE_NAME               1 (b)
              12 LOAD_CONST               2 (None)
              15 RETURN_VALUE


Other versions may be slightly different, for example in Python 1.5 (ancient history!) the constant tuple (5, 8) is not created at compile-time, but at run-time:

# output of dis from Python 1.5:

           0 SET_LINENO          0
           3 SET_LINENO          1
           6 LOAD_CONST          0 (5)
           9 LOAD_CONST          1 (8)
          12 BUILD_TUPLE         2
          15 UNPACK_TUPLE        2
          18 STORE_NAME          0 (a)
          21 STORE_NAME          1 (b)
          24 LOAD_CONST          2 (None)
          27 RETURN_VALUE


But whenever it is created, the right hand side creates a tuple.

An interesting fact: on the left hand side, Python is very flexible with its sequence unpacking syntax. All of these are equivalent, where RHS (Right Hand Side) evaluates to exactly two items:

a, b = RHS
(a, b) = RHS
[a, b] = RHS


Note also that it is *sequence* unpacking, not *tuple* unpacking. Any sequence will work. Actually, any iterable object will work, not just sequences. But the name comes from way back in early Python days when it only worked on sequences.



-- 
Steven

From cybervigilante at gmail.com  Sun May 26 05:04:06 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sat, 25 May 2013 20:04:06 -0700
Subject: [Tutor] why can you swap an immutable tuple?
In-Reply-To: <CAMPXz=pEMCYvhgh+c-aXrVJCkONX+9+13W5s7X-+12u2snuyjA@mail.gmail.com>
References: <CALRAYNVpWXTxSQZ+bswrSjY0oVxiuoLFBEX0mAHMQrB45P-7TQ@mail.gmail.com>
	<CAMPXz=pEMCYvhgh+c-aXrVJCkONX+9+13W5s7X-+12u2snuyjA@mail.gmail.com>
Message-ID: <CALRAYNVVFAp9gqJ4t7mWKvswbEW=xYgWs0N+3vjnN9K_J0rOcw@mail.gmail.com>

On 25 May 2013 18:34, David <bouncingcats at gmail.com> wrote:

> On 26/05/2013, Jim Mooney <cybervigilante at gmail.com> wrote:
> > I thought tuples were immutable but it seems you can swap them, so I'm
> > confused:
> >
> > a,b = 5,8
>
> I think your confusion might arise from not understanding that the
> meaning of the comma differs depending on whether it is on the left or
> the right side of an equals sign.
>

I think the problem is the book I'm reading, which never mentions
"unpacking," so I thought from hearing a comma creates a tuple, that it was
tuples on both sides  ;')  I'm reading Learning Computer Science With
Python and I think it's scanting the Python-detail to get on with the
CompSci. I'll go look for something more PyDetailed ;')
-- 
Jim Mooney

"Coding? A woman can do that! he sneered" --heard from a physics professor
in 1969
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130525/80555b3e/attachment.html>

From tjhanson at yahoo.com  Sun May 26 05:07:43 2013
From: tjhanson at yahoo.com (Tim Hanson)
Date: Sat, 25 May 2013 20:07:43 -0700
Subject: [Tutor] making a string
Message-ID: <201305252007.43454.tjhanson@yahoo.com>

I'm new to this, just getting through the first Mark Lutz book.  

If I start out with :

ham=list('spam');ham
['s','p','a','m']

How do I get a string back?

From breamoreboy at yahoo.co.uk  Sun May 26 05:16:15 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sun, 26 May 2013 04:16:15 +0100
Subject: [Tutor] making a string
In-Reply-To: <201305252007.43454.tjhanson@yahoo.com>
References: <201305252007.43454.tjhanson@yahoo.com>
Message-ID: <knruon$bvr$1@ger.gmane.org>

On 26/05/2013 04:07, Tim Hanson wrote:
> I'm new to this, just getting through the first Mark Lutz book.
>
> If I start out with :
>
> ham=list('spam');ham
> ['s','p','a','m']
>
> How do I get a string back?
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

''.join(ham)

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From cybervigilante at gmail.com  Sun May 26 05:16:23 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sat, 25 May 2013 20:16:23 -0700
Subject: [Tutor] why can you swap an immutable tuple?
In-Reply-To: <51A1759B.9010808@pearwood.info>
References: <CALRAYNVpWXTxSQZ+bswrSjY0oVxiuoLFBEX0mAHMQrB45P-7TQ@mail.gmail.com>
	<knr338$7lr$1@ger.gmane.org> <51A1759B.9010808@pearwood.info>
Message-ID: <CALRAYNX2w45gfYj+kW5DyOZBuTeG1ANCkhyDT3q2at7iSSZW0g@mail.gmail.com>

On 25 May 2013 19:38, Steven D'Aprano <steve at pearwood.info> wrote:

> On 26/05/13 05:23, Mark Lawrence wrote:
>


> On the right hand side, 5,8 creates a tuple, which is then immediately
> unpacked to two individual values. You can see this by disassembling the
> code. In 2.7, you get this:
>
> py> from dis import dis
> py> code = compile("a, b = 5, 8", "", "exec")
> py> dis(code)
>   1           0 LOAD_CONST               3 ((5, 8))
>               3 UNPACK_SEQUENCE          2
>               6 STORE_NAME               0 (a)
>               9 STORE_NAME               1 (b)
>              12 LOAD_CONST               2 (None)
>              15 RETURN_VALUE
>
> That disassembling looks like it could clarify a number of things. I'll
have to try it. It might make more sense to me since my  only programming,
besides a bit of javascript copy-hacking for websites, was A86 Assembler,
some decades ago, when I wrote an ASCII Art prog for Fidonet.

Then I got into other fields entirely to make a living. But Asm actually
makes sense to me and the disassemble looks close to it. (I can't count the
times I wiped out DOS and had to reload it ;')  A86 had a wonderful macro
language, though.

Jim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130525/bdb7e641/attachment.html>

From cybervigilante at gmail.com  Sun May 26 05:21:18 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sat, 25 May 2013 20:21:18 -0700
Subject: [Tutor] got text switched
Message-ID: <CALRAYNU+0LUZ5HRwuue0EeD4Mkzw39seUyMExGMWf0YVUQWSbw@mail.gmail.com>

Oops, Gmail switched me back to rich text. My apologies. Back to plain
;')  I wish I could automate the mode, per-recipient, since I do need
rich text for some things. The way gmail defaults seems to change from
month to month.

--
Jim Mooney

From martin at linux-ip.net  Sun May 26 05:31:49 2013
From: martin at linux-ip.net (Martin A. Brown)
Date: Sat, 25 May 2013 23:31:49 -0400
Subject: [Tutor] making a string
In-Reply-To: <201305252007.43454.tjhanson@yahoo.com>
References: <201305252007.43454.tjhanson@yahoo.com>
Message-ID: <alpine.LNX.2.00.1305252315230.3324@octothorpe.wonderfrog.net>


Greetings Tim,

 : I'm new to this, just getting through the first Mark Lutz book.  

Python objects, either variables your ham below or the string 'spam' 
you entered manually have a specific type.  Each and every variable 
or object has a type.

I think you are trying to figure out how you started with a string 
that looked like 'spam' (and Python calls a <type 'str'>) and end up 
with something that looks like:

   ['s','p','a','m']

Well, I would encourage you to play with everything at the Python 
prompt.  You should be able to enter a t?te-?-t?te with Python as 
follows.  This is what I see when I type 'python' and get an 
interactive console:

  Python 2.7.2 (default, Aug 19 2011, 20:41:43) [GCC] on linux2
  Type "help", "copyright", "credits" or "license" for more information.
  >>> 

Then, I can start playing with variables, strings, lists and all the 
other things that Mark Lutz may mention.

Here's what I actually typed and what Python told me:

  >>> spam = 'spam'
  >>> type(spam)
  <type 'str'>
  >>> ham = list(spam)
  >>> type(ham)
  <type 'list'>
  >>> viking = ''.join(ham)
  >>> viking
  'spam'
  >>> type(viking)
  <type 'str'>

So, the point I'm trying to make here is that you did quite a bit
in just one line, by calling:

  >>> ham=list('spam');ham

Consider playing a bit with the interpreter.

 : ham=list('spam');ham
 : ['s','p','a','m']
 :
 : How do I get a string back?

I will now try to annotate my session above, so that you can maybe
see how I was able to get a string.

  >>> spam = 'spam'          # -- variable spam now contains string 'spam'
  >>> type(spam)
  <type 'str'>               # -- and Python tells me it's a string
  >>> ham = list(spam)       # -- I'm running your command
  >>> type(ham)
  <type 'list'>              # -- Wait, what!?  It's a list?!  Oh.  Yeah.
  >>> viking = ''.join(ham)  # -- create a string of the list elements
  >>> viking
  'spam'
  >>> type(viking)           # -- ah, here's our string!
  <type 'str'>

Try out the .join(ham) trick with other strings.  For
example...what happens when you try these yourself:

  >>> ham = list('spam')
  >>> '-'.join(ham)
  >>> ':'.join(ham)
  >>> 'B'.join(ham)
  >>> '    '.join(ham)

Hopefully, you see that there's no magic here at all--just that
you have learned how create a string with all of the elements in a
list.  Try something else for your amusement, as well...

  >>> ' '.join(list('frobnitz'))

Does that make sense?  Welcome to Python, and Mark Lutz has been
writing books on Python for almost as long as Python has been
around.  So, good luck and ask questions here.  There's quite a
group here willing to help.

-Martin

-- 
Martin A. Brown
http://linux-ip.net/

From tjhanson at yahoo.com  Sun May 26 05:49:09 2013
From: tjhanson at yahoo.com (Tim Hanson)
Date: Sat, 25 May 2013 20:49:09 -0700
Subject: [Tutor] making a string
In-Reply-To: <alpine.LNX.2.00.1305252315230.3324@octothorpe.wonderfrog.net>
References: <201305252007.43454.tjhanson@yahoo.com>
	<alpine.LNX.2.00.1305252315230.3324@octothorpe.wonderfrog.net>
Message-ID: <201305252049.09733.tjhanson@yahoo.com>

On Saturday, May 25, 2013 08:31:49 pm Martin A. Brown wrote:
> Greetings Tim,
> 
>  : I'm new to this, just getting through the first Mark Lutz book.
> 
> Python objects, either variables your ham below or the string 'spam'
> you entered manually have a specific type.  Each and every variable
> or object has a type.
> 
> I think you are trying to figure out how you started with a string
> that looked like 'spam' (and Python calls a <type 'str'>) and end up
> with something that looks like:
> 
>    ['s','p','a','m']
> 
> Well, I would encourage you to play with everything at the Python
> prompt.  You should be able to enter a t?te-?-t?te with Python as
> follows.  This is what I see when I type 'python' and get an
> interactive console:
> 
>   Python 2.7.2 (default, Aug 19 2011, 20:41:43) [GCC] on linux2
>   Type "help", "copyright", "credits" or "license" for more information.
> 
> 
> Then, I can start playing with variables, strings, lists and all the
> other things that Mark Lutz may mention.
> 
> Here's what I actually typed and what Python told me:
>   >>> spam = 'spam'
>   >>> type(spam)
> 
>   <type 'str'>
> 
>   >>> ham = list(spam)
>   >>> type(ham)
> 
>   <type 'list'>
> 
>   >>> viking = ''.join(ham)
>   >>> viking
> 
>   'spam'
> 
>   >>> type(viking)
> 
>   <type 'str'>
> 
> So, the point I'm trying to make here is that you did quite a bit
> 
> in just one line, by calling:
>   >>> ham=list('spam');ham
> 
> Consider playing a bit with the interpreter.
> 
>  : ham=list('spam');ham
>  : ['s','p','a','m']
>  : 
>  : How do I get a string back?
> 
> I will now try to annotate my session above, so that you can maybe
> see how I was able to get a string.
> 
>   >>> spam = 'spam'          # -- variable spam now contains string 'spam'
>   >>> type(spam)
> 
>   <type 'str'>               # -- and Python tells me it's a string
> 
>   >>> ham = list(spam)       # -- I'm running your command
>   >>> type(ham)
> 
>   <type 'list'>              # -- Wait, what!?  It's a list?!  Oh.  Yeah.
> 
>   >>> viking = ''.join(ham)  # -- create a string of the list elements
>   >>> viking
> 
>   'spam'
> 
>   >>> type(viking)           # -- ah, here's our string!
> 
>   <type 'str'>
> 
> Try out the .join(ham) trick with other strings.  For
> 
> example...what happens when you try these yourself:
>   >>> ham = list('spam')
>   >>> '-'.join(ham)
>   >>> ':'.join(ham)
>   >>> 'B'.join(ham)
>   >>> '    '.join(ham)
> 
> Hopefully, you see that there's no magic here at all--just that
> you have learned how create a string with all of the elements in a
> list.  Try something else for your amusement, as well...
> 
>   >>> ' '.join(list('frobnitz'))
> 
> Does that make sense?  Welcome to Python, and Mark Lutz has been
> writing books on Python for almost as long as Python has been
> around.  So, good luck and ask questions here.  There's quite a
> group here willing to help.
> 
> -Martin
The answer was to include ''.join(ham), as in making it a string method 
instead of a function, which doesn't exist.  Thanks!

For me, picking up Python is a retirement project, so no shortage of time to 
learn.

A lot of people tend to be intimidated by Mark Lutz, and so am I, I guess.  
There are a lot of books out there that will get one up and running more 
quickly, but I get the feeling his is _complete_ instruction, not something 
just slopped through.  "Learning Python" has taken a long time.  I'm not sure 
how I'll be able to get through "Programming..."  You'll probably see me on 
the Core list next year sometime.

From eryksun at gmail.com  Sun May 26 06:01:53 2013
From: eryksun at gmail.com (eryksun)
Date: Sun, 26 May 2013 00:01:53 -0400
Subject: [Tutor] why can you swap an immutable tuple?
In-Reply-To: <51A1759B.9010808@pearwood.info>
References: <CALRAYNVpWXTxSQZ+bswrSjY0oVxiuoLFBEX0mAHMQrB45P-7TQ@mail.gmail.com>
	<knr338$7lr$1@ger.gmane.org> <51A1759B.9010808@pearwood.info>
Message-ID: <CACL+1asrdcHoX0YcoTtYMjwyKk0cOk6sxS4zcSYiD16O5QYs3Q@mail.gmail.com>

On Sat, May 25, 2013 at 10:38 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On 26/05/13 05:23, Mark Lawrence wrote:
>>
>> On 25/05/2013 19:56, Jim Mooney wrote:
>>>
>>> I thought tuples were immutable but it seems you can swap them, so I'm
>>> confused:
>>>
>>> a,b = 5,8
>>
>>
>> You've defined two names a and b so where's the tuple?
>
>
> On the right hand side, 5,8 creates a tuple, which is then immediately
> unpacked to two individual values. You can see this by disassembling the
> code. In 2.7, you get this:

The abstract source tree (AST) uses a tuple or list for sequences in
"targets" (multiple targets are generated for chained assignment) and
also for the "value". The tuples and lists for the target(s) obviously
aren't preserved in the source code. They guide the compiler in the
arrangement of UNPACK_SEQUENCE and STORE operations.

A BUILD_TUPLE / BUILD_LIST operation for the right-hand side is
generally preserved for the "value" tuple or list. One optimization in
CPython, as you've shown, is to store a tuple of constants in the code
object.

Also, if the length of the sequence is less than 4, CPython's peephole
optimizer will replace the BUILD/UNPACK with simple stack rotation(s).
For length 2 it replaces it with a ROT_TWO. For length 3 it uses a
ROT_THREE followed by a ROT_TWO. For example:

    def f():
      a,b,c = x,y,z

    >>> dis.dis(f)
      2           0 LOAD_GLOBAL              0 (x)
                  3 LOAD_GLOBAL              1 (y)
                  6 LOAD_GLOBAL              2 (z)
                  9 ROT_THREE
                 10 ROT_TWO
                 11 STORE_FAST               0 (a)
                 14 STORE_FAST               1 (b)
                 17 STORE_FAST               2 (c)
                 20 LOAD_CONST               0 (None)
                 23 RETURN_VALUE

In the original bytecode, before the optimization, there was a
BUILD_TUPLE(3) followed immediately by UNPACK_SEQUENCE(3). The LOAD
operations set the stack as [x,y,z], where z is at the top of the
stack, which sets up for BUILD_TUPLE. But UNPACK_SEQUENCE would unpack
in reverse, leaving the stack as [z,y,x] to be popped off into the
names a, b, and c. So the optimizer inserts a ROT_THREE to get [x,y,z]
=> [z,x,y] and then ROT_TWO to get [z,x,y] => [z,y,x].

> An interesting fact: on the left hand side, Python is very flexible with its
> sequence unpacking syntax. All of these are equivalent, where RHS (Right
> Hand Side) evaluates to exactly two items:

Unpacking in assignment allows an almost comical level of complexity,
not even including subscription and attribute targets that can use
expressions for the primary object and subscript. A 'simple' example:

    def f(arg):
        i0,(i1,i2),(i3,(i4,i5,i6)) = arg
        return i0,i1,i2,i3,i4,i5,i6

    >>> f([0,'ab',[1,'cde']])
    (0, 'a', 'b', 1, 'c', 'd', 'e')

Here's the AST for this silliness:

    >>> src = 'i0,(i1,i2),(i3,(i4,i5,i6)) = arg'
    >>> ast.dump(ast.parse(src).body[0])

I formatted the output a bit:

    Assign(
      targets=[
        Tuple(
          elts=[
            Name(id='i0', ctx=Store()),
            Tuple(
              elts=[
                Name(id='i1', ctx=Store()),
                Name(id='i2', ctx=Store())],
              ctx=Store()),
            Tuple(
              elts=[
                Name(id='i3', ctx=Store()),
                Tuple(
                  elts=[
                    Name(id='i4', ctx=Store()),
                    Name(id='i5', ctx=Store()),
                    Name(id='i6', ctx=Store())],
                  ctx=Store())],
              ctx=Store())],
          ctx=Store())],
      value=Name(id='arg', ctx=Load()))

From cybervigilante at gmail.com  Sun May 26 06:10:00 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sat, 25 May 2013 21:10:00 -0700
Subject: [Tutor] making a string
In-Reply-To: <201305252049.09733.tjhanson@yahoo.com>
References: <201305252007.43454.tjhanson@yahoo.com>
	<alpine.LNX.2.00.1305252315230.3324@octothorpe.wonderfrog.net>
	<201305252049.09733.tjhanson@yahoo.com>
Message-ID: <CALRAYNXOVLd8Ucp7sC09SGR+yvY1q8Opiye6fQX9qqKFiUwxcA@mail.gmail.com>

On 25 May 2013 20:49, Tim Hanson <tjhanson at yahoo.com> wrote:

> A lot of people tend to be intimidated by Mark Lutz, and so am I, I guess.

Interesting coincidence. This is a retirement project and I just
decided on the Lutz book, which looked comprehensive, since the book
I'm using is more CompSci but PyDeficient. However, the 4th edition I
of Lutz that I got only goes up to Py 2.6.

As a general question - is there any Big difference between 2.6 and
2.7 (the Py version I'm using) that I should look out for so I don't
get tripped up?

Jim Mooney

From tjhanson at yahoo.com  Sun May 26 06:36:52 2013
From: tjhanson at yahoo.com (Tim Hanson)
Date: Sat, 25 May 2013 21:36:52 -0700
Subject: [Tutor] making a string
In-Reply-To: <CALRAYNXOVLd8Ucp7sC09SGR+yvY1q8Opiye6fQX9qqKFiUwxcA@mail.gmail.com>
References: <201305252007.43454.tjhanson@yahoo.com>
	<201305252049.09733.tjhanson@yahoo.com>
	<CALRAYNXOVLd8Ucp7sC09SGR+yvY1q8Opiye6fQX9qqKFiUwxcA@mail.gmail.com>
Message-ID: <201305252136.52615.tjhanson@yahoo.com>

On Saturday, May 25, 2013 09:10:00 pm Jim Mooney wrote:
> On 25 May 2013 20:49, Tim Hanson <tjhanson at yahoo.com> wrote:
> > A lot of people tend to be intimidated by Mark Lutz, and so am I, I
> > guess.
> 
> Interesting coincidence. This is a retirement project and I just
> decided on the Lutz book, which looked comprehensive, since the book
> I'm using is more CompSci but PyDeficient. However, the 4th edition I
> of Lutz that I got only goes up to Py 2.6.
> 
> As a general question - is there any Big difference between 2.6 and
> 2.7 (the Py version I'm using) that I should look out for so I don't
> get tripped up?
> 
> Jim Mooney

Don't know.  I'm reading the Kindle version that covers 3.0; before that I was 
playing with 2.6.  Ubuntu had 3.1 in the repository, so I downloaded that, and 
that's what I'm using.

From eryksun at gmail.com  Sun May 26 06:39:36 2013
From: eryksun at gmail.com (eryksun)
Date: Sun, 26 May 2013 00:39:36 -0400
Subject: [Tutor] Fwd: Difference between types
In-Reply-To: <knqk5n$nep$2@ger.gmane.org>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
	<CACL+1auT4ZKdY+zZRu_Mbv2yQ33u2tsvmw9eEe-+8NKZYQuPdQ@mail.gmail.com>
	<1369421613.60441.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<519FBB43.8040501@davea.name>
	<1369486458.39725.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<51A0D123.2090903@davea.name> <knqk5n$nep$2@ger.gmane.org>
Message-ID: <CACL+1atjDy2SmJKo-AAWd_5jJ5Q9sVEVgCL4XXzb6CcgZcUmzw@mail.gmail.com>

On Fri, May 24, 2013 at 2:53 PM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
> Why do I need to use a trailing comma to create a singleton
> tuple? Without a comma it seems to mean "parenthesized single
> object", ie the parentheses are basically not there.

Here are some technical notes and references to augment the other
answers. I think this is on topic in this thread. Even though the
title is "Difference between types", I think Citizen Kant is mostly
concerned with tokenizing and parsing source code.

Python 3.3's grammar definition:

http://hg.python.org/cpython/file/3.3/Grammar/Grammar

Here's an incomplete subset:

  power: atom trailer* ['**' factor]
  factor: ('+'|'-'|'~') factor | power
  term: factor (('*'|'/'|'%'|'//') factor)*
  arith_expr: term (('+'|'-') term)*
  shift_expr: arith_expr (('<<'|'>>') arith_expr)*
  and_expr: shift_expr ('&' shift_expr)*
  xor_expr: and_expr ('^' and_expr)*
  expr: xor_expr ('|' xor_expr)*
  star_expr: '*' expr

  comp_op:
    '<'|'>'|'=='|'>='|'<='|'<>'|'!='|
    'in'|'not' 'in'|'is'|'is' 'not'

  comparison: expr (comp_op expr)*
  not_test: 'not' not_test | comparison
  and_test: not_test ('and' not_test)*
  or_test: and_test ('or' and_test)*
  test:
    or_test ['if' or_test 'else' test] | lambdef

  testlist:
    test (',' test)* [',']

  exprlist:
    (expr|star_expr) (',' (expr|star_expr))* [',']

  testlist_comp:
    (test|star_expr) (
      comp_for | (',' (test|star_expr))* [','] )

  atom:
    ('(' [yield_expr|testlist_comp] ')' |
     '[' [testlist_comp] ']' |
     '{' [dictorsetmaker] '}' |
     NAME | NUMBER | STRING+ |
     '...' | 'None' | 'True' | 'False')

  augassign:
    ('+=' | '-=' | '*=' | '/=' | '%=' |
     '&=' | '|=' | '^=' | '<<=' | '>>=' |
     '**=' | '//=')

  testlist_star_expr:
    (test|star_expr) (',' (test|star_expr))* [',']

  expr_stmt:
    testlist_star_expr (
      augassign (yield_expr|testlist) |
      ('=' (yield_expr|testlist_star_expr))*)

  pass_stmt: 'pass'

  small_stmt:
    (expr_stmt | del_stmt | pass_stmt | flow_stmt |
     import_stmt | global_stmt | nonlocal_stmt |
     assert_stmt)

  simple_stmt:
    small_stmt (';' small_stmt)* [';'] NEWLINE

  suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT

  for_stmt:
    'for' exprlist 'in' testlist ':' suite ['else' ':' suite]

  compound_stmt:
    if_stmt | while_stmt | for_stmt | try_stmt |
    with_stmt | funcdef | classdef | decorated

  stmt:
    simple_stmt | compound_stmt

  eval_input:
    testlist NEWLINE* ENDMARKER

  file_input:
    (NEWLINE | stmt)* ENDMARKER

  single_input:
    NEWLINE | simple_stmt | compound_stmt NEWLINE

A possible match for atom is a set of empty parentheses, which defines
an empty tuple. Another match is a testlist_comp in parentheses. In
this case, if there's only one test/star_expr, then a trailing comma
is required to define a tuple.

The final parse tree depends on where you "start". For example, the
interactive shell uses single_input mode, so it looks for either
NEWLINE (i.e. you hit <enter> at a blank prompt), a simple_stmt, or
compound_stmt NEWLINE. If you enter a compound statement such as a
for_stmt, you have to hit enter on an empty line in order to finish
parsing, compile, and execute the statement. Note also that eval('')
is a syntax error because there's nothing to match testlist in
eval_input mode.

The parser start constants are defined in Include/graminit.h:

    #define single_input 256
    #define file_input 257
    #define eval_input 258

The corresponding C API constants are defined in Include/compile.h:

    #define Py_single_input 256
    #define Py_file_input 257
    #define Py_eval_input 258

For the built-in compile() function these constants map to the modes
'single', 'exec', and 'eval'.

The parser module has a couple of functions that create syntax trees:
parser.expr (eval_input mode) and parser.suite (file_input mode). The
resulting st objects have tolist() and totuple() methods, but the
resulting nested sequences of numeric constants aren't all that
helpful for interactive inspection. I scribbled a little code to
pretty print them using the corresponding names from the tokenize and
symbol modules.

    import parser
    from pprint import pprint
    from tokenize import tok_name
    from symbol import sym_name

    stnames = dict(tok_name)
    stnames.update(sym_name)

    def stnumtoname(st):
        if isinstance(st, parser.STType):
            st = st.tolist()
        stnew = [stnames[st[0]]]
        for item in st[1:]:
            if isinstance(item, (list, tuple)):
                stnew.append(stnumtoname(item))
            elif isinstance(item, int):
                stnew.append(stnames[item])
            else:
                stnew.append(item)
        return stnew

    def pprintst(st, **kwds):
        if 'width' not in kwds:
            kwds['width'] = 60
        pprint(stnumtoname(st), **kwds)


Here's an example tree for the compound statement "for i in (0,): pass":

    >>> pprintst(parser.suite('for i in (0,): pass'))
    ['file_input',
     ['stmt',
      ['compound_stmt',
       ['for_stmt',
        ['NAME', 'for'],
        ['exprlist',
         ['expr',
          ['xor_expr',
           ['and_expr',
            ['shift_expr',
             ['arith_expr',
              ['term',
               ['factor',
                ['power', ['atom', ['NAME', 'i']]]]]]]]]]],
        ['NAME', 'in'],
        ['testlist',
         ['test',
          ['or_test',
           ['and_test',
            ['not_test',
             ['comparison',
              ['expr',
               ['xor_expr',
                ['and_expr',
                 ['shift_expr',
                  ['arith_expr',
                   ['term',
                    ['factor',
                     ['power',
                      ['atom',
                       ['LPAR', '('],
                       ['testlist_comp',
                        ['test',
                         ['or_test',
                          ['and_test',
                           ['not_test',
                            ['comparison',
                             ['expr',
                              ['xor_expr',
                               ['and_expr',
                                ['shift_expr',
                                 ['arith_expr',
                                  ['term',
                                   ['factor',
                                    ['power',
                                     ['atom',
                                      ['NUMBER',
                                       '0']]]]]]]]]]]]]]],
                        ['COMMA', ',']],
                       ['RPAR', ')']]]]]]]]]]]]]]]],
        ['COLON', ':'],
        ['suite',
         ['simple_stmt',
          ['small_stmt', ['pass_stmt', ['NAME', 'pass']]],
          ['NEWLINE', '']]]]]],
     ['NEWLINE', ''],
     ['ENDMARKER', '']]


If you have a debug build of CPython, use the -d command-line option
to see the parser at work. For example here's the [abridged] output
for parsing "(0,)":

    >>> (0,)
    Token LPAR/'(' ... It's a token we know
     DFA 'single_input', state 0: Push ...
     DFA 'simple_stmt', state 0: Push ...
     DFA 'small_stmt', state 0: Push ...
     DFA 'expr_stmt', state 0: Push ...
     DFA 'testlist_star_expr', state 0: Push ...
     DFA 'test', state 0: Push ...
    [snip]
     DFA 'atom', state 0: Shift.

    Token NUMBER/'0' ... It's a token we know
     DFA 'atom', state 1: Push ...
     DFA 'testlist_comp', state 0: Push ...
     DFA 'test', state 0: Push ...
    [snip]
     DFA 'atom', state 0: Shift.
      DFA 'atom', state 4: Direct pop.

    Token COMMA/',' ... It's a token we know
     DFA 'power', state 1: Pop ...
     DFA 'factor', state 2: Pop ...
    [snip]
     DFA 'test', state 1: Pop ...
     DFA 'testlist_comp', state 1: Shift.
    Token RPAR/')' ... It's a token we know
     DFA 'testlist_comp', state 3: Pop ...
     DFA 'atom', state 6: Shift.
      DFA 'atom', state 4: Direct pop.

    Token NEWLINE/'' ... It's a token we know
     DFA 'power', state 1: Pop ...
    [snip]
     DFA 'test', state 1: Pop ...
     DFA 'testlist_star_expr', state 1: Pop ...
     DFA 'expr_stmt', state 1: Pop ...
     DFA 'small_stmt', state 1: Pop ...
     DFA 'simple_stmt', state 1: Shift.
      DFA 'simple_stmt', state 3: Direct pop.
      DFA 'single_input', state 1: Direct pop.
      ACCEPT.
    (0,)

The concrete syntax tree is only the first stage. The next step is to
transform the CST into an AST (abstract syntax tree), constructed
according to the following abstract syntax description (ASDL):

http://hg.python.org/cpython/file/3.3/Parser/Python.asdl

Use ast.parse() and ast.dump() to build and inspect the AST for source
code (it defaults to 'exec' mode):

    >>> print(ast.dump(ast.parse('for i in (0,): pass')))
    Module(body=[For(target=Name(id='i', ctx=Store()),
    iter=Tuple(elts=[Num(n=0)], ctx=Load()),
    body=[Pass()], orelse=[])])

From marc.tompkins at gmail.com  Sun May 26 09:57:15 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Sun, 26 May 2013 00:57:15 -0700
Subject: [Tutor] keyboard interrupt
In-Reply-To: <51A01FC4.8050104@pearwood.info>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
	<CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
	<CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
	<CACL+1avQpoAHPVj-nMCGmJ_4QvEhSXTK3KeEJwMkPCSdQhsi6g@mail.gmail.com>
	<CALRAYNUphqUGCtSbfa3G-m=Gm8=3bALuD7Uz+nE9oH8O3L9BhQ@mail.gmail.com>
	<CACL+1avETMJq1R5qdcwbN_+mbPpc5Q4zNuonBtM5BKDF2w2tFg@mail.gmail.com>
	<CALRAYNVQt7a+QUzHhBQRcf=H5KPmG866bAE8LnshF791BMroPA@mail.gmail.com>
	<519E9DB2.5000205@pearwood.info>
	<CAKK8jXYVqC68O3yyxd3DpjiGn0iyb_PquVgV8=hj3Vt6OthKxw@mail.gmail.com>
	<51A01FC4.8050104@pearwood.info>
Message-ID: <CAKK8jXY=Q=3jDKK+xr9gnDt0KiU4PXXp=_VrQe2sVJ6zJNudzw@mail.gmail.com>

On Fri, May 24, 2013 at 7:19 PM, Steven D'Aprano <steve at pearwood.info>wrote:

You can edit *other* people's questions and answers??!??!??
>
> What. The. Hell.


The idea is to build an authoritative information resource (in particular,
the goal is that the accepted answer to any given question will become the
primary result for someone Googling that same question.)  So it makes very
good sense that both questions and answers can be edited for quality, and
the result is (mostly) good.

My objection is to people gaming the system - making imperceptible edits
like dashes-to-em-dashes - in order to juice their scores.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130526/bf65d486/attachment.html>

From steve at pearwood.info  Sun May 26 10:14:42 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 26 May 2013 18:14:42 +1000
Subject: [Tutor] Fwd: Difference between types
In-Reply-To: <CAMbF=C_-zCSG=FJaOWdx9rd0VSDsA94QwiS0w_5skVcxQ-L0Fg@mail.gmail.com>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
	<519F684D.9080106@pearwood.info>
	<CAMbF=C_-zCSG=FJaOWdx9rd0VSDsA94QwiS0w_5skVcxQ-L0Fg@mail.gmail.com>
Message-ID: <51A1C472.1020007@pearwood.info>

On 25/05/13 02:52, Citizen Kant wrote:
> When I say "coding", anyone can think about what coding is
> in his own daily work, but that's not my way.
> I'll try to refine the concept: right now I'm learning,
> if I say "coding" I refer to what I type inside
> my file named learningpythoncode.py that,
> believe it or not, starts with:
>
> # """After the hash can go my comment.
> That's the first thing I've learned, and it's useful since
> this way I don't feel like as don't knowing any language
> at all. This is part of the code that Python doesn't
> compute, but this isn't less code.
>
> Since I am using the triple quotation, I can continue:

That actually doesn't work. Because you start the first line with a hash mark # Python treats that line as a comment, including the triple-quote marks. That means that the next line will give you a SyntaxError:


py> # """This is not a triple-string
... even though it starts with a """
   File "<stdin>", line 2
     even though it starts with a """
               ^
SyntaxError: invalid syntax


When you use # for comments, each line must begin with a # mark.

Alternatively, you can use strings as pseudo-comments, including triple-quoted (multi-line) strings. Using strings is special. If the first line of code in a module, or a class, or a function, is a string, it gets turned into a "docstring" (documentation string). Python copies it into a special __doc__ attribute of the module (or class, or function) where it can be accessed as documentation.

Otherwise, a bare string has no effect in your code, since it's just data, never touched, never used, it doesn't do anything. That makes it a def facto comment. In fact, the standard, reference implementation of Python, (so-called) CPython, treats such bare strings as comments and drops them from the code when compiling it. (But even if it didn't, it would still be an effective comment, since it has no effect.)

[...]
> Then I consider to code another value, like A, that looks like if
> cannot be reduced by rewriting any further but I arrived
> to the fact that Python doesn't consider those characters like A
> as able to take part in its computations until I put them between
> apostrophes or quotation marks."""

Not at all. If you actually try it, you will see that Python *can* use a character like A as part of its computations. It is a *name*, and when you refer to it, Python tries to look up the value of A and fails, so you get an error:

py> A
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'A' is not defined


Python even tells you *exactly* what the problem is, if you read the error message:

- it is an error to do with names, NameError;

- specifically the name A is not defined, so there is no value to retrieve.


So we can fix this:

py> A = 9
py> A
9


This is where the English language is ambiguous. If I talk about A, am I talking about the *name* A or the *value* of A (in this case, 9)? The convention *when writing English* is to say that referring to A alone means we care about the value, and if we want to refer to the name specifically, we put it in quotation marks, 'A'.

This is unfortunately still ambiguous, since it isn't clear whether 'A' refers to the name or the letter of the alphabet, or perhaps quoting somebody. But in context, it is usually clear.

By analogy: consider the difference between the current Queen of England, and the hereditary position of Queen of England. The "value" (a person) of "the Queen of England" is currently Her Majesty Elizabeth II, an actual person, but the position itself is more abstract, and has been held by many different people, such as Queen Elizabeth I and Queen Victoria, and sometimes not held at all.

(When the ruling monarch is a man, his wife, if any, is the Queen Consort, not the Queen. And the widow of a deceased King is the Dowager Queen, or in the case of the late mother to Queen Elizabeth, Queen Elizabeth the Queen Mother. And of course the rules are different in other countries. Aren't titles fun?)

If Great Britain becomes a republic and abolishes the monarchy, she would presumably either take the surname of her husband, and become Elizabeth Mountbatten, or she would take on the name of the Royal House, and become Elizabeth Windsor.

To put this in Python terms, we might decide that the name "queen" was to refer to the current Queen of England. So:


# Elizabeth ascends to the throne.
queen = "Elizabeth Alexandra Mary"

# Should she abdicate or die, there is no longer a
# ruling queen, but the position remains.
queen = None

# If Great Britain abolishes the monarchy,
# even the position goes away.
liz_mountbatten = queen
del queen


So we can talk about the *name* (variable) "queen", or the *value* queen.



> 'A' # """ I put A between apostrophes and it suddenly turned to something
> that cannot be reduced by rewriting any further,
> or unless that seems to me.
> I thought: if one can turn to value anything by putting it between
> apostrophes or quotation marks, then the trick must be in the
> pair of apostrophes or quotation marks.

No, it is not that you are turning it into a value by putting it between quotation marks, but that you are turning it into a literal string. Strings are just one type of many, many different sorts of values:

None  # a value representing nothingness
42  # a value representing the whole number between forty-one and forty-three
[]  # a value representing an empty list
[42, 23]  # a value representing a list with two values



[...]
> Then any other Python keyword, (def for example) comes to be a
> built-in value since it's (so to speak) built-in
> assigned to one of the above values, or assigned to a name
> that was previously assigned to one of the above values.

No, def is not a value. def is a keyword, that is, a mere part of the language itself, not a value which can be operated on within the language. You can't have a def on its own, that gives a SyntaxError:

py> def
   File "<stdin>", line 1
     def
       ^
SyntaxError: invalid syntax


Nor can you bind the alleged value def to a name:

py> a = def
   File "<stdin>", line 1
     a = def
           ^
SyntaxError: invalid syntax


Of course you can create a string "def", consisting of the three letters d e and f, by putting quotation marks around it, but that's a completely different thing.




-- 
Steven

From steve at pearwood.info  Sun May 26 10:34:57 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 26 May 2013 18:34:57 +1000
Subject: [Tutor] keyboard interrupt
In-Reply-To: <CAKK8jXY=Q=3jDKK+xr9gnDt0KiU4PXXp=_VrQe2sVJ6zJNudzw@mail.gmail.com>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
	<CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
	<CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
	<CACL+1avQpoAHPVj-nMCGmJ_4QvEhSXTK3KeEJwMkPCSdQhsi6g@mail.gmail.com>
	<CALRAYNUphqUGCtSbfa3G-m=Gm8=3bALuD7Uz+nE9oH8O3L9BhQ@mail.gmail.com>
	<CACL+1avETMJq1R5qdcwbN_+mbPpc5Q4zNuonBtM5BKDF2w2tFg@mail.gmail.com>
	<CALRAYNVQt7a+QUzHhBQRcf=H5KPmG866bAE8LnshF791BMroPA@mail.gmail.com>
	<519E9DB2.5000205@pearwood.info>
	<CAKK8jXYVqC68O3yyxd3DpjiGn0iyb_PquVgV8=hj3Vt6OthKxw@mail.gmail.com>
	<51A01FC4.8050104@pearwood.info>
	<CAKK8jXY=Q=3jDKK+xr9gnDt0KiU4PXXp=_VrQe2sVJ6zJNudzw@mail.gmail.com>
Message-ID: <51A1C931.2020104@pearwood.info>

On 26/05/13 17:57, Marc Tompkins wrote:
> On Fri, May 24, 2013 at 7:19 PM, Steven D'Aprano <steve at pearwood.info>wrote:
>
> You can edit *other* people's questions and answers??!??!??
>>
>> What. The. Hell.
>
>
> The idea is to build an authoritative information resource (in particular,
> the goal is that the accepted answer to any given question will become the
> primary result for someone Googling that same question.)  So it makes very
> good sense that both questions and answers can be edited for quality, and
> the result is (mostly) good.

That's all very well and good when you're dealing with a system like Wikipedia, where edits belong to the entire community, not the person who merely made the edit. But Stackoverflow is specifically in the form of Question/Answer, where both questions and answers are labelled as belonging to the person who made them. Stackoverflow has the form of a conversation, with questions and *replies*. How can you judge the quality of a response when you cannot be sure that the question you are reading is the same question that was answered? Your reputation depends on the relevance of your reply. Change the question, and your perfectly sensible, helpful reply may look like an idiot's waffling:


Q: How do I sort a list without using any built-in functions or methods?
A: Start at this Wikipedia page, where many different sort-algorithms are listed.


# Question gets edited.
Q: How do I count the number of 0's, 1's and 2's in a list without using any built-in functions or methods?
A: Start at this Wikipedia page, where many different sort-algorithms are listed.


And now I look like a first degree moron. By the way, I am not making this scenario up. Read this thread starting here:

http://mail.python.org/pipermail/python-list/2013-May/647400.html


> My objection is to people gaming the system - making imperceptible edits
> like dashes-to-em-dashes - in order to juice their scores.

So these edits aren't default-deny, but default-accept? Worse and worse.




-- 
Steven

From c.t.matsumoto at gmail.com  Sun May 26 10:57:11 2013
From: c.t.matsumoto at gmail.com (Todd Matsumoto)
Date: Sun, 26 May 2013 10:57:11 +0200
Subject: [Tutor] Flip the coin 10x and count heads and tails: It works
	now!
In-Reply-To: <51A0B902.8030903@pearwood.info>
References: <CAM-E2X6k+H4=6XcUMLXzpRsEM2Pc0YacTPMK30TOwnLtHZWyPQ@mail.gmail.com>
	<51A0B902.8030903@pearwood.info>
Message-ID: <CAD1ZssR3NKQZb_d62m=xtCoJ_W7V3J2Gu3bcHWok5rRJ=1bsuA@mail.gmail.com>

May I suggest running randint using 0, 1. The results can be tested like a
boolean. See what happens when you do an if test on 1 versus an if test on
0.

Also perhaps store your results in a dictionary with 'heads', 'tails' each
value set to 0.


On Sat, May 25, 2013 at 3:13 PM, Steven D'Aprano <steve at pearwood.info>wrote:

> On 25/05/13 19:25, Rafael Knuth wrote:
>
>  flips = 0
>> heads = 0
>> tails = 0
>>
>> while flips < 10:
>>      flips = flips + 1
>>
>
> Don't do this. It's not 1971 any more, we've had for loops for forty years
> :-)
>
> Use while loops when you don't know how many loops you need. When you know
> how many loops you will have, use a for loop.
>
> for flip in range(10):
>     print(flip)
>
> will print 0 1 2 3 ... 9 which makes ten loops altogether. If you want to
> start counting at 1 instead of 0, use:
>
> for flip in range(1, 11):
>     print(flip)
>
> which will print 1 2 3 ... 9 10.
>
>
> There's no need to count the number of heads and tails separately, since
> every loop is guaranteed to give either head or tails. So just count the
> number of heads, then the number of tails will be ten less the number of
> heads.
>
>
>
>
> --
> Steven
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>



-- 
Todd Matsumoto
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130526/957b0f23/attachment-0001.html>

From breamoreboy at yahoo.co.uk  Sun May 26 11:51:15 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sun, 26 May 2013 10:51:15 +0100
Subject: [Tutor] making a string
In-Reply-To: <CALRAYNXOVLd8Ucp7sC09SGR+yvY1q8Opiye6fQX9qqKFiUwxcA@mail.gmail.com>
References: <201305252007.43454.tjhanson@yahoo.com>
	<alpine.LNX.2.00.1305252315230.3324@octothorpe.wonderfrog.net>
	<201305252049.09733.tjhanson@yahoo.com>
	<CALRAYNXOVLd8Ucp7sC09SGR+yvY1q8Opiye6fQX9qqKFiUwxcA@mail.gmail.com>
Message-ID: <knsltu$328$1@ger.gmane.org>

On 26/05/2013 05:10, Jim Mooney wrote:
> On 25 May 2013 20:49, Tim Hanson <tjhanson at yahoo.com> wrote:
>
>> A lot of people tend to be intimidated by Mark Lutz, and so am I, I guess.
>
> Interesting coincidence. This is a retirement project and I just
> decided on the Lutz book, which looked comprehensive, since the book
> I'm using is more CompSci but PyDeficient. However, the 4th edition I
> of Lutz that I got only goes up to Py 2.6.
>
> As a general question - is there any Big difference between 2.6 and
> 2.7 (the Py version I'm using) that I should look out for so I don't
> get tripped up?
>
> Jim Mooney

Basically no.  Python 2.7 is guaranteed to be backward compatible with 
Python 2.6.  New or improved functionality will be listed in the "What's 
New for Python 2.7".  In fact if you look at the "What's New for Python 
3.3" you'll find all of the "What's New" going back to Python 2.0.  See 
this http://docs.python.org/3/whatsnew/index.html.

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From eryksun at gmail.com  Sun May 26 15:17:46 2013
From: eryksun at gmail.com (eryksun)
Date: Sun, 26 May 2013 09:17:46 -0400
Subject: [Tutor] keyboard interrupt
In-Reply-To: <51A1C931.2020104@pearwood.info>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
	<CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
	<CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
	<CACL+1avQpoAHPVj-nMCGmJ_4QvEhSXTK3KeEJwMkPCSdQhsi6g@mail.gmail.com>
	<CALRAYNUphqUGCtSbfa3G-m=Gm8=3bALuD7Uz+nE9oH8O3L9BhQ@mail.gmail.com>
	<CACL+1avETMJq1R5qdcwbN_+mbPpc5Q4zNuonBtM5BKDF2w2tFg@mail.gmail.com>
	<CALRAYNVQt7a+QUzHhBQRcf=H5KPmG866bAE8LnshF791BMroPA@mail.gmail.com>
	<519E9DB2.5000205@pearwood.info>
	<CAKK8jXYVqC68O3yyxd3DpjiGn0iyb_PquVgV8=hj3Vt6OthKxw@mail.gmail.com>
	<51A01FC4.8050104@pearwood.info>
	<CAKK8jXY=Q=3jDKK+xr9gnDt0KiU4PXXp=_VrQe2sVJ6zJNudzw@mail.gmail.com>
	<51A1C931.2020104@pearwood.info>
Message-ID: <CACL+1auVcHs2bBAM_B-YECxc8P16bi0=xA-PsskYggpN=jJ_Og@mail.gmail.com>

On Sun, May 26, 2013 at 4:34 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>
> So these edits aren't default-deny, but default-accept? Worse and worse.

It shows who made the edit and when they edited it, which links to the
revision history. When a question is closed it shows who voted to
close it. Even retagging shows up in the revision history. Also, since
it requires a rep of 2000 to edit, generally the system isn't abused.
Lower-rep users can suggest an edit, but that goes through a review
process.

You're notified when someone edits your answer, and you can roll it
back to a previous version. However, too many edits causes your post
to become community wiki (I think 10 edits by the owner or edits by 5
different users). An answer marked community wiki will no longer earn
reputation from up votes, and users with a rep of only 100 have edit
privileges.

From cybervigilante at gmail.com  Sun May 26 23:40:24 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sun, 26 May 2013 14:40:24 -0700
Subject: [Tutor] making a string
In-Reply-To: <knsltu$328$1@ger.gmane.org>
References: <201305252007.43454.tjhanson@yahoo.com>
	<alpine.LNX.2.00.1305252315230.3324@octothorpe.wonderfrog.net>
	<201305252049.09733.tjhanson@yahoo.com>
	<CALRAYNXOVLd8Ucp7sC09SGR+yvY1q8Opiye6fQX9qqKFiUwxcA@mail.gmail.com>
	<knsltu$328$1@ger.gmane.org>
Message-ID: <CALRAYNW3UuW3fDDp60OMUDY37VJevUM7eKSkzw=uec6s7WQO1w@mail.gmail.com>

On 26 May 2013 02:51, Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:
> Basically no.  Python 2.7 is guaranteed to be backward compatible with
> Python 2.6.  New or improved functionality will be listed in the "What's New
> for Python 2.7".  In fact if you look at the "What's New for Python 3.3"
> you'll find all of the "What's New" going back to Python 2.0.  See this
> http://docs.python.org/3/whatsnew/index.html.

That's a relief. I started with Py 3.3, realized a lot of stuff wasn't
there for it yet, regressed to 2.7, but still write "input" instead of
"raw_input" now and then, producing an error I think is mine until I
see what I did ;')  "raw_input" is such an awkwardness for a very
common use, that I'm surprised it was there in the first place.

Incidentally, I was figuring how to use compile for multi line
statements since the example I saw was a single line, compiled a small
multi-line routine nicely, and realized I had just compiled a  bad
syntax error. I was trying to iterate an integer.

Good to know that compile doesn't check syntax, since I erroneously
thought it did.

-- 
Jim Mooney

There are those who see.
Those who see when they are shown.
And those who do not see.
                         -- Leonardo da Vinci

From breamoreboy at yahoo.co.uk  Mon May 27 00:03:43 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sun, 26 May 2013 23:03:43 +0100
Subject: [Tutor] making a string
In-Reply-To: <CALRAYNW3UuW3fDDp60OMUDY37VJevUM7eKSkzw=uec6s7WQO1w@mail.gmail.com>
References: <201305252007.43454.tjhanson@yahoo.com>
	<alpine.LNX.2.00.1305252315230.3324@octothorpe.wonderfrog.net>
	<201305252049.09733.tjhanson@yahoo.com>
	<CALRAYNXOVLd8Ucp7sC09SGR+yvY1q8Opiye6fQX9qqKFiUwxcA@mail.gmail.com>
	<knsltu$328$1@ger.gmane.org>
	<CALRAYNW3UuW3fDDp60OMUDY37VJevUM7eKSkzw=uec6s7WQO1w@mail.gmail.com>
Message-ID: <knu0rf$egq$1@ger.gmane.org>

On 26/05/2013 22:40, Jim Mooney wrote:
> On 26 May 2013 02:51, Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:
>> Basically no.  Python 2.7 is guaranteed to be backward compatible with
>> Python 2.6.  New or improved functionality will be listed in the "What's New
>> for Python 2.7".  In fact if you look at the "What's New for Python 3.3"
>> you'll find all of the "What's New" going back to Python 2.0.  See this
>> http://docs.python.org/3/whatsnew/index.html.
>
> That's a relief. I started with Py 3.3, realized a lot of stuff wasn't
> there for it yet, regressed to 2.7, but still write "input" instead of
> "raw_input" now and then, producing an error I think is mine until I
> see what I did ;')  "raw_input" is such an awkwardness for a very
> common use, that I'm surprised it was there in the first place.
>
> Incidentally, I was figuring how to use compile for multi line
> statements since the example I saw was a single line, compiled a small
> multi-line routine nicely, and realized I had just compiled a  bad
> syntax error. I was trying to iterate an integer.
>
> Good to know that compile doesn't check syntax, since I erroneously
> thought it did.
>

You might like to know that it's possible to write code that's usable 
with both Python 2 and Python 3, see this for starters 
https://pypi.python.org/pypi/six/1.3.0.

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From marc.tompkins at gmail.com  Mon May 27 00:33:20 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Sun, 26 May 2013 15:33:20 -0700
Subject: [Tutor] keyboard interrupt
In-Reply-To: <CACL+1auVcHs2bBAM_B-YECxc8P16bi0=xA-PsskYggpN=jJ_Og@mail.gmail.com>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
	<CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
	<CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
	<CACL+1avQpoAHPVj-nMCGmJ_4QvEhSXTK3KeEJwMkPCSdQhsi6g@mail.gmail.com>
	<CALRAYNUphqUGCtSbfa3G-m=Gm8=3bALuD7Uz+nE9oH8O3L9BhQ@mail.gmail.com>
	<CACL+1avETMJq1R5qdcwbN_+mbPpc5Q4zNuonBtM5BKDF2w2tFg@mail.gmail.com>
	<CALRAYNVQt7a+QUzHhBQRcf=H5KPmG866bAE8LnshF791BMroPA@mail.gmail.com>
	<519E9DB2.5000205@pearwood.info>
	<CAKK8jXYVqC68O3yyxd3DpjiGn0iyb_PquVgV8=hj3Vt6OthKxw@mail.gmail.com>
	<51A01FC4.8050104@pearwood.info>
	<CAKK8jXY=Q=3jDKK+xr9gnDt0KiU4PXXp=_VrQe2sVJ6zJNudzw@mail.gmail.com>
	<51A1C931.2020104@pearwood.info>
	<CACL+1auVcHs2bBAM_B-YECxc8P16bi0=xA-PsskYggpN=jJ_Og@mail.gmail.com>
Message-ID: <CAKK8jXbDps_=P=aAcoCcekTvKFbYA9KLvkbqJbTaT1mYYCwxxw@mail.gmail.com>

On Sun, May 26, 2013 at 6:17 AM, eryksun <eryksun at gmail.com> wrote:

> On Sun, May 26, 2013 at 4:34 AM, Steven D'Aprano <steve at pearwood.info>
> wrote:
> >
> > So these edits aren't default-deny, but default-accept? Worse and worse.
>
> It shows who made the edit and when they edited it, which links to the
> revision history. When a question is closed it shows who voted to
> close it. Even retagging shows up in the revision history. Also, since
> it requires a rep of 2000 to edit, generally the system isn't abused.
> Lower-rep users can suggest an edit, but that goes through a review
> process.
>
> You're notified when someone edits your answer, and you can roll it
> back to a previous version. However, too many edits causes your post
> to become community wiki (I think 10 edits by the owner or edits by 5
> different users). An answer marked community wiki will no longer earn
> reputation from up votes, and users with a rep of only 100 have edit
> privileges.
>

Once again: I think that the end result (high-quality answers to relevant
questions) justifies a LOT of unpleasantness along the way; probably eight
times ought of ten that I Google a programming question, the best (and
often the first) answer ends up being on StackOverflow.  In general, the
process leads to good quality.  It just, unfortunately, lends itself to
reputation-gaming, and to useless users appearing far more prominent than
they should.  The actual damage that those parasites are able to do to the
ecosystem is limited, however... except that otherwise-motivated users
sometimes get irritated and drop out.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130526/c276e159/attachment.html>

From steve at pearwood.info  Mon May 27 02:20:25 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 27 May 2013 10:20:25 +1000
Subject: [Tutor] making a string
In-Reply-To: <CALRAYNW3UuW3fDDp60OMUDY37VJevUM7eKSkzw=uec6s7WQO1w@mail.gmail.com>
References: <201305252007.43454.tjhanson@yahoo.com>
	<alpine.LNX.2.00.1305252315230.3324@octothorpe.wonderfrog.net>
	<201305252049.09733.tjhanson@yahoo.com>
	<CALRAYNXOVLd8Ucp7sC09SGR+yvY1q8Opiye6fQX9qqKFiUwxcA@mail.gmail.com>
	<knsltu$328$1@ger.gmane.org>
	<CALRAYNW3UuW3fDDp60OMUDY37VJevUM7eKSkzw=uec6s7WQO1w@mail.gmail.com>
Message-ID: <51A2A6C9.9070405@pearwood.info>

On 27/05/13 07:40, Jim Mooney wrote:

> Good to know that compile doesn't check syntax, since I erroneously
> thought it did.

compile does check syntax.


py> compile("23 = 43", "", "exec")
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "", line 1
SyntaxError: can't assign to literal


The compile built-in function does the same as the Python compiler that compiles your code before you run it. It has three modes:

- "exec", which operates in the same way that Python compiles a module;

- "single", which operates in the same way that Python compiles a single statement in the interactive interpreter; and

- "eval", which tells Python that the code must be a single expression and not a statement or a block of code.



-- 
Steven

From cybervigilante at gmail.com  Mon May 27 02:25:02 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sun, 26 May 2013 17:25:02 -0700
Subject: [Tutor] keyboard interrupt
In-Reply-To: <CAKK8jXbDps_=P=aAcoCcekTvKFbYA9KLvkbqJbTaT1mYYCwxxw@mail.gmail.com>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
	<CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
	<CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
	<CACL+1avQpoAHPVj-nMCGmJ_4QvEhSXTK3KeEJwMkPCSdQhsi6g@mail.gmail.com>
	<CALRAYNUphqUGCtSbfa3G-m=Gm8=3bALuD7Uz+nE9oH8O3L9BhQ@mail.gmail.com>
	<CACL+1avETMJq1R5qdcwbN_+mbPpc5Q4zNuonBtM5BKDF2w2tFg@mail.gmail.com>
	<CALRAYNVQt7a+QUzHhBQRcf=H5KPmG866bAE8LnshF791BMroPA@mail.gmail.com>
	<519E9DB2.5000205@pearwood.info>
	<CAKK8jXYVqC68O3yyxd3DpjiGn0iyb_PquVgV8=hj3Vt6OthKxw@mail.gmail.com>
	<51A01FC4.8050104@pearwood.info>
	<CAKK8jXY=Q=3jDKK+xr9gnDt0KiU4PXXp=_VrQe2sVJ6zJNudzw@mail.gmail.com>
	<51A1C931.2020104@pearwood.info>
	<CACL+1auVcHs2bBAM_B-YECxc8P16bi0=xA-PsskYggpN=jJ_Og@mail.gmail.com>
	<CAKK8jXbDps_=P=aAcoCcekTvKFbYA9KLvkbqJbTaT1mYYCwxxw@mail.gmail.com>
Message-ID: <CALRAYNV9c0QnGbzaiED3WwYwA4Afh07uJMKBQP5gFOp6xm21Yg@mail.gmail.com>

On 26 May 2013 15:33, Marc Tompkins <marc.tompkins at gmail.com> wrote:
> On Sun, May 26, 2013 at 6:17 AM, eryksun <eryksun at gmail.com> wrote:

StackOverflow may be good but I just had an unpleasant experience
wanting to add New .py file to my Windows context menu. The first
advice I saw was missing a backslash and had me adding the string to
the wrong key. Thankfully, it didn't work and I figured out what was
wrong, so I now have New .py file ;')

Bad programming advice is bad enough, but putting up bad advice to
edit the Windows registry is Really, Really bad.

From eryksun at gmail.com  Mon May 27 02:31:57 2013
From: eryksun at gmail.com (eryksun)
Date: Sun, 26 May 2013 20:31:57 -0400
Subject: [Tutor] keyboard interrupt
In-Reply-To: <CALRAYNV9c0QnGbzaiED3WwYwA4Afh07uJMKBQP5gFOp6xm21Yg@mail.gmail.com>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
	<CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
	<CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
	<CACL+1avQpoAHPVj-nMCGmJ_4QvEhSXTK3KeEJwMkPCSdQhsi6g@mail.gmail.com>
	<CALRAYNUphqUGCtSbfa3G-m=Gm8=3bALuD7Uz+nE9oH8O3L9BhQ@mail.gmail.com>
	<CACL+1avETMJq1R5qdcwbN_+mbPpc5Q4zNuonBtM5BKDF2w2tFg@mail.gmail.com>
	<CALRAYNVQt7a+QUzHhBQRcf=H5KPmG866bAE8LnshF791BMroPA@mail.gmail.com>
	<519E9DB2.5000205@pearwood.info>
	<CAKK8jXYVqC68O3yyxd3DpjiGn0iyb_PquVgV8=hj3Vt6OthKxw@mail.gmail.com>
	<51A01FC4.8050104@pearwood.info>
	<CAKK8jXY=Q=3jDKK+xr9gnDt0KiU4PXXp=_VrQe2sVJ6zJNudzw@mail.gmail.com>
	<51A1C931.2020104@pearwood.info>
	<CACL+1auVcHs2bBAM_B-YECxc8P16bi0=xA-PsskYggpN=jJ_Og@mail.gmail.com>
	<CAKK8jXbDps_=P=aAcoCcekTvKFbYA9KLvkbqJbTaT1mYYCwxxw@mail.gmail.com>
	<CALRAYNV9c0QnGbzaiED3WwYwA4Afh07uJMKBQP5gFOp6xm21Yg@mail.gmail.com>
Message-ID: <CACL+1avxAJiPnrgjGyOE-cnuDOqVmeWFLS04HiUZ3FnhnJn2XA@mail.gmail.com>

On Sun, May 26, 2013 at 8:25 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
>
> StackOverflow may be good but I just had an unpleasant experience
> wanting to add New .py file to my Windows context menu. The first
> advice I saw was missing a backslash and had me adding the string to
> the wrong key. Thankfully, it didn't work and I figured out what was
> wrong, so I now have New .py file ;')
>
> Bad programming advice is bad enough, but putting up bad advice to
> edit the Windows registry is Really, Really bad.

Did you leave a comment with the correction?

From cybervigilante at gmail.com  Mon May 27 02:39:13 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sun, 26 May 2013 17:39:13 -0700
Subject: [Tutor] making a string
In-Reply-To: <51A2A6C9.9070405@pearwood.info>
References: <201305252007.43454.tjhanson@yahoo.com>
	<alpine.LNX.2.00.1305252315230.3324@octothorpe.wonderfrog.net>
	<201305252049.09733.tjhanson@yahoo.com>
	<CALRAYNXOVLd8Ucp7sC09SGR+yvY1q8Opiye6fQX9qqKFiUwxcA@mail.gmail.com>
	<knsltu$328$1@ger.gmane.org>
	<CALRAYNW3UuW3fDDp60OMUDY37VJevUM7eKSkzw=uec6s7WQO1w@mail.gmail.com>
	<51A2A6C9.9070405@pearwood.info>
Message-ID: <CALRAYNV3KSr4Y-6_dz-qY2Lue5igSHTiDXw5WH-1j_wwErg-Dw@mail.gmail.com>

On 26 May 2013 17:20, Steven D'Aprano <steve at pearwood.info> wrote:
> On 27/05/13 07:40, Jim Mooney wrote:
>
>> Good to know that compile doesn't check syntax, since I erroneously
>> thought it did.
>
>
> compile does check syntax.

I'm unclear on something. The code below creates bytecode and I don't
see an error message unless I also tack exec code on the end of it. It
has the dumb error of trying to iterate an integer.

from dis import dis

code = compile(
'''a, b = 5, 8
print a
print b
for x in a:
    print x
''','', 'exec'
)

dis(code)

Result below - bytecode but no error message
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)]
Type "help", "copyright", "credits" or "license" for more information.
[evaluate derek.py]
  1           0 LOAD_CONST               3 ((5, 8))
              3 UNPACK_SEQUENCE          2
              6 STORE_NAME               0 (a)
              9 STORE_NAME               1 (b)

  2          12 LOAD_NAME                0 (a)
             15 PRINT_ITEM
             16 PRINT_NEWLINE

  3          17 LOAD_NAME                1 (b)
             20 PRINT_ITEM
             21 PRINT_NEWLINE

  4          22 SETUP_LOOP              19 (to 44)
             25 LOAD_NAME                0 (a)
             28 GET_ITER
        >>   29 FOR_ITER                11 (to 43)
             32 STORE_NAME               2 (x)

  5          35 LOAD_NAME                2 (x)
             38 PRINT_ITEM
             39 PRINT_NEWLINE
             40 JUMP_ABSOLUTE           29
        >>   43 POP_BLOCK
        >>   44 LOAD_CONST               2 (None)
             47 RETURN_VALUE

If I add    exec code    to the end of that program I Do get an error,
after it prints a and b, but that's separate from the compile
statement:

exec code
Traceback (most recent call last):
  File "C:\Program Files (x86)\Wing IDE 101
4.1\src\debug\tserver\_sandbox.py", line 13, in <module>
  File "C:\Program Files (x86)\Wing IDE 101
4.1\src\debug\tserver\_sandbox.py", line 4, in <module>
    #print 'Exiting sandbox process'
TypeError: 'int' object is not iterable

From eryksun at gmail.com  Mon May 27 02:38:36 2013
From: eryksun at gmail.com (eryksun)
Date: Sun, 26 May 2013 20:38:36 -0400
Subject: [Tutor] making a string
In-Reply-To: <51A2A6C9.9070405@pearwood.info>
References: <201305252007.43454.tjhanson@yahoo.com>
	<alpine.LNX.2.00.1305252315230.3324@octothorpe.wonderfrog.net>
	<201305252049.09733.tjhanson@yahoo.com>
	<CALRAYNXOVLd8Ucp7sC09SGR+yvY1q8Opiye6fQX9qqKFiUwxcA@mail.gmail.com>
	<knsltu$328$1@ger.gmane.org>
	<CALRAYNW3UuW3fDDp60OMUDY37VJevUM7eKSkzw=uec6s7WQO1w@mail.gmail.com>
	<51A2A6C9.9070405@pearwood.info>
Message-ID: <CACL+1avd5Ddw3CoCbSr=A_eqM4r=G5Nv_18sfzUbUBQKurcG0g@mail.gmail.com>

On Sun, May 26, 2013 at 8:20 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On 27/05/13 07:40, Jim Mooney wrote:
>
>> Good to know that compile doesn't check syntax, since I erroneously
>> thought it did.
>
> compile does check syntax.

Attempting to iterate an integer is a runtime TypeError, not a
compile-time SyntaxError.

From cybervigilante at gmail.com  Mon May 27 02:43:09 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sun, 26 May 2013 17:43:09 -0700
Subject: [Tutor] making a string
In-Reply-To: <CACL+1avd5Ddw3CoCbSr=A_eqM4r=G5Nv_18sfzUbUBQKurcG0g@mail.gmail.com>
References: <201305252007.43454.tjhanson@yahoo.com>
	<alpine.LNX.2.00.1305252315230.3324@octothorpe.wonderfrog.net>
	<201305252049.09733.tjhanson@yahoo.com>
	<CALRAYNXOVLd8Ucp7sC09SGR+yvY1q8Opiye6fQX9qqKFiUwxcA@mail.gmail.com>
	<knsltu$328$1@ger.gmane.org>
	<CALRAYNW3UuW3fDDp60OMUDY37VJevUM7eKSkzw=uec6s7WQO1w@mail.gmail.com>
	<51A2A6C9.9070405@pearwood.info>
	<CACL+1avd5Ddw3CoCbSr=A_eqM4r=G5Nv_18sfzUbUBQKurcG0g@mail.gmail.com>
Message-ID: <CALRAYNU2FbkQ=0q1xCmY6QK_P48LnMdm8kr--949Rt7SgctCcw@mail.gmail.com>

On 26 May 2013 17:38, eryksun <eryksun at gmail.com> wrote:
> On Sun, May 26, 2013 at 8:20 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> On 27/05/13 07:40, Jim Mooney wrote:
>>
>>> Good to know that compile doesn't check syntax, since I erroneously
>>> thought it did.
>>
>> compile does check syntax.
>
> Attempting to iterate an integer is a runtime TypeError, not a
> compile-time SyntaxError.

Ah, that clears it up.

Jim

From cybervigilante at gmail.com  Mon May 27 02:47:16 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sun, 26 May 2013 17:47:16 -0700
Subject: [Tutor] keyboard interrupt
In-Reply-To: <CACL+1avxAJiPnrgjGyOE-cnuDOqVmeWFLS04HiUZ3FnhnJn2XA@mail.gmail.com>
References: <CALRAYNUVvUqetRz8nWwgn7+YXgzV9dt7TBSv1Fmgw4CCC+FEBQ@mail.gmail.com>
	<CAKK8jXY7CJKVt9Bj9YDHoGT7kECd9YMYpjmaMPNA1r4GUeKzvg@mail.gmail.com>
	<CALRAYNVsjFKNgHFfn1CwLhkQdjgc-1iZKe-KWBHJ2KBPyx23PQ@mail.gmail.com>
	<CALRAYNX7yUfEZZB2h84DT28j2fqj26GMbjP1k9bkHKe7EpMC3w@mail.gmail.com>
	<CACL+1avQpoAHPVj-nMCGmJ_4QvEhSXTK3KeEJwMkPCSdQhsi6g@mail.gmail.com>
	<CALRAYNUphqUGCtSbfa3G-m=Gm8=3bALuD7Uz+nE9oH8O3L9BhQ@mail.gmail.com>
	<CACL+1avETMJq1R5qdcwbN_+mbPpc5Q4zNuonBtM5BKDF2w2tFg@mail.gmail.com>
	<CALRAYNVQt7a+QUzHhBQRcf=H5KPmG866bAE8LnshF791BMroPA@mail.gmail.com>
	<519E9DB2.5000205@pearwood.info>
	<CAKK8jXYVqC68O3yyxd3DpjiGn0iyb_PquVgV8=hj3Vt6OthKxw@mail.gmail.com>
	<51A01FC4.8050104@pearwood.info>
	<CAKK8jXY=Q=3jDKK+xr9gnDt0KiU4PXXp=_VrQe2sVJ6zJNudzw@mail.gmail.com>
	<51A1C931.2020104@pearwood.info>
	<CACL+1auVcHs2bBAM_B-YECxc8P16bi0=xA-PsskYggpN=jJ_Og@mail.gmail.com>
	<CAKK8jXbDps_=P=aAcoCcekTvKFbYA9KLvkbqJbTaT1mYYCwxxw@mail.gmail.com>
	<CALRAYNV9c0QnGbzaiED3WwYwA4Afh07uJMKBQP5gFOp6xm21Yg@mail.gmail.com>
	<CACL+1avxAJiPnrgjGyOE-cnuDOqVmeWFLS04HiUZ3FnhnJn2XA@mail.gmail.com>
Message-ID: <CALRAYNVuciND3WNjaP4FdKTrHarEJBDPhfMEnFCzqCjXHk45JQ@mail.gmail.com>

>> Bad programming advice is bad enough, but putting up bad advice to
>> edit the Windows registry is Really, Really bad.
>
> Did you leave a comment with the correction?

Good point. I wasn't registered on that board but I should go find it.
Not that the mistype in that case could possibly cause a registry
crash. It just didn't work since a backslash in the path to
windows\shellnew was missing, probably due to typing too fast.

-- 
Jim Mooney

There are those who see.
Those who see when they are shown.
And those who do not see.
                         -- Leonardo da Vinci

From steve at pearwood.info  Mon May 27 03:06:35 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 27 May 2013 11:06:35 +1000
Subject: [Tutor] making a string
In-Reply-To: <CALRAYNU2FbkQ=0q1xCmY6QK_P48LnMdm8kr--949Rt7SgctCcw@mail.gmail.com>
References: <201305252007.43454.tjhanson@yahoo.com>
	<alpine.LNX.2.00.1305252315230.3324@octothorpe.wonderfrog.net>
	<201305252049.09733.tjhanson@yahoo.com>
	<CALRAYNXOVLd8Ucp7sC09SGR+yvY1q8Opiye6fQX9qqKFiUwxcA@mail.gmail.com>
	<knsltu$328$1@ger.gmane.org>
	<CALRAYNW3UuW3fDDp60OMUDY37VJevUM7eKSkzw=uec6s7WQO1w@mail.gmail.com>
	<51A2A6C9.9070405@pearwood.info>
	<CACL+1avd5Ddw3CoCbSr=A_eqM4r=G5Nv_18sfzUbUBQKurcG0g@mail.gmail.com>
	<CALRAYNU2FbkQ=0q1xCmY6QK_P48LnMdm8kr--949Rt7SgctCcw@mail.gmail.com>
Message-ID: <51A2B19B.5070502@pearwood.info>

On 27/05/13 10:43, Jim Mooney wrote:
> On 26 May 2013 17:38, eryksun <eryksun at gmail.com> wrote:
>> On Sun, May 26, 2013 at 8:20 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>>> On 27/05/13 07:40, Jim Mooney wrote:
>>>
>>>> Good to know that compile doesn't check syntax, since I erroneously
>>>> thought it did.
>>>
>>> compile does check syntax.
>>
>> Attempting to iterate an integer is a runtime TypeError, not a
>> compile-time SyntaxError.
>
> Ah, that clears it up.


Like most dynamic languages, Python's compiler checks very few things at compile time. In general, there is little that Python *can* check, not without actually running the code, so even when when Python *could* detect an error at compile time, it usually doesn't bother because the programming effort is too high for the benefit.



-- 
Steven

From sunithanc at gmail.com  Mon May 27 04:53:23 2013
From: sunithanc at gmail.com (Sunitha Misra)
Date: Sun, 26 May 2013 22:53:23 -0400
Subject: [Tutor] QT Python: How to re-use the return value of
 fileDialog.openFileName() ?
Message-ID: <CAOeFuMQYgG+obfqmaV6_fmx-_k0PQKuCH8UdNDt9s9=V_UGmaQ@mail.gmail.com>

tutor at python.org

Hello,
I am trying to write a UI for my utility, using QT-Python. I first launch a
GUI and click on a toolButton to open up the directory structure, from
which I select a particular file.

self.fileDialog = QtGui.QFileDialog()

QtCore.QObject.connect(self.toolButton,
QtCore.SIGNAL(_fromUtf8("clicked()")), self.fileDialog.getOpenFileName)

So far so good.

How do I store the return value of getOpenFileName?

For example, if I do the following, it gives error:
QtCore.QObject.connect(self.toolButton,
QtCore.SIGNAL(_fromUtf8("clicked()")),
(filepath=self.fileDialog.getOpenFileName))

The reason I want to store the return value is because I want to capture
the filename/path that getOpenFilename returned in a string so I can copy
it to a lineEdit space as below:

self.lineEdit.setText(filepath)

text = self.lineEdit.text()

(If I do the following, it will re-lauch the directory list), which I don't
want.
self.lineEdit.setText(self.fileDialog.getOpenFileName())

Thanks in advance.
SM
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130526/cd1527bc/attachment-0001.html>

From chigga101 at gmail.com  Mon May 27 12:01:31 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Mon, 27 May 2013 11:01:31 +0100
Subject: [Tutor] Fwd: QT Python: How to re-use the return value of
 fileDialog.openFileName() ?
In-Reply-To: <CACzNyA3njNL=WpGfB+i0nTq7=EP1Ki7tWOUVG9ds4_8z15CcOQ@mail.gmail.com>
References: <CAOeFuMQYgG+obfqmaV6_fmx-_k0PQKuCH8UdNDt9s9=V_UGmaQ@mail.gmail.com>
	<CACzNyA3njNL=WpGfB+i0nTq7=EP1Ki7tWOUVG9ds4_8z15CcOQ@mail.gmail.com>
Message-ID: <CACzNyA1=U_9WPG0wmP3ik_4SQosR9X3jxS=-dpWJNCs+sETNCQ@mail.gmail.com>

Sorry for the forward, i forgot to reply to tutor

On Mon, May 27, 2013 at 3:53 AM, Sunitha Misra <sunithanc at gmail.com> wrote:

> self.fileDialog = QtGui.QFileDialog()
>
> QtCore.QObject.connect(self.toolButton,
> QtCore.SIGNAL(_fromUtf8("clicked()")), self.fileDialog.getOpenFileName)
>

i think the way youre doing it won't allow you to get the filename as
you are calling it through a signal.

Things you can do:

1) dont use self.fileDialog.getOpenFileName as a slot like you are
doing. Create a function and call it when the toolbar's button is
clicked, then in that function assign the filename to the return value
of self.fileDialog.getOpenFileName.

2) if the only thing your self.fileDialog is doing is responding to
the toolbar's button, don't create it at all. do what i said in #1 and
assign a filename variable to the full method of the dialog. What im
saying is there might be no need to create the self.fileDialog
instance variable at all.

From sunithanc at gmail.com  Mon May 27 15:14:32 2013
From: sunithanc at gmail.com (SM)
Date: Mon, 27 May 2013 09:14:32 -0400
Subject: [Tutor] Fwd: QT Python: How to re-use the return value of
 fileDialog.openFileName() ?
In-Reply-To: <CACzNyA1=U_9WPG0wmP3ik_4SQosR9X3jxS=-dpWJNCs+sETNCQ@mail.gmail.com>
References: <CAOeFuMQYgG+obfqmaV6_fmx-_k0PQKuCH8UdNDt9s9=V_UGmaQ@mail.gmail.com>
	<CACzNyA3njNL=WpGfB+i0nTq7=EP1Ki7tWOUVG9ds4_8z15CcOQ@mail.gmail.com>
	<CACzNyA1=U_9WPG0wmP3ik_4SQosR9X3jxS=-dpWJNCs+sETNCQ@mail.gmail.com>
Message-ID: <CAOeFuMSf+pMgkKTAGLbhoDTmqB33tGhR0zTk8JTQhGzmHW7RWQ@mail.gmail.com>

Thanks!
I defined a function, as you suggested, to call when the button was
clicked. But then I also had to use self.fileDialog from within the
function. Not sure how I could avoid using fileDialog.

I also defined global variable (under the class) and assigned it to the
filename, so I could access it from within the main class.

The following works:

 QtCore.QObject.connect(self.toolButton,
QtCore.SIGNAL(_fromUtf8("clicked()")), self.getFileName)


 def getFileName(self):
        self.fileDialog = QtGui.QFileDialog()
        path = self.fileDialog.getOpenFileName()
        print(" File Selected: ", path)
        self.lineEdit.setText(path)
        self.XmlFileName = path


Thanks.


On Mon, May 27, 2013 at 6:01 AM, Matthew Ngaha <chigga101 at gmail.com> wrote:

> Sorry for the forward, i forgot to reply to tutor
>
> On Mon, May 27, 2013 at 3:53 AM, Sunitha Misra <sunithanc at gmail.com>
> wrote:
>
> > self.fileDialog = QtGui.QFileDialog()
> >
> > QtCore.QObject.connect(self.toolButton,
> > QtCore.SIGNAL(_fromUtf8("clicked()")), self.fileDialog.getOpenFileName)
> >
>
> i think the way youre doing it won't allow you to get the filename as
> you are calling it through a signal.
>
> Things you can do:
>
> 1) dont use self.fileDialog.getOpenFileName as a slot like you are
> doing. Create a function and call it when the toolbar's button is
> clicked, then in that function assign the filename to the return value
> of self.fileDialog.getOpenFileName.
>
> 2) if the only thing your self.fileDialog is doing is responding to
> the toolbar's button, don't create it at all. do what i said in #1 and
> assign a filename variable to the full method of the dialog. What im
> saying is there might be no need to create the self.fileDialog
> instance variable at all.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130527/6b886fa3/attachment.html>

From chigga101 at gmail.com  Mon May 27 15:45:04 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Mon, 27 May 2013 14:45:04 +0100
Subject: [Tutor] Fwd: QT Python: How to re-use the return value of
 fileDialog.openFileName() ?
In-Reply-To: <CAOeFuMSf+pMgkKTAGLbhoDTmqB33tGhR0zTk8JTQhGzmHW7RWQ@mail.gmail.com>
References: <CAOeFuMQYgG+obfqmaV6_fmx-_k0PQKuCH8UdNDt9s9=V_UGmaQ@mail.gmail.com>
	<CACzNyA3njNL=WpGfB+i0nTq7=EP1Ki7tWOUVG9ds4_8z15CcOQ@mail.gmail.com>
	<CACzNyA1=U_9WPG0wmP3ik_4SQosR9X3jxS=-dpWJNCs+sETNCQ@mail.gmail.com>
	<CAOeFuMSf+pMgkKTAGLbhoDTmqB33tGhR0zTk8JTQhGzmHW7RWQ@mail.gmail.com>
Message-ID: <CACzNyA0wBHquzc4T7wF0Kafdr0Qac3yyw8dY=yNbR8bZhJBtDQ@mail.gmail.com>

On Mon, May 27, 2013 at 2:14 PM, SM <sunithanc at gmail.com> wrote:

>But then I also had to use self.fileDialog from within the function. Not
> sure how I could avoid using fileDialog.
>
> Thanks.

No problem. to do it without the instance variable, you access its
method directly. so replace:

path = self.fileDialog.getOpenFileName()

with

path = QFileDialog.getOpenFileName(self)

which is basically the same thing except you're going to the method
directly instead of creating a class instance. The self argument may
or may not be needed, its been a while since ive used Qt.

From jacklittlemc at yahoo.com  Mon May 27 16:17:30 2013
From: jacklittlemc at yahoo.com (Jack Little)
Date: Mon, 27 May 2013 07:17:30 -0700 (PDT)
Subject: [Tutor] Buttons
Message-ID: <1369664250.95289.YahooMailNeo@web124502.mail.ne1.yahoo.com>

Is there a way to make buttons a little like a raw_input in the context when the user presses the button, the program performs a function?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130527/34b67fac/attachment.html>

From sunithanc at gmail.com  Mon May 27 16:22:23 2013
From: sunithanc at gmail.com (SM)
Date: Mon, 27 May 2013 10:22:23 -0400
Subject: [Tutor] Fwd: QT Python: How to re-use the return value of
 fileDialog.openFileName() ?
In-Reply-To: <CACzNyA0wBHquzc4T7wF0Kafdr0Qac3yyw8dY=yNbR8bZhJBtDQ@mail.gmail.com>
References: <CAOeFuMQYgG+obfqmaV6_fmx-_k0PQKuCH8UdNDt9s9=V_UGmaQ@mail.gmail.com>
	<CACzNyA3njNL=WpGfB+i0nTq7=EP1Ki7tWOUVG9ds4_8z15CcOQ@mail.gmail.com>
	<CACzNyA1=U_9WPG0wmP3ik_4SQosR9X3jxS=-dpWJNCs+sETNCQ@mail.gmail.com>
	<CAOeFuMSf+pMgkKTAGLbhoDTmqB33tGhR0zTk8JTQhGzmHW7RWQ@mail.gmail.com>
	<CACzNyA0wBHquzc4T7wF0Kafdr0Qac3yyw8dY=yNbR8bZhJBtDQ@mail.gmail.com>
Message-ID: <CAOeFuMSNQ9sDUP-sPGb7rtBHSsh-VgKaoDxfg-tY-v=YAT2rcw@mail.gmail.com>

Yes, the following works.
path = QtGui.QFileDialog.getOpenFileName()

Thanks!


On Mon, May 27, 2013 at 9:45 AM, Matthew Ngaha <chigga101 at gmail.com> wrote:

> On Mon, May 27, 2013 at 2:14 PM, SM <sunithanc at gmail.com> wrote:
>
> >But then I also had to use self.fileDialog from within the function. Not
> > sure how I could avoid using fileDialog.
> >
> > Thanks.
>
> No problem. to do it without the instance variable, you access its
> method directly. so replace:
>
> path = self.fileDialog.getOpenFileName()
>
> with
>
> path = QFileDialog.getOpenFileName(self)
>
> which is basically the same thing except you're going to the method
> directly instead of creating a class instance. The self argument may
> or may not be needed, its been a while since ive used Qt.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130527/07c03176/attachment.html>

From eryksun at gmail.com  Mon May 27 16:13:46 2013
From: eryksun at gmail.com (eryksun)
Date: Mon, 27 May 2013 10:13:46 -0400
Subject: [Tutor] Fwd: QT Python: How to re-use the return value of
 fileDialog.openFileName() ?
In-Reply-To: <CACzNyA0wBHquzc4T7wF0Kafdr0Qac3yyw8dY=yNbR8bZhJBtDQ@mail.gmail.com>
References: <CAOeFuMQYgG+obfqmaV6_fmx-_k0PQKuCH8UdNDt9s9=V_UGmaQ@mail.gmail.com>
	<CACzNyA3njNL=WpGfB+i0nTq7=EP1Ki7tWOUVG9ds4_8z15CcOQ@mail.gmail.com>
	<CACzNyA1=U_9WPG0wmP3ik_4SQosR9X3jxS=-dpWJNCs+sETNCQ@mail.gmail.com>
	<CAOeFuMSf+pMgkKTAGLbhoDTmqB33tGhR0zTk8JTQhGzmHW7RWQ@mail.gmail.com>
	<CACzNyA0wBHquzc4T7wF0Kafdr0Qac3yyw8dY=yNbR8bZhJBtDQ@mail.gmail.com>
Message-ID: <CACL+1auatMajgPOvtQZr-b=uPsY4CRjm_=9sSeC8P5nto05pVQ@mail.gmail.com>

On Mon, May 27, 2013 at 9:45 AM, Matthew Ngaha <chigga101 at gmail.com> wrote:
> On Mon, May 27, 2013 at 2:14 PM, SM <sunithanc at gmail.com> wrote:
>
>>But then I also had to use self.fileDialog from within the function. Not
>> sure how I could avoid using fileDialog.
>>
>
> No problem. to do it without the instance variable, you access its
> method directly. so replace:
>
> path = self.fileDialog.getOpenFileName()
>
> with
>
> path = QFileDialog.getOpenFileName(self)
>
> which is basically the same thing except you're going to the method
> directly instead of creating a class instance. The self argument may
> or may not be needed, its been a while since ive used Qt.

getOpenFileName is a static method. The first parameter is the
[optional] parent widget. The documentation says the dialog should be
centered over the parent, but it probably won't be if you let it use
the default native dialog. This can be disabled with the option
QFileDialog.DontUseNativeDialog. For example:

        path = QtGui.QFileDialog.getOpenFileName(
            parent=self,
            caption='File Dialog',
            directory='path/to/open',
            filter='type1 (*.ext1);;type2 (*.ext2)',
            selectedFilter='type2 (*.ext2)',
            options=QFileDialog.DontUseNativeDialog,
        )

http://pyqt.sourceforge.net/Docs/PyQt4/qfiledialog.html#getOpenFileName
http://pyqt.sourceforge.net/Docs/PyQt4/qfiledialog.html#Option-enum

From alan.gauld at btinternet.com  Mon May 27 21:13:03 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 27 May 2013 20:13:03 +0100
Subject: [Tutor] Buttons
In-Reply-To: <1369664250.95289.YahooMailNeo@web124502.mail.ne1.yahoo.com>
References: <1369664250.95289.YahooMailNeo@web124502.mail.ne1.yahoo.com>
Message-ID: <ko0b7q$uhs$1@ger.gmane.org>

On 27/05/13 15:17, Jack Little wrote:
> Is there a way to make buttons a little like a raw_input in the context
> when the user presses the button, the program performs a function?

Yes, but its a lot more complicated than raw_input.

See the GUI topic of my tutorial for examples.

Also check out the EasyGUI package for an easy way to add GUI style 
dialog boxes to an otherwise console based app. (see my "Talking to the 
User" topic in my V3 tutorial for more on EasyGUI)

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From cybervigilante at gmail.com  Mon May 27 22:01:34 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Mon, 27 May 2013 13:01:34 -0700
Subject: [Tutor] bytecode primer, and avoiding a monster download
Message-ID: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>

I was looking at the bytecode doc page as a break from the Lutz book,
since I like Assembler-type code due to its total non-ambiguity, but
the page doesn't say much. Is there a doc somewhere that corresponds
some of the bytecode to Python source? I thought rot_1, 2, 3, and 4
looked useful, but it would take awhile to disassemble random programs
to see what source they come from.

Another question. I tried installing a package that back-compiles (in
win 7), so I could see things that way, and got the error
"Unable to find vcvarsall.bat"

Looking around it said I needed to install Visual Studio (Express, of
course ;'). I'm on a very slow connection, right now. Is there any
alternative to downloading this monster 600 Mb ISO just to install a
package, or am I doomed to getting Visual Studio?

-- 
Jim Mooney

Atlantis Anyone?
http://www.pnas.org/content/early/2013/05/17/1301760110.abstract?sid=8313cec8-3ee0-47a0-9488-5bc33983b081

From oscar.j.benjamin at gmail.com  Mon May 27 22:09:58 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Mon, 27 May 2013 21:09:58 +0100
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
Message-ID: <CAHVvXxSufr-O-DhoL3brWvsUYMF5yY3ZP-F-syGyGo8ZzgRZNg@mail.gmail.com>

On 27 May 2013 21:01, Jim Mooney <cybervigilante at gmail.com> wrote:
>
> I was looking at the bytecode doc page as a break from the Lutz book,
> since I like Assembler-type code due to its total non-ambiguity, but
> the page doesn't say much. Is there a doc somewhere that corresponds
> some of the bytecode to Python source? I thought rot_1, 2, 3, and 4
> looked useful, but it would take awhile to disassemble random programs
> to see what source they come from.

What do you want these for? I've never needed to know what the
interpreter's bytecodes are.

> Another question. I tried installing a package that back-compiles (in
> win 7), so I could see things that way, and got the error
> "Unable to find vcvarsall.bat"

I don't know what you mean by "back-compiles" but I guess this package
contains extension modules in C. To install that from source you will
need a C compiler. The project may provide an installer with
pre-compiled binaries for Windows (check on their download page).

> Looking around it said I needed to install Visual Studio (Express, of
> course ;'). I'm on a very slow connection, right now. Is there any
> alternative to downloading this monster 600 Mb ISO just to install a
> package, or am I doomed to getting Visual Studio?

You can use MinGW instead of Visual Studio but you will need to apply
the fix to cygwinccompiler.py described here:
http://stackoverflow.com/questions/6034390/compiling-with-cython-and-mingw-produces-gcc-error-unrecognized-command-line-o

Otherwise you could install Python(x, y). This will install Python,
MinGW and a bunch of other useful packages in one go:
https://code.google.com/p/pythonxy/wiki/Downloads?tm=2


Oscar

From cybervigilante at gmail.com  Mon May 27 22:21:04 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Mon, 27 May 2013 13:21:04 -0700
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <CAHVvXxSufr-O-DhoL3brWvsUYMF5yY3ZP-F-syGyGo8ZzgRZNg@mail.gmail.com>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
	<CAHVvXxSufr-O-DhoL3brWvsUYMF5yY3ZP-F-syGyGo8ZzgRZNg@mail.gmail.com>
Message-ID: <CALRAYNVTx2ZoZsdMrACkpupYJg9Mq3tLio-OouwHEqp26B9AAQ@mail.gmail.com>

Oscar Benjamin <oscar.j.benjamin at gmail.com>

> What do you want these for? I've never needed to know what the
> interpreter's bytecodes are.

I programmed A86 Assembler years ago, and just find the bytecode has a
comfortable clarity as a learning tool, at least for me. When an
author vaguely tried to explain that a Name in Python is not the Data,
it confused me at first what he meant. But I could literally see the
disjunction in bytecode. I'm sure it's not for everyone - just aging
Assembler hackers ;')

Thanks for the Python(x,y) tip. That's probably useful for other stuff, too.

-- 
Jim Mooney

Atlantis Anyone?
http://www.pnas.org/content/early/2013/05/17/1301760110.abstract?sid=8313cec8-3ee0-47a0-9488-5bc33983b081

From alan.gauld at btinternet.com  Tue May 28 01:20:21 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 28 May 2013 00:20:21 +0100
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <CALRAYNVTx2ZoZsdMrACkpupYJg9Mq3tLio-OouwHEqp26B9AAQ@mail.gmail.com>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
	<CAHVvXxSufr-O-DhoL3brWvsUYMF5yY3ZP-F-syGyGo8ZzgRZNg@mail.gmail.com>
	<CALRAYNVTx2ZoZsdMrACkpupYJg9Mq3tLio-OouwHEqp26B9AAQ@mail.gmail.com>
Message-ID: <ko0pnf$9kb$1@ger.gmane.org>

On 27/05/13 21:21, Jim Mooney wrote:
> Oscar Benjamin <oscar.j.benjamin at gmail.com>
>
>> What do you want these for? I've never needed to know what the
>> interpreter's bytecodes are.
>
> I programmed A86 Assembler years ago, and just find the bytecode has a
> comfortable clarity as a learning tool,

To me, the bytecodes are the literal hex values corresponding
to the Python "assembler" statements. Are you sure you need the 
bytecodes? You can use the standard library to generate the
assembler listing from the Python code. Like Oscar I'm not sure
how the bytecodes would help?

I'm an ex assembler hacker myself but I've never found a need
for the Python bytecodes. Its not like you ever need to translate
the binary into assembler (the usual reason for reading bytecodes) since 
you usually have the source and from that you can get the dis-assembly 
listing. If you don't have the source it probably
means it's a C module and you need to look at the native machine
code disassembly not the Python one.

Can you give a use case of how you think you could use them?
There may be another way to do what you want.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From sunithanc at gmail.com  Tue May 28 01:25:08 2013
From: sunithanc at gmail.com (SM)
Date: Mon, 27 May 2013 19:25:08 -0400
Subject: [Tutor] Fwd: QT Python: How to re-use the return value of
 fileDialog.openFileName() ?
In-Reply-To: <CACL+1auatMajgPOvtQZr-b=uPsY4CRjm_=9sSeC8P5nto05pVQ@mail.gmail.com>
References: <CAOeFuMQYgG+obfqmaV6_fmx-_k0PQKuCH8UdNDt9s9=V_UGmaQ@mail.gmail.com>
	<CACzNyA3njNL=WpGfB+i0nTq7=EP1Ki7tWOUVG9ds4_8z15CcOQ@mail.gmail.com>
	<CACzNyA1=U_9WPG0wmP3ik_4SQosR9X3jxS=-dpWJNCs+sETNCQ@mail.gmail.com>
	<CAOeFuMSf+pMgkKTAGLbhoDTmqB33tGhR0zTk8JTQhGzmHW7RWQ@mail.gmail.com>
	<CACzNyA0wBHquzc4T7wF0Kafdr0Qac3yyw8dY=yNbR8bZhJBtDQ@mail.gmail.com>
	<CACL+1auatMajgPOvtQZr-b=uPsY4CRjm_=9sSeC8P5nto05pVQ@mail.gmail.com>
Message-ID: <CAOeFuMRxZC5G_gYUu=cSBaERqsCPr9Szp8gwiiNaRXUg-GNoZw@mail.gmail.com>

Thank you, for the details.


On Mon, May 27, 2013 at 10:13 AM, eryksun <eryksun at gmail.com> wrote:

> On Mon, May 27, 2013 at 9:45 AM, Matthew Ngaha <chigga101 at gmail.com>
> wrote:
> > On Mon, May 27, 2013 at 2:14 PM, SM <sunithanc at gmail.com> wrote:
> >
> >>But then I also had to use self.fileDialog from within the function. Not
> >> sure how I could avoid using fileDialog.
> >>
> >
> > No problem. to do it without the instance variable, you access its
> > method directly. so replace:
> >
> > path = self.fileDialog.getOpenFileName()
> >
> > with
> >
> > path = QFileDialog.getOpenFileName(self)
> >
> > which is basically the same thing except you're going to the method
> > directly instead of creating a class instance. The self argument may
> > or may not be needed, its been a while since ive used Qt.
>
> getOpenFileName is a static method. The first parameter is the
> [optional] parent widget. The documentation says the dialog should be
> centered over the parent, but it probably won't be if you let it use
> the default native dialog. This can be disabled with the option
> QFileDialog.DontUseNativeDialog. For example:
>
>         path = QtGui.QFileDialog.getOpenFileName(
>             parent=self,
>             caption='File Dialog',
>             directory='path/to/open',
>             filter='type1 (*.ext1);;type2 (*.ext2)',
>             selectedFilter='type2 (*.ext2)',
>             options=QFileDialog.DontUseNativeDialog,
>         )
>
> http://pyqt.sourceforge.net/Docs/PyQt4/qfiledialog.html#getOpenFileName
> http://pyqt.sourceforge.net/Docs/PyQt4/qfiledialog.html#Option-enum
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130527/fe2d5346/attachment-0001.html>

From jeanpierreda at gmail.com  Tue May 28 01:28:00 2013
From: jeanpierreda at gmail.com (Devin Jeanpierre)
Date: Mon, 27 May 2013 19:28:00 -0400
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <ko0pnf$9kb$1@ger.gmane.org>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
	<CAHVvXxSufr-O-DhoL3brWvsUYMF5yY3ZP-F-syGyGo8ZzgRZNg@mail.gmail.com>
	<CALRAYNVTx2ZoZsdMrACkpupYJg9Mq3tLio-OouwHEqp26B9AAQ@mail.gmail.com>
	<ko0pnf$9kb$1@ger.gmane.org>
Message-ID: <CABicbJK0z-FDWYKVEcBWkt3P0nEGmRP8wUkO401899AWk+EyQQ@mail.gmail.com>

On Mon, May 27, 2013 at 7:20 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> Can you give a use case of how you think you could use them?
> There may be another way to do what you want.

I can't speak for Jim, but I have used the dis module in the past to
quickly check how python parsed an expression (e.g. not x is y).

-- Devin

From steve at pearwood.info  Tue May 28 01:32:36 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 28 May 2013 09:32:36 +1000
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
Message-ID: <51A3ED14.8030405@pearwood.info>

On 28/05/13 06:01, Jim Mooney wrote:
> I was looking at the bytecode doc page as a break from the Lutz book,
> since I like Assembler-type code due to its total non-ambiguity, but
> the page doesn't say much. Is there a doc somewhere that corresponds
> some of the bytecode to Python source? I thought rot_1, 2, 3, and 4
> looked useful, but it would take awhile to disassemble random programs
> to see what source they come from.

Python byte-code is not officially documented, and is subject to change.
But it should be relatively straight-forward to understand, the names
are mostly self-explanatory. The main thing to remember is that the
byte-code is reverse-polish stack-based, like Forth, Postscript, and
most Hewlett-Packard scientific calculators.

http://en.wikipedia.org/wiki/Stack-oriented_programming_language


> Another question. I tried installing a package that back-compiles (in
> win 7), so I could see things that way, and got the error
> "Unable to find vcvarsall.bat"

Shall we guess what package that is? I love guessing games!

Ah, who am I kidding. No I don't.


-- 
Steven

From alan.gauld at btinternet.com  Tue May 28 01:56:38 2013
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Tue, 28 May 2013 00:56:38 +0100 (BST)
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <CABicbJK0z-FDWYKVEcBWkt3P0nEGmRP8wUkO401899AWk+EyQQ@mail.gmail.com>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
	<CAHVvXxSufr-O-DhoL3brWvsUYMF5yY3ZP-F-syGyGo8ZzgRZNg@mail.gmail.com>
	<CALRAYNVTx2ZoZsdMrACkpupYJg9Mq3tLio-OouwHEqp26B9AAQ@mail.gmail.com>
	<ko0pnf$9kb$1@ger.gmane.org>
	<CABicbJK0z-FDWYKVEcBWkt3P0nEGmRP8wUkO401899AWk+EyQQ@mail.gmail.com>
Message-ID: <1369698998.2840.YahooMailNeo@web186001.mail.ir2.yahoo.com>

I can't speak for Jim, but I have used the dis module in the past to
>quickly check how python parsed an expression (e.g. not x is y).
>Yes, I've done that too. But that's not the bytecodes (at least not what?
I understand as bytecodes) that's the dis-assembly listing which is?
usually far more useful. And as you say the dis module provides that
without any need for other tools.

Alan G.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130528/d0c43ac2/attachment.html>

From breamoreboy at yahoo.co.uk  Tue May 28 02:10:52 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 28 May 2013 01:10:52 +0100
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <51A3ED14.8030405@pearwood.info>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
	<51A3ED14.8030405@pearwood.info>
Message-ID: <ko0slq$2n1$1@ger.gmane.org>

On 28/05/2013 00:32, Steven D'Aprano wrote:
> On 28/05/13 06:01, Jim Mooney wrote:
>> Another question. I tried installing a package that back-compiles (in
>> win 7), so I could see things that way, and got the error
>> "Unable to find vcvarsall.bat"
>
> Shall we guess what package that is? I love guessing games!
>
> Ah, who am I kidding. No I don't.
>

Been there, seen it, done it, got the t-shirt 
http://old.nabble.com/Re%3A-Unable-to-install-PyWin32-with-Python-2.6.2-p25202902.html

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From davea at davea.name  Tue May 28 02:23:49 2013
From: davea at davea.name (Dave Angel)
Date: Mon, 27 May 2013 20:23:49 -0400
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <1369698998.2840.YahooMailNeo@web186001.mail.ir2.yahoo.com>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
	<CAHVvXxSufr-O-DhoL3brWvsUYMF5yY3ZP-F-syGyGo8ZzgRZNg@mail.gmail.com>
	<CALRAYNVTx2ZoZsdMrACkpupYJg9Mq3tLio-OouwHEqp26B9AAQ@mail.gmail.com>
	<ko0pnf$9kb$1@ger.gmane.org>
	<CABicbJK0z-FDWYKVEcBWkt3P0nEGmRP8wUkO401899AWk+EyQQ@mail.gmail.com>
	<1369698998.2840.YahooMailNeo@web186001.mail.ir2.yahoo.com>
Message-ID: <51A3F915.7060208@davea.name>

On 05/27/2013 07:56 PM, ALAN GAULD wrote:
> I can't speak for Jim, but I have used the dis module in the past to
>> quickly check how python parsed an expression (e.g. not x is y).
>> Yes, I've done that too. But that's not the bytecodes (at least not what
> I understand as bytecodes) that's the dis-assembly listing which is
> usually far more useful. And as you say the dis module provides that
> without any need for other tools.
>


Certainly dis.dis() doesn't show the entire file, it shows only a single 
function.  And it doesn't show the const-table, or the local-table. 
(Whatever they're called in byte-code-speak)

But within the function it's probably got most all of what you would see 
in a byte code file, barring the hex values of the bytes themselves. 
Notice it shows you the offsets, so you know how many bytes each 
instruction takes.  And when the instruction is more than one byte long, 
it shows the operands, in both decimal form and in mnemonic.

When I first got my hands on the (very good) spec for the java byte code 
file, I wrote a disassembler for it.  Seems to me the python one is very 
analogous to that one.

Note, though that I have never tried to even look at the python one, 
even with a hex editor.  So I could be all wet.


-- 
DaveA

From eryksun at gmail.com  Tue May 28 03:15:59 2013
From: eryksun at gmail.com (eryksun)
Date: Mon, 27 May 2013 21:15:59 -0400
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
Message-ID: <CACL+1atAptSR81Ch-Gi33LUh1MgoSsrXMJ3LzESPo_AdsARXPA@mail.gmail.com>

On Mon, May 27, 2013 at 4:01 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> I was looking at the bytecode doc page as a break from the Lutz book,
> since I like Assembler-type code due to its total non-ambiguity, but
> the page doesn't say much. Is there a doc somewhere that corresponds
> some of the bytecode to Python source? I thought rot_1, 2, 3, and 4
> looked useful, but it would take awhile to disassemble random programs
> to see what source they come from.

Are you referring to the documentation of the dis module?

http://docs.python.org/2/library/dis

AFAIK, that's all the documentation there is. Heed the warning in bold
that bytecode is an implementation detail of the target virtual
machine. For example, Jython creates a .class file containing JVM
bytecode, and its code objects don't even have a co_code attribute...

I once manually instantiated a CPython 2.x code object to create a
very simple function with a default argument. Here was my first and
only attempt, FWIW:

    from opcode import opmap
    from types import FunctionType, CodeType
    from inspect import CO_OPTIMIZED, CO_NEWLOCALS, CO_NOFREE

    OP = type('OP', (), opmap)

    def foo1(x='spam'):
        print x

    foo2 = FunctionType(
      CodeType(            # func_code
        1,                     # co_argcount
        1,                     # co_nlocals
        1,                     # co_stacksize
        CO_OPTIMIZED |         # co_flags
        CO_NEWLOCALS |
        CO_NOFREE,
        str(bytearray([        # co_code
          OP.LOAD_FAST, 0, 0,      # stack.push(fastlocals[0])
                                   #     x is fastlocals[0]
          OP.PRINT_ITEM,           # print stack.pop()
          OP.PRINT_NEWLINE,
          OP.LOAD_CONST, 0, 0,     # stack.push(co_consts[0])
                                   #     co_consts[0] is None
          OP.RETURN_VALUE,         # return stack.pop()
        ])),
        (None,),               # co_consts
        (),                    # co_names
        ('x',),                # co_varnames
        __file__,              # co_filename
        'foo2',                # co_name
        10,                    # co_firstlineno
        '\x00\x01',            # co_lnotab,
                               #   see: Objects/lnotab_notes.txt
        (),                    # co_freevars
        (),                    # co_cellvars
      ),
      globals(),           # func_globals
      'foo2',              # func_name
      ('spam',),           # func_defaults
      None,                # func_closure
    )


For example:

    >>> foo2()
    spam
    >>> foo2('eggs')
    eggs

There's an assembler package on PyPI that does this for real, if this
sort of thing interests you:

https://pypi.python.org/pypi/BytecodeAssembler

As to the VM's ROT operations, I'm not sure what you mean by seeing
"what source they come from". They simply manipulate the top 2, 3, or
4 items on the frame's stack:

    ROT_TWO()
    Swaps the two top-most stack items.

    ROT_THREE()
    Lifts second and third stack item one position up,
    moves top down to position three.

    ROT_FOUR()
    Lifts second, third and forth stack item one position up,
    moves top down to position four.

From tjhanson at yahoo.com  Tue May 28 05:54:58 2013
From: tjhanson at yahoo.com (Tim Hanson)
Date: Mon, 27 May 2013 20:54:58 -0700
Subject: [Tutor] a little loop
Message-ID: <201305272054.58446.tjhanson@yahoo.com>

Okay, so I made it to FOR loops in the Lutz book.  A couple of days ago I was 
helped here with the .join method for creating strings from lists or tuples of 
strings.  I got to wondering if I could just, for the sake of learning, do the 
same thing in a FOR loop, since that's today's chapter:

x=0; ham=''; b=['s','p','a','m'] #or, b=('s','p','a','m')
for t in b:
	ham=ham+b[x]
	print(ham);x+=1

	
s
sp
spa
spam

Alright, it works, eventually.  Can someone help me find a little more elegant 
way of doing this?  I'm sure there are several.

Incidentally, I put the print statement within the FOR loop so I could watch 
progress.

From kartiksundarajan at gmail.com  Tue May 28 06:28:04 2013
From: kartiksundarajan at gmail.com (kartik sundarajan)
Date: Tue, 28 May 2013 09:58:04 +0530
Subject: [Tutor] a little loop
In-Reply-To: <201305272054.58446.tjhanson@yahoo.com>
References: <201305272054.58446.tjhanson@yahoo.com>
Message-ID: <CAJ2_K29Q+n4dfCHkM24Cd7mEOQ2id-V9P7aeuLCrS-CUuhMMeQ@mail.gmail.com>

One way I can suggest is

x=0; ham=''; b=['s','p','a','m'] #or, b=('s','p','a','m')
> for t in b:
>         ham=ham+b[x]
>         print(ham);x+=1
>
>
> 't' is actually  equal to b[x] and its faster then indexed based look-up.
so you can rewrite

ham = ham + b[x]

as

ham += t

and remove the x increment.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130528/c2dafda6/attachment.html>

From johnsteedman360 at gmail.com  Tue May 28 08:36:53 2013
From: johnsteedman360 at gmail.com (John Steedman)
Date: Tue, 28 May 2013 07:36:53 +0100
Subject: [Tutor] a little loop
In-Reply-To: <201305272054.58446.tjhanson@yahoo.com>
References: <201305272054.58446.tjhanson@yahoo.com>
Message-ID: <CAF50Yh_Xqm=vSiCsMegjwE=9c3Qu49-M=EMPRrr9gT=BRWvZ5A@mail.gmail.com>

Some other tools, if you haven't come across them yet.

You already know about str.join ()

Slicing

>>>b=['s','p','a','m']
b [ : 1 ]
['s']
b [ : 2 ]
['s', 'p']

Also, consider

>>>len ( b)
4

>>>range ( 4 )
[ 0, 1, 2, 3, 4]
# which I can iterate over.












On Tue, May 28, 2013 at 4:54 AM, Tim Hanson <tjhanson at yahoo.com> wrote:

> Okay, so I made it to FOR loops in the Lutz book.  A couple of days ago I
> was
> helped here with the .join method for creating strings from lists or
> tuples of
> strings.  I got to wondering if I could just, for the sake of learning, do
> the
> same thing in a FOR loop, since that's today's chapter:
>
> x=0; ham=''; b=['s','p','a','m'] #or, b=('s','p','a','m')
> for t in b:
>         ham=ham+b[x]
>         print(ham);x+=1
>
>
> s
> sp
> spa
> spam
>
> Alright, it works, eventually.  Can someone help me find a little more
> elegant
> way of doing this?  I'm sure there are several.
>
> Incidentally, I put the print statement within the FOR loop so I could
> watch
> progress.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130528/f75c3aab/attachment.html>

From alan.gauld at btinternet.com  Tue May 28 09:38:14 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 28 May 2013 08:38:14 +0100
Subject: [Tutor] a little loop
In-Reply-To: <201305272054.58446.tjhanson@yahoo.com>
References: <201305272054.58446.tjhanson@yahoo.com>
Message-ID: <ko1mt0$cnt$1@ger.gmane.org>

On 28/05/13 04:54, Tim Hanson wrote:

> x=0; ham=''; b=['s','p','a','m'] #or, b=('s','p','a','m')
> for t in b:
> 	ham=ham+b[x]
> 	print(ham);x+=1
>

> Alright, it works, eventually.  Can someone help me find a little more elegant
> way of doing this?  I'm sure there are several.

Python 'for' loops iterate over the target sequence so you usually don't 
need indexes. (And if you do you should use enumerate()). If it helps 
read the word 'for' as 'foreach'. So rewriting your for loop in
a Pythonic style yields:

for letter in b:
     ham += letter
     print(ham)

or if you must for some reason use indexing try

for index, letter in enumerate(b):
     ham += b[index]
     print(ham)

Note however that string addition is very inefficient compared to 
join(), so in the real world you are much better off using join.

There are other ways of doing this but join() is best so
there is little point in reciting them.

Notice also that I used 'letter' as the loop variable. Meaningful names 
make code much easier to understand. The extra effort of typing is 
easily offset by the time saved reading the code later.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From cybervigilante at gmail.com  Tue May 28 13:02:08 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Tue, 28 May 2013 04:02:08 -0700
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <ko0pnf$9kb$1@ger.gmane.org>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
	<CAHVvXxSufr-O-DhoL3brWvsUYMF5yY3ZP-F-syGyGo8ZzgRZNg@mail.gmail.com>
	<CALRAYNVTx2ZoZsdMrACkpupYJg9Mq3tLio-OouwHEqp26B9AAQ@mail.gmail.com>
	<ko0pnf$9kb$1@ger.gmane.org>
Message-ID: <CALRAYNXTwtUxPRPLtsd8QEDX_Snzq38OHayMFQ9Bo89XD=JsNQ@mail.gmail.com>

On 27 May 2013 16:20, Alan Gauld <alan.gauld at btinternet.com> wrote:

>
> To me, the bytecodes are the literal hex values corresponding
> to the Python "assembler" statements. Are you sure you need the bytecodes?
> You can use the standard library to generate the
> assembler listing from the Python code.

Ah good, how do I do that? What's the module? Thanks.

Jim

From cybervigilante at gmail.com  Tue May 28 13:05:54 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Tue, 28 May 2013 04:05:54 -0700
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <51A3ED14.8030405@pearwood.info>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
	<51A3ED14.8030405@pearwood.info>
Message-ID: <CALRAYNVxo0B36EjTkH7NskZWXpprB2XJ6Q9tUkMa8ZdnjdwxPg@mail.gmail.com>

On 27 May 2013 16:32, Steven D'Aprano <steve at pearwood.info> wrote:
> On 28/05/13 06:01, Jim Mooney wrote:
> Shall we guess what package that is? I love guessing games!
>
> Ah, who am I kidding. No I don't.
>

Well, I would hate to keep you guessing ;')  It's called decompyle -
pip couldn't find it, though, and it requires either Msoft Visual or
python(x,y) install, so it's in abeyance.

Jim

From davea at davea.name  Tue May 28 13:18:39 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 28 May 2013 07:18:39 -0400
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <CALRAYNXTwtUxPRPLtsd8QEDX_Snzq38OHayMFQ9Bo89XD=JsNQ@mail.gmail.com>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
	<CAHVvXxSufr-O-DhoL3brWvsUYMF5yY3ZP-F-syGyGo8ZzgRZNg@mail.gmail.com>
	<CALRAYNVTx2ZoZsdMrACkpupYJg9Mq3tLio-OouwHEqp26B9AAQ@mail.gmail.com>
	<ko0pnf$9kb$1@ger.gmane.org>
	<CALRAYNXTwtUxPRPLtsd8QEDX_Snzq38OHayMFQ9Bo89XD=JsNQ@mail.gmail.com>
Message-ID: <51A4928F.3040106@davea.name>

On 05/28/2013 07:02 AM, Jim Mooney wrote:
> On 27 May 2013 16:20, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
>>
>> To me, the bytecodes are the literal hex values corresponding
>> to the Python "assembler" statements. Are you sure you need the bytecodes?
>> You can use the standard library to generate the
>> assembler listing from the Python code.
>
> Ah good, how do I do that? What's the module? Thanks.
>

Alan and Devin already gave more specifics, but to repeat,

import dis

dis.dis(myfunction)

will disassemble one function.

That's not all that's in the byte-code file, but this is 98% of what you 
probably want out of it.  And you can do it in the debugger with just 
the standard library.


-- 
DaveA

From citizenkant at gmail.com  Tue May 28 13:44:40 2013
From: citizenkant at gmail.com (Citizen Kant)
Date: Tue, 28 May 2013 13:44:40 +0200
Subject: [Tutor] Python "well-formed formulas"
Message-ID: <CAMbF=C-ED7=t4ZQx2aZHc2Q0_jXW7nAnFmhvFZJwWoDuQ7pi4w@mail.gmail.com>

Could you please help me with a simple example of a Python well-formed
formula in order to understand "well-formed formulas" and "formation rules"
concepts properly?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130528/6f6695c6/attachment.html>

From wprins at gmail.com  Tue May 28 14:20:04 2013
From: wprins at gmail.com (Walter Prins)
Date: Tue, 28 May 2013 13:20:04 +0100
Subject: [Tutor] Python "well-formed formulas"
In-Reply-To: <CAMbF=C-ED7=t4ZQx2aZHc2Q0_jXW7nAnFmhvFZJwWoDuQ7pi4w@mail.gmail.com>
References: <CAMbF=C-ED7=t4ZQx2aZHc2Q0_jXW7nAnFmhvFZJwWoDuQ7pi4w@mail.gmail.com>
Message-ID: <CANLXbfAcKn8PaqxPKe0Q-a7V4nizb3amjXAcD+0wYHk=1qb_yA@mail.gmail.com>

Hi,

On 28 May 2013 12:44, Citizen Kant <citizenkant at gmail.com> wrote:

> Could you please help me with a simple example of a Python well-formed
> formula in order to understand "well-formed formulas" and "formation rules"
> concepts properly?
>

I'm assuming you perhaps meant "well-formed expression".  If so, here's a
useful link that answers your question:
http://homepage.divms.uiowa.edu/~sriram/16/spring12/lectureNotes/Feb8-2012.pdf


Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130528/f030322d/attachment.html>

From steve at pearwood.info  Tue May 28 14:26:50 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 28 May 2013 22:26:50 +1000
Subject: [Tutor] Python "well-formed formulas"
In-Reply-To: <CAMbF=C-ED7=t4ZQx2aZHc2Q0_jXW7nAnFmhvFZJwWoDuQ7pi4w@mail.gmail.com>
References: <CAMbF=C-ED7=t4ZQx2aZHc2Q0_jXW7nAnFmhvFZJwWoDuQ7pi4w@mail.gmail.com>
Message-ID: <51A4A28A.10504@pearwood.info>

On 28/05/13 21:44, Citizen Kant wrote:
> Could you please help me with a simple example of a Python well-formed
> formula in order to understand "well-formed formulas" and "formation rules"
> concepts properly?


Probably not, since they aren't really Python terms, so I'll be guessing what they are.

But *in general*, "well-formed" means there are no errors according to the grammar or syntax of the language being written. For example, in English:

"Last week, I went to the restaurant and ate a pizza."

is a grammatically-correct sentence, and so is well-formed. But:

"Last weeks, me goed to a restaurants and ated a pizzas?"

is not. Similarly, this is a well-formed mathematical expression:

y = 3x? - 4(x + 5)

while this is not:

y = ? - 4(x+)


In the case of Python, there are many different varieties of well-formed expressions. Some of them look remarkably close to mathematical notation (which is not an accident):

y = 3*x**2 - 4*(x + 5)

Some obvious differences: Python uses ** for the power operator, not superscript; multiplication must be explicitly stated using * and not just implied.

Other well-formed Python expressions:

mylist and mylist[1:]
"This is a string".upper()
function(12, 3.5, {4:None})

and some which are not well-formed:

mylist mylist:[1]
This is a string.)(upper
function 12,, 3.5, {4 None)}


Basically, something is well-formed if it has the form of the syntax or grammar of the language, and is not if it doesn't.




-- 
Steven

From davea at davea.name  Tue May 28 14:32:06 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 28 May 2013 08:32:06 -0400
Subject: [Tutor] Python "well-formed formulas"
In-Reply-To: <CANLXbfAcKn8PaqxPKe0Q-a7V4nizb3amjXAcD+0wYHk=1qb_yA@mail.gmail.com>
References: <CAMbF=C-ED7=t4ZQx2aZHc2Q0_jXW7nAnFmhvFZJwWoDuQ7pi4w@mail.gmail.com>
	<CANLXbfAcKn8PaqxPKe0Q-a7V4nizb3amjXAcD+0wYHk=1qb_yA@mail.gmail.com>
Message-ID: <51A4A3C6.2040803@davea.name>

On 05/28/2013 08:20 AM, Walter Prins wrote:
> Hi,
>
> On 28 May 2013 12:44, Citizen Kant <citizenkant at gmail.com> wrote:
>
>> Could you please help me with a simple example of a Python well-formed
>> formula in order to understand "well-formed formulas" and "formation rules"
>> concepts properly?
>>
>
> I'm assuming you perhaps meant "well-formed expression".  If so, here's a
> useful link that answers your question:
> http://homepage.divms.uiowa.edu/~sriram/16/spring12/lectureNotes/Feb8-2012.pdf
>

That's pretty good.  I had assumed the OP meant the well-formed formula 
of Propositional Calculus.  As defined on the page:

http://www.cs.brandeis.edu/~jamesp/classes/LING130/FirstOrderLogic-1.pdf

I didn't respond because I can't believe that Propositional Calculus 
means the same thing by "free variable" as Python does.



-- 
DaveA

From citizenkant at gmail.com  Tue May 28 15:45:06 2013
From: citizenkant at gmail.com (Citizen Kant)
Date: Tue, 28 May 2013 15:45:06 +0200
Subject: [Tutor] Python "well-formed formulas"
In-Reply-To: <51A4A3C6.2040803@davea.name>
References: <CAMbF=C-ED7=t4ZQx2aZHc2Q0_jXW7nAnFmhvFZJwWoDuQ7pi4w@mail.gmail.com>
	<CANLXbfAcKn8PaqxPKe0Q-a7V4nizb3amjXAcD+0wYHk=1qb_yA@mail.gmail.com>
	<51A4A3C6.2040803@davea.name>
Message-ID: <CAMbF=C8wLARUo8EXzHzE38g+-9Hab8J90gBog+LrkA=9_9Azyw@mail.gmail.com>

2013/5/28 Dave Angel <davea at davea.name>

> On 05/28/2013 08:20 AM, Walter Prins wrote:
>
>> Hi,
>>
>> On 28 May 2013 12:44, Citizen Kant <citizenkant at gmail.com> wrote:
>>
>>  Could you please help me with a simple example of a Python well-formed
>>> formula in order to understand "well-formed formulas" and "formation
>>> rules"
>>> concepts properly?
>>>
>>>
>> I'm assuming you perhaps meant "well-formed expression".  If so, here's a
>> useful link that answers your question:
>> http://homepage.divms.uiowa.**edu/~sriram/16/spring12/**
>> lectureNotes/Feb8-2012.pdf<http://homepage.divms.uiowa.edu/~sriram/16/spring12/lectureNotes/Feb8-2012.pdf>
>>
>>
> That's pretty good.  I had assumed the OP meant the well-formed formula of
> Propositional Calculus.  As defined on the page:
>
> http://www.cs.brandeis.edu/~**jamesp/classes/LING130/**
> FirstOrderLogic-1.pdf<http://www.cs.brandeis.edu/~jamesp/classes/LING130/FirstOrderLogic-1.pdf>
>
> I didn't respond because I can't believe that Propositional Calculus means
> the same thing by "free variable" as Python does.


I'm trying to figure out the rules on how to recognize when a combination
of symbols is considered a well formed expression in Python. Since I
couldn't find any doc that lists all Python syntax rules --or maybe the doc
is too long to be managed by me right now--, stating all kinds of legal
combination among its symbols, I had this idea that well formed expressions
must respond to truth tables. I think I'm not pretty much interested on how
each symbol like 9 or Z or + come to be truth (maybe I'm wrong) but in the
truth of their combinations. Do I am in the correct path? Understanding the
truth tables (which I'm not very familiarized with) would help me on
writing Python in a more intuitive way?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130528/0a457ec1/attachment-0001.html>

From steve at pearwood.info  Tue May 28 17:05:16 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 29 May 2013 01:05:16 +1000
Subject: [Tutor] Python "well-formed formulas"
In-Reply-To: <CAMbF=C8wLARUo8EXzHzE38g+-9Hab8J90gBog+LrkA=9_9Azyw@mail.gmail.com>
References: <CAMbF=C-ED7=t4ZQx2aZHc2Q0_jXW7nAnFmhvFZJwWoDuQ7pi4w@mail.gmail.com>
	<CANLXbfAcKn8PaqxPKe0Q-a7V4nizb3amjXAcD+0wYHk=1qb_yA@mail.gmail.com>
	<51A4A3C6.2040803@davea.name>
	<CAMbF=C8wLARUo8EXzHzE38g+-9Hab8J90gBog+LrkA=9_9Azyw@mail.gmail.com>
Message-ID: <51A4C7AC.7000108@pearwood.info>

On 28/05/13 23:45, Citizen Kant wrote:

> I'm trying to figure out the rules on how to recognize when a combination
> of symbols is considered a well formed expression in Python. Since I
> couldn't find any doc that lists all Python syntax rules

Start by going to the Python website, www.python.org.

Click on the Documentation link on the left hand side:

http://www.python.org/doc/

Decide whether you care about Python 2 or Python 3. I'm going to use Python 3. Click on the "Language Reference" link, http://docs.python.org/3/reference/

Start reading at the beginning, and stop when you reach the end. Feel free to ask specific questions, because unfortunately sometimes the docs make assumptions about the reader's knowledge.


> --or maybe the doc
> is too long to be managed by me right now--, stating all kinds of legal
> combination among its symbols, I had this idea that well formed expressions
> must respond to truth tables.

What do you mean "respond to truth tables"? Do you know what a truth table is?


> Do I am in the correct path? Understanding the
> truth tables (which I'm not very familiarized with) would help me on
> writing Python in a more intuitive way?

No. Truth tables have nothing to do with well-formed expressions.

I'm curious, what chain of reasoning lead you from:

     "I don't understand what 'well-formed expression' means."

to:

     "Therefore it must have something to do with true tables."

?



-- 
Steven

From wprins at gmail.com  Tue May 28 18:28:31 2013
From: wprins at gmail.com (Walter Prins)
Date: Tue, 28 May 2013 17:28:31 +0100
Subject: [Tutor] Python "well-formed formulas"
In-Reply-To: <CAMbF=C8wLARUo8EXzHzE38g+-9Hab8J90gBog+LrkA=9_9Azyw@mail.gmail.com>
References: <CAMbF=C-ED7=t4ZQx2aZHc2Q0_jXW7nAnFmhvFZJwWoDuQ7pi4w@mail.gmail.com>
	<CANLXbfAcKn8PaqxPKe0Q-a7V4nizb3amjXAcD+0wYHk=1qb_yA@mail.gmail.com>
	<51A4A3C6.2040803@davea.name>
	<CAMbF=C8wLARUo8EXzHzE38g+-9Hab8J90gBog+LrkA=9_9Azyw@mail.gmail.com>
Message-ID: <CANLXbfCKyVo5bnsGKh5OKNVVZ-Q0zmusABpofMTShtdzBL=37Q@mail.gmail.com>

Citizen,


On 28 May 2013 14:45, Citizen Kant <citizenkant at gmail.com> wrote:

> I'm trying to figure out the rules on how to recognize when a combination
> of symbols is considered a well formed expression in Python.
>

How do you recognize that an arithmetic expression is a well formed (e.g.
valid) expression?   How do you recognize that an English is valid
grammatically?



> Since I couldn't find any doc that lists all Python syntax rules --or
> maybe the doc is too long to be managed by me right now--,
>

Perhaps you need to look at the Python grammar specification.  One of the
reasons Python is actually relatively easy to learn is that it's grammar is
actually not that big, which means it's actually not that hard to learn, as
you say, to recognize when Python expressions or statements are valid or
invalid:
http://docs.python.org/2.7/reference/grammar.html

Of course, the Python grammar covers the entire language, not just
expressions.

stating all kinds of legal combination among its symbols, I had this idea
> that well formed expressions must respond to truth tables. I think I'm not
> pretty much interested on how each symbol like 9 or Z or + come to be truth
> (maybe I'm wrong) but in the truth of their combinations.
>

Do you know boolean algebra? The combination of boolean values result in
futher boolean values in relatively intuitive ways, which yes, can be
enumerated explicitly using a truth table.


> Do I am in the correct path? Understanding the truth tables (which I'm not
> very familiarized with) would help me on writing Python in a more intuitive
> way?
>

I'm not sure truth tables by themselves will help with your intuition,
though they might if you reason about boolean expressions and then
enumerate all the possible combinations and produce a truth table to
summarise the your reasoning.  For example, suppose you have the boolean
expression "A or B".  What values of A and B will cause the expression to
be True?  And what would cause it to be False?    Now consider the
expression "A and B", and then the expression "A or B and C".  Etc.

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130528/58e41544/attachment.html>

From eryksun at gmail.com  Tue May 28 18:48:58 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 28 May 2013 12:48:58 -0400
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <51A4928F.3040106@davea.name>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
	<CAHVvXxSufr-O-DhoL3brWvsUYMF5yY3ZP-F-syGyGo8ZzgRZNg@mail.gmail.com>
	<CALRAYNVTx2ZoZsdMrACkpupYJg9Mq3tLio-OouwHEqp26B9AAQ@mail.gmail.com>
	<ko0pnf$9kb$1@ger.gmane.org>
	<CALRAYNXTwtUxPRPLtsd8QEDX_Snzq38OHayMFQ9Bo89XD=JsNQ@mail.gmail.com>
	<51A4928F.3040106@davea.name>
Message-ID: <CACL+1auWtQhODrj6fpJ9vtOr8eG7S-kjMkOHv3FdLKE4oiyboA@mail.gmail.com>

On Tue, May 28, 2013 at 7:18 AM, Dave Angel <davea at davea.name> wrote:
>
> dis.dis(myfunction)
>
> will disassemble one function.
>
> That's not all that's in the byte-code file, but this is 98% of what you
> probably want out of it.  And you can do it in the debugger with just the
> standard library.

The argument for dis.dis() can be a module, class, function or code
object. It disassembles all the top-level code objects that it finds,
but it doesn't recursively disassemble code objects that are in the
co_consts.

I'm not sure what Dave means by 'byte-code file'. A .pyc? That's a
marshaled code object with a small header that has a magic number and
a timestamp. Here's an example of reading the pyc for the dis module
itself:

    import dis
    import marshal
    import struct
    import datetime

    # magic number for Python 2.7
    MAGIC27 = 62211 | (ord('\r') << 16) | (ord('\n') << 24)

    pyc = open(dis.__file__, 'rb')  # dis.pyc
    hdr = pyc.read(8)
    magic, tstamp = struct.unpack('<ll', hdr)
    tstamp = datetime.datetime.fromtimestamp(tstamp)

    # the rest of the file is the code object
    code = marshal.load(pyc)

    >>> magic == MAGIC27
    True
    >>> tstamp
    datetime.datetime(2013, 1, 2, 12, 45, 58)

    >>> code.co_consts[0]
    'Disassembler of Python byte code into mnemonics.'

The code object's co_consts tuple also has the code objects for the
defined functions, plus the anonymous functions that build class
objects. The latter are subsequently discarded, as is the .pyc code
object itself after the module is imported/executed. There's no point
in keeping it around.

My previous post is a light intro to instantiating code and function
objects. I think the arguments are mostly self-explanatory -- except
for co_lnotab, co_flags, and closure support (co_cellvars,
co_freevars, func_closure).

I assembled the bytecode with the help of opcode.opmap, to make it
more readable. But to be clear, CPython bytecode is simply a byte
string stored in the co_code attribute. Disassembling the bytecode
nicely with source line numbers requires co_lnotab. While I did
reference the text file that explains co_lnotab, I neglected to
provide the following link:

http://hg.python.org/cpython/file/687295c6c8f2/Objects/lnotab_notes.txt

co_flags indicates various aspects of how the bytecode was compiled
(e.g. optimized to use fastlocals). It's inherited from the current
context when you use exec or eval. compile() can disable this via the
argument dont_inherit.

The code for a class body or a function requires a new local namespace
(CO_NEWLOCALS). For a function, locals is also optimized
(CO_OPTIMIZED) to use the fastlocals array instead of a dict. On the
other hand, the code that creates a module is evaluated with locals
and globals set to the same namespace, so it won't have the
CO_NEWLOCALS flag.

Including the metadata that there are no free variables (CO_NOFREE)
can make a simple function call more efficient, but only if there are
no default arguments or keyword arguments in the call. Refer to
fast_function() in Python/ceval.c.

http://hg.python.org/cpython/file/ab05e7dd2788/Python/ceval.c#l4060

Here are all of the flags for code objects in 2.7:

    CO_OPTIMIZED    0x01
    CO_NEWLOCALS    0x02
    CO_VARARGS      0x04
    CO_VARKEYWORDS  0x08
    CO_NESTED       0x10
    CO_GENERATOR    0x20
    CO_NOFREE       0x40

    /* __future__ imports */
    CO_FUTURE_DIVISION         0x02000
    CO_FUTURE_ABSOLUTE_IMPORT  0x04000
    CO_FUTURE_WITH_STATEMENT   0x08000
    CO_FUTURE_PRINT_FUNCTION   0x10000
    CO_FUTURE_UNICODE_LITERALS 0x20000

For a high-level view on scoping, read the section on the execution
model in the language reference:

http://docs.python.org/2/reference/executionmodel

Subsequently, if you want, we can talk about how this is implemented
in the VM, and especially with respect to closures, cellvars,
freevars, and the opcodes LOAD_DEREF, STORE_DEREF, and MAKE_CLOSURE.

From oscar.j.benjamin at gmail.com  Tue May 28 19:12:07 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Tue, 28 May 2013 18:12:07 +0100
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <CACL+1auWtQhODrj6fpJ9vtOr8eG7S-kjMkOHv3FdLKE4oiyboA@mail.gmail.com>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
	<CAHVvXxSufr-O-DhoL3brWvsUYMF5yY3ZP-F-syGyGo8ZzgRZNg@mail.gmail.com>
	<CALRAYNVTx2ZoZsdMrACkpupYJg9Mq3tLio-OouwHEqp26B9AAQ@mail.gmail.com>
	<ko0pnf$9kb$1@ger.gmane.org>
	<CALRAYNXTwtUxPRPLtsd8QEDX_Snzq38OHayMFQ9Bo89XD=JsNQ@mail.gmail.com>
	<51A4928F.3040106@davea.name>
	<CACL+1auWtQhODrj6fpJ9vtOr8eG7S-kjMkOHv3FdLKE4oiyboA@mail.gmail.com>
Message-ID: <CAHVvXxTyqY+3kPs3F5riZs1dMzKZXTfFad66b6DOYjUu-2YE8g@mail.gmail.com>

On 28 May 2013 17:48, eryksun <eryksun at gmail.com> wrote:
> On Tue, May 28, 2013 at 7:18 AM, Dave Angel <davea at davea.name> wrote:
>>
>> dis.dis(myfunction)
>>
>> will disassemble one function.
>>
>> That's not all that's in the byte-code file, but this is 98% of what you
>> probably want out of it.  And you can do it in the debugger with just the
>> standard library.
>
> The argument for dis.dis() can be a module, class, function or code
> object. It disassembles all the top-level code objects that it finds,
> but it doesn't recursively disassemble code objects that are in the
> co_consts.

What do you mean by this? I tried passing a test module into dis.dis
and nothing happens:

$ python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tmp
>>> tmp.a
1
>>> import dis
>>> dis.dis(tmp)
>>> print(dis.dis(tmp))
None

This module contains no functions but it does contain lines of code
and the interpreter will turn those into bytecode somewhere. I think
that's what Dave meant.


Oscar

From eryksun at gmail.com  Tue May 28 19:24:42 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 28 May 2013 13:24:42 -0400
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <CAHVvXxTyqY+3kPs3F5riZs1dMzKZXTfFad66b6DOYjUu-2YE8g@mail.gmail.com>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
	<CAHVvXxSufr-O-DhoL3brWvsUYMF5yY3ZP-F-syGyGo8ZzgRZNg@mail.gmail.com>
	<CALRAYNVTx2ZoZsdMrACkpupYJg9Mq3tLio-OouwHEqp26B9AAQ@mail.gmail.com>
	<ko0pnf$9kb$1@ger.gmane.org>
	<CALRAYNXTwtUxPRPLtsd8QEDX_Snzq38OHayMFQ9Bo89XD=JsNQ@mail.gmail.com>
	<51A4928F.3040106@davea.name>
	<CACL+1auWtQhODrj6fpJ9vtOr8eG7S-kjMkOHv3FdLKE4oiyboA@mail.gmail.com>
	<CAHVvXxTyqY+3kPs3F5riZs1dMzKZXTfFad66b6DOYjUu-2YE8g@mail.gmail.com>
Message-ID: <CACL+1asHLDVgdJvP1C+TjhSNpXbGLwjWn9KX+U9DkXAWtiKw-Q@mail.gmail.com>

On Tue, May 28, 2013 at 1:12 PM, Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
> On 28 May 2013 17:48, eryksun <eryksun at gmail.com> wrote:
>>
>> The argument for dis.dis() can be a module, class, function or code
>> object. It disassembles all the top-level code objects that it finds,
>> but it doesn't recursively disassemble code objects that are in the
>> co_consts.
>
> What do you mean by this? I tried passing a test module into dis.dis
> and nothing happens:

Obviously dis() has nothing to do if the module or class namespace has
no code objects to disassemble.

>>>> import tmp
>>>> tmp.a
> 1
>>>> import dis
>>>> dis.dis(tmp)
>>>> print(dis.dis(tmp))
> None
>
> This module contains no functions but it does contain lines of code
> and the interpreter will turn those into bytecode somewhere. I think
> that's what Dave meant.

Did you read the rest of my post? I went through an example of loading
the cached code object from a .pyc. But we can just compile one
instead:

    >>> code = compile(r'''
    ... 'module docstring'
    ... class Test(object):
    ...     'class docstring'
    ...     def spam(self):
    ...         pass
    ... ''', '<test>', 'exec')

    >>> dis.dis(code)
      2           0 LOAD_CONST               0 ('module docstring')
                  3 STORE_NAME               0 (__doc__)

      3           6 LOAD_CONST               1 ('Test')
                  9 LOAD_NAME                1 (object)
                 12 BUILD_TUPLE              1
                 15 LOAD_CONST               2 (<code object Test....>)
                 18 MAKE_FUNCTION            0
                 21 CALL_FUNCTION            0
                 24 BUILD_CLASS
                 25 STORE_NAME               2 (Test)
                 28 LOAD_CONST               3 (None)
                 31 RETURN_VALUE

    >>> dis.dis(code.co_consts[2])
      3           0 LOAD_NAME                0 (__name__)
                  3 STORE_NAME               1 (__module__)

      4           6 LOAD_CONST               0 ('class docstring')
                  9 STORE_NAME               2 (__doc__)

      5          12 LOAD_CONST               1 (<code object spam....>)
                 15 MAKE_FUNCTION            0
                 18 STORE_NAME               3 (spam)
                 21 LOAD_LOCALS
                 22 RETURN_VALUE

Let's exec this in a new module and run dis() on it:

    >>> testmod = imp.new_module('testmod')
    >>> exec code in vars(testmod)

    >>> dis.dis(testmod)
    Disassembly of Test:
    Disassembly of spam:
      6           0 LOAD_CONST               0 (None)
                  3 RETURN_VALUE

Admittedly it's not very interesting since spam() does nothing.

From davea at davea.name  Tue May 28 19:25:21 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 28 May 2013 13:25:21 -0400
Subject: [Tutor] Python "well-formed formulas"
In-Reply-To: <CAMbF=C8wLARUo8EXzHzE38g+-9Hab8J90gBog+LrkA=9_9Azyw@mail.gmail.com>
References: <CAMbF=C-ED7=t4ZQx2aZHc2Q0_jXW7nAnFmhvFZJwWoDuQ7pi4w@mail.gmail.com>
	<CANLXbfAcKn8PaqxPKe0Q-a7V4nizb3amjXAcD+0wYHk=1qb_yA@mail.gmail.com>
	<51A4A3C6.2040803@davea.name>
	<CAMbF=C8wLARUo8EXzHzE38g+-9Hab8J90gBog+LrkA=9_9Azyw@mail.gmail.com>
Message-ID: <51A4E881.7030604@davea.name>

On 05/28/2013 09:45 AM, Citizen Kant wrote:
>
>
>    <SNIP>
>
> I'm trying to figure out the rules on how to recognize when a combination
> of symbols is considered a well formed expression in Python. Since I
> couldn't find any doc that lists all Python syntax rules --or maybe the doc
> is too long to be managed by me right now--, stating all kinds of legal
> combination among its symbols, I had this idea that well formed expressions
> must respond to truth tables. I think I'm not pretty much interested on how
> each symbol like 9 or Z or + come to be truth (maybe I'm wrong) but in the
> truth of their combinations. Do I am in the correct path? Understanding the
> truth tables (which I'm not very familiarized with) would help me on
> writing Python in a more intuitive way?
>

Read the first 3 pages of the link Walter sent you:
 
http://homepage.divms.uiowa.edu/~sriram/16/spring12/lectureNotes/Feb8-2012.pdf

Then tell us what didn't you understand.  It's quite informal, and maybe 
not quite complete.  But it covers most of the grammar informally.

When an expression is not well-formed, you'll get a syntax error, which 
happens at compile time.

Later parts of the pdf are describing evaluation, which doesn't happen 
till the code runs.  These are two distinct phases, even if much of your 
code may be running immediately after compiling.  It's at evaluation 
time that you MAY be interested in truth tables.  And then only if parts 
of the expression are boolean.  There's no truth-table involvement in 
deciding the result of 12+3*4, but there is operator precedence, covered 
in the above pdf file.

The full grammar, in BNF, can be found at:

   http://docs.python.org/2/reference/grammar.html

Notice there's lots more to the language than expressions.  And that 
reading BNF is difficult without training.  It's a language, also, one 
that's used for describing the syntax of computer languages.  And some 
language constructs end up with a very confusing BNF.

I'm still bothered that all your symbol examples are single-character. 
But a symbol is 1 OR MORE characters, with certain restrictions on what 
they can be.  And the first phase of compilation is to tokenize the 
source code.  For a simple language, that might be splitting the text by 
white space.  In Python, there are other rules applied for tokenizing. 
For example, in an expression, a * symbol that doesn't have another one 
immediately next to it is a multiply operator.  But if there are two, 
it's the exponentiation operator.

-- 
DaveA

From sparkle.plenty12481632 at gmail.com  Tue May 28 19:25:51 2013
From: sparkle.plenty12481632 at gmail.com (sparkle Plenty)
Date: Tue, 28 May 2013 13:25:51 -0400
Subject: [Tutor] Socket Error Handling Syntax
Message-ID: <CABeS=HaCSZo__PrhN9Jxy7-9oGRfJZ9DY5BHD8EHhsdJHmXd4g@mail.gmail.com>

Python 3.3, Windows operating system:

I am communicating with a device using a Python script and I am
coding except clauses in my send and receive functions to handle a
particular error. I can't find a WinError example, and I can't get the
syntax right.  I have researched this and tried the following:

while not_sent:
    try:
        (my socket send code)

    except OSError.WinError.10057
        (this failed)
    except OSError.WSAENOTCONN
        (this failed)
    except OSError.winerror.WSANOTCONN
        (this failed)

I have another general except/as clause already coded and debugged for each
function to catch unexpected errors and shut down.  I need to catch and
handle 10057 exceptions when they occur and keep running.  I know 10057 is
a WinError, which is a subset of OSError, I just can't find the right
syntax for it.  I would appreciate some help on this one.

Thank you.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130528/98512724/attachment.html>

From oscar.j.benjamin at gmail.com  Tue May 28 19:58:05 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Tue, 28 May 2013 18:58:05 +0100
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <CACL+1asHLDVgdJvP1C+TjhSNpXbGLwjWn9KX+U9DkXAWtiKw-Q@mail.gmail.com>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
	<CAHVvXxSufr-O-DhoL3brWvsUYMF5yY3ZP-F-syGyGo8ZzgRZNg@mail.gmail.com>
	<CALRAYNVTx2ZoZsdMrACkpupYJg9Mq3tLio-OouwHEqp26B9AAQ@mail.gmail.com>
	<ko0pnf$9kb$1@ger.gmane.org>
	<CALRAYNXTwtUxPRPLtsd8QEDX_Snzq38OHayMFQ9Bo89XD=JsNQ@mail.gmail.com>
	<51A4928F.3040106@davea.name>
	<CACL+1auWtQhODrj6fpJ9vtOr8eG7S-kjMkOHv3FdLKE4oiyboA@mail.gmail.com>
	<CAHVvXxTyqY+3kPs3F5riZs1dMzKZXTfFad66b6DOYjUu-2YE8g@mail.gmail.com>
	<CACL+1asHLDVgdJvP1C+TjhSNpXbGLwjWn9KX+U9DkXAWtiKw-Q@mail.gmail.com>
Message-ID: <CAHVvXxRf_q9CXBg46XZ+tp6T94YbEufQq0PFfq6WfdDkWn3bTQ@mail.gmail.com>

On 28 May 2013 18:24, eryksun <eryksun at gmail.com> wrote:
> On Tue, May 28, 2013 at 1:12 PM, Oscar Benjamin
> <oscar.j.benjamin at gmail.com> wrote:
>> On 28 May 2013 17:48, eryksun <eryksun at gmail.com> wrote:
>>>
>>> The argument for dis.dis() can be a module, class, function or code
>>> object. It disassembles all the top-level code objects that it finds,
>>> but it doesn't recursively disassemble code objects that are in the
>>> co_consts.
>>
>> What do you mean by this? I tried passing a test module into dis.dis
>> and nothing happens:
>
> Obviously dis() has nothing to do if the module or class namespace has
> no code objects to disassemble.
>
> Did you read the rest of my post?

Yes. Although I'll admit that I didn't fully absorb all of it. :)

> I went through an example of loading
> the cached code object from a .pyc. But we can just compile one
> instead:

Okay, got you. So the way to dis an ordinary module is to load the .py
file as a string first:

>>> dis.dis(compile(open('tmp.py').read(), 'tmp', 'exec'))
  2           0 LOAD_CONST               0 (1)
              3 STORE_NAME               0 (a)

  3           6 LOAD_CONST               1 (2)
              9 STORE_NAME               1 (b)

  4          12 LOAD_NAME                0 (a)
             15 LOAD_NAME                1 (b)
             18 BINARY_ADD
             19 STORE_NAME               2 (c)
             22 LOAD_CONST               2 (None)
             25 RETURN_VALUE

So what happens to the code object for the top-level code in the
module itself when it is imported in the normal way? Is it just
discarded once import is complete? Is it temporarily accessible during
import?


Oscar

From eryksun at gmail.com  Tue May 28 20:06:10 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 28 May 2013 14:06:10 -0400
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <CAHVvXxRf_q9CXBg46XZ+tp6T94YbEufQq0PFfq6WfdDkWn3bTQ@mail.gmail.com>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
	<CAHVvXxSufr-O-DhoL3brWvsUYMF5yY3ZP-F-syGyGo8ZzgRZNg@mail.gmail.com>
	<CALRAYNVTx2ZoZsdMrACkpupYJg9Mq3tLio-OouwHEqp26B9AAQ@mail.gmail.com>
	<ko0pnf$9kb$1@ger.gmane.org>
	<CALRAYNXTwtUxPRPLtsd8QEDX_Snzq38OHayMFQ9Bo89XD=JsNQ@mail.gmail.com>
	<51A4928F.3040106@davea.name>
	<CACL+1auWtQhODrj6fpJ9vtOr8eG7S-kjMkOHv3FdLKE4oiyboA@mail.gmail.com>
	<CAHVvXxTyqY+3kPs3F5riZs1dMzKZXTfFad66b6DOYjUu-2YE8g@mail.gmail.com>
	<CACL+1asHLDVgdJvP1C+TjhSNpXbGLwjWn9KX+U9DkXAWtiKw-Q@mail.gmail.com>
	<CAHVvXxRf_q9CXBg46XZ+tp6T94YbEufQq0PFfq6WfdDkWn3bTQ@mail.gmail.com>
Message-ID: <CACL+1atGQ7Hhq=838Z7Cpr7s-TTCb4PY-54cx6v17+b6eBBCag@mail.gmail.com>

On Tue, May 28, 2013 at 1:58 PM, Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
>
> So what happens to the code object for the top-level code in the
> module itself when it is imported in the normal way? Is it just
> discarded once import is complete? Is it temporarily accessible during
> import?

Normally, nothing holds a reference to it, so it gets deallocated, as
do the anonymous functions used to build classes. However, in CPython
the current frame is accessible during import via sys._getframe(). The
code object is the f_code attribute:

    >>> code = compile(r'''
    ... import sys
    ... frame = sys._getframe()
    ... ''', '<test>', 'exec')
    >>>
    >>> ns = {}
    >>> exec code in ns
    >>> dis.dis(ns['frame'].f_code)
      2           0 LOAD_CONST               0 (0)
                  3 LOAD_CONST               1 (None)
                  6 IMPORT_NAME              0 (sys)
                  9 STORE_NAME               0 (sys)

      3          12 LOAD_NAME                0 (sys)
                 15 LOAD_ATTR                1 (_getframe)
                 18 CALL_FUNCTION            0
                 21 STORE_NAME               2 (frame)
                 24 LOAD_CONST               1 (None)
                 27 RETURN_VALUE

From andipersti at gmail.com  Tue May 28 21:27:51 2013
From: andipersti at gmail.com (Andreas Perstinger)
Date: Tue, 28 May 2013 21:27:51 +0200
Subject: [Tutor] Socket Error Handling Syntax
In-Reply-To: <CABeS=HaCSZo__PrhN9Jxy7-9oGRfJZ9DY5BHD8EHhsdJHmXd4g@mail.gmail.com>
References: <CABeS=HaCSZo__PrhN9Jxy7-9oGRfJZ9DY5BHD8EHhsdJHmXd4g@mail.gmail.com>
Message-ID: <51A50537.3050201@gmail.com>

On 28.05.2013 19:25, sparkle Plenty wrote:
> I need to catch and handle 10057 exceptions when they occur and keep
> running.  I know 10057 is a WinError, which is a subset of OSError, I
> just can't find the right syntax for it.  I would appreciate some
> help on this one.

I have neither Windows nor Python3.3 to test but according to the docs, 
"winerror" is an attribute of the OSError exception ( 
http://docs.python.org/3/library/exceptions.html?highlight=oserror#OSError 
). Thus something like

try:
    # some code
except OSError as e:
    if e.winerror == 10057:
       # do error handling
    else:
       raise # re-raise any other error

should work.

Bye, Andreas

From sparkle.plenty12481632 at gmail.com  Tue May 28 21:37:13 2013
From: sparkle.plenty12481632 at gmail.com (sparkle Plenty)
Date: Tue, 28 May 2013 15:37:13 -0400
Subject: [Tutor] Socket Error Handling Syntax
In-Reply-To: <CABeS=HaCSZo__PrhN9Jxy7-9oGRfJZ9DY5BHD8EHhsdJHmXd4g@mail.gmail.com>
References: <CABeS=HaCSZo__PrhN9Jxy7-9oGRfJZ9DY5BHD8EHhsdJHmXd4g@mail.gmail.com>
Message-ID: <CABeS=Hbz8jy-m6y5Ujk_cjonCUKver4rd+=PDv4kmBuozsbWoA@mail.gmail.com>

If I use an if statement, I cannot use continue after I do my error
handling, so I am really trying to use the except errorname: instead of an
if statement.  Therefore, I have to find the correct error name to identify
the 10057 condition to the interpreter, but thanks anyway, Andreas.


On Tue, May 28, 2013 at 1:25 PM, sparkle Plenty <
sparkle.plenty12481632 at gmail.com> wrote:

> Python 3.3, Windows operating system:
>
> I am communicating with a device using a Python script and I am
> coding except clauses in my send and receive functions to handle a
> particular error. I can't find a WinError example, and I can't get the
> syntax right.  I have researched this and tried the following:
>
> while not_sent:
>     try:
>         (my socket send code)
>
>     except OSError.WinError.10057
>         (this failed)
>     except OSError.WSAENOTCONN
>         (this failed)
>     except OSError.winerror.WSANOTCONN
>         (this failed)
>
> I have another general except/as clause already coded and debugged for
> each function to catch unexpected errors and shut down.  I need to catch
> and handle 10057 exceptions when they occur and keep running.  I know 10057
> is a WinError, which is a subset of OSError, I just can't find the right
> syntax for it.  I would appreciate some help on this one.
>
> Thank you.
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130528/40331392/attachment-0001.html>

From davea at davea.name  Tue May 28 21:49:06 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 28 May 2013 15:49:06 -0400
Subject: [Tutor] Socket Error Handling Syntax
In-Reply-To: <CABeS=Hbz8jy-m6y5Ujk_cjonCUKver4rd+=PDv4kmBuozsbWoA@mail.gmail.com>
References: <CABeS=HaCSZo__PrhN9Jxy7-9oGRfJZ9DY5BHD8EHhsdJHmXd4g@mail.gmail.com>
	<CABeS=Hbz8jy-m6y5Ujk_cjonCUKver4rd+=PDv4kmBuozsbWoA@mail.gmail.com>
Message-ID: <51A50A32.6030204@davea.name>

On 05/28/2013 03:37 PM, sparkle Plenty wrote:
> If I use an if statement, I cannot use continue after I do my error
> handling,

The presence of an if statement cannot affect whether or not a continue 
can work.  If you give a concrete code example, somebody will be able to 
identify the confusion.

And while you're at it, instead of saying "this failed" why not actually 
show us the traceback?  Big difference between a name error and a type 
problem.

> so I am really trying to use the except errorname: instead of an
> if statement.  Therefore, I have to find the correct error name to identify
> the 10057 condition to the interpreter, but thanks anyway, Andreas.
>

except clauses do not work on "error names" they work on exception 
types.  I don't use Windows, but I doubt if there's a separate exception 
type for 10057.

Incidentally, if you ever do get one of those except clauses to fire, 
you're going to want an exception object. Something like:

    except OSError as theError:

Then you can check the error code for anything you like.


-- 
DaveA

From andipersti at gmail.com  Tue May 28 22:02:53 2013
From: andipersti at gmail.com (Andreas Perstinger)
Date: Tue, 28 May 2013 22:02:53 +0200
Subject: [Tutor] Socket Error Handling Syntax
In-Reply-To: <CABeS=Hbz8jy-m6y5Ujk_cjonCUKver4rd+=PDv4kmBuozsbWoA@mail.gmail.com>
References: <CABeS=HaCSZo__PrhN9Jxy7-9oGRfJZ9DY5BHD8EHhsdJHmXd4g@mail.gmail.com>
	<CABeS=Hbz8jy-m6y5Ujk_cjonCUKver4rd+=PDv4kmBuozsbWoA@mail.gmail.com>
Message-ID: <51A50D6D.50305@gmail.com>

On 28.05.2013 21:37, sparkle Plenty wrote:
> If I use an if statement, I cannot use continue after I do my error
> handling, so I am really trying to use the except errorname: instead of an
> if statement.

I think you haven't understood the code snippet I've posted. The 
if-statement is inside the except clause to check the Windows error number.

> Therefore, I have to find the correct error name to identify
> the 10057 condition to the interpreter,

As Dave told you, the actual traceback will tell you the name of the 
exception.

Bye, Andreas

From cybervigilante at gmail.com  Tue May 28 22:15:38 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Tue, 28 May 2013 13:15:38 -0700
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <51A4928F.3040106@davea.name>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
	<CAHVvXxSufr-O-DhoL3brWvsUYMF5yY3ZP-F-syGyGo8ZzgRZNg@mail.gmail.com>
	<CALRAYNVTx2ZoZsdMrACkpupYJg9Mq3tLio-OouwHEqp26B9AAQ@mail.gmail.com>
	<ko0pnf$9kb$1@ger.gmane.org>
	<CALRAYNXTwtUxPRPLtsd8QEDX_Snzq38OHayMFQ9Bo89XD=JsNQ@mail.gmail.com>
	<51A4928F.3040106@davea.name>
Message-ID: <CALRAYNXfrpr025thJC7hEyCYRiugobDBMFo5tRZ8CqPhPxPEFA@mail.gmail.com>

On 28 May 2013 04:18, Dave Angel <davea at davea.name> wrote:
> On 05/28/2013 07:02 AM, Jim Mooney wrote:

> Alan and Devin already gave more specifics, but to repeat,
>
> import dis
>
> dis.dis(myfunction)
>
> will disassemble one function.

I think authors miss a didactic opportunity by not using bytecode as a
teaching tool now and then, since it's easily explained, at least for
basic statements. Some concepts seem hard to get across in English but
are obvious when you actually see what they do, step-by-step. Not true
for everything for course, but for some things.

I guess it has to do with sales. If someone new to any programming
opens a Python book to buy and sees all these prettily laid-out Python
statements that look almost like natural language, only more ordered,
but then sees a page of bytecode, they'd probably drop the book  and
run ;')

Jim

From alan.gauld at btinternet.com  Wed May 29 01:27:20 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 29 May 2013 00:27:20 +0100
Subject: [Tutor] bytecode primer, and avoiding a monster download
In-Reply-To: <CALRAYNXfrpr025thJC7hEyCYRiugobDBMFo5tRZ8CqPhPxPEFA@mail.gmail.com>
References: <CALRAYNWi6N4XTd2fo2-2MNz362aic_3UHnZK=iG-dh_4E6vaog@mail.gmail.com>
	<CAHVvXxSufr-O-DhoL3brWvsUYMF5yY3ZP-F-syGyGo8ZzgRZNg@mail.gmail.com>
	<CALRAYNVTx2ZoZsdMrACkpupYJg9Mq3tLio-OouwHEqp26B9AAQ@mail.gmail.com>
	<ko0pnf$9kb$1@ger.gmane.org>
	<CALRAYNXTwtUxPRPLtsd8QEDX_Snzq38OHayMFQ9Bo89XD=JsNQ@mail.gmail.com>
	<51A4928F.3040106@davea.name>
	<CALRAYNXfrpr025thJC7hEyCYRiugobDBMFo5tRZ8CqPhPxPEFA@mail.gmail.com>
Message-ID: <ko3egj$tmr$1@ger.gmane.org>

On 28/05/13 21:15, Jim Mooney wrote:

> I think authors miss a didactic opportunity by not using bytecode as a
> teaching tool now and then, since it's easily explained, at least for
> basic statements.

Assuming you mean the assembler statements then it may be true.
Looking at Bytecode is just an exercise in pain for first year 
programming students... or a way to reverse engineer a binary
file for which you don't have source :-(

> I guess it has to do with sales. If someone new to any programming
> opens a Python book to buy and sees all these prettily laid-out Python
> statements that look almost like natural language, only more ordered,
> but then sees a page of bytecode, they'd probably drop the book  and
> run ;')

It's not just sales, it's more that the majority of programmers 
(including professionals) simply have no idea how a computer does things 
internally. They don't think about programs that way they think of them 
in terms of the abstract calculation engine that a computer pretends to 
be. Seeing assembler would not help them at all. But if someone has any 
appreciation of the computer architecture, how CPU and memory are 
related then yes, assembler can clarify some things.

But, especially in a language like Python, too much awareness of how the 
language works at the machine level can be counter productive because 
you start programming for the machine. And that's dangerous because the 
mechanisms are liable to change in a future version and your code stops 
doing what you think it does. Occasionally it is necessary but I've been 
using Python more or less exclusively for
the last 12 years and I've only twice had to delve into the assembler
(and maybe another 5 or 6 times out of curiosity).

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From eryksun at gmail.com  Wed May 29 02:53:29 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 28 May 2013 20:53:29 -0400
Subject: [Tutor] Socket Error Handling Syntax
In-Reply-To: <51A50A32.6030204@davea.name>
References: <CABeS=HaCSZo__PrhN9Jxy7-9oGRfJZ9DY5BHD8EHhsdJHmXd4g@mail.gmail.com>
	<CABeS=Hbz8jy-m6y5Ujk_cjonCUKver4rd+=PDv4kmBuozsbWoA@mail.gmail.com>
	<51A50A32.6030204@davea.name>
Message-ID: <CACL+1asT-cMFw-aXhHMA44K=SsSHF21NpHuy5sDaiUjd=ccU5A@mail.gmail.com>

On Tue, May 28, 2013 at 3:49 PM, Dave Angel <davea at davea.name> wrote:
> I don't use Windows, but I doubt if there's a separate exception
> type for 10057.

Windows sockets error codes at or above 10000 aren't mapped to POSIX
error codes. Instead errno is set directly from winerror. So there's
no reason to look at winerror in this case.

Use the errno module:

Windows:

    >>> errno.errorcode[10057] # Windows-specific name
    'WSAENOTCONN'

    >>> errno.ENOTCONN
    10057

Linux:

    >>> errno.ENOTCONN
    107

>From MSDN, Windows Socket Error Codes:

WSAENOTCONN 10057
Socket is not connected.
A request to send or receive data was disallowed because the socket is
not connected and (when sending on a datagram socket using sendto) no
address was supplied. Any other type of operation might also return
this error?for example, setsockopt setting SO_KEEPALIVE if the
connection has been reset.

http://msdn.microsoft.com/en-us/library/ms740668

From steve at pearwood.info  Wed May 29 04:34:52 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 29 May 2013 12:34:52 +1000
Subject: [Tutor] a little loop
In-Reply-To: <201305272054.58446.tjhanson@yahoo.com>
References: <201305272054.58446.tjhanson@yahoo.com>
Message-ID: <51A5694C.8080908@pearwood.info>

On 28/05/13 13:54, Tim Hanson wrote:
> Okay, so I made it to FOR loops in the Lutz book.  A couple of days ago I was
> helped here with the .join method for creating strings from lists or tuples of
> strings.  I got to wondering if I could just, for the sake of learning, do the
> same thing in a FOR loop, since that's today's chapter:
>
> x=0; ham=''; b=['s','p','a','m'] #or, b=('s','p','a','m')
> for t in b:
> 	ham=ham+b[x]
> 	print(ham);x+=1

There's no need to manually count the index that you are looking at, and no need to manually look up the character using b[x]. That's what the for-loop is already doing. (Also, a good habit to get into is using *meaningful* variable names, not one-letter cryptic names.)


ham = ''
for char in ['s', 'p', 'a', 'm']:
     ham = ham + char
     print(ham)


But wait, there's more! There's no need to split the string "spam" up into characters yourself, since strings can be iterated over too:

ham = ''
for char in 'spam':
     ham = ham + char
     print(ham)


However, a word of warning: although you *can* assemble a new string character by character like that, you should not, because it risks being very slow. *Painfully* slow. If you want to hear the details, please ask, but it risks being slow for much the same reason as the infamous Shlemiel the Painter Algorithm:

http://www.joelonsoftware.com/articles/fog0000000319.html


So while it is okay to assemble strings using + if there are only a few pieces, you should avoid doing it whenever there is a chance of there being many pieces. The standard method for assembling a string from a collection of substrings is to do it in one go, using the join method, instead of piece by piece:

pieces = ['NOBODY', 'expects', 'the', 'Spanish', 'Inquisition!']
mystring = ' '.join(pieces)  # join with a single space between each piece
print(mystring)


The joiner can be any string you like, including the empty string '', it doesn't have to be a space.



-- 
Steven

From cybervigilante at gmail.com  Wed May 29 05:20:35 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Tue, 28 May 2013 20:20:35 -0700
Subject: [Tutor] a little loop
In-Reply-To: <51A5694C.8080908@pearwood.info>
References: <201305272054.58446.tjhanson@yahoo.com>
	<51A5694C.8080908@pearwood.info>
Message-ID: <CALRAYNWJxoMd7N3n4F0sa0g4-Z_LhrU2uhRpVu=AAjZnNQJ6=Q@mail.gmail.com>

On 28 May 2013 19:34, Steven D'Aprano <steve at pearwood.info> wrote:

The standard method for assembling a string from a collection
> of substrings is to do it in one go, using the join method,

Wow, that means I can do this:   print  ''.join('But this parrot is dead!')

-- 
Jim
Ornhgvshy vf orggre guna htyl

From andipersti at gmail.com  Wed May 29 07:33:16 2013
From: andipersti at gmail.com (Andreas Perstinger)
Date: Wed, 29 May 2013 07:33:16 +0200
Subject: [Tutor] a little loop
In-Reply-To: <CALRAYNWJxoMd7N3n4F0sa0g4-Z_LhrU2uhRpVu=AAjZnNQJ6=Q@mail.gmail.com>
References: <201305272054.58446.tjhanson@yahoo.com>
	<51A5694C.8080908@pearwood.info>
	<CALRAYNWJxoMd7N3n4F0sa0g4-Z_LhrU2uhRpVu=AAjZnNQJ6=Q@mail.gmail.com>
Message-ID: <51A5931C.9020904@gmail.com>

On 29.05.2013 05:20, Jim Mooney wrote:
> On 28 May 2013 19:34, Steven D'Aprano <steve at pearwood.info> wrote:
>
> The standard method for assembling a string from a collection
>> of substrings is to do it in one go, using the join method,
>
> Wow, that means I can do this:   print  ''.join('But this parrot is dead!')

But why do you want to do that?

"join" iterates over the string you gave as an argument and puts the 
empty string in between each character:
'B' + '' + 'u' + '' + 't' + '' + ...

Thus you end up with the same string as you started.

Or did you mean something like:

 >>> print '<>'.join('But this parrot is dead!')
B<>u<>t<> <>t<>h<>i<>s<> <>p<>a<>r<>r<>o<>t<> <>i<>s<> <>d<>e<>a<>d<>!

Bye, Andreas

From cybervigilante at gmail.com  Wed May 29 07:58:34 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Tue, 28 May 2013 22:58:34 -0700
Subject: [Tutor] a little loop
In-Reply-To: <51A5931C.9020904@gmail.com>
References: <201305272054.58446.tjhanson@yahoo.com>
	<51A5694C.8080908@pearwood.info>
	<CALRAYNWJxoMd7N3n4F0sa0g4-Z_LhrU2uhRpVu=AAjZnNQJ6=Q@mail.gmail.com>
	<51A5931C.9020904@gmail.com>
Message-ID: <CALRAYNWXqvuRFvYcFun=oq0aGf+HE5NjQF5K61PW1bMy5UqKfw@mail.gmail.com>

On 28 May 2013 22:33, Andreas Perstinger <andipersti at gmail.com> wrote:

> Wow, that means I can do this:   print  ''.join('But this parrot is dead!')
>>
>
> But why do you want to do that?
>

Actually, I meant to do this:

print ''.join(' '.join('But this parrot is dead'.split()))

Which has the same effect.

There is an autodidactic purpose. I kept confusing the join statement by
putting the joined string first, them the joiner, bur fooling around like
this solidifies things in my mind ;')

Jim
Ornhgvshy vf orggre guna htyl
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130528/f2dfd4c8/attachment.html>

From fomcl at yahoo.com  Wed May 29 10:11:34 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Wed, 29 May 2013 01:11:34 -0700 (PDT)
Subject: [Tutor] walk registry using _winreg
Message-ID: <1369815094.27580.YahooMailNeo@web163806.mail.gq1.yahoo.com>

Hello,

I created a program to go through the windows registry and look for a certain key ("file_locations", though in the example I am using a key that every windows user has on his/her computer). If found, I want to replace the data associated with value "temp_dir" in that key. I have chosen this strategy because the exact registry keys may have changed from version to version. Also, multiple versions of the program may be installed on a given computer. I pasted the code below this mail, but also here: http://pastebin.com/TEkyekfi

Is this the correct way to do this? I would actually prefer to specify only "valueNameToSearch" and not also "keyToSearch". As in: start walking through the registry starting at <regkey>, return every key where a temp_dir is defined.

Thank you in advance!


Regards,
Albert-Jan


import _winreg
import os

global __debug__
__debug__ = True

def walkRegistry(regkey, keyToSearch="file_locations",
???????????????? valueNameToSearch="temp_dir", verbose=False):
??? """Recursively search the Windows registry (HKEY_CURRENT_USER),
??? starting at top <regkey>. Return a list of three tuples that contain
??? the registry key, the value and the associated data"""
??? if verbose:
??????? print regkey
??? aReg = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, regkey)
??? i, keys, founds = 0, [], []
??? try:
??????? while True:
??????????? i += 1
??????????? key = _winreg.EnumKey(aReg, i)
??????????? keys.append(key)
??????????? if key == keyToSearch:
??????????????? keyx = os.path.join(regkey, key)
??????????????? aReg = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, keyx)
??????????????? data, type_ = _winreg.QueryValueEx(aReg, valueNameToSearch)
??????????????? founds.append((keyx, valueNameToSearch, data))
??? except WindowsError:
??????? for key in keys:
??????????? try:
??????????????? new_regkey = os.path.join(regkey, key)
??????????????? walkRegistry(new_regkey, keyToSearch,
???????????????????????????? valueNameToSearch, verbose)
??????????? except WindowsError:
??????????????? pass
??? return founds

def setRegistry(regkey, keyToSet, valueToSet, replacementData, verbose=False):
??? """Search for <keyToSet> starting at top <regkey>. If <keyToSet> is found
??? exactly once, replace registry data associated with <valueToSet> with
??? <replacementData>."""
??? founds = walkRegistry(regkey, keyToSet, valueToSet, verbose)
??? if not founds:
??????? return
??? elif len(founds) == 1:
??????? keyx, valueNameToSearch, data = founds[0]
??? else:
??????? msg = "Registry value %r is found multiple times"
??????? raise ValueError(msg % valueToSet)

??? if not __debug__:
??????? try:
??????????? key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, keyx,
????????????????????????????????? 0, _winreg.KEY_ALL_ACCESS)
??????? except:
??????????? key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, regkey)
??????? _winreg.SetValueEx(keyx, valueToSet, 0, _winreg.REG_SZ,
?????????????????????????? replacementData)
??????? _winreg.CloseKey(keyx)

regkey = u"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer"
print founds = walkRegistry(regkey, u"Shell Folders", u"Cookies", True)
setRegistry(regkey, u"Shell Folders", u"Cookies", "this is the replacement value", False)


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
?~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~?

From davea at davea.name  Wed May 29 14:11:18 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 29 May 2013 08:11:18 -0400
Subject: [Tutor] walk registry using _winreg
In-Reply-To: <1369815094.27580.YahooMailNeo@web163806.mail.gq1.yahoo.com>
References: <1369815094.27580.YahooMailNeo@web163806.mail.gq1.yahoo.com>
Message-ID: <51A5F066.9020004@davea.name>

On 05/29/2013 04:11 AM, Albert-Jan Roskam wrote:
> Hello,
>
> I created a program to go through the windows registry and look for a certain key ("file_locations", though in the example I am using a key that every windows user has on his/her computer). If found, I want to replace the data associated with value "temp_dir" in that key. I have chosen this strategy because the exact registry keys may have changed from version to version. Also, multiple versions of the program may be installed on a given computer. I pasted the code below this mail, but also here: http://pastebin.com/TEkyekfi
>
> Is this the correct way to do this? I would actually prefer to specify only "valueNameToSearch" and not also "keyToSearch". As in: start walking through the registry starting at <regkey>, return every key where a temp_dir is defined.
>
> Thank you in advance!
>
>
> Regards,
> Albert-Jan
>
Please specify Python version.  I'll assume 2.7.  Obviously this is 
Windows, though it's also conceivable that it matters which version of 
Windows (XP, Win8, whatever).

First comment is that I'd be writing walkRegistry as a generator, using 
yield for the items found, rather than building a list.  It's generally 
easier to reuse that way, and won't get you in trouble if there are tons 
of matches.  See os.walk for an example.

A generator also would naturally eliminate the need to know KeyToSearch.

>
> import _winreg
> import os
>
> global __debug__
> __debug__ = True
>
> def walkRegistry(regkey, keyToSearch="file_locations",
>                   valueNameToSearch="temp_dir", verbose=False):
>      """Recursively search the Windows registry (HKEY_CURRENT_USER),
>      starting at top <regkey>. Return a list of three tuples that contain
>      the registry key, the value and the associated data"""
>      if verbose:
>          print regkey
>      aReg = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, regkey)
>      i, keys, founds = 0, [], []
>      try:
>          while True:
>              i += 1
>              key = _winreg.EnumKey(aReg, i)

I believe these are zero-based indexes, so you're skipping the first one.

>              keys.append(key)
>              if key == keyToSearch:

If this were a generator, you'd not be restricting the key here.  By 
restricting this key, you're limiting which subkeys you're going to 
search, and in the general case, I believe you're currently skipping 
values incorrectly.

>                  keyx = os.path.join(regkey, key)
>                  aReg = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, keyx)

Unsure here, but having another open here feels wrong.

>                  data, type_ = _winreg.QueryValueEx(aReg, valueNameToSearch)
>                  founds.append((keyx, valueNameToSearch, data))

Generally, recursion should happen here, rather than building a list and 
doing the recursion below.

>      except WindowsError:
>          for key in keys:
>              try:
>                  new_regkey = os.path.join(regkey, key)
>                  walkRegistry(new_regkey, keyToSearch,
>                               valueNameToSearch, verbose)

Nesting exceptions makes me nervous, and doing it recursively, makes me 
even more so.  If you move the recursion to the above area, then all the 
exception has to do is break out of the while loop.

>              except WindowsError:
>                  pass
>      return founds
>
> def setRegistry(regkey, keyToSet, valueToSet, replacementData, verbose=False):
>      """Search for <keyToSet> starting at top <regkey>. If <keyToSet> is found
>      exactly once, replace registry data associated with <valueToSet> with
>      <replacementData>."""
>      founds = walkRegistry(regkey, keyToSet, valueToSet, verbose)

If you changed walkRegistry as I suggest above, then this call becomes 
something like:
        for item in walkRegistry(regkey, keyToSet, valueToSet, verbose):


and inside the loop, you'll be testing the 'item' tuple for your 
criteria.  The test is done here, and NOT in the walkRegistry() function.

>      if not founds:
>          return
>      elif len(founds) == 1:
>          keyx, valueNameToSearch, data = founds[0]
>      else:
>          msg = "Registry value %r is found multiple times"
>          raise ValueError(msg % valueToSet)
>
>      if not __debug__:
>          try:
>              key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, keyx,
>                                    0, _winreg.KEY_ALL_ACCESS)
>          except:
>              key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, regkey)
>          _winreg.SetValueEx(keyx, valueToSet, 0, _winreg.REG_SZ,
>                             replacementData)
>          _winreg.CloseKey(keyx)
>
> regkey = u"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer"
> print founds = walkRegistry(regkey, u"Shell Folders", u"Cookies", True)
> setRegistry(regkey, u"Shell Folders", u"Cookies", "this is the replacement value", False)
>
>


-- 
DaveA

From robertvstepp at gmail.com  Wed May 29 17:38:17 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Wed, 29 May 2013 10:38:17 -0500
Subject: [Tutor] a little loop
In-Reply-To: <51A5694C.8080908@pearwood.info>
References: <201305272054.58446.tjhanson@yahoo.com>
	<51A5694C.8080908@pearwood.info>
Message-ID: <CANDiX9JG79AcAZzrCOK4FX672mTy8LebytVaT4wSLBREPwGc-Q@mail.gmail.com>

On Tue, May 28, 2013 at 9:34 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>
> On 28/05/13 13:54, Tim Hanson wrote:
>>

>
> However, a word of warning: although you *can* assemble a new string character by character like that, you should not, because it risks being very slow. *Painfully* slow. If you want to hear the details, please ask, but it risks being slow for much the same reason as the infamous Shlemiel the Painter Algorithm:
>
> http://www.joelonsoftware.com/articles/fog0000000319.html
>

Okay, I will come out of lurking and ask: What are the details?

BTW, interesting article and interesting site! I will have to bookmark
this one and come back for more exploration.

Thanks!
boB

From oscar.j.benjamin at gmail.com  Wed May 29 18:07:06 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Wed, 29 May 2013 17:07:06 +0100
Subject: [Tutor] a little loop
In-Reply-To: <CANDiX9JG79AcAZzrCOK4FX672mTy8LebytVaT4wSLBREPwGc-Q@mail.gmail.com>
References: <201305272054.58446.tjhanson@yahoo.com>
	<51A5694C.8080908@pearwood.info>
	<CANDiX9JG79AcAZzrCOK4FX672mTy8LebytVaT4wSLBREPwGc-Q@mail.gmail.com>
Message-ID: <CAHVvXxTeGracFatdCsVNOmSMZnFawsbzwTQoNWn1B44oOQwfOg@mail.gmail.com>

On 29 May 2013 16:38, boB Stepp <robertvstepp at gmail.com> wrote:
> On Tue, May 28, 2013 at 9:34 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>>
>> However, a word of warning: although you *can* assemble a new string character by character like that, you should not, because it risks being very slow. *Painfully* slow. If you want to hear the details, please ask, but it risks being slow for much the same reason as the infamous Shlemiel the Painter Algorithm:
>>
>> http://www.joelonsoftware.com/articles/fog0000000319.html
>
> Okay, I will come out of lurking and ask: What are the details?

Here is the code that Steven was referring to:

ham = ''
for char in 'spam':
    ham = ham + char
    print(ham)

What this code does is to create an empty string ham. Then for each
character in 'spam' is creates a new string by appending the character
to ham. However Python cannot append strings it can only create new
strings since strings are immutable*.

On the first iteration of the loop the zero length string is combined
with the character and a string of length 1 is created.
On the second a new string of length 2 is created.
On the third a new string of length 3 is created.
On the fourth a new string of length 4 is created.

So four strings are create with lengths 0, 1, 2, 3, 4.

If we did this with N characters then N strings would be created with
lengths 0, 1, 2, 3, ... , N. If cost of creating each string is
proportional to its length then the cost of the operation as a whole
is proportional to 0 + 1 + 2 + 3 + ... + N. The general formula to
compute this sum is (N**2 + N)/2. In other words the whole operation
is quadratic O(N**2) in the number of characters that are combined.

The Shlemiel the painter story describes a similar operation in which
the time taken to paint each section increases linearly as more
sections get painted. The result is that the time taken for Shlemiel
to paint a stretch of road is proportional to the square of its length
when it should just be proportional to its length.

I don't know exactly how str.join is implemented but it does not use
this quadratic algorithm. For example if str.join would first compute
the length of the resulting string first then it can allocate memory
for exactly one string of that length and copy each substring to the
appropriate place (actually I imagine it uses an exponentially
resizing buffer but this isn't important).

* CPython actually has an optimisation that can append strings in
precisely this situation. However it is an implementation detail of
CPython that may change and it does not work in other interpreters
e.g. Jython. Using this kind of code can damage portability since your
program may run fine in CPython but fail in other interpreters.


Oscar

From robertvstepp at gmail.com  Wed May 29 18:51:12 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Wed, 29 May 2013 11:51:12 -0500
Subject: [Tutor] a little loop
In-Reply-To: <CAHVvXxTeGracFatdCsVNOmSMZnFawsbzwTQoNWn1B44oOQwfOg@mail.gmail.com>
References: <201305272054.58446.tjhanson@yahoo.com>
	<51A5694C.8080908@pearwood.info>
	<CANDiX9JG79AcAZzrCOK4FX672mTy8LebytVaT4wSLBREPwGc-Q@mail.gmail.com>
	<CAHVvXxTeGracFatdCsVNOmSMZnFawsbzwTQoNWn1B44oOQwfOg@mail.gmail.com>
Message-ID: <CANDiX9KN1+97d_Wm-2vu54aRvRACaQ5pivPSapQKwML+Ypf-DA@mail.gmail.com>

On Wed, May 29, 2013 at 11:07 AM, Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
> On 29 May 2013 16:38, boB Stepp <robertvstepp at gmail.com> wrote:
>> On Tue, May 28, 2013 at 9:34 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>>>
>>> However, a word of warning: although you *can* assemble a new string character by character like that, you should not, because it risks being very slow. *Painfully* slow. If you want to hear the details, please ask, but it risks being slow for much the same reason as the infamous Shlemiel the Painter Algorithm:
>>>
>>> http://www.joelonsoftware.com/articles/fog0000000319.html
>>
>> Okay, I will come out of lurking and ask: What are the details?
>
> Here is the code that Steven was referring to:
>
> ham = ''
> for char in 'spam':
>     ham = ham + char
>     print(ham)
>
> What this code does is to create an empty string ham. Then for each
> character in 'spam' is creates a new string by appending the character
> to ham. However Python cannot append strings it can only create new
> strings since strings are immutable*.
>
> On the first iteration of the loop the zero length string is combined
> with the character and a string of length 1 is created.
> On the second a new string of length 2 is created.
> On the third a new string of length 3 is created.
> On the fourth a new string of length 4 is created.
>
> So four strings are create with lengths 0, 1, 2, 3, 4.
>
> If we did this with N characters then N strings would be created with
> lengths 0, 1, 2, 3, ... , N. If cost of creating each string is
> proportional to its length then the cost of the operation as a whole
> is proportional to 0 + 1 + 2 + 3 + ... + N. The general formula to
> compute this sum is (N**2 + N)/2. In other words the whole operation
> is quadratic O(N**2) in the number of characters that are combined.
>
> The Shlemiel the painter story describes a similar operation in which
> the time taken to paint each section increases linearly as more
> sections get painted. The result is that the time taken for Shlemiel
> to paint a stretch of road is proportional to the square of its length
> when it should just be proportional to its length.
>

After reading the link that Steven gave, I understood this, but you
have filled in some details. I was wondering how...

> I don't know exactly how str.join is implemented but it does not use
> this quadratic algorithm. For example if str.join would first compute
> the length of the resulting string first then it can allocate memory
> for exactly one string of that length and copy each substring to the
> appropriate place (actually I imagine it uses an exponentially
> resizing buffer but this isn't important).
>

...str.join gets around these issues? In the linked article it was
discussing increasing memory allocation by powers of two instead of
trying to determine the exact length of the strings involved,
mentioning that the maximum wasted memory would be 50% of what was
actually needed. Is Python more clever in its implementation?

> * CPython actually has an optimisation that can append strings in
> precisely this situation. However it is an implementation detail of
> CPython that may change and it does not work in other interpreters
> e.g. Jython. Using this kind of code can damage portability since your
> program may run fine in CPython but fail in other interpreters.
>
You are speaking of "appending" and not "concatenation" here?

I had not even considered other Python interpreters than CPython. More
complexity to consider for the future...

boB

From fomcl at yahoo.com  Thu May 30 16:47:21 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Thu, 30 May 2013 07:47:21 -0700 (PDT)
Subject: [Tutor] walk registry using _winreg
In-Reply-To: <51A5F066.9020004@davea.name>
References: <1369815094.27580.YahooMailNeo@web163806.mail.gq1.yahoo.com>
	<51A5F066.9020004@davea.name>
Message-ID: <1369925241.69921.YahooMailNeo@web163804.mail.gq1.yahoo.com>

______________________________
>From: Dave Angel <davea at davea.name>
>To: tutor at python.org 
>Sent: Wednesday, May 29, 2013 2:11 PM
>Subject: Re: [Tutor] walk registry using _winreg
>
>
>On 05/29/2013 04:11 AM, Albert-Jan Roskam wrote:
>> Hello,
>>
>> I created a program to go through the windows registry and look for a certain key ("file_locations", though in the example I am using a key that every windows user has on his/her computer). If found, I want to replace the data associated with value "temp_dir" in that key. I have chosen this strategy because the exact registry keys may have changed from version to version. Also, multiple versions of the program may be installed on a given computer. I pasted the code below this mail, but also here: http://pastebin.com/TEkyekfi
>>
>> Is this the correct way to do this? I would actually prefer to specify only "valueNameToSearch" and not also "keyToSearch". As in: start walking through the registry starting at <regkey>, return every key where a temp_dir is defined.
>>
>> Thank you in advance!
>>
>>
>> Regards,
>> Albert-Jan
>>
>Please specify Python version.? I'll assume 2.7.? Obviously this is 
>Windows, though it's also conceivable that it matters which version of 
>Windows (XP, Win8, whatever).

Hi Dave, sorry, Python 2.7 on Windows 7 Enterprise.
?
>First comment is that I'd be writing walkRegistry as a generator, using 
>yield for the items found, rather than building a list.? It's generally 
>easier to reuse that way, and won't get you in trouble if there are tons 
>of matches.? See os.walk for an example.

;-) I removed the "yield" statements at the last moment. I had indeed been looking at os.walk. I put them back now.
Also studied os.walk again.
?
>A generator also would naturally eliminate the need to know KeyToSearch.
>
>>
>> import _winreg
>> import os
>>
>> global __debug__
>> __debug__ = True
>>
>> def walkRegistry(regkey, keyToSearch="file_locations",
>>? ? ? ? ? ? ? ? ? valueNameToSearch="temp_dir", verbose=False):
>>? ? ? """Recursively search the Windows registry (HKEY_CURRENT_USER),
>>? ? ? starting at top <regkey>. Return a list of three tuples that contain
>>? ? ? the registry key, the value and the associated data"""
>>? ? ? if verbose:
>>? ? ? ? ? print regkey
>>? ? ? aReg = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, regkey)
>>? ? ? i, keys, founds = 0, [], []
>>? ? ? try:
>>? ? ? ? ? while True:
>>? ? ? ? ? ? ? i += 1
>>? ? ? ? ? ? ? key = _winreg.EnumKey(aReg, i)
>
>I believe these are zero-based indexes, so you're skipping the first one.

Good catch! Thanks! I wrote a new version (sorry, I don't have access to pastebin in the office,
it's qualified as "online storage"). Here's the code. As far as I can tell, it does exactly what I want now.
I hope I used all your feedback. CAUTION?to anyone who runs this code: it replaces a registry entry.
?
import _winreg
import os
?
def walkRegistry(regkey, keyToSet="file_locations", valueToSet="temp_dir",
????????????????? HKEY=_winreg.HKEY_CURRENT_USER, verbose=False):
??? """Recursively search the Windows registry, starting at top <regkey>.
??? Return a list of three tuples that contain the registry key, the value
??? and the associated data"""
??? if verbose:
??????? print regkey
??? i = 0
??? aReg = _winreg.OpenKey(HKEY, regkey)
??? try:
??????? while True:
??????????? key = _winreg.EnumKey(aReg, i)
??????????? i += 1
??????????? if key:
??????????????? new_regkey = os.path.join(regkey, key)
??????????????? if key == keyToSet:
??????????????????? if verbose:
??????????????????????? print "---> FOUND!!", new_regkey, key, keyToSet, valueToSet
??????????????????? with _winreg.OpenKey(HKEY, new_regkey) as anotherReg:
??????????????????????? value_data = _winreg.QueryValueEx(anotherReg, valueToSet)[0]
??????????????????? yield new_regkey, valueToSet, value_data
??????????????? for x in walkRegistry(new_regkey, keyToSet, valueToSet, HKEY, verbose):
??????????????????? yield x
??? except WindowsError:
??????? pass
?
def setRegistry(regkey, value, data, HKEY=_winreg.HKEY_CURRENT_USER):
??? """Set <value> (subkey) of <regkey> with <data>"""
??? hkey = [item for item in dir(_winreg) if getattr(_winreg, item) == HKEY][0]
??? print "setting value '%s' with data '%s' in regkey\n'%s\\%s'\n" % \
????????? (value, data, hkey, regkey)
??? try:
??????? aReg = _winreg.OpenKey(HKEY, regkey, 0, _winreg.KEY_ALL_ACCESS)
??? except:
??????? aReg = _winreg.CreateKey(HKEY, regkey)
??? try:
??????? _winreg.SetValueEx(aReg, value, 0, _winreg.REG_SZ, data)
??? finally:
??????? _winreg.CloseKey(aReg)
?
if __name__ == "__main__":
??? regkey = u"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer"
??? args = regkey, u"Shell Folders", u"Cookies"
??? regdata = [(regkey, value, data) for regkey, value, data in walkRegistry(*args)]
??? if len(regdata) == 1:
??????? regkey, value, existing_data = regdata[0]
??????? new_data = os.getenv("temp")
??????? setRegistry(regkey, value, new_data)
?
<snip>

From singhsumeet22 at yahoo.com  Thu May 30 18:35:49 2013
From: singhsumeet22 at yahoo.com (Sumeet Singh)
Date: Fri, 31 May 2013 00:35:49 +0800 (SGT)
Subject: [Tutor] google spreadsheet
Message-ID: <1369931749.48178.YahooMailNeo@web193004.mail.sg3.yahoo.com>

Hey Hi 
if possible can u guys please help me regarding accessing Google spreadsheet with the help of python 
i have gone through many blog but have not found any valid solution 

i trying to access google spreadsheet with help of python in eclipse if you can suggest it would really be a lot of help ? 

Thanks and regards,
SUMEET SINGH
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130531/b56e89cc/attachment.html>

From breamoreboy at yahoo.co.uk  Thu May 30 18:50:13 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Thu, 30 May 2013 17:50:13 +0100
Subject: [Tutor] google spreadsheet
In-Reply-To: <1369931749.48178.YahooMailNeo@web193004.mail.sg3.yahoo.com>
References: <1369931749.48178.YahooMailNeo@web193004.mail.sg3.yahoo.com>
Message-ID: <ko7vvl$15i$1@ger.gmane.org>

On 30/05/2013 17:35, Sumeet Singh wrote:
> Hey Hi
> if possible can u guys please help me regarding accessing Google
> spreadsheet with the help of python
> i have gone through many blog but have not found any valid solution
>
> i trying to access google spreadsheet with help of python in eclipse if
> you can suggest it would really be a lot of help
> Thanks and regards,
> SUMEET SINGH
>

Start here 
https://developers.google.com/google-apps/documents-list/v1/developers_guide_python 
I guess!!!

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From fomcl at yahoo.com  Thu May 30 19:21:10 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Thu, 30 May 2013 10:21:10 -0700 (PDT)
Subject: [Tutor] google spreadsheet
In-Reply-To: <1369931749.48178.YahooMailNeo@web193004.mail.sg3.yahoo.com>
References: <1369931749.48178.YahooMailNeo@web193004.mail.sg3.yahoo.com>
Message-ID: <1369934470.37153.YahooMailNeo@web163803.mail.gq1.yahoo.com>



_______________________________
> From: Sumeet Singh <singhsumeet22 at yahoo.com>
>To: "tutor at python.org" <tutor at python.org> 
>Sent: Thursday, May 30, 2013 6:35 PM
>Subject: [Tutor] google spreadsheet
> 
>
>
>Hey Hi 
>if possible can u guys please help me regarding accessing Google spreadsheet with the help of python 
>i have gone through many blog but have not found any valid solution 
>
>i trying to access google spreadsheet with help of python in eclipse if you can suggest it would really be a lot of help ? 
>
>Thanks and regards,
>SUMEET SINGH

Perhaps: https://developers.google.com/drive/quickstart-python


From fomcl at yahoo.com  Thu May 30 19:36:10 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Thu, 30 May 2013 10:36:10 -0700 (PDT)
Subject: [Tutor] walk registry using _winreg
In-Reply-To: <1369925241.69921.YahooMailNeo@web163804.mail.gq1.yahoo.com>
References: <1369815094.27580.YahooMailNeo@web163806.mail.gq1.yahoo.com>
	<51A5F066.9020004@davea.name>
	<1369925241.69921.YahooMailNeo@web163804.mail.gq1.yahoo.com>
Message-ID: <1369935370.16473.YahooMailNeo@web163805.mail.gq1.yahoo.com>

In addition to my previous reply: here's a colour-coded version of the code: http://pastebin.com/bZEezDSG
("Readability counts")


?
Regards,
Albert-Jan


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 


From oscar.j.benjamin at gmail.com  Thu May 30 20:07:41 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Thu, 30 May 2013 19:07:41 +0100
Subject: [Tutor] a little loop
In-Reply-To: <CANDiX9KN1+97d_Wm-2vu54aRvRACaQ5pivPSapQKwML+Ypf-DA@mail.gmail.com>
References: <201305272054.58446.tjhanson@yahoo.com>
	<51A5694C.8080908@pearwood.info>
	<CANDiX9JG79AcAZzrCOK4FX672mTy8LebytVaT4wSLBREPwGc-Q@mail.gmail.com>
	<CAHVvXxTeGracFatdCsVNOmSMZnFawsbzwTQoNWn1B44oOQwfOg@mail.gmail.com>
	<CANDiX9KN1+97d_Wm-2vu54aRvRACaQ5pivPSapQKwML+Ypf-DA@mail.gmail.com>
Message-ID: <CAHVvXxRvcLxouQkO0Fb1HfmsUJ7roGYiueLFx9ekHaGWTQ+_sQ@mail.gmail.com>

Sending again to the list (sorry boB)...

On 29 May 2013 17:51, boB Stepp <robertvstepp at gmail.com> wrote:
>> I don't know exactly how str.join is implemented but it does not use
>> this quadratic algorithm. For example if str.join would first compute
>> the length of the resulting string first then it can allocate memory
>> for exactly one string of that length and copy each substring to the
>> appropriate place (actually I imagine it uses an exponentially
>> resizing buffer but this isn't important).
>>
>
> ...str.join gets around these issues?

As I said I don't know how this is implemented in CPython (I hoped
Eryksun might chime in there :) ).

> In the linked article it was
> discussing increasing memory allocation by powers of two instead of
> trying to determine the exact length of the strings involved,
> mentioning that the maximum wasted memory would be 50% of what was
> actually needed. Is Python more clever in its implementation?

Actually the maximum memory wastage is 100% of what is needed or 50%
of what is actually used. This is if the amount needed is one greater
than a power of two and you end up doubling to the next power of two.
I don't see how CPython could be much cleverer in its implementation.
There aren't that many reasonable strategies here (when implementing
strings as linear arrays like CPython does).

>> * CPython actually has an optimisation that can append strings in
>> precisely this situation. However it is an implementation detail of
>> CPython that may change and it does not work in other interpreters
>> e.g. Jython. Using this kind of code can damage portability since your
>> program may run fine in CPython but fail in other interpreters.
>>
> You are speaking of "appending" and not "concatenation" here?

In this case I was just talking about single characters so you could
think of it as either. However, yes the optimisation is for
concatenation and in particular the '+' and '+=' operators.

> I had not even considered other Python interpreters than CPython. More
> complexity to consider for the future...

It's only a little bit of complexity. Just bear in mind the
distinction between a "language feature" that is true in any
conforming implementation and an "implementation detail" that happens
to be true in some or other interpreter but is not a specified part of
the language, In practise this means not really thinking too hard
about how CPython implements things and just using the recommended
idioms e.g. str.join.

I don't know if it is documented anywhere that str.join is linear
rather than quadratic but I consider that to be a language feature.
Exactly how it achieves linear behaviour (precomputing, resizing,
etc.) is an implementation detail. If your code relies only on
language features then it should not have problems when changing
interpreters.


Oscar

From ramit.prasad at jpmorgan.com  Thu May 30 20:26:02 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Thu, 30 May 2013 18:26:02 +0000
Subject: [Tutor] Random Number Game: Returns always the same number
	-	why?
In-Reply-To: <CAEcwjcyfJ4jweuG8oRBtZ6=ZUqdRquOzbF8_zyBwoHm=izbWSA@mail.gmail.com>
References: <CAM-E2X71W6PVeOpRfrrvT8B9x8S-5Z-vG8XdFO8jY18bvUT_xA@mail.gmail.com>
	<519A52C8.5000903@lightbird.net>
	<CAEcwjcyfJ4jweuG8oRBtZ6=ZUqdRquOzbF8_zyBwoHm=izbWSA@mail.gmail.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF47418429C13@SCACMX008.exchad.jpmchase.net>

[Reordered response to after quote]
Thomas Murphy wrote:
> 
> 
> > There are a few issues here:
> > * variable names should be lower case
> > * for this case it's best to use for loop with range()
> > * you calculate random number only once, outside of loop
> >
> > Try something like:
> >
> > for count in range(100):
> > print random.randint(1, 100)
> >
> >
> > -m
> 
> Mitya,
> Why is it best in this situation to use range() rather than a while
> loop? Curious about best practices for the various iterating
> functions. Thanks!

This is not really a case of "range" vs. "while" loops, it is really
"while" vs "for" loops. In general, you should use "for" loops when
you know the number of times to loop up front. "While" loops should 
be used when you are unsure how many times you need to loop. 

"For" loops are good for use with iterables (lists, strings, sequences).
"While" loops are good for processing until some state is achieved.

In C, it was very easy to interchange "for" and "while" loops, and
while it can probably be done in Python it may require a bit more work. 


~Ramit





This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

From steve at pearwood.info  Thu May 30 21:16:17 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 31 May 2013 05:16:17 +1000
Subject: [Tutor] a little loop
In-Reply-To: <CANDiX9KN1+97d_Wm-2vu54aRvRACaQ5pivPSapQKwML+Ypf-DA@mail.gmail.com>
References: <201305272054.58446.tjhanson@yahoo.com>
	<51A5694C.8080908@pearwood.info>
	<CANDiX9JG79AcAZzrCOK4FX672mTy8LebytVaT4wSLBREPwGc-Q@mail.gmail.com>
	<CAHVvXxTeGracFatdCsVNOmSMZnFawsbzwTQoNWn1B44oOQwfOg@mail.gmail.com>
	<CANDiX9KN1+97d_Wm-2vu54aRvRACaQ5pivPSapQKwML+Ypf-DA@mail.gmail.com>
Message-ID: <51A7A581.4040903@pearwood.info>

On 30/05/13 02:51, boB Stepp wrote:
> On Wed, May 29, 2013 at 11:07 AM, Oscar Benjamin
> <oscar.j.benjamin at gmail.com> wrote:

>> I don't know exactly how str.join is implemented but it does not use
>> this quadratic algorithm. For example if str.join would first compute
>> the length of the resulting string first then it can allocate memory
>> for exactly one string of that length and copy each substring to the
>> appropriate place (actually I imagine it uses an exponentially
>> resizing buffer but this isn't important).

I have not actually read the str.join source code, but what I understand is that it has two cases:

1) If you pass a sequence of sub-strings to join, say, a list, it can look at each sub-string, calculate the total space required, and allocate a string buffer of exactly that amount of memory, and only then copy the characters into the buffer.

2) If you pass an iterator, join cannot go over the sub-strings twice, it has to do so in one pass. It probably over-allocates the buffer, then when finished, shrinks it back down again.


Sure enough, ''.join(list-of-substrings) is measurably faster than ''.join(iterator-of-substrings).




> ...str.join gets around these issues? In the linked article it was
> discussing increasing memory allocation by powers of two instead of
> trying to determine the exact length of the strings involved,
> mentioning that the maximum wasted memory would be 50% of what was
> actually needed. Is Python more clever in its implementation?


In the case of lists, CPython will over-allocate. I believe that up to some relatively small size, lists are initially quadrupled in size, after which time they are doubled. The exact cut-off size is subject to change, but as an illustration, we can pretend that it looks like this:


- An empty list is created with, say, 20 slots, all blank.

- When all 20 slots are filled, the next append or insert will increase the size of the list to 80 slots, 21 of which are used and 59 are blank.

- When those 80 slots are filled, the next append or insert will increase to 320 slots.

- When those are filled, the number of slots is doubled to 640.

- Then 1280, and so forth.


So small lists "waste" more memory, up to 75% of the total size, but who cares, because they're small. Having more slots available, they require even fewer resizes, so they're fast.

However, I emphasis that the exact memory allocation scheme is not guaranteed, and is subject to change without notice. The only promise made, and this is *implicit* and not documented anywhere, is that appending to a list will be amortised to constant time, on average.

(Guido van Rossum, Python's creator, has said that he would not look kindly on anything that changed the basic performance characteristics of lists.)


When creating a string, Python may be able to determine the exact size required, in which case no over-allocation is needed. But when it can't, it may use a similar over-allocation strategy as for lists, except that the very last thing done before returning the string is to shrink it down so there's no wasted space.



>> * CPython actually has an optimisation that can append strings in
>> precisely this situation. However it is an implementation detail of
>> CPython that may change and it does not work in other interpreters
>> e.g. Jython. Using this kind of code can damage portability since your
>> program may run fine in CPython but fail in other interpreters.
>>
> You are speaking of "appending" and not "concatenation" here?


Yes. Because strings are immutable, under normal circumstances, concatenating two strings requires creating a third. Suppose you say:

A = "Hello "
B = "World!"
C = A + B

So Python can see that string A has 6 characters, and B has 6 characters, so C requires space for 12 characters:

C = "------------"

which can then be filled in:

C = "Hello World!"

and now string C is ready to be used.

But, suppose we have this instead:

A = A + B  # or A += B

The *old* A is used, then immediately discarded, and replaced with the new string. This leads to a potential optimization: instead of having to create a new string, Python can resize A in place:

A = "Hello ------"
B = "World!"

then copy B into A:

A = "Hello World!"


But note that Python can only do this if A is the one and only reference to the string. If any other name, list, or other object is pointing to the string, this cannot be done. Also, you can't do it for the reverse:

B = A + B

since memory blocks can generally only grow from one side, not the other.

Finally, it also depends on whether the operating system allows you to grow memory blocks in the fashion. It may not. So the end result is that you cannot really rely on this optimization. It's nice when it is there, but it may not always be there.

And just a reminder, none of this is important for one or two string concatenations. It's only when you build up a string from repeated concatenations that this becomes an issue.



-- 
Steven

From eryksun at gmail.com  Thu May 30 22:05:23 2013
From: eryksun at gmail.com (eryksun)
Date: Thu, 30 May 2013 16:05:23 -0400
Subject: [Tutor] walk registry using _winreg
In-Reply-To: <1369925241.69921.YahooMailNeo@web163804.mail.gq1.yahoo.com>
References: <1369815094.27580.YahooMailNeo@web163806.mail.gq1.yahoo.com>
	<51A5F066.9020004@davea.name>
	<1369925241.69921.YahooMailNeo@web163804.mail.gq1.yahoo.com>
Message-ID: <CACL+1atctpeCkHJWWr6xt-4MhSO8YNQbfFyY4S_zhC0bN+ABRw@mail.gmail.com>

On Thu, May 30, 2013 at 10:47 AM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
>
> def walkRegistry(regkey, keyToSet="file_locations",
>                  valueToSet="temp_dir",
>                  HKEY=_winreg.HKEY_CURRENT_USER, verbose=False):

I suppose you don't need the "sam" option in your case, but in general
it's needed for 64-bit Windows in order to handle both native and
WOW64 keys.

For a WOW64 process, the native 64-bit keys can be read with
sam=KEY_READ | KEY_WOW64_64KEY. For a 64-bit process, the WOW64 keys
can be read with sam=KEY_READ | KEY_WOW64_32KEY.

A WOW64 process will have "PROCESSOR_ARCHITEW6432" defined in os.environ.


>     aReg = _winreg.OpenKey(HKEY, regkey)

You should use a "with" statement here instead of depending on the
garbage collection of the generator frame.

>     try:
>         while True:
>             key = _winreg.EnumKey(aReg, i)
>             i += 1
>             if key:
>                 new_regkey = os.path.join(regkey, key)

There's too much code here under the banner of one "try" suite.
OpenKey and QueryValueEx in the subsequent statements may raise a
WindowsError for various reasons.

Also, as you're currently doing things it leaves several open handles
as you recursively create generators. It's likely not an issue (the
registry isn't deeply nested), but in general I prefer to close a
resource as immediately as is possible.

I'd enumerate the subkeys in a list and only yield a key/value match
for the current regkey (that's basically how os.walk traverses the
file system). This can match on the initial key. If you don't want
that, it can be worked around (e.g. a flag, or a helper function), but
I don't think the additional complexity is worth it.

    import os
    import _winreg

    def walkRegistry(regkey,
                     keyToSet="file_locations",
                     valueToSet="temp_dir",
                     HKEY=_winreg.HKEY_CURRENT_USER,
                     sam=_winreg.KEY_READ,
                     onerror=None,
                     verbose=False):

        try:
            aReg = _winreg.OpenKey(HKEY, regkey)
        except WindowsError as e:
            if onerror is not None:
                onerror(e)
            return

        i = 0
        subkeys = []
        with aReg:
            while True:
                try:
                    subkeys.append(_winreg.EnumKey(aReg, i))
                except WindowsError:
                    break
                i += 1
            # check the key name; not the key path
            if os.path.basename(regkey) == keyToSet:
                if verbose:
                    print "---> FOUND KEY:", regkey
                try:
                    data = _winreg.QueryValueEx(aReg, valueToSet)[0]
                except WindowsError:  # value not found
                    pass
                else:
                    if verbose:
                        print "---> FOUND KEY,VALUE PAIR"
                    yield regkey, valueToSet, data

        for key in subkeys:
            new_regkey = os.path.join(regkey, key)
            for item in walkRegistry(
                    new_regkey, keyToSet, valueToSet,
                    HKEY, sam, onerror, verbose):
                yield item


Minimally tested (sorry):

    >>> HKEY = _winreg.HKEY_LOCAL_MACHINE
    >>> regkey = r'Software\Python\PythonCore\2.7'

    >>> res = list(
    ... walkRegistry(regkey, 'PythonPath', '', HKEY, verbose=True))

    ---> FOUND KEY: Software\Python\PythonCore\2.7\PythonPath
    ---> FOUND KEY,VALUE PAIR

    >>> res[0][2]
    u'C:\\Python27\\Lib;C:\\Python27\\DLLs;C:\\Python27\\Lib\\lib-tk'

From eryksun at gmail.com  Thu May 30 22:35:18 2013
From: eryksun at gmail.com (eryksun)
Date: Thu, 30 May 2013 16:35:18 -0400
Subject: [Tutor] a little loop
In-Reply-To: <CANDiX9KN1+97d_Wm-2vu54aRvRACaQ5pivPSapQKwML+Ypf-DA@mail.gmail.com>
References: <201305272054.58446.tjhanson@yahoo.com>
	<51A5694C.8080908@pearwood.info>
	<CANDiX9JG79AcAZzrCOK4FX672mTy8LebytVaT4wSLBREPwGc-Q@mail.gmail.com>
	<CAHVvXxTeGracFatdCsVNOmSMZnFawsbzwTQoNWn1B44oOQwfOg@mail.gmail.com>
	<CANDiX9KN1+97d_Wm-2vu54aRvRACaQ5pivPSapQKwML+Ypf-DA@mail.gmail.com>
Message-ID: <CACL+1atj2s70YUi2ZSqBi0JrpiOjhUi6i=Uc-9R5TRpd28Lk9Q@mail.gmail.com>

On Wed, May 29, 2013 at 12:51 PM, boB Stepp <robertvstepp at gmail.com> wrote:
> On Wed, May 29, 2013 at 11:07 AM, Oscar Benjamin
> <oscar.j.benjamin at gmail.com> wrote:
>
>> I don't know exactly how str.join is implemented but it does not use
>> this quadratic algorithm. For example if str.join would first compute
>> the length of the resulting string first then it can allocate memory
>> for exactly one string of that length and copy each substring to the
>> appropriate place (actually I imagine it uses an exponentially
>> resizing buffer but this isn't important).
>
> ...str.join gets around these issues? In the linked article it was
> discussing increasing memory allocation by powers of two instead of
> trying to determine the exact length of the strings involved,
> mentioning that the maximum wasted memory would be 50% of what was
> actually needed. Is Python more clever in its implementation?

CPython computes the exact length required. Nothing clever. It first
expands the iterable into a list. It joins the strings in two passes.
In the first pass it computes the total size (3.3 also has to
determine the 'kind' of unicode string in this loop, i.e. ASCII,
2-byte, etc). Then it allocates a new string and copies in the data in
a second pass.


>> * CPython actually has an optimisation that can append strings in
>> precisely this situation. However it is an implementation detail of
>> CPython that may change and it does not work in other interpreters
>> e.g. Jython. Using this kind of code can damage portability since your
>> program may run fine in CPython but fail in other interpreters.
>>
> You are speaking of "appending" and not "concatenation" here?

In terms of sequence methods, it's inplace concatenation. On their
own, immutable string types only support regular concatenation, but
the interpreter can evaluate the concatenation inplace for special
cases. Specifically, it can resize the target string in an INPLACE_ADD
if it's not interned and has only *one* reference. Also, the reference
has to be a local variable; it can't be a global (unless at module
level), an attribute, or a subscript.

Here's an example (tested in 2.7 and 3.3).

Interned strings:

    >>> s = 'abcdefgh' * 128

CPython code objects intern their string constants that are all name
characters (ASCII alphanumeric and underscore). But that's not an
issue if you multiply the string to make it longer than 20 characters.
A sequence length of 20 is the cutoff point for compile-time constant
folding. This keeps the code object size under wraps. The number 20
was apparently chosen for obvious reasons (at least to someone).
Anyway, if the string is determined at runtime, it won't be interned.

But really I'm concatenating the base string with itself so many times
to avoid using the Pymalloc object allocator (see the note below). Its
block sizes are fine grained at just 8 bytes apart. Depending on your
system I don't know if adding even one more byte will push you up to
the next block size, which would defeat an example based on object
id(). I'll take my chances that the stdlib realloc() will be able to
grow the block, but that's not guaranteed either. Strings should be
treated as immutable at all times. This is just a performance
optimization.

The reference count must be 1:

    >>> sys.getrefcount(s)
    2

Hmmm. The reference count of the string is incremented when it's
loaded on the stack, meaning it will always be at least 2. As such,
the original variable reference is deleted before in-place
concatenation. By that I mean that if you have s += 'spam', then mid
operation s is deleted from the current namespace. The next
instruction stores the result back.

Voil?:

    >>> id_s = id(s)
    >>> s += 'spam'
    >>> id(s) == id_s
    True


Note on object reallocation:
The following assumes CPython is built with the Pymalloc small-object
allocator, which is the default configuration in 2.3+. Pymalloc
requests memory from the system in 256 KiB chunks calls arenas. Each
arena is partitioned into 64 pools. Each pool has a fixed block size,
and block sizes increase in steps of 8, from 8 bytes up to 256 bytes
(up to 512 bytes in 3.3).

Resizing the string eventually calls PyObject_Realloc. If the object
isn't managed by Pymalloc, the call to PyObject_Realloc punts to the C
stdlib realloc. Otherwise if the new size maps to a larger block size,
or if it's shrinking by more than 25% to a smaller block size, the
allocation punts to PyObject_Malloc. This allocates a block from the
first available pool. If the requested size is larger than the maximum
block size, it punts to the C stdlib malloc.

From eryksun at gmail.com  Thu May 30 22:39:45 2013
From: eryksun at gmail.com (eryksun)
Date: Thu, 30 May 2013 16:39:45 -0400
Subject: [Tutor] google spreadsheet
In-Reply-To: <ko7vvl$15i$1@ger.gmane.org>
References: <1369931749.48178.YahooMailNeo@web193004.mail.sg3.yahoo.com>
	<ko7vvl$15i$1@ger.gmane.org>
Message-ID: <CACL+1asjSzw7dET+CMLcS1Ewy6SuHZ7KafK_MJzuECEAvOp=JA@mail.gmail.com>

On Thu, May 30, 2013 at 12:50 PM, Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:
>>
>> i trying to access google spreadsheet with help of python
>
> Start here
> https://developers.google.com/google-apps/documents-list/v1/
> developers_guide_python
> I guess!!!
>
> --
> If you're using GoogleCrap? please read this

:D

From alan.gauld at btinternet.com  Thu May 30 23:23:51 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 30 May 2013 22:23:51 +0100
Subject: [Tutor] google spreadsheet
In-Reply-To: <1369931749.48178.YahooMailNeo@web193004.mail.sg3.yahoo.com>
References: <1369931749.48178.YahooMailNeo@web193004.mail.sg3.yahoo.com>
Message-ID: <ko8g12$iru$1@ger.gmane.org>

On 30/05/13 17:35, Sumeet Singh wrote:

> if possible can u guys please help me regarding accessing Google
> spreadsheet with the help of python

This list is for people learning Python and its standard library.
You will likely get more help on the main Python mailing
list/newsgroup.

Or possibly a Google programming forum, assuming such a thing exists.

To improve your chances try asking specific questions and providing 
information about your OS, Python version and what you've tried and how 
it went. Include any error messages. That way people won't have to guess.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From ramit.prasad at jpmorgan.com  Fri May 31 00:10:21 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Thu, 30 May 2013 22:10:21 +0000
Subject: [Tutor] To error statement or not to error statement
In-Reply-To: <CALRAYNVz7n+Gx37AL19aXHnfLfO0gBwyrUuJS7721vfGAcSbZg@mail.gmail.com>
References: <CALRAYNVz7n+Gx37AL19aXHnfLfO0gBwyrUuJS7721vfGAcSbZg@mail.gmail.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF4741842B175@SCACMX008.exchad.jpmchase.net>

Jim Mooney wrote:
> Sent: Wednesday, May 22, 2013 11:28 AM
> To: tutor at python.org
> Subject: [Tutor] To error statement or not to error statement
> 
> >> "I find it amusing when novice programmers believe their main job is
> >> preventing programs from crashing. ... More experienced programmers realize
> >> that correct code is great, code that crashes could use improvement, but
> >> incorrect code that doesn't crash is a horrible nightmare."
> 
> Then am I right to assume that rather than put in error statements I
> barely understand at this point, the best thing would be to work the
> hell out of the program in hope of seeing an error?  Does Python have
> something that would do this automatically since I can't see running a
> program a hundred times by hand?
> 
> Mainly, I'm just learning all this stuff for future reference. I
> really doubt I'll need to use nose to find errors in twenty-line
> programs. Print, assert, and staring at it for a long time should be
> enough for now - and the Wing debugger now and then.
> 
> From the varied replies so far, it sounds to me that debugging is more
> of an art than a science. So far the books I've looked at just mention
> the basics but don't get into the philosophy of when and how.
> 
> Jim
> 

If you mostly just write small programs and use them from 
shell/debugger, then I would just never catch any error.
All raised exceptions will automatically be printed by
the interpreter when they kill your code. That will
automatically show the error and the appropriate stack
trace to fix the error. If you combine that with proper
logging (print can be fine for single threads) you
should have everything you need to solve the problem.

Eventually you get better at logging and anticipating
possible problems. 


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

From oscar.j.benjamin at gmail.com  Fri May 31 00:35:22 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Thu, 30 May 2013 23:35:22 +0100
Subject: [Tutor] a little loop
In-Reply-To: <CACL+1atj2s70YUi2ZSqBi0JrpiOjhUi6i=Uc-9R5TRpd28Lk9Q@mail.gmail.com>
References: <201305272054.58446.tjhanson@yahoo.com>
	<51A5694C.8080908@pearwood.info>
	<CANDiX9JG79AcAZzrCOK4FX672mTy8LebytVaT4wSLBREPwGc-Q@mail.gmail.com>
	<CAHVvXxTeGracFatdCsVNOmSMZnFawsbzwTQoNWn1B44oOQwfOg@mail.gmail.com>
	<CANDiX9KN1+97d_Wm-2vu54aRvRACaQ5pivPSapQKwML+Ypf-DA@mail.gmail.com>
	<CACL+1atj2s70YUi2ZSqBi0JrpiOjhUi6i=Uc-9R5TRpd28Lk9Q@mail.gmail.com>
Message-ID: <CAHVvXxTmj7e1jJ6QC_Oq+u-eerk5gShr1x_ZwCQ7NkTAVsEfiA@mail.gmail.com>

On 30 May 2013 21:35, eryksun <eryksun at gmail.com> wrote:
> In terms of sequence methods, it's inplace concatenation. On their
> own, immutable string types only support regular concatenation, but
> the interpreter can evaluate the concatenation inplace for special
> cases. Specifically, it can resize the target string in an INPLACE_ADD
> if it's not interned and has only *one* reference.

It's also for BINARY_ADD in the form a = a + b:

$ python
Python 2.7.3 (default, Sep 26 2012, 21:51:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = 'abcdefgh' * 128
>>> id_s = id(s)
>>> s = s + 'spam'
>>> print(id(s) == id_s)
True

A rare case of me actually using the dis module:

>>> def f():
...   s = s + 'spam'
...
>>> import dis
>>> dis.dis(f)
  2           0 LOAD_FAST                0 (s)
              3 LOAD_CONST               1 ('spam')
              6 BINARY_ADD
              7 STORE_FAST               0 (s)
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE


Oscar

From eryksun at gmail.com  Fri May 31 00:50:33 2013
From: eryksun at gmail.com (eryksun)
Date: Thu, 30 May 2013 18:50:33 -0400
Subject: [Tutor] a little loop
In-Reply-To: <CAHVvXxTmj7e1jJ6QC_Oq+u-eerk5gShr1x_ZwCQ7NkTAVsEfiA@mail.gmail.com>
References: <201305272054.58446.tjhanson@yahoo.com>
	<51A5694C.8080908@pearwood.info>
	<CANDiX9JG79AcAZzrCOK4FX672mTy8LebytVaT4wSLBREPwGc-Q@mail.gmail.com>
	<CAHVvXxTeGracFatdCsVNOmSMZnFawsbzwTQoNWn1B44oOQwfOg@mail.gmail.com>
	<CANDiX9KN1+97d_Wm-2vu54aRvRACaQ5pivPSapQKwML+Ypf-DA@mail.gmail.com>
	<CACL+1atj2s70YUi2ZSqBi0JrpiOjhUi6i=Uc-9R5TRpd28Lk9Q@mail.gmail.com>
	<CAHVvXxTmj7e1jJ6QC_Oq+u-eerk5gShr1x_ZwCQ7NkTAVsEfiA@mail.gmail.com>
Message-ID: <CACL+1avvncpBs6s82FiuOYCX3U52ifixGwt3pzgG+eby0ScNmQ@mail.gmail.com>

On Thu, May 30, 2013 at 6:35 PM, Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
>
> It's also for BINARY_ADD in the form a = a + b:

Right you are. It sees that the next operation is a store back to "a".
It wouldn't work the other way around, i.e. a = b + a.

From eryksun at gmail.com  Fri May 31 04:55:13 2013
From: eryksun at gmail.com (eryksun)
Date: Thu, 30 May 2013 22:55:13 -0400
Subject: [Tutor] a little loop
In-Reply-To: <51A7A581.4040903@pearwood.info>
References: <201305272054.58446.tjhanson@yahoo.com>
	<51A5694C.8080908@pearwood.info>
	<CANDiX9JG79AcAZzrCOK4FX672mTy8LebytVaT4wSLBREPwGc-Q@mail.gmail.com>
	<CAHVvXxTeGracFatdCsVNOmSMZnFawsbzwTQoNWn1B44oOQwfOg@mail.gmail.com>
	<CANDiX9KN1+97d_Wm-2vu54aRvRACaQ5pivPSapQKwML+Ypf-DA@mail.gmail.com>
	<51A7A581.4040903@pearwood.info>
Message-ID: <CACL+1at=Z=wkUKRuq70-O4dnSomVWfR15BjX6H4du0yM1Sz4sw@mail.gmail.com>

On Thu, May 30, 2013 at 3:16 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>
> Sure enough, ''.join(list-of-substrings) is measurably faster than
> ''.join(iterator-of-substrings).

A tuple or list is used directly. Otherwise join() has to create an
iterator and build a new list.

This isn't directly related to the discussion on string concatenation.
But in relation to the offshoot discussion on lists, I've put together
some examples that demonstrate how different was of creating the same
list lead to different allocated sizes.

First, here's a function to get the allocated length of a list's item array:

    from ctypes import sizeof, c_void_p, c_ssize_t

    alloc_offset = sizeof(c_void_p * 2) + sizeof(c_ssize_t * 2)

    def allocated(alist):
        addr = id(alist)
        alloc = c_ssize_t.from_address(addr + alloc_offset)
        return alloc.value

It uses ctypes to peek into the object, but you can also use a list
object's __sizeof__() method to calculate the result. First get the
array's size in bytes by subtracting the size of an empty list from
the size of the list. Then divide by the number of bytes in a pointer:

    import struct

    pointer_size = struct.calcsize('P')
    empty_size = [].__sizeof__()

    def allocated(alist):
        size_bytes = alist.__sizeof__() - empty_size
        return size_bytes // pointer_size


Example 0:

    >>> allocated([0,1,2,3,4,5,6,7,8,9,10,11])
    12

In this case the constants are pushed on the stack, and the
interpreter evaluates BUILD_LIST(12), which in CPython calls
PyList_New(12). The same applies to using built-in range() in 2.x (not
3.x):

    >>> allocated(range(12))
    12

Example 1:

    >>> allocated([i for i in xrange(12)])
    16

This starts at 0 and grows as follows:

    1 + 1//8 + 3 = 4
    5 + 5//8 + 3 = 8
    9 + 9//8 + 6 = 16


Example 2:

    >>> allocated(list(xrange(12)))
    19

This also applies to range() in 3.x. Some iterators have a
"__length_hint__" method for guessing the initial size:

    >>> iter(xrange(12)).__length_hint__()
    12

The guess is immediately resized as follows:

    12 + 12//8 + 6 = 19


Example 3:

    >>> allocated(list(i for i in xrange(12)))
    12

The initializer here is a generator, compiled from the generator
expression. A generator doesn't have a length hint. Instead, the list
uses a default guess of 8, which is over-allocated as follows:

    8 + 8//8 + 3 = 12

If the generator continues to a 13th item, the list resizes to 13 +
13//8 + 6 = 20:

    >>> allocated(list(i for i in xrange(13)))
    20

From fomcl at yahoo.com  Fri May 31 10:43:03 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Fri, 31 May 2013 01:43:03 -0700 (PDT)
Subject: [Tutor] walk registry using _winreg
In-Reply-To: <CACL+1atctpeCkHJWWr6xt-4MhSO8YNQbfFyY4S_zhC0bN+ABRw@mail.gmail.com>
References: <1369815094.27580.YahooMailNeo@web163806.mail.gq1.yahoo.com>
	<51A5F066.9020004@davea.name>
	<1369925241.69921.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<CACL+1atctpeCkHJWWr6xt-4MhSO8YNQbfFyY4S_zhC0bN+ABRw@mail.gmail.com>
Message-ID: <1369989783.57453.YahooMailNeo@web163801.mail.gq1.yahoo.com>



----- Original Message -----
> From: eryksun <eryksun at gmail.com>
> To: Albert-Jan Roskam <fomcl at yahoo.com>
> Cc: Dave Angel <davea at davea.name>; "tutor at python.org" <tutor at python.org>
> Sent: Thursday, May 30, 2013 10:05 PM
> Subject: Re: [Tutor] walk registry using _winreg
> 
> On Thu, May 30, 2013 at 10:47 AM, Albert-Jan Roskam <fomcl at yahoo.com> 
> wrote:
>> 
>> def walkRegistry(regkey, keyToSet="file_locations",
>> ? ? ? ? ? ? ? ? ? valueToSet="temp_dir",
>> ? ? ? ? ? ? ? ? ? HKEY=_winreg.HKEY_CURRENT_USER, verbose=False):
> 
> I suppose you don't need the "sam" option in your case, but in 
> general
> it's needed for 64-bit Windows in order to handle both native and
> WOW64 keys.
> 
> For a WOW64 process, the native 64-bit keys can be read with
> sam=KEY_READ | KEY_WOW64_64KEY. For a 64-bit process, the WOW64 keys
> can be read with sam=KEY_READ | KEY_WOW64_32KEY.
> 
> A WOW64 process will have "PROCESSOR_ARCHITEW6432" defined in 
> os.environ.
?

That's entirely new to me.So every 64-bit windows registry comes in a WOW64 and a native flavour? If one native registry is already a mess, does two registries mean double mess? I will have to read up on this, although I have to admit that the windows registry is not my favourite topic. The walk function might also come in really handy with searching in virtual registries that Symantec?virtual software layer creates (talking about mess! Yikes!)

?
>> ? ? aReg = _winreg.OpenKey(HKEY, regkey)
> 
> You should use a "with" statement here instead of depending on the
> garbage collection of the generator frame.


Thank you. Yes, I was staring at the code and this?crossed my mind. I found my code?too nested (which I considered to be a bad sign) and I didn't use a 'with' statement because it would add yet another nesting level. 

?
>> ? ? try:
>> ? ? ? ? while True:
>> ? ? ? ? ? ? key = _winreg.EnumKey(aReg, i)
>> ? ? ? ? ? ? i += 1
>> ? ? ? ? ? ? if key:
>> ? ? ? ? ? ? ? ? new_regkey = os.path.join(regkey, key)
> 
> There's too much code here under the banner of one "try" suite.
> OpenKey and QueryValueEx in the subsequent statements may raise a
> WindowsError for various reasons.
> 
> Also, as you're currently doing things it leaves several open handles
> as you recursively create generators. It's likely not an issue (the
> registry isn't deeply nested), but in general I prefer to close a
> resource as immediately as is possible.
> 
> I'd enumerate the subkeys in a list and only yield a key/value match
> for the current regkey (that's basically how os.walk traverses the
> file system). This can match on the initial key. If you don't want
> that, it can be worked around (e.g. a flag, or a helper function), but
> I don't think the additional complexity is worth it.
> 
> ? ? import os
> ? ? import _winreg
> 
> ? ? def walkRegistry(regkey,
> ? ? ? ? ? ? ? ? ? ? keyToSet="file_locations",
> ? ? ? ? ? ? ? ? ? ? valueToSet="temp_dir",
> ? ? ? ? ? ? ? ? ? ? HKEY=_winreg.HKEY_CURRENT_USER,
> ? ? ? ? ? ? ? ? ? ? sam=_winreg.KEY_READ,
> ? ? ? ? ? ? ? ? ? ? onerror=None,


The onerror parameter is nice?(just like in os.walk). Cool way to handle errors.


> ? ? ? ? ? ? ? ? ? ? verbose=False):
> 
> ? ? ? ? try:
> ? ? ? ? ? ? aReg = _winreg.OpenKey(HKEY, regkey)
> ? ? ? ? except WindowsError as e:
> ? ? ? ? ? ? if onerror is not None:
> ? ? ? ? ? ? ? ? onerror(e)
> ? ? ? ? ? ? return
> 
> ? ? ? ? i = 0
> ? ? ? ? subkeys = []
> ? ? ? ? with aReg:


I always forget that "with" statements also work without using "as" (ie, with _winreg.OpenKey(HKEY, regkey) as aReg).

Another remark that happens to be also about "as": is "except WindowsError as e:" a more modern version of "except WindowsError, e:"? Comparable to the old-fashioned "raise SomeError, 'error'"? and the new "raise SomeError('error')".? 
. 

> ? ? ? ? ? ? while True:
> ? ? ? ? ? ? ? ? try:
> ? ? ? ? ? ? ? ? ? ? subkeys.append(_winreg.EnumKey(aReg, i))
> ? ? ? ? ? ? ? ? except WindowsError:
> ? ? ? ? ? ? ? ? ? ? break
> ? ? ? ? ? ? ? ? i += 1
> ? ? ? ? ? ? # check the key name; not the key path
> ? ? ? ? ? ? if os.path.basename(regkey) == keyToSet:
> ? ? ? ? ? ? ? ? if verbose:
> ? ? ? ? ? ? ? ? ? ? print "---> FOUND KEY:", regkey
> ? ? ? ? ? ? ? ? try:
> ? ? ? ? ? ? ? ? ? ? data = _winreg.QueryValueEx(aReg, valueToSet)[0]
> ? ? ? ? ? ? ? ? except WindowsError:? # value not found
> ? ? ? ? ? ? ? ? ? ? pass
> ? ? ? ? ? ? ? ? else:


Thanks for reminding me of the "else" clause in the try-except suite. I knew it existed, but I never use it. For others who are reading along, the links below are useful. Basically, it boils down to: (1) keep the "try" clause as empty as possible (2) the "else" clause is there to prevent you from catching the same type of exception, but with a different cause.
http://stackoverflow.com/questions/855759/python-try-else
http://docs.python.org/2/tutorial/errors.html: "The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn?t raised by the code being protected by the try ... except statement"

?
> ? ? ? ? ? ? ? ? ? ? if verbose:
> ? ? ? ? ? ? ? ? ? ? ? ? print "---> FOUND KEY,VALUE PAIR"
> ? ? ? ? ? ? ? ? ? ? yield regkey, valueToSet, data
> 
> ? ? ? ? for key in subkeys:
> ? ? ? ? ? ? new_regkey = os.path.join(regkey, key)
> ? ? ? ? ? ? for item in walkRegistry(
> ? ? ? ? ? ? ? ? ? ? new_regkey, keyToSet, valueToSet,
> ? ? ? ? ? ? ? ? ? ? HKEY, sam, onerror, verbose):
> ? ? ? ? ? ? ? ? yield item
> 
> 
> Minimally tested (sorry):


You all?have been of enormous help, thank you!! Code reviews are a great way to find errors, make code more readable, make code more efficient (in that order) and learn new tricks
I wrote a simple doctest for the code. Perhaps I should post this somewhere.
??? r"""
??? >>> regkey = u"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer"
??? >>> args = regkey, u"Shell Folders", u"Cookies"
??? >>> regdata = [(key, val, data) for key, val, data in walkRegistry(*args)]
??? >>> print regdata? # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
??? [(u'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders',
??? u'Cookies', u'...\\Microsoft\\Windows\\Cookies')]
??? """
....
if __name__ == "__main__":
??? import doctest
??? doctest.testmod()
??? regkey = u"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer"
??? args = regkey, u"Shell Folders", u"Cookies"
??? regdata = [(key, val, data) for key, val, data in walkRegistry(*args)]
??? print regdata


> 
> ? ? >>> HKEY = _winreg.HKEY_LOCAL_MACHINE
> ? ? >>> regkey = r'Software\Python\PythonCore\2.7'
> 
> ? ? >>> res = list(
> ? ? ... walkRegistry(regkey, 'PythonPath', '', HKEY, 
> verbose=True))
> 
> ? ? ---> FOUND KEY: Software\Python\PythonCore\2.7\PythonPath
> ? ? ---> FOUND KEY,VALUE PAIR
> 
> ? ? >>> res[0][2]
> ? ? 
> u'C:\\Python27\\Lib;C:\\Python27\\DLLs;C:\\Python27\\Lib\\lib-tk'
> 

From cybervigilante at gmail.com  Fri May 31 11:16:37 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Fri, 31 May 2013 02:16:37 -0700
Subject: [Tutor] RLPy
Message-ID: <CALRAYNVhbxhHVnwjD1rznoqyQ3uhToN6aRB_fYb-fFgx7fecJA@mail.gmail.com>

I didn't see this in the archive so I thought I'd mention it since
it's pretty new. According to Ray Kurzweil, the most advanced
publicly-available Artificial Intelligence framework is now available,
exclusively for Python 2.7 installation, as RLPy (Reinforcement
Learning and Python)

http://www.kurzweilai.net/how-computers-can-learn-better - description

http://acl.mit.edu/RLPy/  - download from

-- 
Jim
Ornhgvshy vf orggre guna htyl

From ramit.prasad at jpmorgan.com  Fri May 31 17:04:17 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Fri, 31 May 2013 15:04:17 +0000
Subject: [Tutor] got text switched
In-Reply-To: <CALRAYNU+0LUZ5HRwuue0EeD4Mkzw39seUyMExGMWf0YVUQWSbw@mail.gmail.com>
References: <CALRAYNU+0LUZ5HRwuue0EeD4Mkzw39seUyMExGMWf0YVUQWSbw@mail.gmail.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF4741842D61B@SCACMX008.exchad.jpmchase.net>

Jim Mooney wrote:
> Sent: Saturday, May 25, 2013 10:21 PM
> To: tutor at python.org
> Subject: [Tutor] got text switched
> 
> Oops, Gmail switched me back to rich text. My apologies. Back to plain
> ;')  I wish I could automate the mode, per-recipient, since I do need
> rich text for some things. The way gmail defaults seems to change from
> month to month.
> 
> --
> Jim Mooney

Gmail seems pretty constant to me. It does however seem
to remember my last style and just use that again. If you 
switch back and forth that may be why you think the default 
has changed. Also it may change depending on the message 
received, I have not verified that aspect.

This is all anecdotal, so YMMV...


~Ramit


 
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

From ramit.prasad at jpmorgan.com  Fri May 31 17:24:53 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Fri, 31 May 2013 15:24:53 +0000
Subject: [Tutor] Fwd: Difference between types
In-Reply-To: <CACL+1avbMc9Fp662Vx-hG3miqDurZxCjK88iHdGQXT=g-df9qQ@mail.gmail.com>
References: <CAMbF=C-9eY4HnV_cDUsSYn-pdS2kzdz7cPb+MXYLbs6t6tiZMg@mail.gmail.com>
	<519EF073.2070207@pearwood.info>
	<CAMbF=C-rhR1yJsRxMOGWTswjWr10=GLMQfdUBQ2DDrUMzQDKcw@mail.gmail.com>
	<519F684D.9080106@pearwood.info>
	<CAMbF=C99UDAQgMsLDTf5E1EfCkbsvFYtRfhK8MBrS8Wqrwvd4g@mail.gmail.com>
	<CACL+1avbMc9Fp662Vx-hG3miqDurZxCjK88iHdGQXT=g-df9qQ@mail.gmail.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF4741842D6E3@SCACMX008.exchad.jpmchase.net>

eryksun wrote:
> 
> Also, when you post code remember to use less than 70 characters per
> line. Gmail has a 'feature' to automatically hard wrap plain-text
> messages at about 70 characters, which it applies *after* you send
> (i.e. there's no indicator in the composer... brilliant).

It is not the only editor to do this either. Outlook (2007) does it as
well. >.<
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

From n.shemonsky at gmail.com  Fri May 31 20:23:42 2013
From: n.shemonsky at gmail.com (Nick Shemonsky)
Date: Fri, 31 May 2013 14:23:42 -0400
Subject: [Tutor] Project Euler #8
Message-ID: <CAFDP+gn_GokuaveaHSXgEhD1xJA3TbOgun6-wFZeRjKjjiX4Vg@mail.gmail.com>

Hey there everybody. I'm new to python and am attempting to teach
myself to code while brushing up on my math skills via the problems at
projecteuler.net. My solutions thus far have been mostly brute force
and this is no exception but I'm having an issue with tackling some
iteration in the problem.

Essentially, the problem is to find the largest product of 5
consecutive digits in a random series of numbers. I'm trying to get
things working on a very small string to start... my code thus far is
below.

I begin by getting a list of strings from the original string, only
keeping those that are 5 digits long... then those numbers are
converted to integers and I get the product with the product function.
 As you can see, I'm currently doing it only for the string of 12345
stored at strings[0]. If I run that list comprehension as [int(i) for
i in strings], I get a new list of all the integers I want; 12345,
23456, 34567, etc... but I can no longer iterate through to multiply
them all together...

I feel like I need to either pull each individual string apart first
and temporarily store it then convert each to an int and get the
product or instead, just find a way to iterate through the members of
a member of a list... I've read up on a bunch of stuff regarding
map(), zip() and enumerate() but none of it seems to be applicable
here or maybe I'm misunderstanding it.

Once I have a list of products a simple max() should do the trick...
or maybe it'd be quicker to compare a to b through each iteration and
just keep the larger product rather than creating a giant list of
products once I get this step working? Any ideas towards the next step
would be much appreciated.

str_num = '1234567890'
n = 5

strings = [str_num[i:i+5] for i in range(0, len(str_num)) if
len(str_num[i:i+5])==5]
integers = [int(i) for i in strings[0]]

def product(x):
    p = 1
    for n in integers:
        p*=n
    return p

print product(integers)

Thanks in advance!

Nick

From davea at davea.name  Fri May 31 20:54:10 2013
From: davea at davea.name (Dave Angel)
Date: Fri, 31 May 2013 14:54:10 -0400
Subject: [Tutor] Project Euler #8
In-Reply-To: <CAFDP+gn_GokuaveaHSXgEhD1xJA3TbOgun6-wFZeRjKjjiX4Vg@mail.gmail.com>
References: <CAFDP+gn_GokuaveaHSXgEhD1xJA3TbOgun6-wFZeRjKjjiX4Vg@mail.gmail.com>
Message-ID: <51A8F1D2.1070302@davea.name>

On 05/31/2013 02:23 PM, Nick Shemonsky wrote:
> Hey there everybody. I'm new to python

Welcome.  But are you new to programming, or just to Python in 
particular?  And which Python?  I'd guess 2.7

> and am attempting to teach
> myself to code while brushing up on my math skills via the problems at
> projecteuler.net. My solutions thus far have been mostly brute force
> and this is no exception but I'm having an issue with tackling some
> iteration in the problem.

Good approach.

>
> Essentially, the problem is to find the largest product of 5
> consecutive digits in a random series of numbers. I'm trying to get
> things working on a very small string to start... my code thus far is
> below.
>
> I begin by getting a list of strings from the original string, only
> keeping those that are 5 digits long... then those numbers are
> converted to integers and I get the product with the product function.
>   As you can see, I'm currently doing it only for the string of 12345
> stored at strings[0]. If I run that list comprehension as [int(i) for
> i in strings], I get a new list of all the integers I want; 12345,
> 23456, 34567, etc... but I can no longer iterate through to multiply
> them all together...
>
> I feel like I need to either pull each individual string apart first
> and temporarily store it then convert each to an int and get the
> product or instead, just find a way to iterate through the members of
> a member of a list... I've read up on a bunch of stuff regarding
> map(), zip() and enumerate() but none of it seems to be applicable
> here or maybe I'm misunderstanding it.
>
> Once I have a list of products a simple max() should do the trick...
> or maybe it'd be quicker to compare a to b through each iteration and
> just keep the larger product rather than creating a giant list of
> products once I get this step working? Any ideas towards the next step
> would be much appreciated.
>
> str_num = '1234567890'
> n = 5
>
> strings = [str_num[i:i+5] for i in range(0, len(str_num)) if
> len(str_num[i:i+5])==5]

If you changed the range() size, you could eliminate the extra if test. 
  After all, the only ones that'll be short are the last 4.  Also, 
xrange is better than range, if you ever try this on a really big 
dataset.  Good habit to get into, and in Python 3.x, the original range 
is gone, and xrange is called range.

    strings = [str_num[i:i+5] for i in xrange(0, len(str_num-4)) ]

> integers = [int(i) for i in strings[0]]

No clue why you would do this.  Stick with strings.

>
> def product(x):

Put in a docstring about what this function is intended to do.  Then 
maybe you'll realize why it isn't doing it.  I'd assume you wanted it to 
multiply the 5 digits represented by a single substring, and return the 
product.

>      p = 1
>      for n in integers:

You're referencing a global instead of the parameter you were passed.
        for n in x:

>          p*=n

Since n is now a character, like "6"  you want
            p *= int(n)
>      return p
>
> print product(integers)

In your original code, this should have been
   print product(integers[0])

but now you probably want

for substr in strings:
      print substr, product(substr)

And then you modify that loop so that instead of printing, it'll figure 
out the largest one.



-- 
DaveA

From cybervigilante at gmail.com  Fri May 31 21:41:15 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Fri, 31 May 2013 12:41:15 -0700
Subject: [Tutor] got text switched
In-Reply-To: <5B80DD153D7D744689F57F4FB69AF4741842D61B@SCACMX008.exchad.jpmchase.net>
References: <CALRAYNU+0LUZ5HRwuue0EeD4Mkzw39seUyMExGMWf0YVUQWSbw@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF4741842D61B@SCACMX008.exchad.jpmchase.net>
Message-ID: <CALRAYNXtzZCduk=gmu58uhk+=Ceuv=D2jYhfRDDY9s1WL7BSrw@mail.gmail.com>

 It does however seem
> to remember my last style and just use that again.

I'd like a default - choose rich text when I need it but always go
back to the default. But like Javascript's annoying habit of deciding
your type invisibly, with arcane rules (one reason I switched to
Python), Gmail sometimes does too much for you ;')  I could probably
write something in autohotkey or webmonkey, but there is only so much
time in a day and the Lutz book (Learning Python - O'Reilly) is Big
and Very Detailed, so I'm focusing on that. I'll just try to keep an
eye on my format.

Speaking of which, I was amazed there were so many complaints about
what I consider the Lutz book's PyVirtues, on Amazon - "It's too big,"
or "The author repeats himself."  Well, duh, if it's that big and that
detailed you Need repetition, unless you have a photographic memory,
which I do not. I am glad to see something repeated three times in
different ways. Bythe third time I might remember it.  (A plug for
Clipmate here - when a long string of Python expressions is listed in
a book, Clipmate's automatic text cleanup or exploding paste can
usually strip out all the garbage, like >>> and commas, so you can
just sequentially paste the terms into a Python program to see what
each one does.)  Besides stripping, you can replace those dumb "fancy"
quotes with ones that will work in the interpreter, or even work up a
regex.

I'm amazed more programming authors don't realize it's a lot easier to
just copy a program fragment into an interpreter, from an ebook, than
go hunting for the downloaded folder of examples. Go fancy with the
printed book, but us plain quotes for e-books. Thankfully, Lutz wrote
his book so you can copy and paste easily with no errors. Or he beat
the editor about the head and shoulders until he agreed to usability.

As for the detail, Lutz seems to anticipate nearly every confusion or
screwup I'm about to make, which my last Python book didn't. It left
me in the woods a lot, so I had to come here asking dumb questions.
That's a big timesaver. So I recommend the  Lutz book, which despite
its size, he says is only the Python intro. His second book is on
practical programming in depth.

Jim

From alan.gauld at btinternet.com  Fri May 31 21:54:16 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 31 May 2013 20:54:16 +0100
Subject: [Tutor] got text switched
In-Reply-To: <CALRAYNXtzZCduk=gmu58uhk+=Ceuv=D2jYhfRDDY9s1WL7BSrw@mail.gmail.com>
References: <CALRAYNU+0LUZ5HRwuue0EeD4Mkzw39seUyMExGMWf0YVUQWSbw@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF4741842D61B@SCACMX008.exchad.jpmchase.net>
	<CALRAYNXtzZCduk=gmu58uhk+=Ceuv=D2jYhfRDDY9s1WL7BSrw@mail.gmail.com>
Message-ID: <koav52$ogp$1@ger.gmane.org>

On 31/05/13 20:41, Jim Mooney wrote:

> ... the Lutz book (Learning Python - O'Reilly) is Big

Phah! If you think Learning Python is big take a look at his Programming 
Python opus - around 1250 pages in my second edition.

:-)

Mind you I deliberately set an upper limit of 300 pages
for my original tutor book, I figured more than that would
be too intimidating to beginners...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From alan.gauld at btinternet.com  Fri May 31 22:10:45 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 31 May 2013 21:10:45 +0100
Subject: [Tutor] Project Euler #8
In-Reply-To: <CAFDP+gn_GokuaveaHSXgEhD1xJA3TbOgun6-wFZeRjKjjiX4Vg@mail.gmail.com>
References: <CAFDP+gn_GokuaveaHSXgEhD1xJA3TbOgun6-wFZeRjKjjiX4Vg@mail.gmail.com>
Message-ID: <kob03v$28l$1@ger.gmane.org>

On 31/05/13 19:23, Nick Shemonsky wrote:

> or maybe it'd be quicker to compare a to b through each iteration and
> just keep the larger product rather than creating a giant list

You are probably right if it is a giant list.

> str_num = '1234567890'
> n = 5
>
> strings = [str_num[i:i+5] for i in range(0, len(str_num)) if
> len(str_num[i:i+5])==5]
> integers = [int(i) for i in strings[0]]
>
> def product(x):
>      p = 1
>      for n in integers:
>          p*=n
>      return p

You define a parameter x but don't use it?

You could use reduce here:

import operator
...
def product(intlist):
     return reduce(operator.mul, intlist)

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From cybervigilante at gmail.com  Fri May 31 22:20:28 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Fri, 31 May 2013 13:20:28 -0700
Subject: [Tutor] got text switched
In-Reply-To: <koav52$ogp$1@ger.gmane.org>
References: <CALRAYNU+0LUZ5HRwuue0EeD4Mkzw39seUyMExGMWf0YVUQWSbw@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF4741842D61B@SCACMX008.exchad.jpmchase.net>
	<CALRAYNXtzZCduk=gmu58uhk+=Ceuv=D2jYhfRDDY9s1WL7BSrw@mail.gmail.com>
	<koav52$ogp$1@ger.gmane.org>
Message-ID: <CALRAYNWDN_G1spBgjoQqp4uQo5ybJcMFm5qRbAq+ZXK49kNfxg@mail.gmail.com>

> Phah! If you think Learning Python is big take a look at his Programming
> Python opus - around 1250 pages in my second edition.
>
> :-)

That's waiting in the wings if I ever get done with the first book,
where he mentions offhand, while taking an entire chapter to explain
the differences between the console, shell, editor, and ide, that you
don't even get to indent until chapter 10 ;')

Maybe I should qualify my recommendation that these two books are good
for summer reading or if you are retired,  as I am, but I would
shudder if some professor actually thought we'd finish the book in a
semester packed with other courses ;')

Jim

From n.shemonsky at gmail.com  Fri May 31 22:49:40 2013
From: n.shemonsky at gmail.com (Nick Shemonsky)
Date: Fri, 31 May 2013 16:49:40 -0400
Subject: [Tutor] Project Euler #8
In-Reply-To: <kob03v$28l$1@ger.gmane.org>
References: <CAFDP+gn_GokuaveaHSXgEhD1xJA3TbOgun6-wFZeRjKjjiX4Vg@mail.gmail.com>
	<kob03v$28l$1@ger.gmane.org>
Message-ID: <CAFDP+g=8P61dUHrPw8uOdCaX97=Vd67h0s6QGvnD00qEUzmGZA@mail.gmail.com>

Thanks for the responses. I am using python 2.7.  I'm not new to
programming but might as well be... I last programmed heavily about a
decade ago in college. I was a MIS major so I did my fair share of
c++, sql, and php work but now I'm a windows sys admin so I haven't
used it much at all in a long time. Using powershell a bunch recently
got me back into scripting and that triggered the itch to get back
into coding so I'm starting with python to see where it goes. The
thought of combining my love of computing with my love of music/audio
and eventually doing audio programming would be sweet, but DSP is some
heavy stuff and I'm no electrical engineer!

Anyway, with your suggestions I got it working! Hopefully once I get a
little bit more knowledge under my belt I can start offering some
assistance to others around here.

Here's the final code... I kept the if statement that way if I throw
in a random series of numbers that isn't evenly divisible by 5, it'll
always work itself out. And this answered the 1000 digit problem
without issue.

str_num = '1234567890'
n = 5
strings = [str_num[i:i+5] for i in xrange(0, len(str_num)) if
len(str_num[i:i+5])==5]

def product(x):
    p = 1
    for n in x:
        p*=int(n)
    return p

def get_max(y):
    products = [product(substr) for substr in strings]
    return max(products)

print get_max(str_num)


Alan,

I did stumble upon using reduce in place of writing my own function
for getting the product when googling around but I didn't really
understand what it was doing so I refrained from using it. More to
explore I guess...


Thanks again guys!

On Fri, May 31, 2013 at 4:10 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> On 31/05/13 19:23, Nick Shemonsky wrote:
>
>> or maybe it'd be quicker to compare a to b through each iteration and
>> just keep the larger product rather than creating a giant list
>
>
> You are probably right if it is a giant list.
>
>
>> str_num = '1234567890'
>> n = 5
>>
>> strings = [str_num[i:i+5] for i in range(0, len(str_num)) if
>> len(str_num[i:i+5])==5]
>> integers = [int(i) for i in strings[0]]
>>
>> def product(x):
>>      p = 1
>>      for n in integers:
>>          p*=n
>>      return p
>
>
> You define a parameter x but don't use it?
>
> You could use reduce here:
>
> import operator
> ...
> def product(intlist):
>     return reduce(operator.mul, intlist)
>
> HTH
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From davea at davea.name  Fri May 31 23:03:04 2013
From: davea at davea.name (Dave Angel)
Date: Fri, 31 May 2013 17:03:04 -0400
Subject: [Tutor] Project Euler #8
In-Reply-To: <CAFDP+g=8P61dUHrPw8uOdCaX97=Vd67h0s6QGvnD00qEUzmGZA@mail.gmail.com>
References: <CAFDP+gn_GokuaveaHSXgEhD1xJA3TbOgun6-wFZeRjKjjiX4Vg@mail.gmail.com>
	<kob03v$28l$1@ger.gmane.org>
	<CAFDP+g=8P61dUHrPw8uOdCaX97=Vd67h0s6QGvnD00qEUzmGZA@mail.gmail.com>
Message-ID: <51A91008.2090704@davea.name>

On 05/31/2013 04:49 PM, Nick Shemonsky wrote:
>    <SNIP>
> Here's the final code... I kept the if statement that way if I throw
> in a random series of numbers that isn't evenly divisible by 5, it'll
> always work itself out. And this answered the 1000 digit problem
> without issue.
>
> str_num = '1234567890'
> n = 5
> strings = [str_num[i:i+5] for i in xrange(0, len(str_num)) if
> len(str_num[i:i+5])==5]

My earlier comment here applies regardles of whether the total size is 
divisible by 5.  You just want to stop when the substring ends at the 
end of the full string.  One advantage you have is that you probably 
won't be as likely to be off-by-one.

Another things that's frequently useful is shown by your n=5.  Instead 
of repeating that 5 in multiple places, put in one "const" and use that 
const wherever you would otherwise by hardcoding the 5.

LEN=5
strings = [str_num[i:i+LEN] for i in xrange(0, len(str_num)-LEN+1)]

Notice that I needed -LEN+1 there, and that it'd be easy to be off by 
one.  With practice, you begin to expect that, and always test.  And 
sometimes it's easier to write more complex but understandable code than 
it is to explain the +1 there.



-- 
DaveA

From alan.gauld at btinternet.com  Fri May 31 23:42:13 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 31 May 2013 22:42:13 +0100
Subject: [Tutor] Project Euler #8
In-Reply-To: <CAFDP+g=8P61dUHrPw8uOdCaX97=Vd67h0s6QGvnD00qEUzmGZA@mail.gmail.com>
References: <CAFDP+gn_GokuaveaHSXgEhD1xJA3TbOgun6-wFZeRjKjjiX4Vg@mail.gmail.com>
	<kob03v$28l$1@ger.gmane.org>
	<CAFDP+g=8P61dUHrPw8uOdCaX97=Vd67h0s6QGvnD00qEUzmGZA@mail.gmail.com>
Message-ID: <kob5fg$ngm$1@ger.gmane.org>

On 31/05/13 21:49, Nick Shemonsky wrote:

> I did stumble upon using reduce ...but I didn't really
> understand what it was doing

>> def product(intlist):
>>      return reduce(operator.mul, intlist)

I explain reduce thusly in my Functional Programming topic:

---------------------
The reduce function is a little less obvious in its intent. This 
function reduces a list to a single value by combining elements via a 
supplied function. For example we could sum the values of a list and 
return the total like this:

def add(i,j): return i+j
print reduce(add, numbers)

As before we could do this more conventionally like this:

res = 0
for i in range(len(numbers)): # use indexing
    res = res + numbers[i]
print res

While that produces the same result in this case, it is not always so 
straightforward. What reduce actually does is call the supplied function 
passing the first two members of the sequence and replaces them with the 
result. In other words a more accurate representation of reduce is like 
this:

def reduce(numbers):
   L = numbers[:] # make a copy of original
   while len(L) >= 2:
      i,j = L[0],L[1] # use tuple assignment
      L = [i+j] + L[2:]
   return L[0]
----------------------

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From bhanu.bais at gmail.com  Fri May 24 14:27:52 2013
From: bhanu.bais at gmail.com (Bhanu Pratap Singh)
Date: Fri, 24 May 2013 12:27:52 -0000
Subject: [Tutor] Issue w/ program: Flip a coin and count heads and tails
In-Reply-To: <CAG6BxkcC3AiTaT-miDZfwyCdosCaHxng7PqqEpqkwn=qpjHBLg@mail.gmail.com>
References: <CAM-E2X5vA5YCLb4LQhqk8U1mTczE042YuQNvRHGELeL4nxE4KQ@mail.gmail.com>
	<CAG6BxkcC3AiTaT-miDZfwyCdosCaHxng7PqqEpqkwn=qpjHBLg@mail.gmail.com>
Message-ID: <001201ce587a$16529b90$42f7d2b0$@com>

Hi Rafeal,

You have called random function two times. It must be called single time and check if it produced 1 or 2. See my code.
/* code
---------------------------*/
import random
print("""
	This program flips a coin 10 times.
	It then counts the number of heads and tails.
	""")
flips = 0
heads = 0
tails = 0
while flips < 10:
	rand = random.randint(1, 2)
	if rand == 1:
		heads += 1
		print("We've got " + str(heads) + " heads here.")
	elif rand == 2:
		tails += 1
		print("We've got " + str(tails) + " tails here.")
	flips = flips + 1
/*----------------------------------- */

-----Original Message-----
From: Tutor [mailto:tutor-bounces+bhanubais=gmail.com at python.org] On Behalf Of Bod Soutar
Sent: Friday, May 24, 2013 4:37 PM
To: Rafael Knuth
Cc: Tutor at python.org
Subject: Re: [Tutor] Issue w/ program: Flip a coin and count heads and tails

On 24 May 2013 12:01, Rafael Knuth <rafael.knuth at gmail.com> wrote:
> Hello,
>
> I am writing a program in Python 3.3.0 which flips a coin 10 x times 
> and then counts the number of heads and tails. It obviously does 
> something else than I intended, and I am wondering what I did wrong:
>
> import random
>
> print ("""
>
> This program flips a coin 10 times.
>
> It then counts the number of heads and tails.
>
> """)
>
> flips = 0
>
> heads = 0
>
> tails = 0
>
> while flips < 10:
>
>     flips = flips + 1
>
>     if random.randint(1,2) == 1:
>
>         heads = heads + 1
>
>         print("We've got " + str(heads) + " heads here."
>
>     if random.randint(1,2) == 2:
>
>         tails = tails + 1
>
>         print("We've got " + str(tails) + " tails here.")
>
> This is what I get as output:
>
> This program flips a coin 10 times.
>
> It then counts the number of heads and tails.
>
> We've got 1 tails here.
>
> We've got 1 heads here.
>
> We've got 2 tails here.
>
> We've got 2 heads here.
>
> We've got 3 tails here.
>
> We've got 3 heads here.
>
> We've got 4 tails here.
>
> We've got 5 tails here.
>
> We've got 4 heads here.
>
> We've got 6 tails here.
>
> We've got 7 tails here.
>
> We've got 5 heads here.
>
> Can anyone help?
>
> Thank you so much!
>
> All the best,
>
>
>
> Rafael
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Hint: Look at your second if statement

Bodsda
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


From feather.duster.kung.fu at gmail.com  Wed May 29 23:23:46 2013
From: feather.duster.kung.fu at gmail.com (charles benoit)
Date: Wed, 29 May 2013 21:23:46 -0000
Subject: [Tutor] 2 basic problems
Message-ID: <CAKP_0cVyMVOFO3-RAFGw1zgiVTTjEKHJUt8vtSxpGCR1sTq-rA@mail.gmail.com>

1:Python 2.7.4 (default, Apr 19 2013, 18:32:33)
[GCC 4.7.3] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> 4+4
8
>>> 3+3=4
SyntaxError: can't assign to operator
>>> 3=1
SyntaxError: can't assign to literal
>
I thought the last 2 lines should return False


2:
lot=('1'+'6'+'8')
print(lot)
a=open("acc","w")
a.write(lot)
a.close
b=open("acc","r")
b.read()
print (b)
b.close


returns
>>>
168
<open file 'acc', mode 'r' at 0xb6f9a650>
>>>

I thought I was saving a string to a file and reading and printing the
string. The output looks like a description of the IO textwrapper at some
location. I'm sure this is a syntax/format problem.but this like the other
examples I saw. I ran this using python 2.6.7 on ubuntu 13.0  Thank you for
any help
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130529/095bcd67/attachment.html>

From galhyams at gmail.com  Thu May 30 19:02:59 2013
From: galhyams at gmail.com (Gal Hyams)
Date: Thu, 30 May 2013 17:02:59 -0000
Subject: [Tutor] a bug which I can't fix
Message-ID: <CAPV1HAq-dGdM9Twzz+qYOFixHZ1b40ZWeu-JD6MG6pfOTgT6RQ@mail.gmail.com>

I'm using win 7 64 bit, and Python 3.3. I've ask the flowing question on  a
form, and friends of mine, and I've brought here the answers. I've made
after the instactions, and yet, the problem isn't fixed.. can someone help
me on this, please?

When I open Python's IDLE, sometimes and error name 'port binding error' is
accrues, and IDLE is filed to run on the computer. one this error accrues,
it will repeat every time I'll open IDLE, till the computer will be
restarted. the error box saies: ' ILDE can't bind to a TCP/IP port, which
is necessary to communicate with its Python execution server. This might be
because no networking is installed on this computer. Run IDLE with the -n
command line switch to start without a subprocess and refer to help/IDLE
Help 'Running without a subprocess' for further details.'

WFT?

Every command you type into the idle after >>> will usually be sent to
another subprocess that executes it => the UI can do what it wants, the
user can do as he/she likes. If you use Tkinter to create your own GUI,
this can prevent you from crashing the IDLE windows.

IDLE uses port 3000 I think. It could be that there is something listening
there for connections other than the subprocess.

in the folder of idlelib:

import idlelibprint idlelib.__file__

there is the idle.py, idle.pyw and idle.bat that can be started with -n to
not make a new subproces.

I hope your WTF is answered.
As they said, it looks like a networking problem.
When IDLE starts, it needs to bind a TCP/IP port 8833 (I don't think it's
3000, but it might depend on the version)
In case you have another application that is running and is using the same
port, or you have another instance of IDLE, the new process will fail when
it tries to bind the new port.
Another possible scenario is port lock due to incomplete shutdown of a
previous IDLE instance.

To verify that go to:
Start > run > cmd.exe
Type the following command:
netstat -no | findstr "Proto 8833"

This command will show you which process is locking the 8833 port.
You can locate the PID of that process, and kill it with:
taskkill /PID pid_number_here


WTF?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130530/00bedb14/attachment.html>