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: 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: 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: References: Message-ID: 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 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: 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: References: 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: References: Message-ID: 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 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: 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: 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: Message-ID: 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: 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: 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: References: 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: 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: 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: References: Message-ID: 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: References: Message-ID: 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: References: 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: 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: References: Message-ID: 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 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 . > > Mark Lawrence > > ______________________________**_________________ > 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: 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: References: Message-ID: 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: References: Message-ID: > 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: 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: References: Message-ID: 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: References: 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: 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: References: Message-ID: On Sat, May 4, 2013 at 12:13 AM, 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)) > 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: References: 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: References: Message-ID: 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: Message-ID: 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 or a forum dedicated to that library 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: 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: 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: References: 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: References: 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: 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: 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: References: 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: <5185DB2F.40207@pearwood.info> Message-ID: 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 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 > -------------- next part -------------- An HTML attachment was scrubbed... URL: 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: 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: Message-ID: 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: References: 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: 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: References: 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: 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: References: 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: References: Message-ID: On Sun, May 5, 2013 at 11:56 AM, 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 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: 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: References: Message-ID: On Sun, May 5, 2013 at 6: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 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: 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: References: 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: <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 > from livewires import games > File "C:\Python33\livewires\games.py", line 57, in > 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: <5186FF37.6040802@pearwood.info> Message-ID: On Sun, May 5, 2013 at 7:54 PM, Steven D'Aprano 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: References: <5186FF37.6040802@pearwood.info> Message-ID: On 5 May 2013 22:10, boB Stepp wrote: > On Sun, May 5, 2013 at 7:54 PM, Steven D'Aprano > wrote: > > > > >> 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? > > > 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: 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: References: <5186FF37.6040802@pearwood.info> 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 wrote: > >> On Sun, May 5, 2013 at 7:54 PM, Steven D'Aprano >> wrote: >> > > > > >>> >>>> 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? >> >> > > > >> 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: <5186FF37.6040802@pearwood.info> <51871FA2.1000306@pearwood.info> Message-ID: On 5 May 2013 23:12, Steven D'Aprano wrote: > > On 06/05/13 12:37, Brian van den Broek wrote: >> 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? >>> >> >> >>> 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: I've noticed that if you exit() a program you always get a traceback message: Traceback (most recent call last): File "", line 1, in 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: References: Message-ID: On Mon, May 6, 2013 at 2:24 PM, Jim Mooney wrote: > I've noticed that if you exit() a program you always get a traceback message: > Traceback (most recent call last): > File "", line 1, in > 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: References: Message-ID: > 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 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: References: Message-ID: On Mon, May 6, 2013 at 2:56 PM, Jim Mooney 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 > 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: References: Message-ID: On Sun, May 5, 2013 at 11:24 PM, Jim Mooney wrote: > > I've noticed that if you exit() a program you always get a traceback message: > Traceback (most recent call last): > File "", line 1, in > 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: <5186FF37.6040802@pearwood.info> Message-ID: On Sun, May 5, 2013 at 8:54 PM, Steven D'Aprano 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: References: Message-ID: On Mon, May 6, 2013 at 1:12 AM, Zachary Ware 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: References: Message-ID: > 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: References: Message-ID: 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: References: Message-ID: 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: References: Message-ID: 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 "", line 1, in > 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: References: 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 "", line 1, in > 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: References: Message-ID: 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: On Mon, May 6, 2013 at 5:05 AM, Steven D'Aprano 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: 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: References: Message-ID: 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: 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: References: Message-ID: 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 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: References: Message-ID: On Mon, May 6, 2013 at 1:00 PM, Alan Gauld 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: 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: References: Message-ID: On 6 May 2013 20:54, David Robinow wrote: > On Mon, May 6, 2013 at 1:00 PM, Alan Gauld > 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: References: 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 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: References: Message-ID: 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: References: 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: References: 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 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: <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: 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: 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: Message-ID: 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: References: 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: >>> 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: 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: References: 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: References: Message-ID: On 7 May 2013 18: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 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: References: Message-ID: 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 wrote: > On 7 May 2013 18: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 > > 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: 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: References: Message-ID: On 7 May 2013 19:09, Bjorn Madsen 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: 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: <5B80DD153D7D744689F57F4FB69AF474183A0B2E@SCACMX008.exchad.jpmchase.net> Message-ID: 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: References: 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: References: Message-ID: On Tue, May 7, 2013 at 2:09 PM, Bjorn Madsen 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: References: Message-ID: On Tue, May 7, 2013 at 9:30 PM, eryksun 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: References: Message-ID: 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 wrote: > On 7 May 2013 19:09, Bjorn Madsen 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: 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: 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: References: Message-ID: On Wed, May 8, 2013 at 6:10 PM, Jim Mooney 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: References: Message-ID: On Wed, May 8, 2013 at 4:10 AM, Jim Mooney 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: References: 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: References: 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: <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: References: Message-ID: 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: 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: <20130507045019.GC5145@ando> <5B80DD153D7D744689F57F4FB69AF474183A0676@SCACMX008.exchad.jpmchase.net> <518A4167.90700@pearwood.info> Message-ID: <20130508165730.GF31171@wdfs.graniteweb.com> * Steven D'Aprano [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: <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 [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: <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 [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: <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, 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: <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: 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: References: <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: <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: 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: On 9 May 2013 14:16, 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. 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 "", line 1, in 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 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: 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: References: <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: <20130509144230.GB32155@wdfs.graniteweb.com> * Alan Gauld [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: <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 [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, > > 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: References: Message-ID: On Thu, May 9, 2013 at 4:36 PM, 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? > > 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: 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: <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> <20130509144230.GB32155@wdfs.graniteweb.com> Message-ID: 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: References: 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: References: Message-ID: 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: 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: References: <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> <20130509144230.GB32155@wdfs.graniteweb.com> Message-ID: <20130509201948.GD32155@wdfs.graniteweb.com> * Alan Gauld [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: References: Message-ID: 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: References: Message-ID: > 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: 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 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: References: Message-ID: 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: References: 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 > 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: <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 > 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: References: Message-ID: > 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: 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: 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: References: Message-ID: On Fri, May 10, 2013 at 10:58 AM, Michael O'Leary 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: 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: <518D325A.9050200@btinternet.com> Message-ID: >> 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: References: <518D325A.9050200@btinternet.com> Message-ID: 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: 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: References: 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: References: 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: 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: On Sat, May 11, 2013 at 12:13 PM, Jack Little 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: References: 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: References: <518D325A.9050200@btinternet.com> 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: 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: References: Message-ID: On Fri, May 10, 2013 at 5: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? 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) >>> next(it), next(it), next(it) ('a', 'b', 'c') >>> next(it) Traceback (most recent call last): File "", line 1, in StopIteration >>> it = iter(range(5)) >>> type(it) >>> list(it) [0, 1, 2, 3, 4] >>> next(it) Traceback (most recent call last): File "", line 1, in 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: <518D325A.9050200@btinternet.com> <518DEA6F.8050604@pearwood.info> Message-ID: 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: 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: References: 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: References: Message-ID: On Fri, May 10, 2013 at 3: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? 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: References: Message-ID: On Sat, May 11, 2013 at 10:41 PM, Danny Yoo wrote: > On Fri, May 10, 2013 at 3: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? > > 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: References: <518EC75F.2090206@davea.name> 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: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> Message-ID: 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: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> Message-ID: On Sun, May 12, 2013 at 6:43 AM, Dave Angel 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: 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: -------------- next part -------------- A non-text attachment was scrubbed... Name: testy.py Type: application/octet-stream Size: 8339 bytes Desc: not available URL: 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: References: Message-ID: >> 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: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> Message-ID: On Sun, May 12, 2013 at 9:43 PM, Dave Angel 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. > > > 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: References: Message-ID: 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: References: 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: References: Message-ID: Message: 1 Date: Fri, 03 May 2013 23:05:32 +0100 From: Alan Gauld To: tutor at python.org Subject: Re: [Tutor] creating a corpus from a csv file Message-ID: 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: 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 or a forum dedicated to that library 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: 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: References: <20130513123602.GA30101@hobbyone.CNFILMS> 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: 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: I have seen (and enjoy) people calling double underscore as 'Dunder' On Mon, May 13, 2013 at 12:32 PM, Natal Ng?tal 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: 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: 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: On Mon, May 13, 2013 at 10:21 AM, 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? 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: 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: On Mon, May 13, 2013 at 1:18 PM, Dave Angel 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: 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: 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: References: Message-ID: On Mon, May 13, 2013 at 5:51 PM, 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' 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: <518EC75F.2090206@davea.name> <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 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: References: Message-ID: 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: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> Message-ID: 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: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> Message-ID: On Mon, May 13, 2013 at 4: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? > 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: 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: References: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> Message-ID: On Mon, May 13, 2013 at 5:13 PM, Marc Tompkins 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: 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: <518EC75F.2090206@davea.name> <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: References: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> 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: > >> > > > > 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: <518EC75F.2090206@davea.name> <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: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> <51919545.8090905@davea.name> Message-ID: 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: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> Message-ID: 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: 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: -------------- next part -------------- An HTML attachment was scrubbed... URL: 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: References: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> Message-ID: On Tue, May 14, 2013 at 1:51 AM, Alan Gauld 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: 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: -------------- next part -------------- An HTML attachment was scrubbed... URL: 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: 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: 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: References: Message-ID: 2013/5/15 vasya > 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 > >> 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: 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: References: Message-ID: 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 > 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: 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: References: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> Message-ID: On 14 May 2013 17:11, Marc Tompkins 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: References: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> 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 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: References: Message-ID: On Tue, May 14, 2013 at 3:54 PM, Matthew Ngaha 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: References: Message-ID: 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: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> <20130515092622.GE9103@ando> Message-ID: On Wed, May 15, 2013 at 2:26 AM, Steven D'Aprano 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: 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: References: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> <20130515092622.GE9103@ando> Message-ID: 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: References: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> <20130515092622.GE9103@ando> Message-ID: On Wed, May 15, 2013 at 1:02 PM, 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... > > 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: 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: References: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> <20130515092622.GE9103@ando> Message-ID: On 15 May 2013 22:21, Marc Tompkins wrote: > On Wed, May 15, 2013 at 1:02 PM, 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... >> > > 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: References: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> <20130515092622.GE9103@ando> Message-ID: On Wed, May 15, 2013 at 3:43 PM, Oscar Benjamin wrote: > On 15 May 2013 22:21, Marc Tompkins wrote: > > On Wed, May 15, 2013 at 1:02 PM, 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... > >> > > > > 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: 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: References: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> <20130515092622.GE9103@ando> Message-ID: On 15 May 2013 23:52, Marc Tompkins wrote: > On Wed, May 15, 2013 at 3:43 PM, Oscar Benjamin > wrote: >> >> On 15 May 2013 22:21, Marc Tompkins wrote: >> > On Wed, May 15, 2013 at 1:02 PM, 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... >> >> >> > >> > 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: References: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> <20130515092622.GE9103@ando> Message-ID: On Wed, May 15, 2013 at 3:52 PM, Marc Tompkins 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: 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: References: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> <20130515092622.GE9103@ando> Message-ID: On Wed, May 15, 2013 at 4:14 PM, Oscar Benjamin 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: 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: References: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> <20130515092622.GE9103@ando> Message-ID: On 16/05/13 00:18, Marc Tompkins wrote: > On Wed, May 15, 2013 at 3:52 PM, Marc Tompkins > 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: 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: 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: References: 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: References: Message-ID: 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 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: References: Message-ID: Hi Grace, On Thu, May 2, 2013 at 8:04 AM, Grace Kathryn 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: 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: References: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> <20130515092622.GE9103@ando> 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: References: Message-ID: > 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: References: 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: References: 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: References: Message-ID: 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: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> <20130515092622.GE9103@ando> <51942354.4080908@pearwood.info> Message-ID: On Wed, May 15, 2013 at 5:07 PM, Steven D'Aprano 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: 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: References: Message-ID: 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: 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: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> <20130515092622.GE9103@ando> <51942354.4080908@pearwood.info> Message-ID: On Wed, May 15, 2013 at 8:07 PM, Steven D'Aprano 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 "", line 1, in 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: 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: 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: References: Message-ID: On Thu, May 16, 2013 at 2:12 AM, Jim Mooney 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: References: Message-ID: Hi, On 16 May 2013 07:12, Jim Mooney 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: 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: References: Message-ID: On Thu, May 16, 2013 at 2:06 AM, Jim Mooney 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: References: Message-ID: On 7 May 2013 21:10, Linsey Raaijmakers 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: References: Message-ID: 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: References: Message-ID: 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: References: <518EC75F.2090206@davea.name> <518F8078.9030902@davea.name> <8DD366A4-0256-4589-9D96-83B1BA89DE28@att.net> <20130515092622.GE9103@ando> <51942354.4080908@pearwood.info> Message-ID: On Thu, May 16, 2013 at 1:42 AM, eryksun 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 "", line 1, in 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: 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: 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: 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: 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: 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: References: 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: References: Message-ID: On Thu, May 16, 2013 at 1:58 PM, Rafael Knuth 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: <5195302C.9060104@davea.name> Message-ID: 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 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 > -------------- next part -------------- An HTML attachment was scrubbed... URL: 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: 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: 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: References: 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: References: Message-ID: 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: References: Message-ID: 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 wrote: > On Thu, May 16, 2013 at 2:06 AM, Jim Mooney 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: References: Message-ID: On Thu, May 16, 2013 at 2:06 AM, Jim Mooney 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: References: Message-ID: > 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: References: Message-ID: You may want to consider pillow. Oil hasn't been maintained in some time. On May 16, 2013 6:12 PM, "Jim Mooney" 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: 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: References: Message-ID: On Thu, May 16, 2013 at 1:03 PM, Arvind Virk 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: 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: References: Message-ID: On 16 May 2013 16:11, James Reynolds 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: 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: References: Message-ID: 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: References: Message-ID: On Thu, May 16, 2013 at 6:12 PM, Jim Mooney 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: References: Message-ID: On Thu, May 16, 2013 at 6:15 PM, Jim Mooney 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: 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: References: Message-ID: > 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: References: Message-ID: On Fri, May 17, 2013 at 3:23 AM, Jim Mooney 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: References: Message-ID: Hi, On 16 May 2013 23:49, Jim Mooney 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: 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: References: Message-ID: On 17 May 2013 05:56, eryksun wrote: > On Thu, May 16, 2013 at 6:15 PM, Jim Mooney 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: References: Message-ID: 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 > To: Jim Mooney > Cc: tutor at python.org > Subject: Re: [Tutor] Pygraphics crashed > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > > On Thu, May 16, 2013 at 6:15 PM, Jim Mooney 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: > 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 > To: tutor at python.org > Subject: Re: [Tutor] Can't install latest PIL > Message-ID: > > 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 > To: Jim Mooney > Cc: tutor at python.org > Subject: Re: [Tutor] Can't install latest PIL > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > > On Fri, May 17, 2013 at 3:23 AM, Jim Mooney 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: References: 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: References: Message-ID: On Fri, May 17, 2013 at 10:31 AM, Oscar Benjamin 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: References: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com> 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: References: Message-ID: On 17 May 2013 17:04, eryksun wrote: > On Fri, May 17, 2013 at 10:31 AM, Oscar Benjamin > 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> <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> <519665D8.9080103@gmail.com> Message-ID: 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> <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: 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: References: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com> <519665D8.9080103@gmail.com> <5B80DD153D7D744689F57F4FB69AF474183D0837@SCACMX008.exchad.jpmchase.net> 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 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> <519665D8.9080103@gmail.com> <5B80DD153D7D744689F57F4FB69AF474183D0837@SCACMX008.exchad.jpmchase.net> <5B80DD153D7D744689F57F4FB69AF474183D0995@SCACMX008.exchad.jpmchase.net> Message-ID: On Fri, May 17, 2013 at 12:35 PM, Prasad, Ramit 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: 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: References: , <5B80DD153D7D744689F57F4FB69AF474183CE208@SCACMX008.exchad.jpmchase.net> 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: References: <1368728222.12357.YahooMailNeo@web126203.mail.ne1.yahoo.com> <519665D8.9080103@gmail.com> 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 "", line 1, in 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: On Fri, May 17, 2013 at 3:23 PM, Albert-Jan Roskam 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: On Fri, May 17, 2013 at 11:06 PM, Dave Angel 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: 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: 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: 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: 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: 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: References: <5196C3F7.6030507@bigpond.com> 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> <51973EA2.6040007@bigpond.com> Message-ID: 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(""))? >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: References: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com> <5196CF4B.20809@pearwood.info> <5196F02F.5000508@davea.name> Message-ID: <1368873562.40750.YahooMailNeo@web163805.mail.gq1.yahoo.com> ----- Original Message ----- > From: eryksun > 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 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: References: 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: References: <5196C3F7.6030507@bigpond.com> <51973EA2.6040007@bigpond.com> 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: References: <5196C3F7.6030507@bigpond.com> <51973EA2.6040007@bigpond.com> 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> <51973EA2.6040007@bigpond.com> <51975509.2020102@bigpond.com> Message-ID: 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: 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: On Sat, May 18, 2013 at 6:01 AM, Albert-Jan Roskam 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. ) 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: References: <1368818621.56494.YahooMailNeo@web163801.mail.gq1.yahoo.com> <5196FA52.9090000@pearwood.info> <1368871300.10705.YahooMailNeo@web163805.mail.gq1.yahoo.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: References: <5196C3F7.6030507@bigpond.com> <51973EA2.6040007@bigpond.com> <51975509.2020102@bigpond.com> Message-ID: 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: 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> <1368895532.71831.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: On Sat, May 18, 2013 at 12:45 PM, Albert-Jan Roskam 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 : 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: 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: References: 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: 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: References: <5196C3F7.6030507@bigpond.com> <51973EA2.6040007@bigpond.com> <51975509.2020102@bigpond.com> 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: > 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> <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: References: 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: 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: 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: References: 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: <51983757.3020504@davea.name> Message-ID: On Sat, May 18, 2013 at 10:22 PM, Dave Angel 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) >>> meth.__self__ eggs A method doesn't have a __dict__ for setting dynamic attributes: >>> meth.boolean = False Traceback (most recent call last): File "", line 1, in AttributeError: 'instancemethod' object has no attribute 'boolean' But you can set attributes on the underlying function object: >>> type(meth.__func__) >>> 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 "", line 1, in 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: References: <5196C3F7.6030507@bigpond.com> <51973EA2.6040007@bigpond.com> <51975509.2020102@bigpond.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: References: Message-ID: > 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: References: Message-ID: On Sun, May 19, 2013 at 3:37 AM, Jim Mooney 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> <51973EA2.6040007@bigpond.com> <51975509.2020102@bigpond.com> <51985CAC.2000908@bigpond.com> Message-ID: 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 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: References: <51983757.3020504@davea.name> Message-ID: 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> <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 > 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: References: <51983757.3020504@davea.name> Message-ID: On Sun, May 19, 2013 at 6:35 AM, Matthew Ngaha 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: References: <51983757.3020504@davea.name> Message-ID: > 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: References: <5196C3F7.6030507@bigpond.com> <51973EA2.6040007@bigpond.com> <51975509.2020102@bigpond.com> <51985CAC.2000908@bigpond.com> 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> <51973EA2.6040007@bigpond.com> <51975509.2020102@bigpond.com> <51985CAC.2000908@bigpond.com> <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 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: 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 name = str(input("What is your name? ")) File "", line 1, in NameError: name 'Rafael' is not defined Can anyone help? Thanks in advance! Rafael -------------- next part -------------- An HTML attachment was scrubbed... URL: 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> <51973EA2.6040007@bigpond.com> <51975509.2020102@bigpond.com> <51985CAC.2000908@bigpond.com> <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: References: Message-ID: On 19 May 2013 14:04, Rafael Knuth 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 > name = str(input("What is your name? ")) > File "", line 1, in > 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: References: Message-ID: 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 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: 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: References: Message-ID: 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 wrote: > On 19 May 2013 14:04, Rafael Knuth 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 > > name = str(input("What is your name? ")) > > File "", line 1, in > > NameError: name 'Rafael' is not defined > > > Oscar > -------------- next part -------------- An HTML attachment was scrubbed... URL: 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: References: <51983757.3020504@davea.name> Message-ID: On Sun, May 19, 2013 at 7:20 AM, Matthew Ngaha 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: References: Message-ID: > 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: References: <51983757.3020504@davea.name> Message-ID: > 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: References: 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 "", line 1, in File "", line 1, in 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: References: 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: Message-ID: 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: <5198E2FF.6040600@pearwood.info> Message-ID: On Sun, May 19, 2013 at 3:34 PM, Steven D'Aprano 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: References: <5198E2FF.6040600@pearwood.info> Message-ID: On Sun, May 19, 2013 at 10:49 AM, Matthew Ngaha wrote: > On Sun, May 19, 2013 at 3:34 PM, Steven D'Aprano 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: 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: References: 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: References: <5196C3F7.6030507@bigpond.com> <51973EA2.6040007@bigpond.com> <51975509.2020102@bigpond.com> <51985CAC.2000908@bigpond.com> 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 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: 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: 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: Message-ID: 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> <51973EA2.6040007@bigpond.com> <51975509.2020102@bigpond.com> <51985CAC.2000908@bigpond.com> <5199881C.9080106@bigpond.com> Message-ID: 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 > 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 ...