Re: [Tutor] Why is this only catching one occurance?

2006-10-27 Thread Luke Paireepinart
Chris Hengge wrote:
 Here is my code:
 for unWantedItem in directoryList:
 try:
 if hex in unWantedItem.lower():
 if not bmc in unWantedItem.lower():
print unWantedItem +  removed!
directoryList.remove(unWantedItem)

 This only seems to loop through once, and removes 1 of 2 occurances 
 from this list that should be captured. Should for keep the list 
 going through each instance?

You're removing stuff from something you're iterating over!
*slaps your fingers with a ruler*
Make a copy of the list!
HTH,
-Luke

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


[Tutor] Why is this only catching one occurance?

2006-10-27 Thread Chris Hengge
Here is my code:for unWantedItem in directoryList: try: if hex in unWantedItem.lower(): if not bmc in unWantedItem.lower(): print unWantedItem +  removed!
 directoryList.remove(unWantedItem)This only seems to loop through once, and removes 1 of 2 occurances from this list that should be captured. Should for keep the list going through each instance?
Thanks alot. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Mailing list question

2006-10-27 Thread rolando
Oh, ok :D


Luke Paireepinart escreveu:
 rolando wrote:
 I just use the reply button in my Thunderbird, and then change the 
 email I want to send to tutor@python.org
 It's better to use reply-all, in my opinion, because then, if 
 someone's involved in an e-mail thread, they'll get an instant
 update on it even if they only get the Tutor Digest and not every 
 individual mail.
 Cheers,
 -Luke



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


Re: [Tutor] Witch gui to choose for this script?

2006-10-27 Thread Luke Paireepinart
rolando wrote:
 Well, I don't know if I can ask this question here, but never mind 
 that :)

 It´s like this, I created this python script that translates human 
 language to Al-bhed language (it's a language from the game Final 
 Fantasy 10, it's basicly a change in the letters for example A becomes 
 W or B become H).

 Since I like the script, and it's my first program, I am now trying 
 to create a GUI for it.

 So what do you recommend?

I don't think something like this lends itself to a particular GUI set,
so the question I have to ask you is:
Do you feel lucky?

Just kidding.
It's really up to you on this one.
TKInter would probably be easier to learn, since it's your first program.
You could go the route of a GUI builder such as Boa Constructor, but I'd 
recommend that you learn
how to use a GUI toolkit before you use a builder, so that you know 
exactly what the builder is automating for you.

However, are you sure you want to jump into a GUI right now?
If you're just going for a simple two-textbox, one button, 'type here, 
hit the button, and the translated text appears in the other box'
type thing, and not something fancy, I guess it's about as simple of an 
introduction to a GUI toolkit as you can get, aside from a
label that says Hello, World or other such thing.
Just remember that it's important that you have a firm understanding of 
python's built-ins, and I guess Python in general,
before you start trying to use a big external package like a GUI 
toolkit, and a little up-front time learning the basics will help you a 
great deal in the long run.

 I'm going to attach the script, just in case you want to see it.
Good job on attaching the script!
I did want to see it.
I can't read the comments, though, but I think I got what it was doing.

Good luck in whatever you choose to do.
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] line number when reading files using csv module

2006-10-27 Thread Duncan Gibson

If I have the following data file, data.csv:
1 2 3
2 3 4 5

then I can read it in Python 2.4 on linux using:

import csv
f = file('data.csv', 'rb')
reader = csv.reader(f)
for data in reader:
print data

OK, that's all well and good, but I would like to record
the line number in the file. According to the documentation,
each reader object has a public 'line_num' attribute
http://docs.python.org/lib/node265.html and
http://docs.python.org/lib/csv-examples.html supports this.

If I now change the loop to read:

for data in reader:
print reader.line_num, data

I'm presented with the error:
AttributeError: '_csv.reader' object has no attribute 'line_num'

This has floored me. I've even looked at the source code and I can
see the line_num variable in the underlying _csv.c file. I can even
see the test_csv.py code that checks it!

def test_read_linenum(self):
r = csv.reader(['line,1', 'line,2', 'line,3'])
self.assertEqual(r.line_num, 0)

I suspect this is something so obvious that I just can't see the
wood for the trees and I will kick myself.

Any ideas?

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


Re: [Tutor] Witch gui to choose for this script?

2006-10-27 Thread rolando
If you're just going for a simple two-textbox, one button, 'type here, 
hit the button, and the translated text appears in the other box' 


Yeah, its something like that :D

Nothing to much fancy, it just that it can get kind of boring always 
going to the linux console to run the script.


I'm going to try the Boa Contructor.


I'm going to attach the script, just in case you want to see it.
Good job on attaching the script!
I did want to see it.
I can't read the comments, though, but I think I got what it was doing.


Yeah, I kind of forgot to translate the comments.

Now I have attached the script with the translated comments.

Also any comments about the program are welcome.





Luke Paireepinart escreveu:

rolando wrote:
Well, I don't know if I can ask this question here, but never mind 
that :)


It´s like this, I created this python script that translates human 
language to Al-bhed language (it's a language from the game Final 
Fantasy 10, it's basicly a change in the letters for example A 
becomes W or B become H).


Since I like the script, and it's my first program, I am now trying 
to create a GUI for it.


So what do you recommend?


I don't think something like this lends itself to a particular GUI set,
so the question I have to ask you is:
Do you feel lucky?

Just kidding.
It's really up to you on this one.
TKInter would probably be easier to learn, since it's your first program.
You could go the route of a GUI builder such as Boa Constructor, but 
I'd recommend that you learn
how to use a GUI toolkit before you use a builder, so that you know 
exactly what the builder is automating for you.


However, are you sure you want to jump into a GUI right now?
If you're just going for a simple two-textbox, one button, 'type here, 
hit the button, and the translated text appears in the other box'
type thing, and not something fancy, I guess it's about as simple of 
an introduction to a GUI toolkit as you can get, aside from a

label that says Hello, World or other such thing.
Just remember that it's important that you have a firm understanding 
of python's built-ins, and I guess Python in general,
before you start trying to use a big external package like a GUI 
toolkit, and a little up-front time learning the basics will help you 
a great deal in the long run.


I'm going to attach the script, just in case you want to see it.
Good job on attaching the script!
I did want to see it.
I can't read the comments, though, but I think I got what it was doing.

Good luck in whatever you choose to do.
-Luke




#!/usr/bin/python
#V 0.4
import string

contador = s # Creates a counter that checks if it should run the script or not

while contador.lower() == s or contador.lower() == sim: # While the counter is a lower s or sim (that's yes in portuguese) the program doesn't quit

	print Escolhe a lingua que queres traduzir. [p]ortugues ou [a]l-bhed

	lingua = raw_input() # Chosse the language to translate
	
	if lingua.isspace() == True: # If lingua is only white space

		print Tens de escrever alguma coisa ok?

	if lingua == : # If lingua is empty
		
		print Tens de escrever alguma coisa ok?

	if lingua.lower() == a or lingua.lower() == al-bhed:
		lista = string.maketrans('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'epstiwknuvgclrybxhmdofzqajEPSTIWKNUVGCLRYBXHMDOFZQAJ') # Creates the list of letter, and the way they are going to be changed

		print Escreve a palavra que queres traduzir.

		palavra = raw_input() # Ask for a word

		print  + palavra.translate(lista) +  # Print the translated words

	if lingua.lower() == p or lingua.lower() == portugues:
		lista = string.maketrans('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'ypltavkrezgmshubxncdijfqowYPLTAVkREZGMSHUBXNCDIJFQOW') # Creates the list of letter, and the way they are going to be changed

		print Escreve a palavra que queres traduzir.

		palavra = raw_input() # Ask for a word

		print  + palavra.translate(lista) +  # Print the translated words
	

	print Ainda tens mais alguma coisa para traduzir? [S/N]
	
	contador = raw_input() # Possibility of changing the counter in the begging of the script

if contador.lower() == n or contador.lower() == nao: # If counter equals lower n or nao (that portugues for no) the program quits and prints the lower message
	print Entao adeus.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] database question

2006-10-27 Thread euoar
I'm learning to use python with  the database mysql. I'm writing a 
widget in pygtk that should show the results of a sql query. For example 
with SELECT * FROM a, I use this code
count = 0
a = db.cursor.description
for tuple in a:
print tuple[0][0]
count = count + 1


... to know how many columns are in the result, and then, what I have to 
do is to create a liststore with  count columns. The method to create 
a ListStore is: liststore = gtk.ListStore(str, str, str, ...[number of 
columns]). I was wondering how to create the liststore with the proper 
number of columns, if there would a way to do something like this with 
python:

# to store the number of columns that will be needed
count = 0
a = db.cursor.description
for tuple in a:
print tuple[0][0]
count = count + 1
   
# this is the string with the method to execute
method_string = gtk.ListStore(
for var in range(count):
method_string = function_string + str,
  
function_string = function_string + )

# is there something like this execute_function?
list_store = execute_function(method_string)


Thank you very much for your advices.


__ 
LLama Gratis a cualquier PC del Mundo. 
Llamadas a fijos y móviles desde 1 céntimo por minuto. 
http://es.voice.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Witch gui to choose for this script?

2006-10-27 Thread Kent Johnson
rolando wrote:
 Well, I don't know if I can ask this question here, but never mind that :)

Yes, it's fine.
 
 It´s like this, I created this python script that translates human 
 language to Al-bhed language (it's a language from the game Final 
 Fantasy 10, it's basicly a change in the letters for example A becomes W 
 or B become H).
 
 Since I like the script, and it's my first program, I am now trying to 
 create a GUI for it.
 
 So what do you recommend?

I think Tkinter is the easiest to get started with. You might also like 
to try PythonCard which is a wrapper around wxPython that makes it 
easier to use.
 
 I'm going to attach the script, just in case you want to see it.

I have a few comments below.
 
 
 
 
 #!/usr/bin/python
 #V 0.4
 import string
 
 contador = s # Cria um contador que verifica que deve ou nao executar o 
 script
 
 while contador.lower() == s or contador.lower() == sim: # Enquanto o 
 valor for s ou sim o programa nao sai (converte a palavra em minusculas)
 
   print Escolhe a lingua que queres traduzir. [p]ortugues ou [a]l-bhed
 
   lingua = raw_input() # Escolhe a lingua
   
   if lingua.isspace() == True: # Se lingua e constituida por espacos em 
 branco
 
   print Tens de escrever alguma coisa ok?
 
   if lingua == : # Se lingua estiver vazia
   
   print Tens de escrever alguma coisa ok?

These two tests could be combined into
   if not lingua.strip():
 print Tens de escrever alguma coisa ok?

 
   if lingua.lower() == a or lingua.lower() == al-bhed:
   lista = 
 string.maketrans('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 
 'epstiwknuvgclrybxhmdofzqajEPSTIWKNUVGCLRYBXHMDOFZQAJ') # Cria a lista de 
 palavra e de que maneira vao ser trocadas
 
   print Escreve a palavra que queres traduzir.
 
   palavra = raw_input() # Pede por uma palavra
 
   print  + palavra.translate(lista) +  # Imprime as palavras 
 trocadas
 
   if lingua.lower() == p or lingua.lower() == portugues:
   lista = 
 string.maketrans('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 
 'ypltavkrezgmshubxncdijfqowYPLTAVkREZGMSHUBXNCDIJFQOW') # Cria a lista de 
 palavra e de que maneira vao ser trocadas

I would define the two listas outside the loop at the top of the program 
and give them more descriptive names like portugueseToAlBled. I think it 
would make the loop easier to read.

Kent
 
   print Escreve a palavra que queres traduzir.
 
   palavra = raw_input() # Pede por uma palavra
 
   print  + palavra.translate(lista) +  # Imprime as palavras 
 trocadas

You don't need the extra , just print palavra.translate(lista).

Kent
   
 
   print Ainda tens mais alguma coisa para traduzir? [S/N]
   
   contador = raw_input() # Modifica o contador que esta inicio do script
 
 if contador.lower() == n or contador.lower() == nao: # Se contador igual 
 a n ou nao minusculos
   print Entao adeus.
 
 
 
 
 ___
 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] line number when reading files using csv module

2006-10-27 Thread Duncan Gibson
On Fri, 27 Oct 2006 11:35:40 +0200
Duncan Gibson [EMAIL PROTECTED] wrote:

 
 If I have the following data file, data.csv:
 1 2 3
 2 3 4 5
 
 then I can read it in Python 2.4 on linux using:
 
 import csv
 f = file('data.csv', 'rb')
 reader = csv.reader(f)
 for data in reader:
 print data

Oops, mixing examples here. I forgot to say that
I'm actually using

reader = csv.reader(f, delimiter=' ')

so it will read the data correctly even if there
isn't a comma in sight in the csv file, but that's
a side issue to the line number problem.

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


Re: [Tutor] Why is this only catching one occurance?

2006-10-27 Thread Kent Johnson
Chris Hengge wrote:
 Here is my code:
 for unWantedItem in directoryList:
 try:
 if hex in unWantedItem.lower():
 if not bmc in unWantedItem.lower():
print unWantedItem +  removed!
directoryList.remove(unWantedItem)
 
 This only seems to loop through once, and removes 1 of 2 occurances from 
 this list that should be captured. Should for keep the list going 
 through each instance?

The problem is that when you remove the item from the list, the iterator 
that is looping over the list gets confused and skips the next item. 
(The iterator keeps an internal counter that is not updated when you 
remove an item.) See http://effbot.org/zone/python-list.htm#modifying 
for more.

The simplest fix is to use a list comprehension to create a new list 
with only the elements you want, and assign it to the same name:

directoryList = [ item for item in directoryList if 'hex not in 
item.lower() or 'bmc' in item.lower() ]

Note I changed the sense of the conditional because it is now selecting 
items to include.

The list comp doesn't have exactly the same result as your (intended) 
code, it creates a new list rather than modifying the old one in place. 
Most of the time this doesn't matter but if you have other references to 
dictionaryList only one will be changed.

Kent

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


Re: [Tutor] line number when reading files using csv module

2006-10-27 Thread Kent Johnson
Duncan Gibson wrote:
 If I have the following data file, data.csv:
 1 2 3
 2 3 4 5
 
 then I can read it in Python 2.4 on linux using:
 
 import csv
 f = file('data.csv', 'rb')
 reader = csv.reader(f)
 for data in reader:
 print data
 
 OK, that's all well and good, but I would like to record
 the line number in the file. According to the documentation,
 each reader object has a public 'line_num' attribute
 http://docs.python.org/lib/node265.html and
 http://docs.python.org/lib/csv-examples.html supports this.
 
 If I now change the loop to read:
 
 for data in reader:
 print reader.line_num, data
 
 I'm presented with the error:
 AttributeError: '_csv.reader' object has no attribute 'line_num'

The line_num attribute is new in Python 2.5. This is a doc bug, it 
should be noted in the description of line_num.

Kent

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


[Tutor] XML parsing in Python.. resources needed

2006-10-27 Thread Asrarahmed Kadri


Hi Folks,

ANy comments about ELementTree module...

I have heard that it is more 'Pythonic'... 

I need some basic examples to start learning the stuff.. If anyone has got the information, please pass it along..

Thanks.

Regards,
Asrarahmed Kadri-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] XML parsing in Python.. resources needed

2006-10-27 Thread Kent Johnson
Asrarahmed Kadri wrote:
  
  
 Hi Folks,
  
 ANy comments about ELementTree module...
  
 I have heard that it is more 'Pythonic'...
  
 I need some basic examples to start learning the stuff.. If anyone has 
 got the information, please pass it along..

http://effbot.org/zone/element.htm

Kent

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


[Tutor] I am terribly confused about generators and iterators.. Help me

2006-10-27 Thread Asrarahmed Kadri


Hi Folks,

What are generators and iterators...??And why are they areneeded..??

I can domy stuff with a 'for' or a 'while' loop.. so why do I need an ITERATOR..?

And what is a generator ..? I did try to read about these two things on the web, but still I AM CONFUSED.

To be honest, I am used to the nice and lucid style of the wonderful people on this forum.. :)-

Regards,
Asrarahmed Kadri
-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] line number when reading files using csv module

2006-10-27 Thread Duncan Gibson


Kent Johnson wrote:
 The line_num attribute is new in Python 2.5. This is a doc bug,
 it should be noted in the description of line_num.

Is there some way to create a wrapper around a 2.4 csv.reader to
give me pseudo line number handling? I've been experimenting with:

import csv

class MyReader(object):

def __init__(self, inputFile):
self.reader = csv.reader(inputFile, delimiter=' ')
self.lineNumber = 0

def __iter__(self):
self.lineNumber += 1
return self.reader.__iter__()

def next(self):
self.lineNumber += 1# do I need this one?
return self.reader.next()

if __name__ == '__main__':
inputFile = file('data.csv', 'rb')
reader = MyReader(inputFile)
for data in reader:
print reader.lineNumber, data

But that doesn't seem to do what I want. If I add some print statements
to the methods, I can see that it calls __iter__ only once:

__iter__
1 ['1', '2', '3']
1 ['2', '3', '4', '5']
1 ['3', '4', '5', '6', '7']
1 ['4', '5', '6', '7']
1 ['5', '6', '7', '8', '9']

Is there some other __special__ method that I need to forward to the
csv.reader, or have I lost all control once __iter__ has done its job?

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


Re: [Tutor] line number when reading files using csv module

2006-10-27 Thread Kent Johnson
Duncan Gibson wrote:
 
 Kent Johnson wrote:
 The line_num attribute is new in Python 2.5. This is a doc bug,
 it should be noted in the description of line_num.
 
 Is there some way to create a wrapper around a 2.4 csv.reader to
 give me pseudo line number handling? I've been experimenting with:
 
 import csv
 
 class MyReader(object):
 
 def __init__(self, inputFile):
 self.reader = csv.reader(inputFile, delimiter=' ')
 self.lineNumber = 0
 
 def __iter__(self):
 self.lineNumber += 1
 return self.reader.__iter__()

__iter__() should return self, not self.reader.__iter__(), otherwise 
Python is using the actual csv.reader not your wrapper. And don't 
increment line number here.

 
 def next(self):
 self.lineNumber += 1# do I need this one?

Yes.

 return self.reader.next()

An easier way to do this is to use enumerate():
inputFile = file('data.csv', 'rb')
reader = csv.reader(inputFile)
for i, data in enumerate(reader):
   print i, data

Of course this will not necessarily give you the true line number, as a 
record may span multiple file lines and you may be processing header and 
blank lines at the start of the file before you get any records. But it 
is probably the best you can do and maybe it is what you need.

 
 if __name__ == '__main__':
 inputFile = file('data.csv', 'rb')
 reader = MyReader(inputFile)
 for data in reader:
 print reader.lineNumber, data
 
 But that doesn't seem to do what I want. If I add some print statements
 to the methods, I can see that it calls __iter__ only once:

__iter__() will only be called once, it is next() that is called 
multiple times.

 
 __iter__
 1 ['1', '2', '3']
 1 ['2', '3', '4', '5']
 1 ['3', '4', '5', '6', '7']
 1 ['4', '5', '6', '7']
 1 ['5', '6', '7', '8', '9']
 
 Is there some other __special__ method that I need to forward to the
 csv.reader, or have I lost all control once __iter__ has done its job?

You lost control because you gave it away.

Kent

 
 Cheers
 Duncan
 ___
 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] [pygtk] ListStore question

2006-10-27 Thread shawn bright
this is cool, ill give it a shotskOn 10/27/06, euoar [EMAIL PROTECTED] wrote:
euoar escribió: mc collilieux escribió: euoar wrote: I'm learning the use of liststores and treeviews. I have wrotten this litle class as exercice:
 # name is the name of the new column to add, values is a tuple withthe values to add def add_result (self, name, values): self.iter = self.liststore.append
(values[0]) for value in values: self.liststore.insert_after(self.iter,value) rereading the tutorial, I note ...The row parameter specifies the data that should be inserted in the row after it is created ... If row is
 specified it must be a tuple or list containing as many items as the number of columns in the ListStore...so self.liststore.insert_after(self.iter, [value])
 Hope it's the good answer... PS : sorry for the answer directly to your mail. too quickly clic That's exactly the solution. It has to be a tuple. Thank you very much
 for your help! __ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y móviles desde 1 céntimo por minuto. 
http://es.voice.yahoo.com ___ pygtk mailing list pygtk@daa.com.au 
http://www.daa.com.au/mailman/listinfo/pygtk Read the PyGTK FAQ: http://www.async.com.br/faq/pygtk/I think I have the solution (I'm answering myself to avoid people to
waste time thinking in my question):args = [str, str, str]gtk.ListStore(*args)__LLama Gratis a cualquier PC del Mundo.Llamadas a fijos y móviles desde 1 céntimo por minuto.
http://es.voice.yahoo.com___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] Getting the type of a variable

2006-10-27 Thread Etrade Griffiths
Hi

I want to check the type of a variable so that I know which format to use 
for printing eg

def print_correct_format(a):

if type(a) == 'int':
print a is an integer, value %i % (a)
elif type(a) == 'float':
print a is a float, value %f % (a)
else:
print a is unknown type

The comparison type(a) == 'int' etc does not work - I'm sure there's a 
simple way to fix this but can't see it at the moment - any suggestions?


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


Re: [Tutor] Getting the type of a variable

2006-10-27 Thread Asrarahmed Kadri
Use this:

if type(a) == type(1):
 print a is int %d
elif type(a) == type(1.1):
 ...

HTH..
Regards,
Asrarahmed Kadri

On 10/27/06, Etrade Griffiths [EMAIL PROTECTED] wrote:
HiI want to check the type of a variable so that I know which format to usefor printing eg
def print_correct_format(a): if type(a) == 'int': print a is an integer, value %i % (a) elif type(a) == 'float': print a is a float, value %f % (a)
 else: print a is unknown typeThe comparison type(a) == 'int' etc does not work - I'm sure there's asimple way to fix this but can't see it at the moment - any suggestions?
___Tutor maillist-Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Getting the type of a variable

2006-10-27 Thread Etrade Griffiths


Thanks, guys - like so many things, easy when you know how!
Alun Griffiths

At 14:27 27/10/2006, you wrote:
Use this:

if type(a) == type(1):
 print a is int %d
elif type(a) == type(1.1):
 ...

HTH..
Regards,
Asrarahmed Kadri


On 10/27/06, Etrade Griffiths
[EMAIL PROTECTED]
wrote: 


Hi

I want to check the type of a variable so that I know which format to
use

for printing eg

def print_correct_format(a):

 if type(a) == 'int':


print a is an integer, value %i % (a)

 elif type(a) == 'float':


print a is a float, value %f % (a) 

 else:


print a is unknown type

The comparison type(a) == 'int' etc does not work - I'm sure there's
a

simple way to fix this but can't see it at the moment - any
suggestions? 


___

Tutor maillist -
Tutor@python.org

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




-- 
To HIM you shall return. 

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


Re: [Tutor] Why is this only catching one occurance?

2006-10-27 Thread Bob Gailer
Chris Hengge wrote:
 Here is my code:
 for unWantedItem in directoryList:
 try:
 if hex in unWantedItem.lower():
 if not bmc in unWantedItem.lower():
print unWantedItem +  removed!
directoryList.remove(unWantedItem)

 This only seems to loop through once, and removes 1 of 2 occurances 
 from this list that should be captured. Should for keep the list 
 going through each instance?
for goes thru the list accessing item[0], item[1], item[2], etc. Let's 
say for is on item[1] and you remove item[1]. All the subsequent items 
move left, so item[2] becomes item[1], item[3] becomes item[2], etc. 
for then steps to item[2], skipping the original item[2].

There are several ways around this. The easiest is to process the list 
backwards: for unWantedItem in directoryList[,,-1]:

-- 
Bob Gailer
510-978-4454

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


Re: [Tutor] I am terribly confused about generators and iterators.. Help me

2006-10-27 Thread Bob Gailer
Asrarahmed Kadri wrote:
  
  
 Hi Folks,
  
 What are generators and iterators...??And why are they are needed..??
  
 I can do my stuff with a 'for' or a 'while' loop.. so why do I need an 
 ITERATOR..?
iterators  generators do not replace while or for loops! 
  
 And what is a generator ..? I did try to read about these two things 
 on the web, but still I AM CONFUSED.
Well at risk of offering more web stuff, try 
http://heather.cs.ucdavis.edu/~matloff/Python/PyIterGen.pdf

 To HIM you shall return.
I am glad that this thought brings you some comfort or stimulation. I 
used to believe something similar, and all it did was bring me fear 
guilt and shame.


-- 
Bob Gailer
510-978-4454

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


Re: [Tutor] line number when reading files using csv module

2006-10-27 Thread Bob Gailer
Duncan Gibson wrote:
 If I have the following data file, data.csv:
 1 2 3
 2 3 4 5

 then I can read it in Python 2.4 on linux using:

 import csv
 f = file('data.csv', 'rb')
 reader = csv.reader(f)
 for data in reader:
 print data

 OK, that's all well and good, but I would like to record
 the line number in the file. According to the documentation,
 each reader object has a public 'line_num' attribute
 http://docs.python.org/lib/node265.html and
 http://docs.python.org/lib/csv-examples.html supports this.

 If I now change the loop to read:

 for data in reader:
 print reader.line_num, data

 I'm presented with the error:
 AttributeError: '_csv.reader' object has no attribute 'line_num'
   
Well I get the same exception. dir(reader) does not show line_num.
 This has floored me. I've even looked at the source code and I can
 see the line_num variable in the underlying _csv.c file. I can even
 see the test_csv.py code that checks it!

 def test_read_linenum(self):
 r = csv.reader(['line,1', 'line,2', 'line,3'])
 self.assertEqual(r.line_num, 0)

 I suspect this is something so obvious that I just can't see the
 wood for the trees and I will kick myself.

 Any ideas?

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

   


-- 
Bob Gailer
510-978-4454

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


Re: [Tutor] I am terribly confused about generators and iterators.. Help me

2006-10-27 Thread Kent Johnson
Bob Gailer wrote:
 Asrarahmed Kadri wrote:
  
 What are generators and iterators...??And why are they are needed..??
  
 I can do my stuff with a 'for' or a 'while' loop.. so why do I need an 
 ITERATOR..?
 iterators  generators do not replace while or for loops! 

No, actually iterators and generators are the foundation of for loops. 
Whenever you write a for loop, Python creates an iterator to return the 
values that are assigned to the loop variables.

Writing your own iterator is a way to make a new kind of thing that can 
be iterated in a for loop. Generators are a convenient way to make 
iterators. They can be used to encapsulate loop logic. For some examples 
see these recent threads:
http://thread.gmane.org/gmane.comp.python.tutor/36068/focus=36069
http://article.gmane.org/gmane.comp.python.tutor/36105/match=generator

  
 And what is a generator ..? I did try to read about these two things 
 on the web, but still I AM CONFUSED.
 Well at risk of offering more web stuff, try 
 http://heather.cs.ucdavis.edu/~matloff/Python/PyIterGen.pdf

Thanks, that is very nice!

Kent

 To HIM you shall return.
 I am glad that this thought brings you some comfort or stimulation. I 
 used to believe something similar, and all it did was bring me fear 
 guilt and shame.
 
 


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


Re: [Tutor] I am terribly confused about generators and iterators.. Help me

2006-10-27 Thread David Heiser

May I invite EVERYONE to NOT introduce political or religious elements
into these discussions. It has no place here and can destroy this
excellent discussion group. I've seen it happen.

PLEASE take it elsewhere.


-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On
Behalf Of Bob Gailer
Sent: Friday, October 27, 2006 10:11 AM
To: Asrarahmed Kadri
Cc: pythontutor
Subject: Re: [Tutor] I am terribly confused about generators and
iterators.. Help me


Asrarahmed Kadri wrote:
  
  
 Hi Folks,
  
 What are generators and iterators...??And why are they are needed..??
  
 I can do my stuff with a 'for' or a 'while' loop.. so why do I need an
 ITERATOR..?
iterators  generators do not replace while or for loops! 
  
 And what is a generator ..? I did try to read about these two things
 on the web, but still I AM CONFUSED.
Well at risk of offering more web stuff, try 
http://heather.cs.ucdavis.edu/~matloff/Python/PyIterGen.pdf

 To HIM you shall return.
I am glad that this thought brings you some comfort or stimulation. I 
used to believe something similar, and all it did was bring me fear 
guilt and shame.


-- 
Bob Gailer
510-978-4454

___
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] Getting the type of a variable

2006-10-27 Thread Joshua Simpson



On 10/27/06, Etrade Griffiths
[EMAIL PROTECTED]
wrote: 


Hi

I want to check the type of a variable so that I know which format to
use

for printing egAlternatively, you could just cast it as a string. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Getting the type of a variable

2006-10-27 Thread wesley chun
  I want to check the type of a variable so that I know which format to use
  for printing eg
 
 Alternatively, you could just cast it as a string.

what joshua is saying is that for just displaying something, that it's
just as easy to convert it to a string, or, if you're using print, to
not do anything at all (since objects which are part of print
statements are automagically sent to str()), e.g.,

print a is a number with a value of, a # no need to convert a

as many others have pointed out, using type() works too, but type(x)
is type(0) works slightly faster than type(x) == type(0) ... can
any non-tutors guess why?

also, isinstance() works great if you want to do multi-compares.  for
example, here's a snippet out of chapter 4 in my book:

def displayNumType(num):
print num, 'is',
if isinstance(num, (int, long, float, complex)):
print 'a number of type:', type(num).__name__
else:
print 'not a number at all!!'

displayNumType(-69)
displayNumType(99L)
displayNumType(98.6)
displayNumType(-5.2+1.9j)
displayNumType('xxx')

when you run it, you get:

-69 is a number of type: int
99 is a number of type: long
98.6 is a number of type: float
(-5.2+1.9j) is a number of type: complex
xxx is not a number at all!!

the good news is that isinstance() means only one function call, and
it's pretty fast. if there's any downside of isinstance(), and it's
pretty minor -- well, perhaps it's a feature -- is that it is *not* a
direct type/class comparison, meaning that subclasses will match too:

 isinstance(1, object)
True
 isinstance('xxx', object)
True

anyway, hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Core Python Programming, Prentice Hall, (c)2007,2001
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I am terribly confused about generators and iterators.. Help me

2006-10-27 Thread wesley chun
 What are generators and iterators...??And why are they are needed..??

 I can do my stuff with a 'for' or a 'while' loop.. so why do I need an
 ITERATOR..?

 And what is a generator ..? I did try to read about these two things on the
 web, but still I AM CONFUSED.


here are some more places to look in addition to what others have
already posted...

1. i wrote a short article in Linux Journal back when Python 2.2 was
released, highlighting its new features; it includes a discussion and
examples of iterators and generators:

http://www2.linuxjournal.com/article/5597

my short take on it is that iterators let you use for-loops over
sequence-*like* objects.  in older versions of Python, they had to
*be* sequences, i.e. strings, lists, tuples.  but with iterators, you
can now go through lines of a file, keys of a dictionary, etc. and
generators are like iterators with brains because you can generate
successive items to be iterated over, in addition to the cool
co-routine-like resumable function features.

2. i do Python training professionally, and for people considering my
services, i offer a free 5 minute sample podcast/video of what it's
like to take a course from me.  the example filmed is where i discuss
generators right after i introduce iterators.

http://cyberwebconsulting.com (click Python Training)

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Core Python Programming, Prentice Hall, (c)2007,2001
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] line number when reading files using csv module

2006-10-27 Thread Bob Gailer
Duncan Gibson wrote:
 [snip]

 but I would like to record the line number in the file. 
   
How about using enumerate():

 for line_num, data in enumerate(reader):
 print reader.line_num, data

   


-- 
Bob Gailer
510-978-4454

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


Re: [Tutor] Why is this only catching one occurance?

2006-10-27 Thread Chris Hengge
Thats for this very humorous reply =DOn 10/26/06, Luke Paireepinart [EMAIL PROTECTED] wrote:
Chris Hengge wrote: Here is my code: for unWantedItem in directoryList: try:
 if hex in unWantedItem.lower(): if not bmc in unWantedItem.lower():print unWantedItem +  removed!
directoryList.remove(unWantedItem) This only seems to loop through once, and removes 1 of 2 occurances from this list that should be captured. Should for keep the list
 going through each instance?You're removing stuff from something you're iterating over!*slaps your fingers with a ruler*Make a copy of the list!HTH,-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why is this only catching one occurance?

2006-10-27 Thread Chris Hengge
I've tried to use your example:for unWantedItem in directoryList[,,-1]:but I get an error:for unWantedItem in directoryList[,,-1]:  ^SyntaxError: invalid syntax
I understand what you are saying to do, and it makes sense, but I'm not sure how to impliment it. On 10/27/06, Bob Gailer 
[EMAIL PROTECTED] wrote:Chris Hengge wrote: Here is my code: for unWantedItem in directoryList:
 try: if hex in unWantedItem.lower(): if not bmc in unWantedItem.lower():print unWantedItem +  removed!
directoryList.remove(unWantedItem) This only seems to loop through once, and removes 1 of 2 occurances from this list that should be captured. Should for keep the list
 going through each instance?for goes thru the list accessing item[0], item[1], item[2], etc. Let'ssay for is on item[1] and you remove item[1]. All the subsequent itemsmove left, so item[2] becomes item[1], item[3] becomes item[2], etc.
for then steps to item[2], skipping the original item[2].There are several ways around this. The easiest is to process the listbackwards: for unWantedItem in directoryList[,,-1]:--Bob Gailer
510-978-4454
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] line number when reading files using csv module CORRECTION

2006-10-27 Thread Bob Gailer
Bob Gailer wrote:
 Duncan Gibson wrote:
   
 [snip]
 

   
 but I would like to record the line number in the file. 
   
 
 How about using enumerate():
   
 for line_num, data in enumerate(reader):
 # print reader.line_num, data # SHOULD BE:
 print line_num, data


 
   


-- 
Bob Gailer
510-978-4454

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


Re: [Tutor] Why is this only catching one occurance?

2006-10-27 Thread Chris Hengge
That was supposed to say Thanks for this but I was in a hurry.Anyways, here is my solution:# Remove any copies of .hex that aren't BMC for foundItem in directoryList: try:
 if .hex in foundItem.lower(): if bmc in foundItem.lower(): wantedList.append(foundItem) else: 
 print foundItem +  removed! else: wantedList.append(foundItem) except: print Failed to strip excess hex files.
On 10/27/06, Chris Hengge [EMAIL PROTECTED] wrote:
Thats for this very humorous reply =DOn 10/26/06, Luke Paireepinart 
[EMAIL PROTECTED] wrote:
Chris Hengge wrote: Here is my code: for unWantedItem in directoryList:
 try:
 if hex in unWantedItem.lower(): if not bmc in unWantedItem.lower():print unWantedItem +  removed!

directoryList.remove(unWantedItem) This only seems to loop through once, and removes 1 of 2 occurances from this list that should be captured. Should for keep the list
 going through each instance?You're removing stuff from something you're iterating over!*slaps your fingers with a ruler*Make a copy of the list!HTH,-Luke



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


Re: [Tutor] Why is this only catching one occurance?

2006-10-27 Thread Carroll, Barry
Chris:

See below.  


 -Original Message-
 Message: 7
 Date: Fri, 27 Oct 2006 12:20:51 -0700
 From: Chris Hengge [EMAIL PROTECTED]
 Subject: Re: [Tutor] Why is this only catching one occurance?
 To: Bob Gailer [EMAIL PROTECTED]
 Cc: Tutor tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain; charset=iso-8859-1
 
 I've tried to use your example:
 for unWantedItem in directoryList[,,-1]:
 
 but I get an error:
 for unWantedItem in directoryList[,,-1]:
  ^
 SyntaxError: invalid syntax
 
SNIP

The problem is the commas.  Python uses colons to describe slices.  Try
this instead:

 for unWantedItem in directoryList[::-1]:

I think that will work for you.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed

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


Re: [Tutor] XML parsing in Python.. resources needed

2006-10-27 Thread Gabriel Farrell
On Fri, Oct 27, 2006 at 11:24:00AM +0100, Asrarahmed Kadri wrote:
 Hi Folks,
 
 ANy comments about ELementTree module...
 
 I have heard that it is more 'Pythonic'...
 
 I need some basic examples to start learning the stuff.. If anyone has got
 the information, please pass it along..
 

ElementTree is great, and will be in Python2.5, so it's good to know.
Go through the documentation at http://effbot.org/zone/element.htm, as
Kent mentioned, and return to the list with specific questions.  

I recommend you also take a look at Amara[1], which I enjoy using
because of it's clear API and clean output.

gabe

[1] http://uche.ogbuji.net/tech/4suite/amara/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] (OT) Non-Python discussions (Was: I am terribly confused about generators ...)

2006-10-27 Thread Carroll, Barry
Greetings:

I agree completely with David.  There are plenty of places to discuss
controvercial topics.  Let's not do it here, where it will only disrupt,
and possibly ruin, an exceptionally useful teaching and learning
channel.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


 -Original Message-
 Message: 1
 Date: Fri, 27 Oct 2006 10:41:51 -0600
 From: David Heiser [EMAIL PROTECTED]
 Subject: Re: [Tutor] I am terribly confused about generators and
   iterators.. Help me
 To: pythontutor tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain; charset=us-ascii
 
 May I invite EVERYONE to NOT introduce political or religious elements
 into these discussions. It has no place here and can destroy this
 excellent discussion group. I've seen it happen.
 
 PLEASE take it elsewhere.
 
 -Original Message-
 From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On
 Behalf Of Bob Gailer
 Sent: Friday, October 27, 2006 10:11 AM
 To: Asrarahmed Kadri
 Cc: pythontutor
 Subject: Re: [Tutor] I am terribly confused about generators and
 iterators.. Help me
 
 Asrarahmed Kadri wrote:
 
  Hi Folks,
 
snip
  To HIM you shall return.
 I am glad that this thought brings you some comfort or stimulation. I
 used to believe something similar, and all it did was bring me fear
 guilt and shame.
 
 --
 Bob Gailer
 510-978-4454
 ___
 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] recommendations for database module based on my needs

2006-10-27 Thread Pine Marten

I'm hoping to create an app which takes user data via a GUI with checkboxes, 
textcontrols, spinner controls, etc.  The data would be some text, some 
numbers, some checkboxes checked or not, etc.  I've been making a little 
progress on that via wxPython and Boa Constructor.

Now I want to save that info such that:

- the user can later search for any piece of data (search by date entered, 
for example).
- the non-text data can be plotted on a chart and simple line regression, 
etc., applied to it.
  this could be some variable over time line graph or one variable vs. 
another scatterplot.

The plotting I will pursue at another time, possibly via MatPlotLib or 
something.  But as for databases, I've heard a few choices, including gadfly 
or SQL and others.  I know zero about this, but I've heard gadfly is good if 
it is just a small dataset.  But how small is small?  The app I'm thinking 
of would take maybe 10-20 numbers/day and a few textboxes worth for 
potentially years.   Or should I just pony up to SQL or some other option 
that I don't know about?

Any recommendations or small python projects which are like this I might 
want to check out?  thanks.

_
Try the next generation of search with Windows Live Search today!  
http://imagine-windowslive.com/minisites/searchlaunch/?locale=en-ussource=hmtagline

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


Re: [Tutor] Getting the type of a variable

2006-10-27 Thread Alan Gauld

Etrade Griffiths [EMAIL PROTECTED] wrote

 I want to check the type of a variable so that I know which format 
 to use
 for printing eg

That's sometimes necessary but you may find that just
using %s will suffice.

print %s\n % 42
print %s\n % 42
print %s\n % 42.0

You usually only need to check the type if the format string includes
type specific precision and justification characters. but the %s 
format
will work for most types most of the time.

 The comparison type(a) == 'int' etc does not work

type(a) == type(1)

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


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


Re: [Tutor] recommendations for database module based on my needs

2006-10-27 Thread Alan Gauld

Pine Marten [EMAIL PROTECTED] wrote 

 it is just a small dataset.  But how small is small?  

A potentially big topic.

But heres my purely arbitrary guidelines:

Less than 1000 records use a text file (or maybe XML)
1,000 - 100,000 records consider an in memory database 
or something like gdm (or gadfly in this case)
100,000=1000,000 records small scale or industrial SQL
Access, or SqlLite would be good examples
over 1,000,000 records go industrial. 
Postgres, MySql, Firebird/Interbase, Oracle, DB2, Sql server etc

There are lots of other issues to consider too, like numbers of 
tables, indexes, need for stored procedures etc etc. 
But for simple data storage those rough guidelines should 
suffice.

Caveat: Hardware improvements are changing the rules 
all the time. If its only simple one-off lookup, a text file 
could be used for 1,000,000 records on a fast machine 
nowadays, and if your server has 16G RAM say, then an 
in-memory database may scale up much farther. My figures 
assume long term multiple access during the application and 
average PC hardware.

And all IMHO of course :-)

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


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


Re: [Tutor] database question

2006-10-27 Thread Alan Gauld
 For example
 with SELECT * FROM a, I use this code

 ... to know how many columns are in the result,

As a general rule its better to avoid Select * From in production 
SQL.
If the table definition changes the data returned can change in 
unexpected
ways and break your application. In addition you can wind up sucking
up an awful lot of unnecessary data (think bandwidth and server 
throughput).
Its much safer to  explicitly list all of the columns you want to pull 
back
if at all possible.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


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


[Tutor] basic question ...

2006-10-27 Thread Ravi Kondamuru
Hi,How does one figure all the builtin libraries/ classes that python supports?For example if I want to sort a list of names, I would normally think of implementing the sorting routine in C. I am just beginning to learn python. It looks like there is a rich set available builtin libraries. So, is there one place where I can look to figure out I dont have to write afresh.
thanks,Ravi.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] basic question ...

2006-10-27 Thread Glenn T Norton
Ravi Kondamuru wrote:

 Hi,

 How does one figure all the builtin libraries/ classes that python 
 supports?

 For example if I want to sort a list of names, I would normally think 
 of implementing the sorting routine in C. I am just beginning to learn 
 python. It looks like there is a rich set available builtin libraries. 
 So, is there one place where I can look to figure out I dont have to 
 write  afresh.

 thanks,
 Ravi.



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

A good way to start is the dir() method which will show what is 
available to an object
  mylist = []
  dir(mylist)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', 
'__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', 
'__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', 
'__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', 
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', 
'__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 
'remove', 'reverse', 'sort']
 

  myString = ''
  dir(myString)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', 
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', 
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', 
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', 
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 
'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 
'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 
'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 
'translate', 'upper', 'zfill']
 

also, try the builtin help in the interpreter

  help(mylist.sort)
Help on built-in function sort:

sort(...)
L.sort(cmpfunc=None) -- stable sort *IN PLACE*; cmpfunc(x, y) - -1, 
0, 1

 

Good Luck,
Glenn


-- 
Ketchup. For the good times...  - Ketchup Advisory Board 
Glenn Norton
Application Developer
Nebraska.gov
1-402-471-2777
[EMAIL PROTECTED]

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


Re: [Tutor] basic question ...

2006-10-27 Thread Danny Yoo


On Fri, 27 Oct 2006, Ravi Kondamuru wrote:

 How does one figure all the builtin libraries/ classes that python 
 supports?

 For example if I want to sort a list of names, I would normally think of 
 implementing the sorting routine in C. I am just beginning to learn 
 python. It looks like there is a rich set available builtin libraries. 
 So, is there one place where I can look to figure out I dont have to 
 write afresh.


Hi Ravi,

As with any reference material, it's a good idea to try the index of the 
relevant documentation.  You might not always find what you're looking 
for, but it can be effective.

In this particular case, you've guessed that there might be something in 
the Library that might help you.  If you search for sort in the Library 
Reference:

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

You should see an index entry labeled sort() (list method).  Looking up 
that index entry should bring you to a page describing the methods on 
lists:

 http://www.python.org/doc/lib/typesseq-mutable.html

So looking at the reference is useful if you already know what you're 
looking for.  In this case, yes, there is a built-in sort.  Even better, 
there's a dedicated guide to using Python's sort functionality:

 http://wiki.python.org/moin/HowTo/Sorting



If you want to get an overview of the extent of Python's library, try the 
table of contents:

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

There's a heck of a lot of stuff there, so asking someone to memorize it 
is ridiculous.  Still, it can help to scan through it sometimes to get a 
better idea of what services the Library provides.  I've often been amazed 
at the gems in there.  (bisect?  Wow, I don't have to code my own binary 
search anymore!)

Another good way to learn the library is to look at what libraries other 
people use: you can read other people's code.  For example, the Python 
Cookbook provides a good source of programs that you can browse:

 http://aspn.activestate.com/ASPN/Python/Cookbook/


Finally, well, ask other people.  You've done so on Tutor, so that's a 
good start.  Many of us are happy to act as librarians to point you in 
some direction, and we usually aim not to mislead.  *grin*
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] problem importing class

2006-10-27 Thread Danny Yoo
 It looks like people have identified the problem, that your site.py 
 module isn't being found because it conflicts with something from 
 Python's Standard Library.

 This isn't the first time this kind of problem has hit people.  This
 problem is well known and is the subject of a Python Enhancement Proposal
 (PEP 328).  If you're using Python 2.5, you can use a new feature called
 'absolute_import' to avoid the import problem.  See:

  http://docs.python.org/whatsnew/pep-328.html

 for more details.

 Hmm, I don't see how that would help since AFAICT shawn's site.py is not 
 in a package. Or maybe I don't understand what you are suggesting?

Hi Kent,

I don't think I replied back to you on this one!  Python loads up 
'site.py' on startup if called without the '-S' option:

 http://docs.python.org/lib/module-site.html

So imagine if we're a program, and we run Python on it.  For some reason 
--- at least on startup --- Python places precendence on the modules 
located in Python's library directory.  So we pick up the Standard 
Library's site.py, which is then cached in sys.modules like any other 
module import.

Later on, if we try to 'import site', Python reuses the already-loaded 
site.py (because it's already cached in sys.modules) , regardless if 
there's a 'site.py' module in the current working directory.  The reason 
PEP 328 can be a solution here is because, if the absolute_import feature 
were on, we'd be able to do:

 from . import site

which would pick up the correct relative path.


Concretely, here's what probably happened with the original poster:

##
mumak:~ dyoo$ echo print 'hi'  site.py
mumak:~ dyoo$ python
Python 2.3.5 (#1, Mar 20 2005, 20:38:20)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin
Type help, copyright, credits or license for more information.
 import site
 print site.__file__
/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site.pyc
###

Note that the 'site.py' in the current directory was not used.  I have no 
idea why.  I suspect that this has some relation to the way that site.py 
is handled by a special case in the Python interpreter, but I have really 
no clue.


Python's module import lookup was handled in an implicit way which goes 
against its traditional explicit instead of implicit philosophy. 
That's why PEP 328 is so critically important: the name-collision problem 
gets much worse as either Standard Library or our own programs grow.  I'm 
amazed that we've been able to tolerate this situation for so long. 
*grin*
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor