Re: [Tutor] Who uses input()? [was Re: question on input]

2005-07-18 Thread Nathan Pinno
  Terry and all,

  I thought something like this might popup.

  I find it easier to remember and faster to code than int(raw_input()). The 
faster I can code a program, the better in my opinion. So what if it has a 
few bugs, I fix them gradually.

  Nathan Pinno
  - Original Message - 
  From: Terry Reedy [EMAIL PROTECTED]
  To: python-list@python.org
  Sent: Monday, July 18, 2005 1:04 AM
  Subject: Re: Who uses input()? [was Re: question on input]


  
   Nathan Pinno [EMAIL PROTECTED] wrote in message
   news:[EMAIL PROTECTED]
I use input() all the time. I know many people say it ain't safe, but
   whose going to use it to crash their own comp? Only an insane person
   would,
  
   This is usage Guido intended it for, not for production apps distributed 
to
   world.
  
  
  
   -- 
   http://mail.python.org/mailman/listinfo/python-list
  
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT, Tcl Python

2005-07-18 Thread Alan G
 Why do not do this entirely  in Python ?

The answer is in the original post:

  past. My motivation is the greater ease of deployment across 
  systems
  that Tcl seems to offer, with Starkits and Starpacks,

  cumbersome. A typical GUI app is approximately 5 MB in python,
  distributed as a collection of files in a folder, whereas a Tcl
  Starpack is a compact 1 MB, distributed as a single file 
  executable.

So primarily the OP was interested in small easily distributed files.
Tcl generally beats Python at that game.

Alan G. 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regular expressions

2005-07-18 Thread Alan G
 Using regular expressions how do I represent Floats.

I'm not certain what you mean by that. Regex searches strings,
so the only way floats would be recognised is if you had the
string representation of them. Regex won't work with raw floating
point data.

Assuming you do mean floating point numbers as strings then it depends
again on the representation used in the string.

.
.MMMe

etc

You have to look at the string pattern you are interested in
and write a regex to match. The first form is the more common
and searcging for a sequence of numbers followed by a literal
period followed by another sequence of numbers is what you
need. But then you might consider plus/minus signs in front etc.

Can you show us what you tried?

Alan G. 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to add python code to a webpage

2005-07-18 Thread EJP



Mustafa Abbasi asked:

i want to create a simple page which has a formand takes in 
persons date of birth and give out exact age.how do i add python codeto an 
html page.i don't have any dreamweaver or frontpage.this is basically 
cuz some freinds advised me to create this isnce i am learning programming 
python..so please help 

Mustfa, it sounds like you want a cgi script. The Python 
script would reside on a server, and your webpage would send the form data to 
that script. Often such script are kept in a "folder" called a 
cgi-bin.

You would want to get a basic understanding of "cgi" 
first. You will find cgi mentioned both in Python documentation, and in 
Google search results for "cgi".

Good luck.

EP



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] File transfer

2005-07-18 Thread Raj Moodley








Hi All, am a newbie to
python and need some help.



I need to transfer a
file from a client over a normal telephone call (no ISP) or an
internet connection (thro ISP) to a central server. 

The server
needs to open this file process it and then output a file which then needs to
be sent back to the above client. 



How do I do this in
Python? What if the server is a plone setup?



Kind regards



Raj 








___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pager in Python?

2005-07-18 Thread Alan G
 Is there a command like more(1) or less(1) in python to display
 the output of a command (e.g. dir()) one page at a time?

First define a page.
A page is effectively a screenful, but screens differ in capacity,
especially when users can control font sizes etc.

And what about teletype interfaces that have no screen, what size
is a page there? Maybe the distance between paper perforations?
But some paper rolls have no perforations. (And before anyone
shouts, I do have one system that still uses teletypes as their
only output - albeit not written in Python!)

You can certainly write a paging function that will break up a
long string into sections of N length - especially now that we
have generators, but the function would need to take account of
terminal capabilities. Most folks find it easier to write
their own simplied version, something like:

def page(str, lines=25):
   text = str.split('\n')
   for linenum in range(len(text)):
   print text[linenum]
   if linenum % (lines - 1) == 0
  key = raw_input('Hit any key to continue...')
  if key == 'q' : break

For full less/more equivalence you would need to parse the raw_input
value and take appropriate action... For OS indepencence you should
split by linesep etc too...

Writing a fully fledged OS/terminal independant pager with
backward/forward scrolling etc would be a useful and potentially
challenging beginners project if anyone has the time and inclination!

:-)

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to add python code to a webpage

2005-07-18 Thread Alan G
 i want to create a simple page which has a form
 and takes in persons date of birth and give out exact age.

CGI would be the normal route but...

 how do i add python codeto an html page.

You can use an ASP style approach if you install winall and have WSH 
enabled
on Windows, but it will only work in IE, not Mozilla based browsers.

Another way of doing it is to use Zope, but thats way overkill for 
your needs.

 i don't have any dreamweaver or frontpage.

Thats OK, you can write html in Notepad if necessary.

Take a look at the 'Getting Started' page in my tutor,
there it talks about setting up JavaScript and VBScript.

You would do the same but use

script language=python
   # your code here
/script

instead of the other languages.

 some freinds advised me to create this isnce i am learning 
 programming python..

Writing web pages is only one kind of programming (And not really a 
very fun
kind IMHO!). Python can do many other types of programs including GUI 
based
applications too. But either CGI or Client Side Scripting (as the 
above technique
is called) can be done in Python.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Parsing problem

2005-07-18 Thread Liam Clarke
Hi all, 

I am a Europa Universalis II freak, and in attempting to recreate a
lost saved game, I had to delve into the mechanics of the save game
file. 
Which, luckily, is plain text. 

It's formatted like this - 

country = { 
 tag = ENG 
 ai = { 
 flags = { } 
 combat = { DAU FRA ORL PRO } 
 continent = { } 
 area = { } 
 region = { British Isles
NorthSeaSea ECAtlanticSea NAtlanticSea TagoSea WCAtlanticSea
} 
 war = 60 
 ferocity = no 
 }
}

Now, it tends to conform to certain rules, which make it a bit easier,
there's always a space either side of an equals sign and such forth,
which should hopefully make parsing stuff like - 

date = { year = 1421 month = july day = 7 }

a bit less complex, considering that it uses space to separate list items. 

What I need to do, is to turn this into a data structure, and I think
this relates to XML in a way. Basically, I want to parse the above (I
assume I'll be counting braces to find where I am) so that a country
object called ENG has a dictionary called ai, which points to lists,
integers, strings etc. and so forth. 

If anyone has any links to any (simple) examples of XML parsing or
similar which could give me pointers as to how to go about this, it'd
be much appreciated. 

Regards, 

Liam Clarke

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] File transfer

2005-07-18 Thread Alan G
 I need to transfer a file from a client over a normal telephone 
 call (no

You still need some kind of protocol between the two computers.
Common protocol for file transfers include xmodem and zmodem and
ISTR seeing modules for each of them on the vaults of parnassus.

You could do it at the raw data level if you also have control of
the remote computer, but thats hard, you effectively have to write
your own protocol... If you are on unix you could use the 'fcntl' 
module.
I think there is a non standard 'serial' module somewhere too.

 ISP) or an internet connection (thro ISP) to a central server.

That's probably easiest using the standard ftplib module.

 The server needs to open this file process it and then output a 
 file which
 then needs to be sent back to the above client.

Same principles apply provided you have access to the remote box.
If you need to rely on it using existing tools it might get a tad
more tricky!

No idea about plone however...

Alan G. 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] ListBox in Tkinter

2005-07-18 Thread geon

Hi,

I would like to ask if it is possible to create such a listbox 
(attached) in TKinter itself or must have pmw ot tix...or ...


Thank you

--
geon
Vyjímka je pravidlo. Rekurzivní.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to add python code to a webpage

2005-07-18 Thread Ron Phillips



snipMustafa Abbasi asked:

i want to create a simple page which has a formand takes in persons date of birth and give out exact age.how do i add python codeto an html page.i don't have any dreamweaver or frontpage.this is basically cuz some freinds advised me to create this isnce i am learning programming python..so please help /snip

Ifind CherryPy is easy and lightweight to get started. http://www.cherrypy.org

Ron


Header
Description: Binary data
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] File transfer

2005-07-18 Thread Andreas Kostyrka
Am Montag, den 18.07.2005, 11:39 +0200 schrieb Raj Moodley:
 Hi All, am a newbie to python and need some help.
 
  
 
 I need to transfer a file from a “client” over a normal telephone call
 (no ISP) or an internet connection (thro ISP) to a central “server”. 
Well, even without ISP you can have a TCP/IP connection. Or you can send
the file directly over the modem connection. How this is accomplished is
highly OS-dependant ;)

Andreas



signature.asc
Description: Dies ist ein digital signierter Nachrichtenteil
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Hy, I'm a n00b to Python, have some questions

2005-07-18 Thread Alex Nedelcu
Hy all,

I am a Java/PHP programmer.
I read the tutorial and I like the language. I am more interested in the web capabilities of the platform (CPython).

I have some questions I'd like to ask you guys:

1. Is there any decent forum were people are talking in python ?
2. what about speed ? (any beginners question I suppose). Is it
something to be concerned about ? Does anyone know how it compares to
PHP ? (for Java I allready know)
3. I want any usefull resources you can provide me with 
4. What's the hottest web framework right now that does not require an application server (meaning that it runs on fastcgi)

Also, why is www.python.org so ugly :) ? If I'd like to point others to
learn Python I would need a site that markets Python through eye-candy
case studies, not some boring old site :). Just joking. I don't want to
give examples of others. I am sure you guys know what I mean.

Thank you,
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Who uses input()? [was Re: question on input]

2005-07-18 Thread Nathan Pinno
  Danny,

  It sure did, though I wish there was an easier way of coding it than 
int(raw_input())! Any ideas would gladly be appreciated.

  By the way, is there any code floating out there that can show how many 
possible mixtures there are, e.g. for x0, x1, x2, x3, and a0, a1, a2, and a3 
for example. If there is, show me it, please. I'm getting confused writing 
my MasterMind and don't want to screw up bad, e.g. repeat the same answer in 
a different way.

  Thanks,
  Nathan Pinno.
  - Original Message - 
  From: Danny Yoo [EMAIL PROTECTED]
  To: Nathan Pinno [EMAIL PROTECTED]
  Cc: Terry Reedy [EMAIL PROTECTED]; tutor@python.org
  Sent: Monday, July 18, 2005 2:14 AM
  Subject: Re: [Tutor] Who uses input()? [was Re: question on input]


  
  
   On Mon, 18 Jul 2005, Nathan Pinno wrote:
  
   I find it easier to remember and faster to code than int(raw_input()).
   The faster I can code a program, the better in my opinion. So what if 
it
   has a few bugs, I fix them gradually.
  
   Hi Nathan
  
   You're right, just as long as we're writing programs that are only meant
   to be used by ourselves, and as long as we're sure that it's not talking
   to the outside world.  The driving issue behind getting paranoid is 
this:
   it's getting much easier to write programs that we think might be just 
for
   ourselves, but which become useful for others.
  
   And as soon as we write programs that other people are going to use, we
   really do have to play by a different set of rules than just ease of
   programming.  Some folks were casual about eval(), and look what 
happened
   to them:
  
  http://gulftech.org/?node=researcharticle_id=00088-07022005
  
   They should have known better.
  
   This problem is not exclusive to programmers in PHP:  programmers in
   Python make the same kind of mistakes.  As a concrete example, take a 
look
   at the comments about the deprecated SimpleCookie and SerialCookie
   functions:
  
  http://www.python.org/doc/lib/module-Cookie.html
  
   Again, they should have known better.  And we should know better.
  
   So we do have a responsibility to state up front that using 'eval' (or
   things that call 'eval' for us) is convenient, but it's not safe. 
That's
   why we bug about it every so often.
  
  
   Hope this helps!
  
  
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hy, I'm a n00b to Python, have some questions

2005-07-18 Thread Alberto Troiano
Hey Alex

First of all welcome

I've been programming in Python for almost 1 year now and I think I can 
answer two of your questions

1. Is there any decent forum were people are talking in python ?
You found one of them, here you have people willing to help each others at 
no cost.
Send an email with your problem and someone here will answer

2. what about speed ? (any beginners question I suppose). Is it something 
to
be concerned about ? Does anyone know how it compares to PHP ? (for Java I
allready know)
I have no experience in web Python but I do have experience with PHP, 
JavaScript and ASP.NET and I have to tell you: you can't compare PHP with 
JavaScript, PHP is server-side and JavaScript is Client-side so the speed is 
irrelevant because they are two different things. You can compare PHP with 
ASP. About Python I'm not sure if this is a server or client-side. This is 
the first thing I would ask.

3. I want any usefull resources you can provide me with
You may want to invest in some books. Try searching in Amazon. I have one 
very practical called Python: Developing Applicattions
In fact this is a database book, but the aim is Python on web pages with 
databases
The autor is Sonu Mangla

Best Regards

Alberto


From: Alex Nedelcu [EMAIL PROTECTED]
Reply-To: Alex Nedelcu [EMAIL PROTECTED]
To: tutor@python.org
Subject: [Tutor] Hy, I'm a n00b to Python, have some questions
Date: Mon, 18 Jul 2005 16:17:11 +0300

Hy all,

I am a Java/PHP programmer.
I read the tutorial and I like the language. I am more interested in the 
web
capabilities of the platform (CPython).

I have some questions I'd like to ask you guys:



3. I want any usefull resources you can provide me with
4. What's the hottest web framework right now that does not require an
application server (meaning that it runs on fastcgi)

Also, why is www.python.org http://www.python.org so ugly :) ? If I'd 
like
to point others to learn Python I would need a site that markets Python
through eye-candy case studies, not some boring old site :). Just joking. I
don't want to give examples of others. I am sure you guys know what I mean.

Thank you,
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Scrolling multilistbox help

2005-07-18 Thread Alberto Troiano
Hey tutors

I'm using the Multilistbox class and I noticed that it only handles the 
mouse scroll and the scrollbar to go down or up.I succesfully implemented 
the sort function that came with the class
I also added code to handle the up and down arrow keys and it goes down all 
right but only select the item and it doesn't scroll down or up

How can make it go up or down?
I'm sendind the class here:

class MultiListbox(Frame):
fila=0
sortedBy=-1
def __init__(self, master, lists):
Frame.__init__(self, master)
self.lists = []
for l,w,a in lists:
frame = Frame(self,background=red); frame.pack(side=LEFT, 
expand=YES, 
fill=BOTH)
Button(frame,background=red,foreground=white,font=Verdana 8 
bold,text=l, borderwidth=1, relief=RAISED,command=lambda a=a: 
self._sortBy(a)).pack(fill=X)
lb = Listbox(frame, width=w, borderwidth=0, selectborderwidth=0,
 relief=FLAT, exportselection=FALSE)
lb.pack(expand=YES, fill=BOTH)
self.lists.append(lb)
lb.bind('B1-Motion', lambda e, s=self: s._select(e.y))
lb.bind('Double-Button-3', lambda e, s=self: s._devolverfila(e.y))
lb.bind('Return', lambda e, s=self: s._devolverfila(e.y))
lb.bind('Button-1', lambda e, s=self: s._select(e.y))
lb.bind('Down', lambda s: _select1())
lb.bind('Up', lambda s: _select2())
lb.bind('Leave', lambda e: 'break')
lb.bind('B2-Motion', lambda e, s=self: s._b2motion(e.x, e.y))
lb.bind('Button-2', lambda e, s=self: s._button2(e.x, e.y))
frame = Frame(self,background=red); frame.pack(side=LEFT, fill=Y)
Label(frame,background=red,foreground=white,font=Verdana 8 bold, 
borderwidth=1, relief=RAISED).pack(fill=X)
sb = Scrollbar(frame,background=red, orient=VERTICAL, 
command=self._scroll)
sb.pack(expand=YES, fill=Y)
self.lists[0]['yscrollcommand']=sb.set

def _sortBy(self, column):
 Sort by a given column. 
if column == self.sortedBy:
direction = -1 * self.direction
else:
direction = 1
elements = self.get(0, END)
self.delete(0, END)
elements.sort(lambda x, y: self._sortAssist(column, direction, x, 
y))
self.insert(END, *elements)
self.sortedBy = column
self.direction = direction

def _sortAssist(self, column, direction, x, y):
if column!=0:
c = cmp(x[column], y[column])
if c:
return direction * c
else:
return direction * cmp(x, y)
else:
c = cmp(int(x[column]), int(y[column]))
if c:
return direction * c
else:
return direction * cmp(x, y)

def _select(self, y):
row = self.lists[0].nearest(y)
self.selection_clear(0, END)
self.selection_set(row)
self.fila=row
return 'break'

def _devolverfila(self, y):
row = self.lists[0].nearest(y)
self.selection_clear(0, END)
self.selection_set(row)
self.fila=row

def _select1(self):
if self.fila==self.size()-1:
pass
else:
self.selection_clear(0, END)
self.selection_set(self.fila+1)
self.fila+=1
self._scroll()
return 'break'

def _select2(self):
if self.fila==0:
pass
else:
self.selection_clear(0, END)
self.selection_set(self.fila-1)
self.fila-=1
return 'break'

def _button2(self, x, y):
for l in self.lists: l.scan_mark(x, y)
return 'break'

def _b2motion(self, x, y):
for l in self.lists: l.scan_dragto(x, y)
return 'break'

def _scroll(self, *args):
for l in self.lists:
apply(l.yview, args)

def curselection(self):
return self.lists[0].curselection()

def delete(self, first, last=None):
for l in self.lists:
l.delete(first, last)

def get(self, first, last=None):
result = []
for l in self.lists:
result.append(l.get(first,last))
if last: return apply(map, [None] + result)
return result

def index(self, index):
self.lists[0].index(index)

def insert(self, index, *elements):
for e in elements:
i = 0
for l in self.lists:
l.insert(index, e[i])
i = i + 1

def size(self):
return self.lists[0].size()

def see(self, index):
for l in self.lists:
l.see(index)

def selection_anchor(self, index):
for l in self.lists:
l.selection_anchor(index)

def selection_clear(self, first, last=None):
for l in self.lists:
l.selection_clear(first, last)

def selection_includes(self, 

Re: [Tutor] Parsing problem

2005-07-18 Thread Kent Johnson
Liam Clarke wrote:
 What I need to do, is to turn this into a data structure, and I think 
 this relates to XML in a way. Basically, I want to parse the above (I 
 assume I'll be counting braces to find where I am) so that a country 
 object called ENG has a dictionary called ai, which points to lists, 
 integers, strings etc. and so forth. 
 
 If anyone has any links to any (simple) examples of XML parsing or 
 similar which could give me pointers as to how to go about this, it'd be 
 much appreciated.

Take a look at pyparsing, I think it is the easiest Python parsing package.
http://pyparsing.sourceforge.net/

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ListBox in Tkinter

2005-07-18 Thread Alan G
 I would like to ask if it is possible to create such a listbox 
 (attached) in TKinter itself or must have pmw ot tix...or ...

PMW is written in Tkinter so yes, you could do it yourself 
but it is not a native widget. Using PMW would be much easier!

Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hy, I'm a n00b to Python, have some questions

2005-07-18 Thread Alan G
 I am a Java/PHP programmer.

Sorry to hear it ;-)

 I read the tutorial and I like the language. I am more interested 
 in the web capabilities of the platform (CPython).

For serious web work with python look at Zope.

http://www.zope.org

 1. Is there any decent forum were people are talking in python ?

Lots, look in the communities page for mailing lists etc.

There is a wiki too.

And of course comp.lang.python on newnet.

 2. what about speed ? 
 Is it something to be concerned about ? 
 Does anyone know how it compares to PHP ? 
 (for Java I allready know)

The above set of questions are self contradictory.
If you know about Java that means you know that Python 
is sometimes faster than Java and sometimes slower 
depending on what you are doing, how you build it etc. 
( The same applies to almost any language including 
assembler - badly written assembler can be much worse 
than well written python utilising maoinly C libraries...)

In practice almost any programming language will be 
fast enough for most purposes. IF OTOH you want to 
build a killer web site taking millions of hits per 
day you may want to look elsewhere (but it wouldn't 
be PHP or Java either!) or be prepared to spend a 
fortune on hardware... And probably both.

 3. I want any usefull resources you can provide me with 

Google...

 4. What's the hottest web framework right now that 
 does not require an application server (meaning that 
 it runs on fastcgi)

Why constrain the solution? If an app server can run fast 
and small why not use one? Popular Python web platforms 
exist, they are nearly all freeware so try them and see 
what suits. Zope is the battleship, CherryPy(sp?) the 
lightweight with vanilla CGI etc around in various forms.

 Also, why is www.python.org http://www.python.org so ugly :) ? 

Dunno, its always been ugly since I started with Python in 1997 
or so...

HTH,

Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hy, I'm a n00b to Python, have some questions

2005-07-18 Thread André Roberge
Alex Nedelcu wrote:
[snip]
 
 Also, why is www.python.org http://www.python.org so ugly :) ? If I'd 
 like to point others to learn Python I would need a site that markets 
 Python through eye-candy case studies, not some boring old site :). Just 
 joking. I don't want to give examples of others. I am sure you guys know 
 what I mean.
 

Well, joke or not, a new draft web site was shown at the recent 
Europython conference.  I looked for it ... but my google skills didn't 
help me.  (Tim Parkin at http://www.pollenation.net/ is the one that 
showed it.)

Be prepared to see something nice :-)

André

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ListBox in Tkinter

2005-07-18 Thread geon
Alan G napsal(a):

 I would like to ask if it is possible to create such a listbox 
 (attached) in TKinter itself or must have pmw ot tix...or ...


 PMW is written in Tkinter so yes, you could do it yourself but it is 
 not a native widget. Using PMW would be much easier!

I have just found this: http://effbot.org/tkinterbook/optionmenu.htm - 
that is nearly what I needed , just another design.
I think there are even other new widgets in new Tk/Tcl compared to the 
http://www.pythonware.com/library/tkinter/introduction/, but 
undocumented yet. Or poorly or only in original Tk documentation.


-- 
geon
Vyjímka je pravidlo. Rekurzivní.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] shape_calc.py

2005-07-18 Thread Nathan Pinno




  Raj,
  
  My original interest was for school, now I use it to develop games and 
  apps. I work at McDonalds Restaurant as Crew. I have developed another app 
  called mini_calc and a game called Guess the Number; and was working on Giant 
  Calculator, but gave up on it. I am also working on a MasterMind-like game, 
  but it giving me headaches :).
  
  Nathan Pinno.
  P.S. Enjoy the shape_calc. You can find Mini_calc and Guess the Number on 
  my site at this address: http://www.npinnowebsite.ca/download.htm. 
  
  
- Original Message - 
From: 
Raj 
Moodley 
To: 'Nathan Pinno' 
Sent: Monday, July 18, 2005 9:56 
AM
Subject: RE: shape_calc.py


Hi Nathan, thanks 
for the email, please send it to me, would like to improve my 
understanding.

What do u do? 
What’s your interest in Python? Have you developed any other apps using 
Python?


Kind 
regards

Raj 
Moodley 






From: 
Nathan Pinno [mailto:[EMAIL PROTECTED]] Sent: 18 July 2005 03:41 PMTo: Raj MoodleyCc: tutor@python.orgSubject: Re: 
shape_calc.py


  
  Raj,
  
  
  
  Shape_calc is a calculator for 
  finding information about shapes, e.g. perimeter, area, and so 
  forth.
  
  
  
  HTH (Hope This 
  Helps),
  
  Nathan 
  Pinno
  

- Original 
Message - 

From: Raj 
Moodley 

To: [EMAIL PROTECTED] 


Sent: Monday, July 
18, 2005 2:54 AM

Subject: 
shape_calc.py


Hi Nathan, 
wanted to find out what is shape_calc.py 
about? Am a newbie.

Kind 
regards

Raj 
Moodley


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Performance difference, ``in'' vs ``has_key()''

2005-07-18 Thread Bill Campbell
On Sun, Jul 17, 2005, Danny Yoo wrote:
 A related question is where's the trade-off between using ``in'' with a
 list, and a dictionary?  I presume that using it with small hashes will
 be faster than dictionries since it doesn't have to calculate the
 hashes.

Hi Bill,

Scanning for an elements in a list is a linear operation, in the sense
that the time it takes to search is proportional to the size of the list.
(Big list == big search time.)

I just noticed that I said it backwards in my first post, ``using it with
small hashes'' should have been ``using it with small lists'' (and my perl
background leaks out referring to dictionaries as hashes :-).

...
This doesn't mean that dictionaries are always faster than lists: as you
know, calculating hash values can take time.  But the cost of hashing is
usually negligible, since many of Python primitive data types (like
strings) automatically cache their hash values too!

This would say that it's better to create the dictionary with string keys
rather than tuples, but that seems pretty obvious in any case.

The problem I'm working on involves going through a large list of invoices
that are now zero balance, to purge those before a certain date that have
no payment applications after that date.  I have a dictionary of zero-
balance invoices containing invoice objects, and each invoice object
contains a list of invoice keys applied to it.  This internal list may well
contain keys that refer to invoices that are either non-zero or have a date
after the cutoff date.

# begin code snippet
global invoices # dictionary of all zero balance invoices with date = cutoff

deleted = True
while deleted:
deleted = False
keys = invoices.keys()
for key in keys:
# use try/except since the instance may be deleted
try: invoice = invoices[keys]
except KeyError: continue
for appKey in invoice.appKeys:
if not appKey in invoices:
deleted = True
del invoices[key] # this invoice can't be purged
for appKey in invice.appKeys:
try: del invoices[appKey]
except KeyError: pass

# finish processing invoices

...
A good book in algorithms will almost always cover the performance
characteristics of those two strategies; there are also a lot of good
resources on the web about them.  NIST has two articles on those two:

http://www.nist.gov/dads/HTML/linearSearch.html
http://www.nist.gov/dads/HTML/hashtab.html

Thanks for the references (occassionaly there's something that
government does that's actually useful :-).

Bill
--
INTERNET:   [EMAIL PROTECTED]  Bill Campbell; Celestial Software LLC
UUCP:   camco!bill  PO Box 820; 6641 E. Mercer Way
FAX:(206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676
URL: http://www.celestial.com/

When the customer has beaten upon you long enough, give him what he asks
for, instead of what he needs.  This is very strong medicine, and is
normally only required once.
-- The Consultant's Curse:
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Which is safer and easier to code, raw_input or int(raw_input))?

2005-07-18 Thread Nathan Pinno



Hi all,

The subject line says it all. What's the answer?

Let's let everyone talk about this.

Nathan Pinno.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] int uncallable

2005-07-18 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
 Hi,
 
 This code:
 
 for line in satFile:
 lineListed = line.split() 
 start = int(lineListed[5])-1
 end = int(lineListed[6])
 hitLength = end - start
 extra = len(lineListed[9])
 total = hitLength + 2(extra)

You are trying to call 2 as a function - 2(extra). You can't do that. Maybe you 
mean 2*(extra) ??

Kent

 
 gives an error:
 
 Traceback (most recent call last):
   File test2.py, line 29, in ?
 total = hitLength+ 2(extra)
 TypeError: 'int' object is not callable
 
 which confuses me. Why can't I call extra? Have I not called int objects 
 when I define hitLength, and that works fine.
 
 Thanks,
 
 Chris
 
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How do I add an argument too...

2005-07-18 Thread Jeffrey Maitland
Well I use the getopt module.

so in my foo.py it would be something like.

import getopt

try:
   opts, args = getopt.getopt(sys.argv[1:], U:u:P:p:H:h:?,
[Username=, username=, Password=, password=, Help=,help=])
except getopt.GetoptError:
print :nothing specila just an error
   sys.exit(1)

for o, a in opts:
   if o in (-U, -u,  --Username, --username): username = a
   if o in (-P, -p, --Password, --password): password = a
   if o in (-H, -h,--Help, --help,?): print foo help


Hope the example helps. 

Jeff
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] cPickle.load()

2005-07-18 Thread David Jimenez
hello everybody,

I am trying to learn to use Python. Currently, I am
reading Michael Dawson's Python Programming for the
Absolute Beginner. Right now, I am having the
following problem: I try to read all the pickles in a
file, but keep on getting the same error: EOFError.


This is what the code looks like:

import cPickle, shelve

print Pickling lists.
variety=[sweet,hot,dill]
shape=[whole,spear,chip]
brand=[Claussen,Heinz,Vlassic]
pickle_file=open(pickles1.dat,w)
cPickle.dump(variety,pickle_file)
cPickle.dump(shape,pickle_file)
cPickle.dump(brand,pickle_file)
pickle_file.close()

print \nUnpickling lists.
pickle_file=open(pickles1.dat,rb)
for i in pickle_file:
i=cPickle.load(pickle_file)
print i
pickle_file.close()

This is what I keep on getting:
Pickling lists.

Unpickling lists.

Traceback (most recent call last):
  File /Users/davidjimenez/Documents/trypickle, line
20, in -toplevel-
i=cPickle.load(pickle_file)
EOFError

Thank you,
David Jimenez

__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] This should be easy

2005-07-18 Thread nephish
Hey there,

i have a script that i am trying to use to add a record to a MySQL
database.

i keep getting a syntax error.

this works
cursor.execute(INSERT INTO Table ( numberone ) VALUES ( 'one');)

but this does not
cursor.execute(INSERT INTO Table ( numberone, numbertwo ) VALUES
( 'one','two');)

what is getting scrambled here?

the error i get is syntax error in MySQL query, check the documentation,
blah blah blah

thanks


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Scrolling multilistbox help

2005-07-18 Thread Alberto Troiano
Hey tutors

I'm using the Multilistbox class and I noticed that it only handles the
mouse scroll and the scrollbar to go down or up.I succesfully implemented
the sort function that came with the class
I also added code to handle the up and down arrow keys and it goes down all
right but only select the item and it doesn't scroll down or up

How can make it go up or down?
I'm sendind the class here:

class MultiListbox(Frame):
 fila=0
 sortedBy=-1
 def __init__(self, master, lists):
Frame.__init__(self, master)
self.lists = []
for l,w,a in lists:
frame = Frame(self,background=red); frame.pack(side=LEFT, 
expand=YES,
fill=BOTH)
Button(frame,background=red,foreground=white,font=Verdana 8
bold,text=l, borderwidth=1, relief=RAISED,command=lambda a=a:
self._sortBy(a)).pack(fill=X)
lb = Listbox(frame, width=w, borderwidth=0, selectborderwidth=0,
 relief=FLAT, exportselection=FALSE)
lb.pack(expand=YES, fill=BOTH)
self.lists.append(lb)
lb.bind('B1-Motion', lambda e, s=self: s._select(e.y))
lb.bind('Double-Button-3', lambda e, s=self: s._devolverfila(e.y))
lb.bind('Return', lambda e, s=self: s._devolverfila(e.y))
lb.bind('Button-1', lambda e, s=self: s._select(e.y))
lb.bind('Down', lambda s: _select1())
 lb.bind('Up', lambda s: _select2())
lb.bind('Leave', lambda e: 'break')
lb.bind('B2-Motion', lambda e, s=self: s._b2motion(e.x, e.y))
lb.bind('Button-2', lambda e, s=self: s._button2(e.x, e.y))
frame = Frame(self,background=red); frame.pack(side=LEFT, fill=Y)
Label(frame,background=red,foreground=white,font=Verdana 8 bold,
borderwidth=1, relief=RAISED).pack(fill=X)
sb = Scrollbar(frame,background=red, orient=VERTICAL,
command=self._scroll)
sb.pack(expand=YES, fill=Y)
self.lists[0]['yscrollcommand']=sb.set

 def _sortBy(self, column):
  Sort by a given column. 
 if column == self.sortedBy:
 direction = -1 * self.direction
 else:
 direction = 1
 elements = self.get(0, END)
 self.delete(0, END)
 elements.sort(lambda x, y: self._sortAssist(column, direction, x,
y))
 self.insert(END, *elements)
 self.sortedBy = column
 self.direction = direction

 def _sortAssist(self, column, direction, x, y):
 if column!=0:
 c = cmp(x[column], y[column])
 if c:
 return direction * c
 else:
 return direction * cmp(x, y)
 else:
 c = cmp(int(x[column]), int(y[column]))
 if c:
 return direction * c
 else:
 return direction * cmp(x, y)

 def _select(self, y):
row = self.lists[0].nearest(y)
self.selection_clear(0, END)
self.selection_set(row)
self.fila=row
return 'break'

 def _devolverfila(self, y):
row = self.lists[0].nearest(y)
self.selection_clear(0, END)
self.selection_set(row)
self.fila=row

 def _select1(self):
 if self.fila==self.size()-1:
 pass
 else:
 self.selection_clear(0, END)
self.selection_set(self.fila+1)
 self.fila+=1
 self._scroll()
return 'break'

 def _select2(self):
 if self.fila==0:
 pass
 else:
 self.selection_clear(0, END)
 self.selection_set(self.fila-1)
 self.fila-=1
return 'break'

 def _button2(self, x, y):
for l in self.lists: l.scan_mark(x, y)
return 'break'

 def _b2motion(self, x, y):
for l in self.lists: l.scan_dragto(x, y)
return 'break'

 def _scroll(self, *args):
for l in self.lists:
apply(l.yview, args)

 def curselection(self):
return self.lists[0].curselection()

 def delete(self, first, last=None):
for l in self.lists:
l.delete(first, last)

 def get(self, first, last=None):
result = []
for l in self.lists:
result.append(l.get(first,last))
if last: return apply(map, [None] + result)
return result

 def index(self, index):
self.lists[0].index(index)

 def insert(self, index, *elements):
for e in elements:
i = 0
for l in self.lists:
l.insert(index, e[i])
i = i + 1

 def size(self):
return self.lists[0].size()

 def see(self, index):
for l in self.lists:
l.see(index)

 def selection_anchor(self, index):
for l in self.lists:
l.selection_anchor(index)

 def selection_clear(self, first, last=None):
for l in self.lists:

[Tutor] Minesweeper the return

2005-07-18 Thread Alberto Troiano
Hi

I now get stucked in the arguments of the buttons
Here's what I've got:

def crearbutton(self):
for i in range(self.fil):
for j in range(self.col):

self.buttonmatrix[i][j]=Button(root,width=1,height=0,command=lambda: 
self.hello(i,j))
self.buttonmatrix[i][j].grid(row=i,column=j,sticky=N+S+W+E)

def hello(self,f,c):
self.buttonmatrix[f][c].configure(text=d)

I'm trying to create the buttons dinamically (that's not a problem) the 
problem is wherever I click the hello function returns the last button I 
created. I know that the problem is in the lambda part and that the variable 
i (the one I change the value within the for) but I don't how to fix it

Any hints?

Thanks in advanced

Alberto


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] int uncallable

2005-07-18 Thread cgw501
Hi,

This code:

for line in satFile:
lineListed = line.split() 
start = int(lineListed[5])-1
end = int(lineListed[6])
hitLength = end - start
extra = len(lineListed[9])
total = hitLength + 2(extra)

gives an error:

Traceback (most recent call last):
  File test2.py, line 29, in ?
total = hitLength+ 2(extra)
TypeError: 'int' object is not callable

which confuses me. Why can't I call extra? Have I not called int objects 
when I define hitLength, and that works fine.

Thanks,

Chris

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Getting two files to print

2005-07-18 Thread Philip Carl
I have no more hair to pull out, so I'm asking the group for help on a 
VERY simple question.  I have two very similar text files to read-one 
with the final letters in the name 10%.txt and the other 20%.txt.  I've 
written the following simple code to read these two files:

# Program to read and print two text fiiles
fileNameA = 
'c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_10%.txt'   
#text file one
firstFile=open (fileNameA,'r')
inFileLeftA = 1 #more file to read
inLineA=[0]
while inFileLeftA:
inLineA = firstFile.readline()
if (inLineA == ''):
infileLeftA = 0 #if empty line end of first file
   
else:
print inLineA
firstFile.close()

fileNameB = 
'c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_20%.txt'  
#text file two
secondFile=open (fileNameB,'r')
inFileLeftB = 1 #more file to read
inLineB=[0]
while inFileLeftB:
inLineB = secondFile.readline()
if (inLineB == ''):
infileLeftB = 0 #if empty line end of second file
   
else:
 print inLineB
secondFile.close()

I realize that I probably ought to be able to code this more 
efficiently, but as a rank beginner I am less worried about efficiency 
than output.  I can't seem to get BOTH files to print  when run as 
presented, although when I split the program into two programs each file 
seems to print OK.  As written here however,  I can get the first but 
not the second textfile to print. What am I doing wrong?. 

Philip Carl
Associate Professor of Pharmacology
1026A Mary Ellen Jones Bld. CB 7365
University of North Carolina Medical School
Chapel Hill, NC 27599
Phone: 919-966-3544
FAX: 919-966-5640


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Creating MySQL table

2005-07-18 Thread Don Parris
On 7/18/05, Bernard Lebel [EMAIL PROTECTED] wrote:
 Hello,
 
 How do I create a MySQL table in Python?
 
 Here is what I'm trying:
 
 
 import MySQLdb as sql
 
 def connect2db():
   return sql.connect( blah blah blah )
 
 
 oConnection = connect2db()
 oCursor = oConnection.cursor()
 
 
 sQuery = CREATE TABLE '3DPipeline'.'TB_MT_NAME' (;\
   'ID' INTEGER UNSIGNED CHARACTER SET latin1 COLLATE latin1_swedish_ci
 NOT NULL AUTO_INCREMENT,
   'text' TINYTEXT CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
   PRIMARY KEY('ID')
 )
 ENGINE = InnoDB
 
 
Looking above, I'm not sure why there's a . after 3DPipeline.  Also,
the ; should be placed after the last command before the closing
parenthesis, not at the beginning.  I have no idea about your use of
the backslash.


 When I run that, I get this:
 
 Traceback (most recent call last):
   File stdin, line 1, in ?
   File D:\Python24\Lib\site-packages\MySQLdb\cursors.py, line 137, in 
 execute
 self.errorhandler(self, exc, value)
   File D:\Python24\Lib\site-packages\MySQLdb\connections.py, line
 33, in defaulterrorhandler
 raise errorclass, errorvalue
 _mysql_exceptions.ProgrammingError: (1064, You have an error in your
 SQL syntax; check the manual that corresponds to your MySQL server
 version for the right syntax to use near ''3DPipline'.'TB_MT_NAME' (
 'ID' INTERGER UNSIGNED CHARACTER SET latin1 COLLATE l' at line 1)
 
 
This error message points to your SQL syntax.  Notice that it wants
you to check your MySQL server version for the right syntax to use. 
That should alert you to the fact that your SQL syntax is incorrect.

HTH,
Don
-- 
DC Parris GNU Evangelist
http://matheteuo.org/
[EMAIL PROTECTED]
Free software is like God's love - 
you can share it with anyone anywhere anytime!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] This should be easy

2005-07-18 Thread Alberto Troiano
I think it would be better for us if you send us the entire line that's 
giving you problems along with the error its givin you so we can start 
somewhere

Right now I don't know where to look at

Best Regards

Alberto

From: nephish [EMAIL PROTECTED]
To: tutor@python.org
Subject: [Tutor] This should be easy
Date: Mon, 18 Jul 2005 20:02:38 +

ok here is the error i am getting.
You have an error in your SQL syntax. Check the manual that corrosponds
to your MySQL version for the right syntax near Name ) values ('one',
'two')

thanks

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Gaucho


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Forms

2005-07-18 Thread gordnjen




HELP!
This is my latest assignment:
For this assignment, you will create a web script that lets the user explore 
RGB colours.
On the first page the user sees, they should specify two RGB colours. 
When they submit this page, they should be presented with a range of colours in 
between the two.The intermediate colours will be calculated by your 
program.
For example, if the user enters the colours red (100% red, 0% green, 0% blue) 
and white (100% red, 100% green, 100% blue), your program might output a page 
containing this:
Your program must never output more than 150 total colours, no matter how 
many the user asks for. If the users asks for more, it should only output 
150. 
 
You have to be careful about the spacing when outputting the RGB percentage 
values. You will have to convert the numbers to strings and concatenate 
them. For example, this statement will output part of the style 
attribute: 
 print 'style="background-color: 
rgb(' + str(r) + 
'%' 
 All of your XHTML (including generated XHTML) and 
CSS must be valid. 

1. Create the query page that asks the user for the colours they 
want to view.
 2. Create a web script that converts the values the user entered 
to integers, stores them in variables, and outputs them. 
 3. Modify the web script so it counts from 0 up to the number of 
steps they requested minus 1. So, if they ask for 5 steps, it outputs "0 1 
2 3 4." 
 4. Modify the web script so it calculates and outputs the 
percentages of red for each step. Check these and make sure they're right: 
they start and end at the values specified by the user; there are the right 
number of steps; the steps are separated by the same amount. 
 5. Add in the calculation of the green and blue values and check 
those.
 6. Use the calculated percentages to output the divs and 
make sure the colours look right. Make sure the generated XHTML is valid. 

 7. Add the checking for more than 150 steps. 
I have attached the two files I have so far for this.
Please have a look and advise.
Thanks!
Jennine





--
No virus found in this outgoing message.
Checked by AVG Anti-Virus.
Version: 7.0.323 / Virus Database: 267.9.0/50 - Release Date: 16/07/2005
 

  
Title: Colour Blend




Colour Blend

Colour 1
Red: %
Green: %
Blue: %
Colour 2
Red: %
Green: %
Blue: %
Steps
Number of steps: 
 

Return to the index.

Title: Colour Blend
import cgitb;
cgitb.enable()
import cgi
form = cgi.FieldStorage()
print "Content-type: text/html"
print
print """
"""
print form int(["red1"].value),"%"
print form int(["green1"].value),"%"
print form int(["blue1"].value),"%"
print form int(["red2"].value),"%"
print form int(["green2"].value),"%"
print form int(["blue2"].value),"%"
for i in range(nsteps):
	print i,
print """fraction = (i+1.0)/nsteps
r = (1-fraction)*red1 + fraction*red2
g = (1-fraction)*green1 + fraction*green2
b = (1-fraction)*blue1 + fraction*green2"""




Colour Blend
Here is a mix of the two colours you specified:






















Return to http://mail.python.org/mailman/listinfo/tutor


[Tutor] Creating MySQL table

2005-07-18 Thread Bernard Lebel
Hello,

How do I create a MySQL table in Python?

Here is what I'm trying:


import MySQLdb as sql

def connect2db():
  return sql.connect( blah blah blah )


oConnection = connect2db()
oCursor = oConnection.cursor()


sQuery = CREATE TABLE '3DPipeline'.'TB_MT_NAME' (;\
  'ID' INTEGER UNSIGNED CHARACTER SET latin1 COLLATE latin1_swedish_ci
NOT NULL AUTO_INCREMENT,
  'text' TINYTEXT CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
  PRIMARY KEY('ID')
)
ENGINE = InnoDB


oCursor.execute( sQuery )


When I run that, I get this:

Traceback (most recent call last):
  File stdin, line 1, in ?
  File D:\Python24\Lib\site-packages\MySQLdb\cursors.py, line 137, in execute
self.errorhandler(self, exc, value)
  File D:\Python24\Lib\site-packages\MySQLdb\connections.py, line
33, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near ''3DPipline'.'TB_MT_NAME' (
'ID' INTERGER UNSIGNED CHARACTER SET latin1 COLLATE l' at line 1)



Any pointer would be appreciated.

Thanks
Bernard
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] replaying

2005-07-18 Thread Ben Vinger
Mailman can be set up to reply to the forum, but
people on this list prefer to live with pain!

--- geon [EMAIL PROTECTED] wrote:
 Hi,
 
 Seems to me as very unuseful thing in this phorum,
 when I choose Replay 
 to any message, the field to whom or Receiver is
 all the time not 
 tutor@python.org but the original sender! Why? I can
 not understand that?
 
 It sould be prefferably posted back to mailing list
 IMHO.
 
 
 -- 
 geon
 
 
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
 




___ 
How much free photo storage do you get? Store your holiday 
snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How do I add an argument too...

2005-07-18 Thread Joseph Quigley
How do I add an argument too my program (with sys.argv) so that at a 
console I can type:

python foo.py -info

or
python foo.py open /home/joe/foo.txt

Thanks,
Joe

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] This should be easy

2005-07-18 Thread Pujo Aji
the code looks ok for me,

Can you post more specific, including the error ?

pujo

On 7/18/05, nephish [EMAIL PROTECTED] wrote:
 Hey there,
 
 i have a script that i am trying to use to add a record to a MySQL
 database.
 
 i keep getting a syntax error.
 
 this works
 cursor.execute(INSERT INTO Table ( numberone ) VALUES ( 'one');)
 
 but this does not
 cursor.execute(INSERT INTO Table ( numberone, numbertwo ) VALUES
 ( 'one','two');)
 
 what is getting scrambled here?
 
 the error i get is syntax error in MySQL query, check the documentation,
 blah blah blah
 
 thanks
 
 
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] This should be easy

2005-07-18 Thread Alberto Troiano
Hey

Your problem is in the database
I'm surprised how MySQL let you put a space in a field
In MySQL you can't have spaces, as far as I know
Try renaming the field by enteriig to the console and making the alter table 
sentence and put Site_Name instead of Site Name. Then make the query again 
and see what happens

mysql create table d(autoinc int(4) primary key,Site Name varchar(30));
ERROR 1064: You have an error in your SQL syntax.  Check the manual that 
corresponds to your MySQL server version for the right syntax to use near 
'Name varchar(30))'

This is the error I get from MySQL Server when I try to create a field with 
a space and check the solution:
mysql create table d(autoinc int(4) primary key,Site_Name varchar(30));
Query OK, 0 rows affected (0.14 sec)

This should fix your problem.

Best Regards to you

Alberto

From: nephish [EMAIL PROTECTED]
To: Alberto Troiano [EMAIL PROTECTED]
CC: tutor@python.org
Subject: Re: [Tutor] This should be easy
Date: Mon, 18 Jul 2005 20:32:55 +

ok here is what i have,
cursor.execute(INSERT INTO History (autoinc, Site Name) VALUES
(12, 'Test');)

gives me this
''' _mysql_exceptions.ProgrammingError : (1064, You have an error in
your SQL syntax.  Check the manual that corresponds to your MySQL
server version for the right syntax to use near 'Name) VALUES (12,
'Test')' at line 1) '''

the autoinc field isn't really an auto-increment field, its an int.
That is left over from the migration from Access.

there are other fields in the table but all can be null.

this line works fine though
cursor.execute(INSERT INTO History (autoinc) VALUES (12);)

this line does not
cursor.execute(INSERT INTO History (Site Name) VALUES ('test');)

can you not have spaces in a field name ? is the quotes gone awry?

dont know what to do next.
please help !

thanks




On 07/18/2005 03:06:34 PM, Alberto Troiano wrote:
  I think it would be better for us if you send us the entire line
  that's giving you problems along with the error its givin you so we
  can start somewhere
 
  Right now I don't know where to look at
 
  Best Regards
 
  Alberto
 
  From: nephish [EMAIL PROTECTED]
  To: tutor@python.org
  Subject: [Tutor] This should be easy
  Date: Mon, 18 Jul 2005 20:02:38 +
 
  ok here is the error i am getting.
  You have an error in your SQL syntax. Check the manual that
  corrosponds
  to your MySQL version for the right syntax near Name ) values ('one',
  'two')
 
  thanks
 
  ___
  Tutor maillist  -  Tutor@python.org
  http://mail.python.org/mailman/listinfo/tutor
 
 
  Gaucho
 
 
 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Gaucho


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] This should be easy

2005-07-18 Thread nephish
ok here is the error i am getting.
You have an error in your SQL syntax. Check the manual that corrosponds  
to your MySQL version for the right syntax near Name ) values ('one',  
'two')

thanks

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] replaying

2005-07-18 Thread geon
Hi,

Seems to me as very unuseful thing in this phorum, when I choose Replay 
to any message, the field to whom or Receiver is all the time not 
tutor@python.org but the original sender! Why? I can not understand that?

It sould be prefferably posted back to mailing list IMHO.


-- 
geon


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] This should be easy

2005-07-18 Thread nephish
Hey! looks like that is what the problem was.
i used the MySQL Migration toolkit to transfer all the records
over from Access to MySQL.
man, you really saved me a lot of time and frustration.
should have written in about 6 hours ago
thank you very much.


On 07/18/2005 03:41:59 PM, Alberto Troiano wrote:
 Hey
 
 Your problem is in the database
 I'm surprised how MySQL let you put a space in a field
 In MySQL you can't have spaces, as far as I know
 Try renaming the field by enteriig to the console and making the  
 alter table sentence and put Site_Name instead of Site Name. Then  
 make the query again and see what happens
 
 mysql create table d(autoinc int(4) primary key,Site Name  
 varchar(30));
 ERROR 1064: You have an error in your SQL syntax.  Check the manual  
 that corresponds to your MySQL server version for the right syntax to  
 use near 'Name varchar(30))'
 
 This is the error I get from MySQL Server when I try to create a  
 field with a space and check the solution:
 mysql create table d(autoinc int(4) primary key,Site_Name  
 varchar(30));
 Query OK, 0 rows affected (0.14 sec)
 
 This should fix your problem.
 
 Best Regards to you
 
 Alberto
 
 From: nephish [EMAIL PROTECTED]
 To: Alberto Troiano [EMAIL PROTECTED]
 CC: tutor@python.org
 Subject: Re: [Tutor] This should be easy
 Date: Mon, 18 Jul 2005 20:32:55 +
 
 ok here is what i have,
 cursor.execute(INSERT INTO History (autoinc, Site Name) VALUES
 (12, 'Test');)
 
 gives me this
 ''' _mysql_exceptions.ProgrammingError : (1064, You have an error in
 your SQL syntax.  Check the manual that corresponds to your MySQL
 server version for the right syntax to use near 'Name) VALUES  
 (12,
 'Test')' at line 1) '''
 
 the autoinc field isn't really an auto-increment field, its an int.
 That is left over from the migration from Access.
 
 there are other fields in the table but all can be null.
 
 this line works fine though
 cursor.execute(INSERT INTO History (autoinc) VALUES (12);)
 
 this line does not
 cursor.execute(INSERT INTO History (Site Name) VALUES ('test');)
 
 can you not have spaces in a field name ? is the quotes gone awry?
 
 dont know what to do next.
 please help !
 
 thanks
 
 
 
 
 On 07/18/2005 03:06:34 PM, Alberto Troiano wrote:
  I think it would be better for us if you send us the entire line
  that's giving you problems along with the error its givin you so we
  can start somewhere
 
  Right now I don't know where to look at
 
  Best Regards
 
  Alberto
 
  From: nephish [EMAIL PROTECTED]
  To: tutor@python.org
  Subject: [Tutor] This should be easy
  Date: Mon, 18 Jul 2005 20:02:38 +
 
  ok here is the error i am getting.
  You have an error in your SQL syntax. Check the manual that
  corrosponds
  to your MySQL version for the right syntax near Name ) values  
 ('one',
  'two')
 
  thanks
 
  ___
  Tutor maillist  -  Tutor@python.org
  http://mail.python.org/mailman/listinfo/tutor
 
 
  Gaucho
 
 
 
 
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
 
 
 Gaucho
 
 
 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Creating MySQL table

2005-07-18 Thread Bernard Lebel
See [Bernard]

On 7/18/05, Don Parris [EMAIL PROTECTED] wrote:
 On 7/18/05, Bernard Lebel [EMAIL PROTECTED] wrote:
  Hello,
 
  How do I create a MySQL table in Python?
 
  Here is what I'm trying:
 
 
  import MySQLdb as sql
 
  def connect2db():
return sql.connect( blah blah blah )
 
 
  oConnection = connect2db()
  oCursor = oConnection.cursor()
 
 
  sQuery = CREATE TABLE '3DPipeline'.'TB_MT_NAME' (;\
'ID' INTEGER UNSIGNED CHARACTER SET latin1 COLLATE latin1_swedish_ci
  NOT NULL AUTO_INCREMENT,
'text' TINYTEXT CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
PRIMARY KEY('ID')
  )
  ENGINE = InnoDB
 
 
 Looking above, I'm not sure why there's a . after 3DPipeline.  Also,
 the ; should be placed after the last command before the closing
 parenthesis, not at the beginning.  I have no idea about your use of
 the backslash.

[Bernard] The backslash thing is a trick that you can use to lure
Python, it acts like a line break in your code, and allows you to
bypass the indentation.

The dot is to separate the database from the table. Before the dot is
the database.

See later for the semi-colon.

 
 
  When I run that, I get this:
 
  Traceback (most recent call last):
File stdin, line 1, in ?
File D:\Python24\Lib\site-packages\MySQLdb\cursors.py, line 137, in 
  execute
  self.errorhandler(self, exc, value)
File D:\Python24\Lib\site-packages\MySQLdb\connections.py, line
  33, in defaulterrorhandler
  raise errorclass, errorvalue
  _mysql_exceptions.ProgrammingError: (1064, You have an error in your
  SQL syntax; check the manual that corresponds to your MySQL server
  version for the right syntax to use near ''3DPipline'.'TB_MT_NAME' (
  'ID' INTERGER UNSIGNED CHARACTER SET latin1 COLLATE l' at line 1)
 
 
 This error message points to your SQL syntax.  Notice that it wants
 you to check your MySQL server version for the right syntax to use.
 That should alert you to the fact that your SQL syntax is incorrect.
 
 HTH,
 Don

[Bernard] Well I kind of figured it was telling it's a syntax error. ;-)

After trial and error for an hour or two, I managed to get it sorted.

First, I noticed that in Python there is no need for a semi-colon
terminator (even for SQL commands).
Also, removing all quotes except the opening and closing one made the code work.

The SQL book I am using uses DOS command line syntax, not Python, so I
had to translate the examples into Python syntax.



Cheers
Bernard
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Creating MySQL table

2005-07-18 Thread Don Parris
On 7/18/05, Bernard Lebel [EMAIL PROTECTED] wrote:
 Hello,
 
 How do I create a MySQL table in Python?
 
 Here is what I'm trying:
 
 
 import MySQLdb as sql
 
 def connect2db():
   return sql.connect( blah blah blah )
 
 
 oConnection = connect2db()
 oCursor = oConnection.cursor()
 
 
 sQuery = CREATE TABLE '3DPipeline'.'TB_MT_NAME' (;\
   'ID' INTEGER UNSIGNED CHARACTER SET latin1 COLLATE latin1_swedish_ci
 NOT NULL AUTO_INCREMENT,
   'text' TINYTEXT CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
   PRIMARY KEY('ID')
 )

O.k., it looks like 3DPipeline is your database name, and TB_MT_NAME
is your table name.  Your single quotes, if needed at all, most likely
need to look like:
'3DPipeline.TB_MT_NAME'(\
fieldone key1 key2 key3\
fieldtwo key1 key2 key3\
fieldthree key1 key2 key3
);

If you're using the backslash for line continuation, you need to add
the \ at the end of each line in your SQL statement.

Hope this is a bit more helpful.
-- 
DC Parris GNU Evangelist
http://matheteuo.org/
[EMAIL PROTECTED]
Free software is like God's love - 
you can share it with anyone anywhere anytime!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ot, pythonmonks

2005-07-18 Thread Bob Gailer


At 03:52 AM 7/14/2005, Johan Meskens CS3 jmcs3 wrote:
hello
is there such a place as
www.perlmonks.org
 for python ?
My first and only visit to perlmonks leaves me puzzled. What is it for?
All I see are posts and chats, nothing to help a newcomer grok the site.


Bob Gailer
phone 510 978 4454 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Creating MySQL table

2005-07-18 Thread Don Parris
On 7/18/05, Bernard Lebel [EMAIL PROTECTED] wrote:
 See [Bernard]
 

 
 [Bernard] Well I kind of figured it was telling it's a syntax error. ;-)
 
I didn't want to assume too much. ;)

 After trial and error for an hour or two, I managed to get it sorted.
 
 First, I noticed that in Python there is no need for a semi-colon
 terminator (even for SQL commands).
 Also, removing all quotes except the opening and closing one made the code 
 work.
 
That was where my last post was headed - and I left out the part about
the semi-colons not being needed.  I was looking at my own select
queries.

 The SQL book I am using uses DOS command line syntax, not Python, so I
 had to translate the examples into Python syntax.
 
I got Python books.  I can figure out the SQL stuff pretty easily -
it's programming the front-end that twists my brain around. ;)

Don
-- 
DC Parris GNU Evangelist
http://matheteuo.org/
[EMAIL PROTECTED]
Free software is like God's love - 
you can share it with anyone anywhere anytime!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Scrolling multilistbox help

2005-07-18 Thread jfouhy
Quoting Alberto Troiano [EMAIL PROTECTED]:

 I'm using the Multilistbox class and I noticed that it only handles the
 mouse scroll and the scrollbar to go down or up.I succesfully
 implemented the sort function that came with the class
 I also added code to handle the up and down arrow keys and it goes down
 all right but only select the item and it doesn't scroll down or up
 How can make it go up or down?

I haven't actually tried your code, but this might be the problem here:

  def _select1(self):
  if self.fila==self.size()-1:
  pass
  else:
  self.selection_clear(0, END)
self.selection_set(self.fila+1)
  self.fila+=1
  self._scroll()
   return 'break'

  def _scroll(self, *args):
   for l in self.lists:
apply(l.yview, args)

You call self._scroll with no arguments to make the selected index visible (I
guess).  But self._scroll just calls yview on each list..and yview with no
arguments returns a tuple, but otherwise does nothing.

Try replacing self._scroll with self.see --- possibly: self.see(self.fila).

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] replaying

2005-07-18 Thread Danny Yoo


On Mon, 18 Jul 2005, geon wrote:

 Seems to me as very unuseful thing in this forum, when I choose Replay
 to any message, the field to whom or Receiver is all the time not
 tutor@python.org but the original sender! Why? I can not understand
 that?

[meta: mailing list admin stuff]


Hi Geon,

Yes, we've considered this before.  It's actually not that difficult to
enable this from the mailing list admin interface, so if we ever find the
need to do this, I'll be happy to.

However, there are significant downsides to enabling Reply-to munging:

http://www.unicom.com/pw/reply-to-harmful.html

I agree with most of those reasons, and so I won't enable Reply-to munging
unless there's a real overriding reason that trumps the ones listed on
that page.


Hope that makes sense!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Forms

2005-07-18 Thread Danny Yoo

Hello,



 This is my latest assignment:

[assignment cut]

We should make this perfectly clear: we will not do your homework.


 Please have a look and advise.

If you're having a problem with Python programming, bring up the specific
problem you're having, and we'll see what we can do to help clarify things
for you.  It is not that we don't want to help you: it's just that we will
not do your work for you.

What you've just done is write out the whole homework assignment, and
asked the group: What should I do?  Please understand that just dumping
a homework assignment on the volunteers on this mailing list forum isn't
nice --- it may not seem that way to you, but it's a bit demoralizing to
us.


See:

http://www.catb.org/~esr/faqs/smart-questions.html

as a rough guide to asking questions that people will be happy to answer.

Good luck.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] FW: Forms

2005-07-18 Thread gordnjen



Apparently, my last post was interpreted by 
some as "please do this assignment for me". By no means do I want this. What I 
would like, is for someone to look at my attached files and see if there is 
anything glaring they can see where I am going wrong. The error message that I 
get when I input values into the first page and click "Go" reads as 
follows:

Script Error

There was an error with your script and it didn't exit properly.
This was its output:
  File "/home/jgates/public_html/Fifthone.py", line 12
print form int(["red1"].value),"%"
 ^
SyntaxError: invalid syntaxThe instructions I listed below were put there so that you could understand what exactly I was trying to do with these pages.Any help you could provide would be much appreciated.If you think I am out of line in asking the above, just ignore this post and I will get the drift.But any help would be a godsend!!!Thanks!Regards,Jennine

-Original Message-From: gordnjen 
[mailto:[EMAIL PROTECTED] Sent: July 18, 2005 4:23 
PMTo: 'tutor@python.org'Subject: 
Forms

HELP!
This is my latest assignment:
For this assignment, you will create a web script that lets the user explore 
RGB colours.
On the first page the user sees, they should specify two RGB colours. 
When they submit this page, they should be presented with a range of colours in 
between the two.The intermediate colours will be calculated by your 
program.
For example, if the user enters the colours red (100% red, 0% green, 0% blue) 
and white (100% red, 100% green, 100% blue), your program might output a page 
containing this:
Your program must never output more than 150 total colours, no matter how 
many the user asks for. If the users asks for more, it should only output 
150. 
 
You have to be careful about the spacing when outputting the RGB percentage 
values. You will have to convert the numbers to strings and concatenate 
them. For example, this statement will output part of the style 
attribute: 
 print 'style="background-color: 
rgb(' + str(r) + 
'%' 
 All of your XHTML (including generated XHTML) and 
CSS must be valid. 

1. Create the query page that asks the user for the colours they 
want to view.
 2. Create a web script that converts the values the user entered 
to integers, stores them in variables, and outputs them. 
 3. Modify the web script so it counts from 0 up to the number of 
steps they requested minus 1. So, if they ask for 5 steps, it outputs "0 1 
2 3 4." 
 4. Modify the web script so it calculates and outputs the 
percentages of red for each step. Check these and make sure they're right: 
they start and end at the values specified by the user; there are the right 
number of steps; the steps are separated by the same amount. 
 5. Add in the calculation of the green and blue values and check 
those.
 6. Use the calculated percentages to output the divs and 
make sure the colours look right. Make sure the generated XHTML is valid. 

 7. Add the checking for more than 150 steps. 
I have attached the two files I have so far for this.
Please have a look and advise.
Thanks!
Jennine



--No virus found in this outgoing message.Checked by AVG 
Anti-Virus.Version: 7.0.323 / Virus Database: 267.9.0/50 - Release Date: 
16/07/2005



--
No virus found in this outgoing message.
Checked by AVG Anti-Virus.
Version: 7.0.323 / Virus Database: 267.9.0/50 - Release Date: 16/07/2005
 

  
Title: Colour Blend




Colour Blend

Colour 1
Red: %
Green: %
Blue: %
Colour 2
Red: %
Green: %
Blue: %
Steps
Number of steps: 
 

Return to the index.

Title: Colour Blend
import cgitb;
cgitb.enable()
import cgi
form = cgi.FieldStorage()
print "Content-type: text/html"
print
print """
"""
print form int(["red1"].value),"%"
print form int(["green1"].value),"%"
print form int(["blue1"].value),"%"
print form int(["red2"].value),"%"
print form int(["green2"].value),"%"
print form int(["blue2"].value),"%"
for i in range(nsteps):
	print i,
print """fraction = (i+1.0)/nsteps
r = (1-fraction)*red1 + fraction*red2
g = (1-fraction)*green1 + fraction*green2
b = (1-fraction)*blue1 + fraction*green2"""




Colour Blend
Here is a mix of the two colours you specified:






















Return to http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FW: Forms

2005-07-18 Thread Danny Yoo


On Mon, 18 Jul 2005, gordnjen wrote:

 There was an error with your script and it didn't exit properly.

 This was its output:

   File /home/jgates/public_html/Fifthone.py, line 12

 print form int([red1].value),%

  ^

 SyntaxError: invalid syntax



Hi Jennine,

Ok, it looks like you're using the cgi.FieldStorage class and you're
trying to look up the 'red1' value in the form.


But it also looks like you have some int() stuff there that I'm not quite
sure about yet.  Is it ok if we strip that out for the moment, and
simplify things to something smaller?  (We can talk more about int()
later.)

##
print form([red1].value),%
##

If you do this, you won't get a SyntaxError, although you'll probably get
a different kind of error.  *grin*



So let's look at this a bit more.  According to the documentation of the
'cgi' module, there's a :

http://www.python.org/doc/lib/node467.html

you can ask a form for its values by using getfirst().  So the code above
would look like:

##
print form.getfirst('red1'), '%'
##

Try that and see if that works any better.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



Re: [Tutor] replaying

2005-07-18 Thread geon
Danny Yoo napsal(a):

However, there are significant downsides to enabling Reply-to munging:

http://www.unicom.com/pw/reply-to-harmful.html

I agree with most of those reasons, and so I won't enable Reply-to munging
unless there's a real overriding reason that trumps the ones listed on
that page.
  

Firtsly, sorry for my English.

Then I must must admit I didnt understand all what is written  in 
http://www.unicom.com/pw/reply-to-harmful.html and even I didnt read it 
attentively. Anyway the main reason IMHO why he decided to do so is 
having Elm (or even creating it?) which *easily* (I could say freedomly 
for lector=helper) supports both sending to mailing list and to 
original sender.

I got tho some reason against:

* I like to help. But I like to help all, All should have benefit from 
my replay. I know this from my own experience. Often, very often I 
browse the old messages and read what other wrote. Its also good when 
there are always the same questions My effort shouldnt die 
immendiately after sending my replay. The freedom of all is more that 
freedom of one.

* My TB doesnt support it. And maybe even others mail clients.Its really 
wasting of time to change the adress all the time. I like to help, but 
if the was more of such a inconvieniencies I would give it up. My time 
is expensive :-)

* There is no reason for questioner not to like to see my replay in 
mailing list, I think. Why would he do it? Why should he want me just 
for him?

To be able to read your replay pls use easy english ;-)

-- 
geon
Vyjímka je pravidlo. Rekurzivní.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Parsing problem

2005-07-18 Thread Danny Yoo


On Mon, 18 Jul 2005, Liam Clarke wrote:

 country = {
 tag = ENG
 ai = {
 flags = { }
 combat = { DAU FRA ORL PRO }
 continent = { }
 area = { }
 region = { British Isles NorthSeaSea ECAtlanticSea NAtlanticSea
 TagoSea WCAtlanticSea }
 war = 60
 ferocity = no
 }
 }

[Long message ahead; skip if you're not interested.]


Kent mentioned PyParsing,

http://pyparsing.sourceforge.net/

which is a really excellent system.  Here's a demo of what it can do, just
so you have a better idea what pyparsing is capable of.

(For the purposes of this demo, I'm doing 'import pyparsing', but in real
usage, I'd probably use 'from pyparsing import ...' just to make things
less verbose.)


Let's say that we want to recognize a simpler subset of the data that you
have there, something like:

{ fee fie foo fum }

And let's imagine that we have a function parse() that can take a string
like:

##
 testString = 
... { fee fie foo fum }
... 
##


This imaginary parse() function could turn that into something that looks
like a Python value, like this:

##
 parse(testString)
([fee, fie, foo, fum])
##

That's our goal; does this make sense so far?  So how do we start?



Instead of going at the big goal of doing:

country = { fee fie foo fum }

let's start small by teaching our system how to recognize the innermost
parts, the small things like fee or foo.  Let's start there:

##
 Symbol = pyparsing.Word(pyparsing.alphas)
##

We want a Symbol to be able to recognize a Word made up of alphabetic
letters.  Does this work?

##
 Symbol.parseString(fee)
(['fee'], {})
###

Symbol is now a thing that can parse a string, and return a list of
results in a pyparsing.ParseResults object.


Ok, if we can recognize Symbols, let's go for the jugular:

{ fee fie foo fum }


Let's call this a Sequence.

##
 Sequence = { + pyparsing.ZeroOrMore(Symbol) + }
##


A Sequence is made up of zero or more Symbols.


Wait, let's change that, for a moment, to A Sequence is made up of zero
or more Values.  (You'll see why in a moment.  *grin*)



If we turn toward this strange way, then we need a definition for a Value:

##
 Value = Symbol
##

and now we can say that a Sequence is a bunch of Values:

##
 Sequence = { + pyparsing.ZeroOrMore(Value) + }
##


Let's try this out:

##
 Sequence.parseString('{ fee fiefoo fum}')
(['{', 'fee', 'fie', 'foo', 'fum', '}'], {})
##


This is close, but it's not quite right: the problem is that we'd like to
somehow group the results all together in a list, and without the braces.
That is, we actually want to see:

[['fee', 'fie', 'foo', 'fum']]

in some form.  (Remember, we want a list of a single result, and that
result should be our Sequence.)


How do we get this working?  We have to tell pyparsing to Group the
middle elements together in a collection, and to suppress the braces
from the result.

Here we go:

##
 Sequence = (pyparsing.Suppress({) +
... pyparsing.Group(pyparsing.ZeroOrMore(Value)) +
... pyparsing.Suppress(}))
##

Does this work?


##
 Sequence.parseString('{ fee fiefoo fum}')
([(['fee', 'fie', 'foo', 'fum'], {})], {})
##


That looks a little messy and more nested than expected.


Actually, what's happening is that we're looking at that
pyparsing.ParseResults object, so there's more nesting in the string
representation than what's really there.  We can use the ParseResults's
asList() method to make it a little easier to see what the real result
value looks like:

##
 Sequence.parseString('{ fee fiefoo fum}').asList()
[['fee', 'fie', 'foo', 'fum']]
##

That's better.



Out of curiosity, wouldn't it be neat if we could parse out something like
this?

 { fee fie {foo fum} }

*cough* *cough*

What we'd like to do is make Sequence itself a possible value.  The
problem is that then there's a little circularity involved:


### Illegal PyParsing pseudocode  ###
Value = Symbol | Sequence

Sequence = (pyparsing.Suppress({) +
pyparsing.Group(pyparsing.ZeroOrMore(Value)) +
pyparsing.Suppress(}))
##

The problem is that Value can't be defined before Sequence is, and
vice-versa.  We break this problem by telling PyParsing ok, the following
rules will come up soon and forward define them:

##
 Value = pyparsing.Forward()
 Sequence = pyparsing.Forward()
##

and once we have these forward declarations, we can then reconnect them to
their real definitions by using ''.  (This looks bizarre, but it applies
just to rules that are Forward()ed.)

##
Value (Symbol | Sequence)
Sequence  (pyparsing.Suppress({) +
 pyparsing.Group(pyparsing.ZeroOrMore(Value)) +
 pyparsing.Suppress(}))
##


Let's try it:

##
 Value.parseString(' { fee fie {foo fum} } ').asList()
[['fee', 'fie', ['foo', 'fum']]]
##


Cool.


Ok, that was a little artificial, but oh well.  The idea is we now know
how to say:

A Value is