Re: [Tutor] Handling 'None' (null) values when processing sqlite cursor results

2010-07-14 Thread Andre Engels
On Wed, Jul 14, 2010 at 6:31 AM, Monte Milanuk  wrote:
> Hello all,
>
> I'm struggling a bit trying to find the right way to deal with null values
> in my sqlite database when querying it and processing the results in python.
>
> If my cursor.fetchall() results return the following:
>
> (104, None, u'Sylvester', None, u'Evans', None, u'527-9210 Proin Av.',
> u'Liberal', u'VT', u'24742', u'1-135-197-1139',
> u'vehicula.pellentes...@idmollis.edu', u'2010-07-13 22:52:50', u'2010-07-13
> 22:52:50')
>
> At first I was having fits as str.join() was giving me a 'NoneType error'.
>  I found one way around that, by processing the results so the 'None' values
> got omitted from the list by the time they got to str.join().
>
> I thought that was the end of that, until I tried working with the returned
> records in another fashion and found that having the 'None' values omitted
> really messed with the list order which I was depending on i.e. list[5]
> could be different fields depending on how many 'None' values had been
> omitted.  And if I didn't omit them, when I printed out the user name in the
> format 'first''middle''last' from the above record, I got
> 'Sylvester''None''Evans' rather than just 'Sylvester''Evans' (i.e. with no
> middle initial).
>
> So... I guess my question is, is there a good/proper way to handle the
> 'None' values as returned by sqlite from a table that may have some null
> values in individual records?  Basically I want not have the None/Null
> values show up but to keep them as place holders to make sure i get the
> values in the right spots...

It depends a bit on what you want to do with the values. My preference
would be to keep the result of cursor.fetchall(), and instead
re-define the output function(s) that I use (so don't use
str.join(record), but some myjoin(str,record) that I defined). Or,
even better, to define a class for these, create an object of the
class from the fetchall result, and have things like the myjoin before
as class methods or properties.

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2010-07-14 Thread Andre Engels
On Tue, Jul 13, 2010 at 12:34 PM, Nitin Pawar  wrote:
> Adding to what Andre said,
> another way of optimizing the problem would be
> storing the prime number in the range you want to check an array and see if
> the given number is divisible by any of those prime number

As I wrote, my code was not optimalized for either code size or
execution time. Other obvious speed-ups, apart from the one you
mention, are to only search up to the square root of the number
(rather than to the number minus 1), and to immediately break out of
the loop once a divisor has been found.


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] I don't understand this code

2010-07-14 Thread ZUXOXUS
Hi,

I am a true beginner in programming, and im learning with
inventwithpython.com.

There's something I dont understand, and i would really appreciate any help.

In chapter 9, the one about the Hangman game, I don't get the block of code
in line 61

59.  words = 'ant baboon badger bat bear'
60.

   1. def getRandomWord(wordList):
   2. # This function returns a random string from the passed list of
   strings.
   3. wordIndex = random.randint(0, len(wordList) - 1)
   4. return wordList[wordIndex]


The thing is, the "passed list of strings" is called "words", not
"wordList", so I see it shouldn't work.

On the other hand, the variable "wordList" is defined nowhere!

The code is ok, because the program runs ok. So there is somethings that i
dont get.

Thank you very much in advance.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I don't understand this code

2010-07-14 Thread Stefan Behnel

ZUXOXUS, 13.07.2010 16:43:

Hi,

I am a true beginner in programming, and im learning with
inventwithpython.com.

There's something I dont understand, and i would really appreciate any help.

In chapter 9, the one about the Hangman game, I don't get the block of code
in line 61

59.  words = 'ant baboon badger bat bear'
60.

1. def getRandomWord(wordList):
2. # This function returns a random string from the passed list of
strings.
3. wordIndex = random.randint(0, len(wordList) - 1)
4. return wordList[wordIndex]


The thing is, the "passed list of strings" is called "words", not
"wordList", so I see it shouldn't work.


I'm pretty sure that's not how it's called. However, you can transform the 
whitespace separated string into a list by calling .split() on it:


wordList = words.split()

Also, the function above is redundant with the stdlib, use random.choice() 
instead, which does exactly the same thing.


Stefan

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I don't understand this code

2010-07-14 Thread Nitin Pawar
I tried replying with inline the questions
read below within your mail

On Tue, Jul 13, 2010 at 8:13 PM, ZUXOXUS  wrote:

> Hi,
>
> I am a true beginner in programming, and im learning with
> inventwithpython.com.
>
> There's something I dont understand, and i would really appreciate any
> help.
>
> In chapter 9, the one about the Hangman game, I don't get the block of code
> in line 61
>
> 59.  words = 'ant baboon badger bat bear'
> 60.
>
>1. def getRandomWord(wordList):
>2. # This function returns a random string from the passed list of
>strings.
>3. wordIndex = random.randint(0, len(wordList) - 1)
>4. return wordList[wordIndex]
>
>
> The thing is, the "passed list of strings" is called "words", not
> "wordList", so I see it shouldn't work.
>

>> wordList is just a parameter defined for the function and the code which
you are showing, it does not call the function anywhere, there should be
another line like

print getRandomWord(words)

>
> On the other hand, the variable "wordList" is defined nowhere!
>

>> You dont have to define the function parameters usually as you can use
them as they are appearing. In this case, wordList is parameter to funtion
which will be replaced with passed value when the function is called


> The code is ok, because the program runs ok. So there is somethings that i
> dont get.
>
> Thank you very much in advance.
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Nitin Pawar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I don't understand this code

2010-07-14 Thread Peter Otten
ZUXOXUS wrote:

> Hi,
> 
> I am a true beginner in programming, and im learning with
> inventwithpython.com.
> 
> There's something I dont understand, and i would really appreciate any
> help.
> 
> In chapter 9, the one about the Hangman game, I don't get the block of
> code in line 61
> 
> 59.  words = 'ant baboon badger bat bear'
> 60.
> 
>1. def getRandomWord(wordList):
>2. # This function returns a random string from the passed list of
>strings.
>3. wordIndex = random.randint(0, len(wordList) - 1)
>4. return wordList[wordIndex]
> 
> 
> The thing is, the "passed list of strings" is called "words", not
> "wordList", so I see it shouldn't work.
> 
> On the other hand, the variable "wordList" is defined nowhere!
> 
> The code is ok, because the program runs ok. So there is somethings that i
> dont get.
> 
> Thank you very much in advance.

A value can have a different name inside a function when it is passed as a 
parameter. Consider the following session:

>>> def get_first_word(whatever_you_like):
... return whatever_you_like[0]
...
>>> names = "peter paul mary".split()
>>> words = "nobody expects the spanish inquisition".split()
>>> get_first_word(names)
'peter'
>>> get_first_word(words)
'nobody'

Both the 'names' and the 'words' list of strings are referred to as 
'whatever_you_like' inside the get_first_word() function.

Peter

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I don't understand this code

2010-07-14 Thread Michael M Mason
> The thing is, the "passed list of strings" is called "words",
> not "wordList", so I see it shouldn't work.
>
> On the other hand, the variable "wordList" is defined nowhere!

"wordList" is just a name that the function (getRandomWord) uses to
refer to
whatever values get passed to it. Remember that you don't have to put
your
list of words into a variable before you call the function.  You could
just
do this:-

getRandomWord('ant baboon badger bat bear')

...and it will work. Or consider having two or three variables:-

   words = 'ant baboon badger bat bear'
   mylist= 'left right backward forward up down'
   morestuff = 'run walk stand sit'

Naturally you can feed any of these into the function:-

   getRandomWord(words)
   getRandomWord(mylist)
   getRandomWord(morestuff)

You can think of "getRandomWord(wordList)" as a convenient
shorthand for:-

   wordList = words 
   getRandomWord(wordList)

Hope this helps

-- 
Michael
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I don't understand this code

2010-07-14 Thread Serdar Tumgoren
The rest of the list does a great job explaining the situation, which bears
out in the code itself. If you look farther down in the code sample in
Chapter 9, you'll see the function called twice.

http://inventwithpython.com/chapter9/

<< snipped >>
print('H A N G M A N')
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words)
gameIsDone = False
<< end snippet >>

And then again a bit below:

<< snippet >>

gameIsDone = False
secretWord = getRandomWord(words)
else:
break

<< end snippet >>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Response to responses about list of lists: a metaexercise in mailinglist recursion

2010-07-14 Thread Alan Gauld


"Steven D'Aprano"  wrote

If you're starting a new discussion, or raising a new question, make 
a

fresh, blank email, put a descriptive title in the subject line, and
put tutor@python.org as the To address.

If you're replying to an existing message, using reply is fine, but 
just
trim the quoted text. You have a delete key -- learn how to use it 
:)


And I'll just add that you should use Reply All not vanilla Reply.
Reply will send your response back to the person who sent the
original message. Reply All sends it, as the name suggests,
to everyone on the list.

HTH,

Alan G. 



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] GUI Creation Aide

2010-07-14 Thread Corey Richardson
Hey tutors! I'm creating a GUI for a program. Really simple. I don't 
mind coding it out, but I was looking into things like Glade and the 
like. Do you recommend those over just coding it out by hand, or should 
I try Glade (or similiar) out? Also, I don't really have a preference 
for which toolkit I use, wx/Tk/GTK, etc.


Thanks,
~Corey Richardson
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I don't understand this code

2010-07-14 Thread Alan Gauld


"ZUXOXUS"  wrote


59.  words = 'ant baboon badger bat bear'

  1. def getRandomWord(wordList):
  3. wordIndex = random.randint(0, len(wordList) - 1)
  4. return wordList[wordIndex]


The thing is, the "passed list of strings" is called "words", not
"wordList", so I see it shouldn't work.


Note that wordList appears in the def line.
Have you studied functions yet? (I'm not familiar with your tutorial)
If so you should have read about parammeters or arguments?
parameters are local; variables within the function that take on 
the values passed to the function.


So if we define a function to return the square of a number:

def square(x):
return x*x

We define the functon to have a parameter x.

When we call the function we must pass in a value for x:

foo = 20
bar = square(foo)

Notice that we pass foo to square() but the value inside 
the function is called x.


Now lets look again at your example:


  1. def getRandomWord(wordList):
  3. wordIndex = random.randint(0, len(wordList) - 1)
  4. return wordList[wordIndex]


It has a parameter called wordList. That will take on the 
value passed into it and the reyrn value will be a random 
item from that list.



On the other hand, the variable "wordList" is defined nowhere!


Yes it is, in the function definition.

So when you call it with

getRandomWord(words)

wordList takes on the value of words.

You can find an alternative explanation of functions, parameters 
and arguments in the "Modules and Functions" topic of my tutorial.


HTH,


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



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Handling 'None' (null) values when processing sqlite cursorresults

2010-07-14 Thread Alan Gauld


"Monte Milanuk"  wrote

(104, None, u'Sylvester', None, u'Evans', None, u'527-9210 Proin 
Av.', u'Liberal', u'VT', u'24742', u'1-135-197-1139', 
u'vehicula.pellentes...@idmollis.edu', u'2010-07-13 22:52:50', 
u'2010-07-13 22:52:50')


At first I was having fits as str.join() was giving me a 'NoneType 
error'.  I found one way around that, by processing the results so 
the 'None' values got omitted from the list by the time they got to 
str.join().


Keep the storage and manipulation of data separate from the
display of that data. That is an important and fundamental principle
of data processing. Store the data with the nulls. Display the data 
without.


values omitted really messed with the list order which I was 
depending on i.e. list[5] could be different fields depending on how 
many 'None'


And that is why.

values had been omitted.  And if I didn't omit them, when I printed 
out the user name in the format 'first''middle''last' from the above 
record,


You need a display function that can strip out the nulls as needed.
A simple list comprehension or generator expression would work
in this case:

print ' '.join(str(field) for field in data if field is not 'None')

If you use a Class to model your data you can write a __str__() method
that does the intellifgent production of a string fit for printing. 
Then you just
print the records as normal. But for this scenario the complexity of 
building

a class may not be worth it.

The key principle is do not try to store your data in a display 
format.



HTH,


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


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] GUI Creation Aide

2010-07-14 Thread Alex Hall
On 7/14/10, Corey Richardson  wrote:
> Hey tutors! I'm creating a GUI for a program. Really simple. I don't
> mind coding it out, but I was looking into things like Glade and the
> like. Do you recommend those over just coding it out by hand, or should
> I try Glade (or similiar) out? Also, I don't really have a preference
> for which toolkit I use, wx/Tk/GTK, etc.
I have only ever used wx with the XRCed program, but I really like it.
Learning xrc is pretty straightforward, and there are some good
tutorials for it. It also has the advantage of keeping the code
generating your gui separate from your program, so code management is
easier. I have heard xrc/python compared to css/html regarding code
separation. For a really simple gui it is probably not too important,
but if you do larger projects later on it will probably make life
easier.
>
> Thanks,
> ~Corey Richardson
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] GUI Creation Aide

2010-07-14 Thread Alan Gauld


"Corey Richardson"  wrote

Hey tutors! I'm creating a GUI for a program. Really simple. I don't 
mind coding it out, but I was looking into things like Glade and the 
like. Do you recommend those over just coding it out by hand, or 
should I try Glade (or similiar) out? Also, I don't really have a 
preference for which toolkit I use, wx/Tk/GTK, etc.


I spent some time a couple of years back looking at different GUI
builders for Python. Frankly I didn't like any of them. Nothing comes
close to the tools used in VisualBasic or Delphi etc.

Things may have improved in recent years and there are a few 
commercial
tools that I didn't look at but for my limited GUI programming needs I 
find

I'm just as well hand coding the GUI.

Just a personal view, others may differ. And if you intend to do a lot 
of
GUI work (especially if you get paid for it!)  then it may be worth 
paying for

something that really does a good job.

HTH,

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


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] GUI Creation Aide

2010-07-14 Thread Wayne Werner
On Wed, Jul 14, 2010 at 7:18 AM, Corey Richardson  wrote:

> Hey tutors! I'm creating a GUI for a program. Really simple. I don't mind
> coding it out, but I was looking into things like Glade and the like. Do you
> recommend those over just coding it out by hand, or should I try Glade (or
> similiar) out? Also, I don't really have a preference for which toolkit I
> use, wx/Tk/GTK, etc.


Honestly it depends on how "pretty" you want it to look. Tkinter is the
ugliest GUI toolkit, but it's the easiest one to create simple GUIs.  To
create a window with a button with the text "hello world" that quits when
you push the button:

import Tkinter as tk

root = tk.Tk()
btn = tk.Button(root, text="Hello World", command=root.quit)
btn.pack()
root.mainloop()

And it's as simple as that. There are some fairly powerful widgets, but
nothing quite as advanced as you'll find in other frameworks. However, the
other frameworks do a have the benefit of a lot more power, so it really
comes down to what you want and what you need. If you need a simple GUI with
maybe a list or some text entry and some buttons, and maybe a menu, Tk is
the way to go.

If you want an advanced GUI with all sorts of pretty widgets and drawing
capabilities and bells and whistles, wx or GTK (my personal fave) are all
great options.

Of course, it's also my personal opinion that every python programmer should
learn Tkinter - it's a quick and easy way to throw up a GUI - so if you need
to just slap something together, it's right there. Plus it introduces you to
layout managers and callbacks, both of which are super useful programming
GUIs down the road.

HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Handling 'None' (null) values when processing sqlite cursorresults

2010-07-14 Thread Christian Witts

On 14/07/2010 14:32, Alan Gauld wrote:


"Monte Milanuk"  wrote

(104, None, u'Sylvester', None, u'Evans', None, u'527-9210 Proin 
Av.', u'Liberal', u'VT', u'24742', u'1-135-197-1139', 
u'vehicula.pellentes...@idmollis.edu', u'2010-07-13 22:52:50', 
u'2010-07-13 22:52:50')


At first I was having fits as str.join() was giving me a 'NoneType 
error'.  I found one way around that, by processing the results so 
the 'None' values got omitted from the list by the time they got to 
str.join().


Keep the storage and manipulation of data separate from the
display of that data. That is an important and fundamental principle
of data processing. Store the data with the nulls. Display the data 
without.


values omitted really messed with the list order which I was 
depending on i.e. list[5] could be different fields depending on how 
many 'None'


And that is why.

values had been omitted.  And if I didn't omit them, when I printed 
out the user name in the format 'first''middle''last' from the above 
record,


You need a display function that can strip out the nulls as needed.
A simple list comprehension or generator expression would work
in this case:

print ' '.join(str(field) for field in data if field is not 'None')




The problem with that is if you're relying on a set delimiter you are 
removing elements so you would be better served by doing `str(field) if 
field != None else '' for field in record`


--
Kind Regards,
Christian Witts


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Response to responses about list of lists: a meta exercise in mailinglist recursion

2010-07-14 Thread Siren Saren
Steven D'Aprano,

Your response was profoundly helpful to me.  If that sounds grandiose, I mean 
it nonetheless.  You not only answered all of my specific questions and taught 
me general methods I will use and reuse, you also gave me some hope.  It's a 
lonely process teaching myself to program in my mid-thirties. I tend to ask the 
wrong questions in the wrong way.  Even though I try to read all the FAQs and 
do 'my homework' before asking something, I still make an unfavorable 
impression because of errors I didn't even consider, like accidentally 
attaching all the group's prior messages to my first post here.  

I thought something in the culture of programming was particularly intolerant 
of the sort of errors I'd make, perhaps because of the syntactic precision 
required to program well.  But I realize now, retrospectively, I might have 
been offending people because I'd often ask questions about how to make 
something work on windows.  After reading some of the tutor links, I see that 
there's a cultural anger toward windows, which makes sense.  Anyway between 
installing ubuntu yesterday and getting your response, I feel more hopeful that 
I won't need to be quite so isolated in my learning.  Let me buy you a virtual 
beer.  Thanks again,

Soren   


Message: 2
Date: Wed, 14 Jul 2010 10:19:34 +1000
From: Steven D'Aprano 
To: tutor@python.org
Subject: Re: [Tutor] Response to responses about list of lists: a meta
    exercise in mailinglist recursion
Message-ID: <201007141019.34529.st...@pearwood.info>
Content-Type: text/plain;  charset="utf-8"

On Tue, 13 Jul 2010 10:40:44 pm Siren Saren wrote:
> I'm not sure if there's a way to submit responses 'live' or
> whether it's better to respond to subthreads at once or together, so
> I'll err on the side of discretion and just send one response.?

Generally it's better, or at least more common, to respond to each 
response individually. But that's generally because people on mailing 
lists receive individual pieces of mail instead of a single giant 
digest containing the entire day's email traffic.


> In response to the first question: the consensus seems to be
> that there is no good way to sort a non-alternating one-to-many list
> like this, so my strategy of deriving the index numbers of every
> item, as awkward as it appears, may actually be the best approach.

No, a better approach is to split the list into separate lists:

mixedlist = [
 'Crime and punishment', 10, 40, 30, 
 "Brother's Karamazov", 22, 55, 9000, 
 "Father's and Sons", 100,
 'Anna Karenina', 1, 2, 4, 7, 9,
]

# untested
current_book = None
current_pages = []
result = []
for item in mixedlist:
    # Is it a title, or an integer page?
    if isinstance(item, str):
        # It's a title.
        if current_book is not None:
            result.append( (current_book, current_pages) )
        current_book = item
        current_pages = []
    else:
        # It's a page number.
        current_pages.append(item)

This will split the mixed list of titles, page numbers into a 
consolidated list of (title, list-of-page-numbers) like this:

booklist = [
?("Crime and punishment", [10, 40, 30]),
?("Brother's Karamazov", [22, 55, 9000]),
?("Father's and Sons", [100]),
?("Anna Karenina", [1, 2, 4, 7, 9]),
]

It's easy to adapt it to use a dictionary instead of a list. Change 
result to an empty dict {} instead of an empty list [], and change the 
line:

result.append( (current_book, current_pages) )

into:

result[current_book] = current_pages



One other thing... it's possible that your data is provided to you in 
text form, so that you have a single string like:

"Crime and punishment, page 10, page 40, page 30, ..."

instead of the more useful list of titles and integers. Some people have 
suggested using regular expressions to process the page numbers. That's 
fine, but it's rather overkill, like using a bulldozer to move a 
shovelful of dirt. Here's an (untested) filter to convert the one long 
string into a list of titles and integer pages:

result = []
for item in long_string.split(','):
    item = item.strip()  # get rid of leading and trailing spaces
    if item.startswith('page '):
        item = int(item[5:])
    result.append(item)

This assumes the data is well-formed, there are no typos such as "pgae 
15" in the data, and most importantly, no commas in the book titles.

This can be written as a two-liner, at the cost of some readability:

items = [item.strip() for item in long_string.split(',')]
result = [int(s[5:]) if s.startswith('page ') else s for s in items]

Making it into a one-liner is left as an exercise for the masochistic.


This demonstrates the basic principle of data processing of this kind. 
You start with a bunch of data in one form, and you transform it into 
another, slightly different and more useful form, using a series on 
individual filters or transformation functions:

Start with one long string.
Divide it into a list of substrings.
Transform it into a list o

Re: [Tutor] Path?

2010-07-14 Thread Adam Bark
On 14 July 2010 02:53, Jim Byrnes  wrote:

> Adam Bark wrote:
>
> 
>
>
>  If I use the terminal to start the program it has no problem using the
> file.  There are multiple files in multiple directories so I was
> looking
> for
> a way to just double click them and have them run.  If it turns out
> that
> I
> must make changes to or for each of the files it will be easier to just
> keep
> using the terminal.  I've only been using Ubuntu for a few months so I
> was
> surprised that the program could not see a file that is in the same
> directory.
>
> Regards,  Jim
>
>

 The problem is ubuntu doesn't run the script from the directory it's in
 so
 it's looking for wxPython.jpg somewhere else.


  OK, I mistakenly thought that double-clicking on file in Nautilus would
>>> take care of the path info.
>>>
>>> In my reply above I also mentioned that I tried by dropping it on a
>>> Launcher on the top panel and that the command the launcher uses is
>>> usr/bin/python2.6.  Is there a way that the command can be changed so
>>> that
>>> it will look in the same directory the python script is in for any file
>>> it
>>> needs?
>>>
>>> Thanks,  Jim
>>>
>>
>>
>> Not sure if you got my previous email but you could try writing the bash
>> script I posted (with the $1 line to get the path) and setting that as
>> your
>> launcher, I think it should work.
>>
>> Let me know if you didn't get it or it doesn't work.
>>
>> HTH,
>> Adam.
>>
>>
> I got it, got sidetracked and then forgot to look at it again.  Thanks for
> reminding me.  Your idea works, but with one little downside.  The
> directories I am working with are chapters in a book.  So as I move from
> chapter to chapter I will need to change the bash script, but this seems to
> be less typing than using the terminal.
>
>
> Thanks,  Jim
>

Ok cool, glad it works. It might be possible to get the path so you don't
have to set it each time, try this:

 #!/bin/bash

IFS="/"
path=($1)
cd $(path[0:#path[*]])
python $1


# Warning, I'm not exactly a competent bash programmer so this may not work
:-p

Let me know if you need a hand to fix it,

HTH,
Adam.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Response to responses about list of lists: a meta exercise in mailinglist recursion

2010-07-14 Thread Steven D'Aprano
On Wed, 14 Jul 2010 11:53:38 pm Siren Saren wrote:
> Steven D'Aprano,
>
> Your response was profoundly helpful to me.
[...]

Thank you for the kind words, and cheers! I wish you good fortunate and 
a lot of fun in your endeavour.

> I thought something in the culture of programming was particularly
> intolerant of the sort of errors I'd make, perhaps because of the
> syntactic precision required to program well.

Programmers, especially *mediocre* programmers, are often well known for 
their arrogance and rudeness. Sometimes this arrogance is justified; 
often it is not.

Remember also that, sadly, the Internet encourages rudeness. You can 
easily fire off an instant response without thinking about the 
consequences; there is anonymity and the urge to show off; there is the 
urge to win the argument no matter what. I admit that sometimes I fall 
into this trap myself. If I've had a bad day at work, or have had to 
put up with one too many annoyance, sometimes I might be a bit 
short-tempered. I would like to hope only at those who deserve it, but 
I'm only human.

But fortunately, the Python community is usually much, much friendlier 
than some other places. Perhaps that's because Python is a programming 
language designed to be usable by people of all levels, from beginners 
and children to programming geniuses. With a willingness to learn and a 
little bit of care, I am sure you will be fine.

You might like to read this:

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

Take it with a grain of salt -- not every smart programmer or hacker is 
as anti-social as described, but nevertheless, the basic principles are 
sound.



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Global name not found, though clearly in use

2010-07-14 Thread Corey Richardson

Hey tutors. Two separate submissions one day, guess I'm getting busy ;)

Anyway, I'm re-writing my hangman program to make use of my new-found 
understanding of OOP, and using a GUI this time around. I decided on 
coding with Tkinter, to get my feet wet with GUI stuff.

Here is the traceback:

Traceback (most recent call last):
 File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__
   return self.func(*args)
 File "C:/Users/Corey/Desktop/HangmanApp.py", line 45, in getLetter
   self.guess = eWordEntryBox.get()
NameError: global name 'eWordEntryBox' is not defined

However, not even 30 lines down, (29, to be exact) there is this line:
   eWordEntryBox = tk.Entry(fWordEntry)

Not understanding what is happening here. Same happens when I tack self 
at the beginning of it, except it says global name self is not defined.


Thanks!
~Corey Richardson
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global name not found, though clearly in use

2010-07-14 Thread Nitin Pawar
>From the logs looks like the variable is not initiated when it was used.

If I read it correct, you said it down ... that means below the line where
the error came? and if they belong to same function then this error is valid

Thanks,
Nitin

On Wed, Jul 14, 2010 at 7:48 PM, Corey Richardson  wrote:

> Hey tutors. Two separate submissions one day, guess I'm getting busy ;)
>
> Anyway, I'm re-writing my hangman program to make use of my new-found
> understanding of OOP, and using a GUI this time around. I decided on coding
> with Tkinter, to get my feet wet with GUI stuff.
> Here is the traceback:
>
> Traceback (most recent call last):
>  File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__
>   return self.func(*args)
>  File "C:/Users/Corey/Desktop/HangmanApp.py", line 45, in getLetter
>   self.guess = eWordEntryBox.get()
> NameError: global name 'eWordEntryBox' is not defined
>
> However, not even 30 lines down, (29, to be exact) there is this line:
>   eWordEntryBox = tk.Entry(fWordEntry)
>
> Not understanding what is happening here. Same happens when I tack self at
> the beginning of it, except it says global name self is not defined.
>
> Thanks!
> ~Corey Richardson
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Nitin Pawar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Help execution time calculation:

2010-07-14 Thread Vineeth Rakesh
Hello all,

I want to calculate the execution time of a program. Say I have a function
like below:

def RepAdd(i):
  j = 0
  while(j___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global name not found, though clearly in use

2010-07-14 Thread Steven D'Aprano
On Thu, 15 Jul 2010 12:18:58 am Corey Richardson wrote:
> Hey tutors. Two separate submissions one day, guess I'm getting busy
> ;)
>
> Anyway, I'm re-writing my hangman program to make use of my new-found
> understanding of OOP, and using a GUI this time around. I decided on
> coding with Tkinter, to get my feet wet with GUI stuff.

With respect, I'm not sure your new-found understanding is that 
complete, if you're having problems with simple variables. Have you 
considered doing some basic tutorials to ensure your understanding of 
Python has a solid foundation?

> Here is the traceback:
>
> Traceback (most recent call last):
>   File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__
> return self.func(*args)
>   File "C:/Users/Corey/Desktop/HangmanApp.py", line 45, in getLetter
> self.guess = eWordEntryBox.get()
> NameError: global name 'eWordEntryBox' is not defined
>
> However, not even 30 lines down, (29, to be exact) there is this
> line: eWordEntryBox = tk.Entry(fWordEntry)

Without seeing your actual code, it's impossible to say what's going on 
except in vague generalities. But consider a program made of just TWO 
lines:

print(x)
x = 1

What do you expect will happen? If you are surprised that Python will 
raise NameError when it tries to print the value of x, then you really 
should do some basic tutorials.

At the point that the line "print x" is called, x hasn't been defined 
*yet*, and so it doesn't exist. My guess is that your error is exactly 
the same -- you might have a line that defines eWordEntryBox 29 lines 
further down, but at the point that the error occurs, that line hasn't 
been reached yet, and so eWordEntryBox doesn't exist:

self.guess = eWordEntryBox.get()  # Error occurs here
...
...
29 lines of code
...
...
eWordEntryBox = tk.Entry(fWordEntry)  # Defined for the first time!


> Not understanding what is happening here. Same happens when I tack
> self at the beginning of it, except it says global name self is not
> defined.

You can't just "tack" self at the beginning of variables and expect it 
to work, any more than you could tack on "akjfhbcvgsaj" and hope for 
the best! You need to understand *where* the variable self exists, and 
*what* value it has.




-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help execution time calculation:

2010-07-14 Thread Steven D'Aprano
On Thu, 15 Jul 2010 01:11:58 am Vineeth Rakesh wrote:
> Hello all,
>
> I want to calculate the execution time of a program. Say I have a
> function like below:
>
> def RepAdd(i):
>   j = 0
>   while(j  j += 1
>   return j
>
> now I want to calculate the execution time of the function RepAdd
> when say 10 is passed as an argument. I did come across the module
> timeit, if that is the module to be used can any one illustrate it
> using the above program as input.

timeit is the *right* solution for timing small code snippets like 
RepAdd above, but the recipe for using it can appear a little 
mysterious.

If you have RepAdd in a file "test.py", then from the command line:

python -m timeit -s "from test import RepAdd" "RepAdd(10)"

should work.

Otherwise, type RepAdd into the Python interactive interpreter, or into 
IDLE, and then do this:

from timeit import Timer
t = Timer('RepAdd(10)', 'from __main__ import RepAdd')
print(min(t.repeat()))



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global name not found, though clearly in use

2010-07-14 Thread Corey Richardson
 I was under the impression that when you define a function, it doesn't 
try to evaluate anything yet. If I had called the function before I 
defined the variable, I would understand, but I haven't. The entirety of 
my (incomplete and buggy) code is now available here: 
http://pastebin.com/QTNmKYC6


Steven D'Aprano wrote:

On Thu, 15 Jul 2010 12:18:58 am Corey Richardson wrote:
  

Hey tutors. Two separate submissions one day, guess I'm getting busy
;)

Anyway, I'm re-writing my hangman program to make use of my new-found
understanding of OOP, and using a GUI this time around. I decided on
coding with Tkinter, to get my feet wet with GUI stuff.



With respect, I'm not sure your new-found understanding is that 
complete, if you're having problems with simple variables. Have you 
considered doing some basic tutorials to ensure your understanding of 
Python has a solid foundation?


  

Here is the traceback:

Traceback (most recent call last):
  File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__
return self.func(*args)
  File "C:/Users/Corey/Desktop/HangmanApp.py", line 45, in getLetter
self.guess = eWordEntryBox.get()
NameError: global name 'eWordEntryBox' is not defined

However, not even 30 lines down, (29, to be exact) there is this
line: eWordEntryBox = tk.Entry(fWordEntry)



Without seeing your actual code, it's impossible to say what's going on 
except in vague generalities. But consider a program made of just TWO 
lines:


print(x)
x = 1

What do you expect will happen? If you are surprised that Python will 
raise NameError when it tries to print the value of x, then you really 
should do some basic tutorials.


At the point that the line "print x" is called, x hasn't been defined 
*yet*, and so it doesn't exist. My guess is that your error is exactly 
the same -- you might have a line that defines eWordEntryBox 29 lines 
further down, but at the point that the error occurs, that line hasn't 
been reached yet, and so eWordEntryBox doesn't exist:


self.guess = eWordEntryBox.get()  # Error occurs here
...
...
29 lines of code
...
...
eWordEntryBox = tk.Entry(fWordEntry)  # Defined for the first time!


  

Not understanding what is happening here. Same happens when I tack
self at the beginning of it, except it says global name self is not
defined.



You can't just "tack" self at the beginning of variables and expect it 
to work, any more than you could tack on "akjfhbcvgsaj" and hope for 
the best! You need to understand *where* the variable self exists, and 
*what* value it has.





  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Searching a text file's contents and comparing them to a list

2010-07-14 Thread Eric Hamiter
Hi all,

New programmer here. This is what I want to do:

1. Open an existing text file named "grocery_list.txt", which has one
item per line, like so:

butter
juice
bread
asparagus
magazines
ice cream

2. ...and search for these items in a pre-defined list.

But I can't seem to get this working. Right now after trying the following:


aisle_one = ["chips", "bread", "pretzels", "magazines"]

grocery_list = open("grocery_list.txt", "r")
for line in grocery_list.readlines():
if line in aisle_one:
   print "success"
else:
   print "no joy"
grocery_list.close()


I get this:

no joy
no joy
no joy
no joy
no joy
no joy

when I'm expecting this:

no joy
no joy
success
no joy
success
no joy


Am I close? This seems like it should work but I'm obviously missing something.

Thanks,

Eric
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global name not found, though clearly in use

2010-07-14 Thread Emile van Sebille

On 7/14/2010 8:31 AM Corey Richardson said...

I was under the impression that when you define a function, it doesn't
try to evaluate anything yet. If I had called the function before I
defined the variable, I would understand, but I haven't.



The difference is in understanding what's executed and what's deferred.

Consider the following:

#-Start File test.py-
def test():
  print "in def test"

class Test:
  print "in class Test"
  def __init__(self):
print "in class Test.__init__"

print "in __main__"

test()
t = Test()

#-End File test.py-

Output:

in class Test
in __main__
in def test
in class Test.__init__

-

As you can see, the print statements at the class level are executing 
when encountered, but the prints in defs only when executed.


HTH,

Emile


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching a text file's contents and comparing them to a list

2010-07-14 Thread Emile van Sebille

On 7/14/2010 8:46 AM Eric Hamiter said...

Hi all,

New programmer here. This is what I want to do:

1. Open an existing text file named "grocery_list.txt", which has one
item per line, like so:

butter
juice
bread
asparagus
magazines
ice cream

2. ...and search for these items in a pre-defined list.

But I can't seem to get this working. Right now after trying the following:


aisle_one = ["chips", "bread", "pretzels", "magazines"]

grocery_list = open("grocery_list.txt", "r")
for line in grocery_list.readlines():
 if line in aisle_one:


So it's failing this test.


print "success"
 else:
print "no joy"


Try adding some debugging code here, maybe changing the print to:
  print "no joy matching %s" % line

Then read up on readlines and string.strip.

HTH,

Emile


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching a text file's contents and comparing them to a list

2010-07-14 Thread Eric Hamiter
Fantastic! I have this, which now works. Is there a better place to put
string.strip?

aisle_one = ["chips", "bread", "pretzels", "magazines"]

grocery_list = open("grocery_list.txt", "r")
for line in grocery_list.readlines():
if line.strip() in aisle_one:
   print "success! i found %s" % line
else:
   print "no joy matching %s" % line
grocery_list.close()


Thanks Emile.


On Wed, Jul 14, 2010 at 11:02 AM, Emile van Sebille  wrote:


> Try adding some debugging code here, maybe changing the print to:
>  print "no joy matching %s" % line
>
> Then read up on readlines and string.strip.
>
> HTH,
>
> Emile
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global name not found, though clearly in use

2010-07-14 Thread Corey Richardson




Hmm..If
I add a few debugging lines like that into my code, I get this:


Starting program

In class Hangman

done defs in class

eWordEntryBox defined

Exception in Tkinter callback

Traceback (most recent call last):

 File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__

   return self.func(*args)

 File "C:/Users/Corey/Desktop/HangmanApp.py", line 48, in getLetter

   self.guess = eWordEntryBox.get()

NameError: global name 'eWordEntryBox' is not defined


I have the line "eWordEntryBox" right after the definition.


Emile van Sebille wrote:

The difference is in understanding what's
executed and what's deferred.
  
  
Consider the following:
  
  
#-Start File test.py-
  
def test():
  
  print "in def test"
  
  
class Test:
  
  print "in class Test"
  
  def __init__(self):
  
    print "in class Test.__init__"
  
  
print "in __main__"
  
  
test()
  
t = Test()
  
  
#-End File test.py-
  
  
Output:
  
  
in class Test
  
in __main__
  
in def test
  
in class Test.__init__
  
  
-
  
  
As you can see, the print statements at the class level are executing
when encountered, but the prints in defs only when executed.
  
  
HTH,
  
  
Emile
  
  
  
___
  
Tutor maillist  -  Tutor@python.org
  
To unsubscribe or change subscription options:
  
  http://mail.python.org/mailman/listinfo/tutor
  
  





___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Path?

2010-07-14 Thread Jim Byrnes

Adam Bark wrote:

On 14 July 2010 02:53, Jim Byrnes  wrote:


Adam Bark wrote:




  If I use the terminal to start the program it has no problem using the

file.  There are multiple files in multiple directories so I was
looking
for
a way to just double click them and have them run.  If it turns out
that
I
must make changes to or for each of the files it will be easier to just
keep
using the terminal.  I've only been using Ubuntu for a few months so I
was
surprised that the program could not see a file that is in the same
directory.

Regards,  Jim




The problem is ubuntu doesn't run the script from the directory it's in
so
it's looking for wxPython.jpg somewhere else.


  OK, I mistakenly thought that double-clicking on file in Nautilus would

take care of the path info.

In my reply above I also mentioned that I tried by dropping it on a
Launcher on the top panel and that the command the launcher uses is
usr/bin/python2.6.  Is there a way that the command can be changed so
that
it will look in the same directory the python script is in for any file
it
needs?

Thanks,  Jim




Not sure if you got my previous email but you could try writing the bash
script I posted (with the $1 line to get the path) and setting that as
your
launcher, I think it should work.

Let me know if you didn't get it or it doesn't work.

HTH,
Adam.



I got it, got sidetracked and then forgot to look at it again.  Thanks for
reminding me.  Your idea works, but with one little downside.  The
directories I am working with are chapters in a book.  So as I move from
chapter to chapter I will need to change the bash script, but this seems to
be less typing than using the terminal.


Thanks,  Jim



Ok cool, glad it works. It might be possible to get the path so you don't
have to set it each time, try this:

#!/bin/bash
IFS="/"
path=($1)
cd $(path[0:#path[*]])
python $1


# Warning, I'm not exactly a competent bash programmer so this may not work
:-p

Let me know if you need a hand to fix it,

HTH,
Adam.



I tried the new bash code but when I dropped a file on the launcher it 
just flashed an gave no output.  So I tried running the bash script 
(name=runpython) in a terminal and got this error:


/home/jfb/runpython: line 4: path[0:#path[*]]: command not found
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

I know even less about bash than you do, so I don't where to start to 
debug this.


Thanks,  Jim

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching a text file's contents and comparing them to a list

2010-07-14 Thread Emile van Sebille

On 7/14/2010 9:22 AM Eric Hamiter said...

Fantastic! I have this, which now works. Is there a better place to put
string.strip?


I might make the changes below, but there's nothing wrong with the way 
you've got it.




aisle_one = ["chips", "bread", "pretzels", "magazines"]

grocery_list = open("grocery_list.txt", "r")


grocery_list= [ item.strip()
   for item in open("grocery_list.txt", "r").readlines() ]


for line in grocery_list.readlines():


for item in grocery_list:


 if line.strip() in aisle_one:


if item in aisle_one:


print "success! i found %s" % line
 else:
print "no joy matching %s" % line
grocery_list.close()




___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global name not found, though clearly in use

2010-07-14 Thread Dave Angel

Corey Richardson wrote:
The entirety of 
my (incomplete and buggy) code is now available here: 
http://pastebin.com/QTNmKYC6  ..

Hmm..If I add a few debugging lines like that into my code, I get this:

Starting program
In class Hangman
done defs in class
eWordEntryBox defined
Exception in Tkinter callback
Traceback (most recent call last):
 File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__
   return self.func(*args)
 File "C:/Users/Corey/Desktop/HangmanApp.py", line 48, in getLetter
   self.guess = eWordEntryBox.get()
NameError: global name 'eWordEntryBox' is not defined


  
Why do you indent the main code in this file?  In particular, you've 
defined the lines starting at


  1.
 top = tk.Tk()
  2.
 F = tk.Frame(top)
  3.
 F.pack()

as part of the class, rather than at top-level.  Therefore the 
eWordEntryBox is a class attribute, rather than a global symbol.


I think you need to unindent those lines, so they'll be module-level code.

There are a bunch more problems with the code, starting with the fact 
that you never instantiate a Hangman instance, and continuing to missing 
self parameters on some of the methods.


DaveA



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global name not found, though clearly in use

2010-07-14 Thread Alan Gauld


"Corey Richardson"  wrote

defined the variable, I would understand, but I haven't. The 
entirety of

my (incomplete and buggy) code is now available here:
http://pastebin.com/QTNmKYC6


There are quite a few errors here, one is that many of your class's 
methods
don't have self as their first parameter, rendering them pretty 
useless.

Also you do not create an instance of the class Hangman anywhere.

The only access of eWordEntryBox seems to be in the getletter()
function (one of those weith no self). But that should only cause
an error when called...which it never is.

Are you sure thats the code that is creating the error message?

Alan G. 



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global name not found, though clearly in use

2010-07-14 Thread Emile van Sebille

On 7/14/2010 9:33 AM Corey Richardson said...

Hmm..If I add a few debugging lines like that into my code, I get this:


The point was that statements in a class at class level (ie, not in 
defs) are executed sequentially and expect referenced variables to exist 
(ie, defined somewhere 'above' the current statement) -- there is no 
forward peeking going on.  Statements within def's (think 'deferred 
execution' if it helps) expect that the variables referred to will exist 
by the time the def is invoked.


Python executes code top to bottom.  def's create an executable object 
and defers execution until invoked.  Other statements execute when 
encountered.  The statements in your class that start


top = tk.Tk()
thru...
F.mainloop()

execute in top-down sequence as they are outside of def's.  That's your 
problem.  It's unusual to have that done within a class definition and I 
expect it shouldn't be there.


HTH,

Emile

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching a text file's contents and comparing them toa list

2010-07-14 Thread Alan Gauld


"Eric Hamiter"  wrote

Fantastic! I have this, which now works. Is there a better place to 
put

string.strip?


Its largely a matter of taste and how you intend using the value.


aisle_one = ["chips", "bread", "pretzels", "magazines"]

grocery_list = open("grocery_list.txt", "r")
for line in grocery_list.readlines():


You could improve that with

for line in open('grocery_list.txt'):

ie no need for readlines()

Or if using recent(post 2.5) versions of Python you could use with:

with open('grocery_list.txt') as grocery_list:
 for line in grocery_list:

which will ensure the file is closed correctly without you
having to do it yourself. This is probably the best option.


   if line.strip() in aisle_one:
  print "success! i found %s" % line


If you never need a stripped version of line again, or if you
are planning on writing it out to another file then this is fine.
If you are going to use it again its probably better to strip()
and asign to itelf:

line = line.strip()

Also you might find rstrip() slightly safer if you have any
unusual characters at the start of line...

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


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Handling 'None' (null) values when processing sqlite cursorresults

2010-07-14 Thread Alan Gauld


"Christian Witts"  wrote


You need a display function that can strip out the nulls as needed.
A simple list comprehension or generator expression would work
in this case:
print ' '.join(str(field) for field in data if field is not 
'None')


The problem with that is if you're relying on a set delimiter you 
are removing elements so you would be better served by doing 
`str(field) if field != None else '' for field in record`


True, although in this case we do seem to have a fixed condition
since it's the database's representation of null but I originally 
didn't

notice the quotes around None. When I fixed that I should have
changed is to equals..


print ' '.join(str(field) for field in data if field != 'None')


But your modification confuses me. can you explain?
What would the print line look like?

Alan G. 



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching a text file's contents and comparing them toa list

2010-07-14 Thread Eric Hamiter
On Wed, Jul 14, 2010 at 12:26 PM, Alan Gauld wrote:

>
> If you never need a stripped version of line again, or if you
> are planning on writing it out to another file then this is fine.
> If you are going to use it again its probably better to strip()
> and asign to itelf:
>
> line = line.strip()
>
> Also you might find rstrip() slightly safer if you have any
> unusual characters at the start of line...
>

Thanks for the tip Alan, I think I'll assign it to itself.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Path?

2010-07-14 Thread Adam Bark
On 14 July 2010 17:41, Jim Byrnes  wrote:

> Adam Bark wrote:
>
>> On 14 July 2010 02:53, Jim Byrnes  wrote:
>>
>>  Adam Bark wrote:
>>>
>>> 
>>>
>>>
>>>  If I use the terminal to start the program it has no problem using the
>>>
  file.  There are multiple files in multiple directories so I was
>>> looking
>>> for
>>> a way to just double click them and have them run.  If it turns out
>>> that
>>> I
>>> must make changes to or for each of the files it will be easier to
>>> just
>>> keep
>>> using the terminal.  I've only been using Ubuntu for a few months so
>>> I
>>> was
>>> surprised that the program could not see a file that is in the same
>>> directory.
>>>
>>> Regards,  Jim
>>>
>>>
>>>
>> The problem is ubuntu doesn't run the script from the directory it's
>> in
>> so
>> it's looking for wxPython.jpg somewhere else.
>>
>>
>>  OK, I mistakenly thought that double-clicking on file in Nautilus
>> would
>>
> take care of the path info.
>
> In my reply above I also mentioned that I tried by dropping it on a
> Launcher on the top panel and that the command the launcher uses is
> usr/bin/python2.6.  Is there a way that the command can be changed so
> that
> it will look in the same directory the python script is in for any file
> it
> needs?
>
> Thanks,  Jim
>
>

 Not sure if you got my previous email but you could try writing the bash
 script I posted (with the $1 line to get the path) and setting that as
 your
 launcher, I think it should work.

 Let me know if you didn't get it or it doesn't work.

 HTH,
 Adam.


  I got it, got sidetracked and then forgot to look at it again.  Thanks
>>> for
>>> reminding me.  Your idea works, but with one little downside.  The
>>> directories I am working with are chapters in a book.  So as I move from
>>> chapter to chapter I will need to change the bash script, but this seems
>>> to
>>> be less typing than using the terminal.
>>>
>>>
>>> Thanks,  Jim
>>>
>>>
>> Ok cool, glad it works. It might be possible to get the path so you don't
>> have to set it each time, try this:
>>
>> #!/bin/bash
>> IFS="/"
>> path=($1)
>> cd $(path[0:#path[*]])
>> python $1
>>
>>
>> # Warning, I'm not exactly a competent bash programmer so this may not
>> work
>> :-p
>>
>> Let me know if you need a hand to fix it,
>>
>> HTH,
>> Adam.
>>
>>
> I tried the new bash code but when I dropped a file on the launcher it just
> flashed an gave no output.  So I tried running the bash script
> (name=runpython) in a terminal and got this error:
>
> /home/jfb/runpython: line 4: path[0:#path[*]]: command not found
> Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
> [GCC 4.4.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>>
>
> I know even less about bash than you do, so I don't where to start to debug
> this.
>
>
> Thanks,  Jim
>
> Ok then, this time it's tested and not just improvised, here we go:

#!/bin/bash

script=$1 # Full path for calling the script later
orig_IFS=$IFS # This is to reset IFS so that "script" is correct (otherwise
has spaces instead of /)
IFS="/"
path=( $1 )
IFS=$orig_IFS
last_ind=${#pa...@]} # Works out the length of path
let "last_ind -= 1" # Sets last_ind to index of script name
len_path=${pa...@]:0:last_ind} # Gets the path without the script name
let "len_path=${#len_path[0]} + 1" # This gives the length of the script
string upto just before the last /
cd ${scri...@]:0:len_path} # cds to the path
python script


As pretty much my first non-trivial bash script it's probably horrible but
it seems to work.

HTH,
Adam.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global name not found, though clearly in use

2010-07-14 Thread Serdar Tumgoren
>  Hmm..If I add a few debugging lines like that into my code, I get this:
>>
>
> The point was that statements in a class at class level (ie, not in defs)
> are executed sequentially and expect referenced variables to exist (ie,
> defined somewhere 'above' the current statement) -- there is no forward
> peeking going on.  Statements within def's (think 'deferred execution' if it
> helps) expect that the variables referred to will exist by the time the def
> is invoked.
>
> Python executes code top to bottom.  def's create an executable object and
> defers execution until invoked.  Other statements execute when encountered.
>  The statements in your class that start
>
>
Aside from other scattered problems with the code, Emile's explanation seems
to get at the core of the OP's confusion. But I was wondering (for my own
edification), can anyone point to the portion of the docs that clearly
spells out the order of execution (top to bottom, classes vs. functions,
etc.). The only place I've encountered such a discussion of execution order
was in Chapter 2 of Pro Django, and the below doc pages don't seem to
address the issue head-on (unless I'm misunderstanding or missed something):

http://docs.python.org/tutorial/classes.html
http://docs.python.org/reference/executionmodel.html

Thanks!
Serdar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] str format conversion help

2010-07-14 Thread eMyListsDDg

'\x00\x11\xb2\x00@,O\xa4'


the above str is being returned from one key/value pair in a dictionary. it is 
the addr of a network device.


i want to store the addr's in their 8byte mac format like this,

[00 11 b2 00 40 2C 4F A4]

the combinations of format strings using the print statement hasn't resulted in 
what i need.


looking for a suggestion on how to format this, '\x00\x11\xb2\x00@,O\xa4' into 
this [00-11-B2-00-40-2C-4F-A4]


tia
 
Best regards,
 eMyListsDDgmailto:emylists...@gmail.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] str format conversion help

2010-07-14 Thread Steve Willoughby

On 14-Jul-10 11:35, eMyListsDDg wrote:


'\x00\x11\xb2\x00@,O\xa4'


the above str is being returned from one key/value pair in a dictionary. it is 
the addr of a network device.


i want to store the addr's in their 8byte mac format like this,

 [00 11 b2 00 40 2C 4F A4]

the combinations of format strings using the print statement hasn't resulted in 
what i need.


A few hints:

Remember that the string is a set of raw binary values, so using ord() 
on each character would give you the numbers you can then have 
str.format() render as hex values.


You might also find the struct module helpful.



looking for a suggestion on how to format this, '\x00\x11\xb2\x00@,O\xa4' into 
this [00-11-B2-00-40-2C-4F-A4]


tia

Best regards,
  eMyListsDDgmailto:emylists...@gmail.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching a text file's contents and comparing them toa list

2010-07-14 Thread Eric Hamiter
Follow-up question: My code is now this:

aisle_one = ["chips", "bread", "pretzels", "magazines"]
aisle_two = ["juice", "ice cream"]
aisle_three = ["asparagus"]

def find_groceries():
grocery_list = open("grocery_list.txt", "r")
for line in grocery_list.readlines():
line = line.strip()
if line in aisle_one:
first_run = "%s" % line + " - aisle one.\n"
elif line in aisle_two:
second_run = "%s" % line + " - aisle two.\n"
elif line in aisle_three:
third_run = "%s" % line + " - aisle three.\n"
else:
out_of_luck = "%s" % line
print first_run, second_run, third_run
print "I couldn't find any %s. Add it to the database. \n" % out_of_luck
grocery_list.close()

find_groceries()


I can see that the variables first_run, second_run and third_run are
writing over themselves while looping, which is logical, but this is
not what I want. If I simply print them immediately instead of storing
them as variables, all items will print, but not in the order I wish.
The ultimate goal of the program will be to sort the items based on
aisle locations. Is there an efficient way to do this?

I think I want some kind of incremental counter going on in the loop
to prevent them from overwriting themselves, or a way to store
multiple variables, but I'm not sure how to do that.

Thanks for any ideas. This list and all its participants are super
helpful-- I'm very appreciative.

Eric
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching a text file's contents and comparing them toa list

2010-07-14 Thread Luke Paireepinart
You already know how to store multiple vars -- use lists! Just create a blank 
one before your loop and append() to it. Also you might think of a generic way 
to do this without relying on separate variables for each aisle, what if your 
store has 30 aisles? Hint: lists can contain any python object, even other 
lists.

Sent from my iPhone

On Jul 14, 2010, at 2:05 PM, Eric Hamiter  wrote:

> Follow-up question: My code is now this:
> 
> aisle_one = ["chips", "bread", "pretzels", "magazines"]
> aisle_two = ["juice", "ice cream"]
> aisle_three = ["asparagus"]
> 
> def find_groceries():
>grocery_list = open("grocery_list.txt", "r")
>for line in grocery_list.readlines():
>line = line.strip()
>if line in aisle_one:
>first_run = "%s" % line + " - aisle one.\n"
>elif line in aisle_two:
>second_run = "%s" % line + " - aisle two.\n"
>elif line in aisle_three:
>third_run = "%s" % line + " - aisle three.\n"
>else:
>out_of_luck = "%s" % line
>print first_run, second_run, third_run
>print "I couldn't find any %s. Add it to the database. \n" % out_of_luck
>grocery_list.close()
> 
> find_groceries()
> 
> 
> I can see that the variables first_run, second_run and third_run are
> writing over themselves while looping, which is logical, but this is
> not what I want. If I simply print them immediately instead of storing
> them as variables, all items will print, but not in the order I wish.
> The ultimate goal of the program will be to sort the items based on
> aisle locations. Is there an efficient way to do this?
> 
> I think I want some kind of incremental counter going on in the loop
> to prevent them from overwriting themselves, or a way to store
> multiple variables, but I'm not sure how to do that.
> 
> Thanks for any ideas. This list and all its participants are super
> helpful-- I'm very appreciative.
> 
> Eric
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] str format conversion help

2010-07-14 Thread Alan Gauld


"eMyListsDDg"  wrote 

First please start new threads wirth a new email, do not reply to 
a previous post - it confuses threaded readers. (and sometimes 
human readers too!)



'\x00\x11\xb2\x00@,O\xa4'

the above str is being returned from one key/value pair in 
a dictionary. it is the addr of a network device.


i want to store the addr's in their 8byte mac format like this,

   [00 11 b2 00 40 2C 4F A4]


Thats what you've got. The string is merely a representation 
of that data.


the combinations of format strings using the print statement 
hasn't resulted in what i need.


format strings are used to display data not to store it.
Do you really want to display the data in the format you've 
shown? Or do you really want to store it as 8 bytes?


The two concepts are completely different and more 
or less unrelated.


looking for a suggestion on how to format this, 
'\x00\x11\xb2\x00@,O\xa4' into this [00-11-B2-00-40-2C-4F-A4]


OK, to display it you need to extract each byte and convert it to 
a string representing the hex value. Fortunately you an treat a 
string of bytes as charactrers and the hex() function will give you 
the hex representation. So...


print "[%s]" % ('-'.join([hex(v) for v in theValue]) )

should be close...

HTH,


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


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching a text file's contents and comparing them toalist

2010-07-14 Thread Alan Gauld


"Eric Hamiter"  wrote


aisle_one = ["chips", "bread", "pretzels", "magazines"]
aisle_two = ["juice", "ice cream"]
aisle_three = ["asparagus"]

def find_groceries():
   grocery_list = open("grocery_list.txt", "r")
   for line in grocery_list.readlines():


See previous about removing the redundant readlines()


   line = line.strip()
   if line in aisle_one:
   first_run = "%s" % line + " - aisle one.\n"


The string formatting is redundant here since you assign a string to a 
string

You could just dio:

   first_run = line + " - aisle one.\n"


I can see that the variables first_run, second_run and third_run are
writing over themselves while looping, which is logical, but this is
not what I want. If I simply print them immediately instead of 
storing
them as variables, all items will print, but not in the order I 
wish.


So store the strings in a list then at the end print each list of 
strings.



The ultimate goal of the program will be to sort the items based on
aisle locations. Is there an efficient way to do this?


You can sort the lists before printing...


I think I want some kind of incremental counter going on in the loop
to prevent them from overwriting themselves, or a way to store
multiple variables, but I'm not sure how to do that.


No need for counters, just append() to a list.


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


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global name not found, though clearly in use

2010-07-14 Thread Emile van Sebille

On 7/14/2010 11:11 AM Serdar Tumgoren said...

But I was wondering (for my own
edification), can anyone point to the portion of the docs that clearly
spells out the order of execution (top to bottom, classes vs. functions,
etc.).


I found this in the tutorial in the modules section:
  ( see http://docs.python.org/tutorial/modules.html )

   "A module is a file containing Python definitions and statements."

Ergo, stuff that executes and stuff that defines.

Further clarification provided:
"""A module can contain executable statements as well as function 
definitions. These statements are intended to initialize the module. 
They are executed only the first time the module is imported somewhere."""


... and a Footnote:
"""In fact function definitions are also statements that are executed; 
the execution of a module-level function enters the function name in the 
modules global symbol table."""


The same applies to the class namespaces created and the contained defs.

As to the execution order, that's apparently buried in the c sources of 
the scanner and tokenizer bits.  I didn't see anything more specific 
than "stream processing" and "*file" pointers hinting at serial 
processing of the source py file.



I also found this interesting (but possibly not to newbies :) :
  http://www.shinetech.com/attachments/108_python-language-internals.pdf

Emile

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching a text file's contents and comparing them toalist

2010-07-14 Thread Eric Hamiter
Thanks for the pointers! This is now working, albeit probably ugly and clunky:


aisle_one = ["chips", "bread", "pretzels", "magazines"]
aisle_two = ["juice", "ice cream"]
aisle_three = ["asparagus"]

def find_groceries():
with open("grocery_list.txt") as grocery_list:

first_trip = ["Located on aisle 1: "]
second_trip = ["Located on aisle 2: "]
third_trip = ["Located on aisle 3: "]
no_trip = ["Not found in the database: "]

for item in grocery_list:
item = item.rstrip()
if item in aisle_one:
first_trip.append(item)
elif item in aisle_two:
second_trip.append(item)
elif item in aisle_three:
third_trip.append(item)
else:
no_trip.append(item)

sorted_list = first_trip, second_trip, third_trip, no_trip
print sorted_list

find_groceries()


Last question (for today, at least): Right now, the output is less
than aesthetically pleasing:

(['Located on aisle 1: ', 'bread', 'magazines'], ['Located on aisle 2:
', 'juice', 'ice cream'], ['Located on aisle 3: ', 'asparagus'], ['Not
found in the database: ', 'butter', 'soap'])

How can I format it so it looks more like this:

Located on aisle 1:
bread
magazines

Located on aisle 2
[etc...]


I tried putting "\n" into it but it just prints the literal string.
I'm sure it has to do with the list format of holding multiple items,
but so far haven't found a way to break them apart.

Thanks,

Eric
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching a text file's contents and comparing them to alist

2010-07-14 Thread davidheiserca


There are probably "return" characters at the end of each "line" from the 
"grocery_list".


Try using the String method "line.strip()".

Or "grocery_list.read().splitlines()"




- Original Message - 
From: "Eric Hamiter" 

To: 
Sent: Wednesday, July 14, 2010 8:46 AM
Subject: [Tutor] Searching a text file's contents and comparing them to 
alist




Hi all,

New programmer here. This is what I want to do:

1. Open an existing text file named "grocery_list.txt", which has one
item per line, like so:

butter
juice
bread
asparagus
magazines
ice cream

2. ...and search for these items in a pre-defined list.

But I can't seem to get this working. Right now after trying the 
following:



aisle_one = ["chips", "bread", "pretzels", "magazines"]

grocery_list = open("grocery_list.txt", "r")
for line in grocery_list.readlines():
   if line in aisle_one:
  print "success"
   else:
  print "no joy"
grocery_list.close()


I get this:

no joy
no joy
no joy
no joy
no joy
no joy

when I'm expecting this:

no joy
no joy
success
no joy
success
no joy


Am I close? This seems like it should work but I'm obviously missing 
something.


Thanks,

Eric
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor 


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global name not found, though clearly in use

2010-07-14 Thread Serdar Tumgoren
>
>
>>
> I also found this interesting (but possibly not to newbies :) :
>  http://www.shinetech.com/attachments/108_python-language-internals.pdf
>
> Very helpful, especially that last resource. Thank you!

Serdar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching a text file's contents and comparing them toalist

2010-07-14 Thread christopher . henk
Eric Hamiter wrote on 07/14/2010 04:57:57 PM:

> Thanks for the pointers! This is now working, albeit probably ugly and 
clunky:
> 
> 
> aisle_one = ["chips", "bread", "pretzels", "magazines"]
> aisle_two = ["juice", "ice cream"]
> aisle_three = ["asparagus"]
> 
> def find_groceries():
> with open("grocery_list.txt") as grocery_list:
> 
> first_trip = ["Located on aisle 1: "]
> second_trip = ["Located on aisle 2: "]
> third_trip = ["Located on aisle 3: "]
> no_trip = ["Not found in the database: "]
> 
> for item in grocery_list:
> item = item.rstrip()
> if item in aisle_one:
> first_trip.append(item)
> elif item in aisle_two:
> second_trip.append(item)
> elif item in aisle_three:
> third_trip.append(item)
> else:
> no_trip.append(item)
> 
> sorted_list = first_trip, second_trip, third_trip, no_trip
> print sorted_list
> 
> find_groceries()
> 
> 
> Last question (for today, at least): Right now, the output is less
> than aesthetically pleasing:
> 
> (['Located on aisle 1: ', 'bread', 'magazines'], ['Located on aisle 2:
> ', 'juice', 'ice cream'], ['Located on aisle 3: ', 'asparagus'], ['Not
> found in the database: ', 'butter', 'soap'])
> 
> How can I format it so it looks more like this:
> 
> Located on aisle 1:
> bread
> magazines
> 
> Located on aisle 2
> [etc...]
> 
> 
> I tried putting "\n" into it but it just prints the literal string.
> I'm sure it has to do with the list format of holding multiple items,
> but so far haven't found a way to break them apart.
> 


your sorted_list is a tuple of lists so when you print it python is 
showing you that structure.
You want the contents of each of those lists printed in a more readable 
format, so you need to loop through the tuple to get each list(trips down 
an aisle)and then within that loop, loop through each list to print each 
item.

in pseudo code to output like you suggest

for each aisle_list in sorted_list
for each item in the aisle_list
print the item
print the space (to separate the aisles, this is part of the loop 
through the tuple, so will run once for each aisle)


Instead of replacing the print statement with the above, I would have this 
as another function which takes sorted_list as a parameter, changing 
find_groceries to return sorted_list instead of printing it.  This keeps 
the two tasks separate and easier to understand and/or debug.

so the last lines of your program are:
sorted_list=find_groceries()
print_shoppinglist(sorted_list)

instead of just calling find_groceries()


Chris___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching a text file's contents and comparing them toalist

2010-07-14 Thread Nick Raptis

On 07/14/2010 11:57 PM, Eric Hamiter wrote:

Last question (for today, at least): Right now, the output is less
than aesthetically pleasing:

(['Located on aisle 1: ', 'bread', 'magazines'], ['Located on aisle 2:
', 'juice', 'ice cream'], ['Located on aisle 3: ', 'asparagus'], ['Not
found in the database: ', 'butter', 'soap'])

How can I format it so it looks more like this:

Located on aisle 1:
bread
magazines

Located on aisle 2
[etc...]


I tried putting "\n" into it but it just prints the literal string.
I'm sure it has to do with the list format of holding multiple items,
but so far haven't found a way to break them apart.


   
Readup on str.join() 
http://docs.python.org/library/stdtypes.html#str.join (link is not that 
helpful I admit, google some uses too)

For example,
print "\n".join(first_run)
will get you started.

I think the end code you're looking for is something like

output = ["\n".join(run) for run in sorted_list]
print "\n".join(output)

but I'm not sure if you've got the hang of list comprehensions by now.

Nick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Searching a text file's contents and comparing them toalist

2010-07-14 Thread bob gailer

[snip]

Since you look up the items in the grocery list it seems to me a 
dictionary relating each item to its aisle would be best.


inventory = {"chips" : 1, "bread" : 1, "pretzels" : 1, "magazines" : 1,
 "juice" : 2, "ice cream" : 2,
 "asparagus" : 3}
MAX_AISLE = 3
aisles = [[] for i in range(MAX_AISLE)]
for item in grocery_list:
  aisle = inventory.get(item.strip(), MAX_AISLE)
  aisles[aisle-1].append(item)

To address the formatting question:

for aisleNo, items in enumerate(aisles):
  if aisleNo < MAX_AISLE - 1:
print "Located on aisle %s" % aisleNo + 1
  else:
print "Not in store"
  print "\n".join(items)


--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] str format conversion help

2010-07-14 Thread eMyListsDDg
Steve,


glad you pointed that out. 

struct.unpack or something...i'll look into that module.

thx



> On 14-Jul-10 11:35, eMyListsDDg wrote:

>> '\x00\x11\xb2\x00@,O\xa4'


>> the above str is being returned from one key/value pair in a dictionary. it 
>> is the addr of a network device.


>> i want to store the addr's in their 8byte mac format like this,

>>  [00 11 b2 00 40 2C 4F A4]

>> the combinations of format strings using the print statement hasn't resulted 
>> in what i need.

> A few hints:

> Remember that the string is a set of raw binary values, so using ord() 
> on each character would give you the numbers you can then have 
> str.format() render as hex values.

> You might also find the struct module helpful.


>> looking for a suggestion on how to format this, '\x00\x11\xb2\x00@,O\xa4' 
>> into this [00-11-B2-00-40-2C-4F-A4]


>> tia

>> Best regards,
>>   eMyListsDDgmailto:emylists...@gmail.com

>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor

> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



-- 
Best regards,
 eMyListsDDgmailto:emylists...@gmail.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] str format conversion help

2010-07-14 Thread eMyListsDDg
Hello Alan,

> First please start new threads wirth a new email, do not reply to 

thought i did, my apologies.



> "eMyListsDDg"  wrote 

> First please start new threads wirth a new email, do not reply to 
> a previous post - it confuses threaded readers. (and sometimes 
> human readers too!)

>> '\x00\x11\xb2\x00@,O\xa4'

>> the above str is being returned from one key/value pair in 
>> a dictionary. it is the addr of a network device.

>> i want to store the addr's in their 8byte mac format like this,

>>[00 11 b2 00 40 2C 4F A4]

> Thats what you've got. The string is merely a representation 
> of that data.

>> the combinations of format strings using the print statement 
>> hasn't resulted in what i need.

> format strings are used to display data not to store it.
> Do you really want to display the data in the format you've 
> shown? Or do you really want to store it as 8 bytes?


the format shown. now that you point out a few things, it really wouldn't 
matter. 

> The two concepts are completely different and more 
> or less unrelated.

i see that now, as a newbie to python. 


>> looking for a suggestion on how to format this, 
>> '\x00\x11\xb2\x00@,O\xa4' into this [00-11-B2-00-40-2C-4F-A4]

> OK, to display it you need to extract each byte and convert it to 
> a string representing the hex value. Fortunately you an treat a 
> string of bytes as charactrers and the hex() function will give you 
> the hex representation. So...

> print "[%s]" % ('-'.join([hex(v) for v in theValue]) )

helps me to understand the concept differences you pointed out better

appreciate the help...


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Handling 'None' (null) values when processing sqlite cursorresults

2010-07-14 Thread Monte Milanuk

On 7/14/10 5:32 AM, Alan Gauld wrote:


The key principle is do not try to store your data in a display format.


Never was my intention.  I just hadn't anticipated needing to write my 
own function to handle something as (I would think) common as a NULL 
value in a database field.


I had been working with something very simple like:

for lines in cursor.fetchall()
title = lines[1]
first = lines[2]
mid = lines[3]
last = lines[4]
...

print "%s %s %s %s" % (title, first, mid, last)
print "%s" % (street)
print "%s, %s %s" % (city, state, zipcode)
print "%s" % (phone)
print "%s" % (email)

etc. etc.  for one format (supposed to look like a mailing label, more 
or less), and then I was going to experiment with other formatting later.


I'll work with the stuff you all have provided as I get time... thanks a 
bunch!


Monte

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Handling 'None' (null) values when processing sqlite cursorresults

2010-07-14 Thread Christian Witts

On 14/07/2010 19:34, Alan Gauld wrote:


"Christian Witts"  wrote


You need a display function that can strip out the nulls as needed.
A simple list comprehension or generator expression would work
in this case:

print ' '.join(str(field) for field in data if field is not 'None')

The problem with that is if you're relying on a set delimiter you are 
removing elements so you would be better served by doing `str(field) 
if field != None else '' for field in record`


True, although in this case we do seem to have a fixed condition
since it's the database's representation of null but I originally didn't
notice the quotes around None. When I fixed that I should have
changed is to equals..


print ' '.join(str(field) for field in data if field != 'None')


But your modification confuses me. can you explain?
What would the print line look like?

Alan G.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



I prefer not to use a space delimiter, generally a pipe |, so the output 
would look a lot like
104||Sylvester||Evans||527-9210 Prion 
Av.|Liberal|VT|24742|1-135-197-1139|vehicula.pellentes...@idmollis.edu|2010-07-13 
22:52:50|2010-07-13 22:52:50


The reason I suggested that usage instead is because Monte said
>>> having the 'None' values omitted really messed with the list order 
which I was depending on


So if you're wanting to create a new list which removes the Nones but 
still keeps the same indexing it would be the way to do it, imho.


--
Kind Regards,
Christian Witts


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor