Re: [Tutor] How to handle try and except in this case

2011-11-29 Thread Mic


On 2011-11-27 17:58, Mic wrote:
Say that I want to try and open 10 files. If none of these exists, I want 
an

error
message to appear. But only if NONE of these files exists.



I know how to handle this with one file. But I don't know how to do that
with more than one.
So the program should try and open all 10 files and if, and only if, none
of the files exists I want en error message to appear.



[Andreas wrote]:

Use a counter which increments with every existing file. After opening
all files check if the counter is bigger than 0.



Or, if you need to know which files exist, use a list, append existing
files to it and check at the end if it's not empty.



Do you need more help?


Andreas,


Thanks for your answer. I am afraid I don't understand this:
"Use a counter which increments with every existing file. After opening
all files check if the counter is bigger than 0."


I thought I could co along those lines earlier

try:
   text_file=open("Hey","r") and text_file1=open("Hey","r")
except:
   print("hi")


So that hi is printed only and only if both files aren't existing.


Thank you!





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


Re: [Tutor] useful function or reinventing the wheel??

2011-11-29 Thread Mark Lybrand
>
>
> You're welcome.  I'd look forward to seeing your rewrite, and whether it's
> really shorter and more straightforward.
>
> Another advantage is doing less disk I/O if you start by trying the
> requested directory directly, and only recursing to parents if you can't
> make the requested directory.
>
> I took a quick stab at it  (ask me later for mark.py)  and it wasn't as
> straightforward as I expected.  The main problem comes down to how to
> define the base case.  I think you might have the same problem also. You
> assume that you can safely go back to the mount point.  But if the path
> given is relative, you have to allow for that as well. Perhaps a call to
> os.path.abspath is in order.  I also think that ismount() might not be
> legal on Windows, if you care about that.
>
> Also, we have to worry about what happens when one of the directories
> cannot be made for reasons unrelated to the syntax of the string.  For
> example, the user might not have write permissions for one or more of the
> directories.  In fact, the user might not have read permissions either.
>
>
I am actually passing in the path already os.path.abspath-ed.  So, I should
probably move that into the function for better encapsulation.  I am on
Windows, so ismount is behaving correctly (I tested it in Idle before going
with that as my base case).  Since this will end up being a throw-away, I
will probably not worry too much about permissions and failures, but I can
appreciate the need for such checks, should I decide to keep this for more
widespread use.

Thanks again.  I will send my solution when I get a chance to get back to
it (gotta get myself ahead in machine learning before the weekend gets too
close :)

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


[Tutor] Programming Collective Intelligence Study Group

2011-11-29 Thread Mark Lybrand
Over on the Machine Learning Class, I mentioned the idea of setting up some
online resources to go through the Programming Collective Intelligence book
as a group. This would include a group or discussion board of some type,
maybe a Google+ or Facebook page, and a wiki.  Then we would set a pace and
work through the book.  Since it is in Python, I thought this group would
be interested.  Am I wrong?  If it works out pretty good, we will probably
continue with Natural Language Processing (also Python) after we finish.

So, what is the interest like here?  Let me know and I will give you guys a
heads up when I get everything all set up.

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


Re: [Tutor] Do loop in Python

2011-11-29 Thread stm atoc
Thank you so much. This script and all information was totally helpful
and actually helped me for the next step of my work as well.

Have a great time.
Sue

On Fri, Nov 25, 2011 at 10:44 PM, Andreas Perstinger
 wrote:
> On 2011-11-25 14:46, stm atoc wrote:
>>
>> Here is the new version of the program:
>>
>> zvalues = [-200]  # starting value
>> hvalues = [10]  # starting value
>> increments = [1, 1, 1, 1, 1, 1, 1, 1]
>> for N in increments:
>>        h = hvalues[-1] - N
>>        hvalues.append(h)
>>        z = zvalues[-1] + h
>>        zvalues.append(z)
>>        height = arange((z)*dz,0,dz)
>
>
> There is no "arange" in python. Could it be that you use numpy and import it
> with "from numpy import *"?
>
>>        for z,when in enumerate(height):
>
>
> I'm pretty sure this line doesn't do what you expect it to do. You have a
> sequence (a numpy array) named "height" and after calling "enumerate" you
> get a list of tuples in the form of [(0, height[0]), (1, height[1]), ...].
> Now the for-loop iterates over this list and assigns "z" to the first value
> of the tuple (the index-values) and "when" to the second (the values from
> "height"). You later never use "when" but just use "z". If you really want
> that, the "enumerate" is completly unnecessary and you could just use "for z
> in range(len(height))". But I'm not sure if numpy arrays work with "len()".
>
>
>>            nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence
>> diffusivity m**2/s
>>            nu.append(num + nuh[z])
>>
>> The story is like this:
>> I should define layers and thickness and see how the diffusion profile
>> changes over the z.
>> height (or depth) of the total thickness or 'z'.
>> I basically, define 'z' in 10 layers and each layer is called  ' N' .
>> Difference between each layer is 'h', which is equal 10 micrometer.
>> Now, what I like to do is the modification of nu based on each zvalue
>> In fact, for each 'zvalue' o'z' step, I need to calculate a different
>> value for 'nu' based on the available equation in the program.
>>
>> BUT, I am not sure, exactly, how to add the new do loop of z inside
>> another loop of nu.
>
>
> For me your explanations are still too confusing. Could it be that you are
> thinking way too complicated?
>
> My guess is you want to have a range of material thicknesses (from 1 to 200
> micrometers in 10 micrometer-steps) and then you want from each thickness 10
> different layers, right?
>
> import math # you should always tell us which modules you import
> num = 0.05 # some constant
> nu = [] # list of resulting values
> h = 10.0 # height of one layer
> thickness = range(0, 210, 10) # a list from 0 to 200 with step 10 (0, 10,
> 20, ..., 190, 200)
> layers = range(1,11) # a list from 1 to 10
> for t in thickness:
>  for l in layers:
>    z = t + h * l # I'm not sure if you want to add or subtract the layer
> thickness
>    nu = num + (0.01 * math.exp(-0.05 * (z + 200.0)))
>
> This will result in a big one-dimensional list where you calculate for each
> thickness the nu-value for 10 layers. Am I close?
> I'm still not sure about the steps and the height of the layers. I also
> wonder if it wouldn't be better to use a two-dimensional list.
>
>
>> I have done this way as well (the other way around):
>>
>> height = arange((z)*dz,0,dz)
>> for z,when in enumerate(height):
>>     for N in increments:
>>        h = hvalues[-1] - N
>>        hvalues.append(h)
>>        z = zvalues[-1] + h
>>        zvalues.append(z)
>>        nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence
>> diffusivity m**2/s
>>        nu.append(num + nuh[z])
>>
>> but still no sign of 'nu changes' over 'z'!
>
>
> As Charles has already mentioned, the values for "nu" are very similar (they
> start beginning to differ just at the seventh digit after the comma). How do
> you further process this values? If you plot them what's your scale?
>
> Bye, Andreas
>
> ___
> 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] How to handle try and except in this case

2011-11-29 Thread Dave Angel

On 11/29/2011 03:37 AM, Mic wrote:


On 2011-11-27 17:58, Mic wrote:
Say that I want to try and open 10 files. If none of these exists, I 
want an

error
message to appear. But only if NONE of these files exists.


I know how to handle this with one file. But I don't know how to do 
that

with more than one.
So the program should try and open all 10 files and if, and only if, 
none

of the files exists I want en error message to appear.



[Andreas wrote]:

Use a counter which increments with every existing file. After opening
all files check if the counter is bigger than 0.



Or, if you need to know which files exist, use a list, append existing
files to it and check at the end if it's not empty.



Do you need more help?


Andreas,


Thanks for your answer. I am afraid I don't understand this:
"Use a counter which increments with every existing file. After opening
all files check if the counter is bigger than 0."

Could you explain what's unclear about it?  Andreas couldn't get more 
specific, since you didn't say how these 10 names are provided.  If 
they're in a list called filenames, you could do something like:


fileobjects = []
for fname in filenames:
try:
fileobj = open(fname, "r")
fileobjects.append(fileobj)
catch SomeExceptionType as e:
pass

and when you're done, use something like:

if len(fileobjects) == 0:
 print "no files could be opened"



I thought I could co along those lines earlier

try:
   text_file=open("Hey","r") and text_file1=open("Hey","r")


Unfortunately this isn't valid Python syntax.  The equal sign has a 
specific statement syntax, and the only time you can have more than one 
of them in one statement, is the chained assignments, where they all get 
bound to the same object.  You wouldn't want to do this anyway, since it 
would leave all those open files in an unspecified state.


To go one step further, if it could work, it would give an exception if 
any ONE of the files couldn't be open, and you want the message to 
appear if none of the files could be opened.



except:
   print("hi")


So that hi is printed only and only if both files aren't existing.
If you didn't need to open them, but just to make sure they exist, you 
could use if  os.exist(filename)  much more easily.


--

DaveA

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


Re: [Tutor] How to handle try and except in this case

2011-11-29 Thread Peter Otten
Mic wrote:

> 
> On 2011-11-27 17:58, Mic wrote:
>>> Say that I want to try and open 10 files. If none of these exists, I
>>> want an
>>> error
>>> message to appear. But only if NONE of these files exists.
> 
>>> I know how to handle this with one file. But I don't know how to do that
>>> with more than one.
>>> So the program should try and open all 10 files and if, and only if,
>>> none of the files exists I want en error message to appear.
> 
> 
> [Andreas wrote]:
>>Use a counter which increments with every existing file. After opening
>>all files check if the counter is bigger than 0.
> 
>>Or, if you need to know which files exist, use a list, append existing
>>files to it and check at the end if it's not empty.
> 
>>Do you need more help?
> 
> Andreas,
> 
> 
> Thanks for your answer. I am afraid I don't understand this:
> "Use a counter which increments with every existing file. After opening
> all files check if the counter is bigger than 0."
> 
> 
> I thought I could co along those lines earlier
> 
> try:
> text_file=open("Hey","r") and text_file1=open("Hey","r")
> except:
> print("hi")
> 
> 
> So that hi is printed only and only if both files aren't existing.

filenames = ["file1.txt", "file2.txt"]
files = []
for name in filenames:
try:
files.append(open(name))
except IOError:
pass
if not files:
print("couldn't open any files")

If you don't need the file objects:

filenames = ["file1.txt", "file2.txt"]
if not any(os.path.exists(name) for name in filenames):
   print("didn't find any existing files")


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


Re: [Tutor] Programming Collective Intelligence Study Group (Mark Lybrand)

2011-11-29 Thread tommy
Hey Mark

Id be very much interested in this. While I mostly lurk on the python
mailing list and have only dabbled in a few quick scripts. Then I wouldnt
mind getting deeper into via a collective group.

This is the first I've heard of this, Im not sure if you've posted before
but which book are you using?

/Regards
Tommy
On Tue, 29 Nov 2011 10:18:25 +0100, tutor-requ...@python.org wrote:
> Send Tutor mailing list submissions to
>   tutor@python.org
> 
> To subscribe or unsubscribe via the World Wide Web, visit
>   http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>   tutor-requ...@python.org
> 
> You can reach the person managing the list at
>   tutor-ow...@python.org
> 
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
> 
> 
> Today's Topics:
> 
>1. Re: How to handle try and except in this case (Mic)
>2. Re: useful function or reinventing the wheel?? (Mark Lybrand)
>3. Programming Collective Intelligence Study Group (Mark Lybrand)
>4. Re: Do loop in Python (stm atoc)
>5. Re: How to handle try and except in this case (Dave Angel)
> 
> 
> --
> 
> Message: 1
> Date: Tue, 29 Nov 2011 09:37:28 +0100
> From: "Mic" 
> To: 
> Subject: Re: [Tutor] How to handle try and except in this case
> Message-ID: 
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>   reply-type=original
> 
> 
> On 2011-11-27 17:58, Mic wrote:
>>> Say that I want to try and open 10 files. If none of these exists, I
>>> want
>>> an
>>> error
>>> message to appear. But only if NONE of these files exists.
> 
>>> I know how to handle this with one file. But I don't know how to do
that
>>> with more than one.
>>> So the program should try and open all 10 files and if, and only if,
>>> none
>>> of the files exists I want en error message to appear.
> 
> 
> [Andreas wrote]:
>>Use a counter which increments with every existing file. After opening
>>all files check if the counter is bigger than 0.
> 
>>Or, if you need to know which files exist, use a list, append existing
>>files to it and check at the end if it's not empty.
> 
>>Do you need more help?
> 
> Andreas,
> 
> 
> Thanks for your answer. I am afraid I don't understand this:
> "Use a counter which increments with every existing file. After opening
> all files check if the counter is bigger than 0."
> 
> 
> I thought I could co along those lines earlier
> 
> try:
> text_file=open("Hey","r") and text_file1=open("Hey","r")
> except:
> print("hi")
> 
> 
> So that hi is printed only and only if both files aren't existing.
> 
> 
> Thank you!
> 
> 
> 
> 
> 
> 
> 
> --
> 
> Message: 2
> Date: Tue, 29 Nov 2011 00:37:40 -0800
> From: Mark Lybrand 
> To: d...@davea.name
> Cc: tutor@python.org
> Subject: Re: [Tutor] useful function or reinventing the wheel??
> Message-ID:
>   
> Content-Type: text/plain; charset="utf-8"
> 
>>
>>
>> You're welcome.  I'd look forward to seeing your rewrite, and whether
>> it's
>> really shorter and more straightforward.
>>
>> Another advantage is doing less disk I/O if you start by trying the
>> requested directory directly, and only recursing to parents if you
can't
>> make the requested directory.
>>
>> I took a quick stab at it  (ask me later for mark.py)  and it wasn't as
>> straightforward as I expected.  The main problem comes down to how to
>> define the base case.  I think you might have the same problem also.
You
>> assume that you can safely go back to the mount point.  But if the path
>> given is relative, you have to allow for that as well. Perhaps a call
to
>> os.path.abspath is in order.  I also think that ismount() might not be
>> legal on Windows, if you care about that.
>>
>> Also, we have to worry about what happens when one of the directories
>> cannot be made for reasons unrelated to the syntax of the string.  For
>> example, the user might not have write permissions for one or more of
the
>> directories.  In fact, the user might not have read permissions either.
>>
>>
> I am actually passing in the path already os.path.abspath-ed.  So, I
should
> probably move that into the function for be

Re: [Tutor] Programming Collective Intelligence Study Group

2011-11-29 Thread Steven D'Aprano

Mark Lybrand wrote:

Over on the Machine Learning Class, I mentioned the idea of setting up some
online resources to go through the Programming Collective Intelligence book


What are the Machine Learning Class and the Programming Collective 
Intelligence book? Should I have heard of them before?




as a group. This would include a group or discussion board of some type,
maybe a Google+ or Facebook page, and a wiki.  Then we would set a pace and


If it's Google+ or Facebook, count me out.



work through the book.  Since it is in Python, I thought this group would
be interested.  Am I wrong?


If I had any idea what you were talking about, other than "something to do 
with Python", then I might be.




--
Steven

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


Re: [Tutor] Programming Collective Intelligence Study Group (Mark Lybrand)

2011-11-29 Thread Mark Lybrand
mail.com>
> > Content-Type: text/plain; charset="utf-8"
> >
> >>
> >>
> >> You're welcome.  I'd look forward to seeing your rewrite, and whether
> >> it's
> >> really shorter and more straightforward.
> >>
> >> Another advantage is doing less disk I/O if you start by trying the
> >> requested directory directly, and only recursing to parents if you
> can't
> >> make the requested directory.
> >>
> >> I took a quick stab at it  (ask me later for mark.py)  and it wasn't as
> >> straightforward as I expected.  The main problem comes down to how to
> >> define the base case.  I think you might have the same problem also.
> You
> >> assume that you can safely go back to the mount point.  But if the path
> >> given is relative, you have to allow for that as well. Perhaps a call
> to
> >> os.path.abspath is in order.  I also think that ismount() might not be
> >> legal on Windows, if you care about that.
> >>
> >> Also, we have to worry about what happens when one of the directories
> >> cannot be made for reasons unrelated to the syntax of the string.  For
> >> example, the user might not have write permissions for one or more of
> the
> >> directories.  In fact, the user might not have read permissions either.
> >>
> >>
> > I am actually passing in the path already os.path.abspath-ed.  So, I
> should
> > probably move that into the function for better encapsulation.  I am on
> > Windows, so ismount is behaving correctly (I tested it in Idle before
> going
> > with that as my base case).  Since this will end up being a throw-away,
> I
> > will probably not worry too much about permissions and failures, but I
> can
> > appreciate the need for such checks, should I decide to keep this for
> more
> > widespread use.
> >
> > Thanks again.  I will send my solution when I get a chance to get back
> to
> > it (gotta get myself ahead in machine learning before the weekend gets
> too
> > close :)
> >
> > Mark
> > -- next part --
> > An HTML attachment was scrubbed...
> > URL:
> >
> <
> http://mail.python.org/pipermail/tutor/attachments/2029/991cc3a9/attachment-0001.html
> >
> >
> > --
> >
> > Message: 3
> > Date: Tue, 29 Nov 2011 00:42:01 -0800
> > From: Mark Lybrand 
> > To: tutor@python.org
> > Subject: [Tutor] Programming Collective Intelligence Study Group
> > Message-ID:
> >   <
> calsubtzsqtjh4mx2ixuvo-j5ztn5xqlt+o4zdyevse1vjkn...@mail.gmail.com>
> > Content-Type: text/plain; charset="utf-8"
> >
> > Over on the Machine Learning Class, I mentioned the idea of setting up
> some
> > online resources to go through the Programming Collective Intelligence
> book
> > as a group. This would include a group or discussion board of some type,
> > maybe a Google+ or Facebook page, and a wiki.  Then we would set a pace
> and
> > work through the book.  Since it is in Python, I thought this group
> would
> > be interested.  Am I wrong?  If it works out pretty good, we will
> probably
> > continue with Natural Language Processing (also Python) after we finish.
> >
> > So, what is the interest like here?  Let me know and I will give you
> guys a
> > heads up when I get everything all set up.
> >
> > --
> > Mark :)
> > -- next part --
> > An HTML attachment was scrubbed...
> > URL:
> >
> <
> http://mail.python.org/pipermail/tutor/attachments/2029/82dcebaf/attachment-0001.html
> >
> >
> > --
> >
> > Message: 4
> > Date: Tue, 29 Nov 2011 09:51:45 +0100
> > From: stm atoc 
> > To: Andreas Perstinger 
> > Cc: tutor@python.org
> > Subject: Re: [Tutor] Do loop in Python
> > Message-ID:
> >   <
> cahnhts68pqeq5xvk4tn3c6hqymenrby1o7xnqn-fxjmdki4...@mail.gmail.com>
> > Content-Type: text/plain; charset=ISO-8859-1
> >
> > Thank you so much. This script and all information was totally helpful
> > and actually helped me for the next step of my work as well.
> >
> > Have a great time.
> > Sue
> >
> > On Fri, Nov 25, 2011 at 10:44 PM, Andreas Perstinger
> >  wrote:
> >> On 2011-11-25 14:46, stm atoc wrote:
> >>>
> >>> Here is the new version of the program:
> >>>
> >>> zvalues = [-200] ?# starting valu

Re: [Tutor] Programming Collective Intelligence Study Group

2011-11-29 Thread Mark Lybrand
>
> What are the Machine Learning Class and the Programming Collective
> Intelligence book? Should I have heard of them before?
>
>
Sorry for being unclear.  Machine Learning Class is one of the free classes
offered online by Stanford.  http://www.ml-class.org  This one started in
October.  Another round to start in January.  I highly recommend it.

Programming Collective Intelligence is a book by Toby Segaran from O'Reilly
ISBN-13: 978-0596529321  It uses Python to apply machine learning
techniques to real life problems and looks like loads of fun.

The Natural Language Processing with Python book is freely available here:
http://www.nltk.org/book


>
> If it's Google+ or Facebook, count me out.
>
>
Well, that would only be one dimension of what I propose, so totally
avoidable if you are that averse.  You should be fine with the discussion
forum and reference site I propose, which would be independent of any
social networks.

 If I had any idea what you were talking about, other than "something to do
with Python", then I might be.

>
Hopefully, I have done something to clarify what I was talking about.  If
not, don't hesitate to express your concerns via the list or to me
personally, either by email or on Facebook (just kidding).

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


Re: [Tutor] Programming Collective Intelligence Study Group (Mark Lybrand)

2011-11-29 Thread tommy
ements with every existing file. After
opening
>> > all files check if the counter is bigger than 0."
>> >
>> >
>> > I thought I could co along those lines earlier
>> >
>> > try:
>> > text_file=open("Hey","r") and text_file1=open("Hey","r")
>> > except:
>> > print("hi")
>> >
>> >
>> > So that hi is printed only and only if both files aren't existing.
>> >
>> >
>> > Thank you!
>> >
>> >
>> >
>> >
>> >
>> >
>> >
>> > --
>> >
>> > Message: 2
>> > Date: Tue, 29 Nov 2011 00:37:40 -0800
>> > From: Mark Lybrand 
>> > To: d...@davea.name
>> > Cc: tutor@python.org
>> > Subject: Re: [Tutor] useful function or reinventing the wheel??
>> > Message-ID:
>> >   > bw5h3w3pcur0dctprbg--2...@mail.gmail.com>
>> > Content-Type: text/plain; charset="utf-8"
>> >
>> >>
>> >>
>> >> You're welcome.  I'd look forward to seeing your rewrite, and
whether
>> >> it's
>> >> really shorter and more straightforward.
>> >>
>> >> Another advantage is doing less disk I/O if you start by trying the
>> >> requested directory directly, and only recursing to parents if you
>> can't
>> >> make the requested directory.
>> >>
>> >> I took a quick stab at it  (ask me later for mark.py)  and it wasn't
>> >> as
>> >> straightforward as I expected.  The main problem comes down to how
to
>> >> define the base case.  I think you might have the same problem also.
>> You
>> >> assume that you can safely go back to the mount point.  But if the
>> >> path
>> >> given is relative, you have to allow for that as well. Perhaps a
call
>> to
>> >> os.path.abspath is in order.  I also think that ismount() might not
be
>> >> legal on Windows, if you care about that.
>> >>
>> >> Also, we have to worry about what happens when one of the
directories
>> >> cannot be made for reasons unrelated to the syntax of the string. 
For
>> >> example, the user might not have write permissions for one or more
of
>> the
>> >> directories.  In fact, the user might not have read permissions
>> >> either.
>> >>
>> >>
>> > I am actually passing in the path already os.path.abspath-ed.  So, I
>> should
>> > probably move that into the function for better encapsulation.  I am
on
>> > Windows, so ismount is behaving correctly (I tested it in Idle before
>> going
>> > with that as my base case).  Since this will end up being a
throw-away,
>> I
>> > will probably not worry too much about permissions and failures, but
I
>> can
>> > appreciate the need for such checks, should I decide to keep this for
>> more
>> > widespread use.
>> >
>> > Thanks again.  I will send my solution when I get a chance to get
back
>> to
>> > it (gotta get myself ahead in machine learning before the weekend
gets
>> too
>> > close :)
>> >
>> > Mark
>> > -- next part --
>> > An HTML attachment was scrubbed...
>> > URL:
>> >
>> <
>>
http://mail.python.org/pipermail/tutor/attachments/2029/991cc3a9/attachment-0001.html
>> >
>> >
>> > --
>> >
>> > Message: 3
>> > Date: Tue, 29 Nov 2011 00:42:01 -0800
>> > From: Mark Lybrand 
>> > To: tutor@python.org
>> > Subject: [Tutor] Programming Collective Intelligence Study Group
>> > Message-ID:
>> >   <
>> calsubtzsqtjh4mx2ixuvo-j5ztn5xqlt+o4zdyevse1vjkn...@mail.gmail.com>
>> > Content-Type: text/plain; charset="utf-8"
>> >
>> > Over on the Machine Learning Class, I mentioned the idea of setting
up
>> some
>> > online resources to go through the Programming Collective
Intelligence
>> book
>> > as a group. This would include a group or discussion board of some
>> > type,
>> > maybe a Google+ or Facebook page, and a wiki.  Then we would set a
pace
>> and
>> > work through the book.  Since it is in Python, I thought this group
>> would
>> > be interested.  Am I wrong?  If it works out pretty good, we will
>> probab

Re: [Tutor] pass tuples to user defined function(beginner)

2011-11-29 Thread Steven D'Aprano

bob gailer wrote:

On 11/28/2011 12:47 PM, James Reynolds wrote:



On Mon, Nov 28, 2011 at 12:32 PM, Mayo Adams > wrote:


I am trying to pass a set of tuple strings from a file to a 
function I

have defined.  Each tuple is on a separate line, and looks something
like this:
 ('note',2048)



As already pointed out - this is a string (a representation of a tuple), 
not a tuple.


Your code must parse the string to extract the string representations of 
the values, then convert as needed to the desired Python values.


Tasks like this are not trivial.



In general, parsing can be a hard problem. In this case though, it is easy to 
solve 95% of the problem with a hand-built converter, which may be good enough.


def strto2tuple(s):
"""Convert a string like "('abc', 42)" to a tuple with two items."""
# Ignore leading and trailing whitespace.
s = s.strip()
# Check for round brackets (parentheses), and remove them.
if s[0] != '(' or s[-1] != ')':
raise ValueError('malformed string, missing ( or )')
s = s[1:-1]
# Split the string into exactly two pieces.
# FIXME this assumes that the first item contains no commas.
items = s.split(',')
n = len(items)
if n != 2:
raise ValueError('expected exactly two items but found %d' % n)
a, b = items
# Ignore spaces around each item, e.g. ( 'abc' , 42 ) => ('abc', 42)
a = a.strip()
b = b.strip()
# Make sure that the first item looks like a string.
quotes = '"\''  # FIXME no support for triple quotes yet, or raw strings.
assert len(quotes) == 2
for q in quotes:
if a.startswith(q) and a.endswith(q):
# Don't include the delimiter quotes in the string.
a = a[1:-1]
break
else:
# This executes if we don't hit a break in the for loop.
raise ValueError('mismatched or missing quotes')
assert isinstance(a, str)
# Make sure the second item is an integer.
b = int(b, 0)  # Support hex and octal formats too.
return (a, b)  # And return a real tuple.


This untested function will convert strings in a file like these:

(  'fe', 1)
(  'fi' ,2 )
  ("fo",0x03)
( "fum",   4  )

into proper tuples with a string and a number. Notice that we allow the user 
to be sloppy with spaces, but we are strict about quotation marks and brackets.



Our converter function is both a little too strict (e.g. it forbids the user 
from including triple-quoted strings) and a little too lax (e.g. it allows 
malformed strings like ''abc'). You might not care about these weaknesses. If 
you do, you need to move up to a real parser, which is significantly more complex.






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


Re: [Tutor] How to use try and except in this case?

2011-11-29 Thread Steven D'Aprano

Mic wrote:

Say that I want to try and open 10 files. If none of these exists, I 
want an error

message to appear. But only if NONE of these files exists.

I know how to handle this with one file. But I don't know how to do that 
with more than one.
So the program should try and open all 10 files and if, and only if, 
none of the files exists I want en error message to appear.


Your description isn't quite clear enough. What happens if, say, only 3 of the 
files exist? Is the intention to open the first file that you can find?


# Ten file names to try:
names = ['file 1', 'file 2', 'a', 'b', 'c', 'backup file',
 'backup file 2', 'spam', 'ham', 'eggs'
 ]
# Find the first one that exists and is readable.
for name in names:
try:
f = open(name, 'r')
except (OSError, IOError):
continue  # try the next one
break  # this only runs when a file opens successfully
else:
# we didn't break
raise ValueError('no file could be opened')



Or is it your intention to open as many of the files as possible?


# Ten file names to try:
names = ['file 1', 'file 2', 'a', 'b', 'c', 'backup file',
 'backup file 2', 'spam', 'ham', 'eggs'
 ]
files = []  # list of opened file objects
for name in names:
try:
f = open(name, 'r')
files.append(f)
except (OSError, IOError):
continue  # missing, go on to the next one
if files == []:
raise ValueError('no file could be opened')
else:
# do stuff with the files...
# ...
# ...
# don't forget to close them when done (optional but recommended)
for f in files:
f.close()




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


Re: [Tutor] How to raise error without the stack trace

2011-11-29 Thread Steven D'Aprano

Karim wrote:

I did not explain myself clearly. I Kow when I fired it because it is in 
code like:


If not value:
raise MyError('You did wrong here!')

And in that case I did not want the stack trace because I know perfectly 
where the message is triggered.


Really?

You must have amazingly tiny programs that are incredibly bug free then. I'm 
jealous :-)


In my programs, if I get MyError('You did wrong here!'), I need all the help I 
can get to find out what sort of wrong it was, why value is incorrect, what 
function called it, and where the value came from originally. The stack trace 
is often very helpful for that: the variable might get the wrong value half a 
dozen function calls away from where the exception happens.


Sometimes the error is obvious, and the stack trace is easy to ignore. It's 
the cases that aren't obvious that you should care about.


If you think Python stack traces are annoying, you haven't seen anything. 
Once, I saw a SAP application unexpected crash, and it printed (I am not 
exaggerating, or joking) half a ream of printouts. Seriously. The stack of 
printouts was two centimetres thick.


We called the supplier and asked if they wanted the printouts for debugging, 
and they said no.





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


Re: [Tutor] pass tuples to user defined function(beginner)

2011-11-29 Thread Peter Otten
Steven D'Aprano wrote:

> bob gailer wrote:
>> On 11/28/2011 12:47 PM, James Reynolds wrote:
>>>
>>>
>>> On Mon, Nov 28, 2011 at 12:32 PM, Mayo Adams >> > wrote:
>>>
>>> I am trying to pass a set of tuple strings from a file to a
>>> function I
>>> have defined.  Each tuple is on a separate line, and looks something
>>> like this:
>>>  ('note',2048)
>>>
>> 
>> As already pointed out - this is a string (a representation of a tuple),
>> not a tuple.
>> 
>> Your code must parse the string to extract the string representations of
>> the values, then convert as needed to the desired Python values.
>> 
>> Tasks like this are not trivial.
> 
> 
> In general, parsing can be a hard problem. In this case though, it is easy
> to solve 95% of the problem with a hand-built converter, which may be good
> enough.
> 
> def strto2tuple(s):
>  """Convert a string like "('abc', 42)" to a tuple with two items."""
>  # Ignore leading and trailing whitespace.
>  s = s.strip()
>  # Check for round brackets (parentheses), and remove them.
>  if s[0] != '(' or s[-1] != ')':
>  raise ValueError('malformed string, missing ( or )')
>  s = s[1:-1]
>  # Split the string into exactly two pieces.
>  # FIXME this assumes that the first item contains no commas.
>  items = s.split(',')
>  n = len(items)
>  if n != 2:
>  raise ValueError('expected exactly two items but found %d' % n)
>  a, b = items
>  # Ignore spaces around each item, e.g. ( 'abc' , 42 ) => ('abc', 42)
>  a = a.strip()
>  b = b.strip()
>  # Make sure that the first item looks like a string.
>  quotes = '"\''  # FIXME no support for triple quotes yet, or raw
>  strings. assert len(quotes) == 2
>  for q in quotes:
>  if a.startswith(q) and a.endswith(q):
>  # Don't include the delimiter quotes in the string.
>  a = a[1:-1]
>  break
>  else:
>  # This executes if we don't hit a break in the for loop.
>  raise ValueError('mismatched or missing quotes')
>  assert isinstance(a, str)
>  # Make sure the second item is an integer.
>  b = int(b, 0)  # Support hex and octal formats too.
>  return (a, b)  # And return a real tuple.
> 
> 
> This untested function will convert strings in a file like these:
> 
> (  'fe', 1)
> (  'fi' ,2 )
>("fo",0x03)
> ( "fum",   4  )
> 
> into proper tuples with a string and a number. Notice that we allow the
> user to be sloppy with spaces, but we are strict about quotation marks and
> brackets.
> 
> 
> Our converter function is both a little too strict (e.g. it forbids the
> user from including triple-quoted strings) and a little too lax (e.g. it
> allows malformed strings like ''abc'). You might not care about these
> weaknesses. If you do, you need to move up to a real parser, which is
> significantly more complex.

And here's the lazy-bastard version:

>>> lines = """(  'fe', 1)
... (  'fi' ,2 )
...("fo",0x03)
... ( "fum",   4  )
... ("gvn", __import__("os").remove("that could be your valuable data.txt"))
... """.splitlines()
>>> import ast
>>> for line in lines:
... print ast.literal_eval(line.strip())
...
('fe', 1)
('fi', 2)
('fo', 3)
('fum', 4)
Traceback (most recent call last):
  File "", line 2, in 
  File "/usr/lib/python2.6/ast.py", line 68, in literal_eval
return _convert(node_or_string)
  File "/usr/lib/python2.6/ast.py", line 58, in _convert
return tuple(map(_convert, node.elts))
  File "/usr/lib/python2.6/ast.py", line 67, in _convert
raise ValueError('malformed string')
ValueError: malformed string


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


Re: [Tutor] Do loop in Python

2011-11-29 Thread Steven D'Aprano

stm atoc wrote:

Thank you so much for your reply. It was very helpful information and
I used it in order to improve the program

Here is the new version of the program:

zvalues = [-200]  # starting value
hvalues = [10]  # starting value
increments = [1, 1, 1, 1, 1, 1, 1, 1]
for N in increments:
   h = hvalues[-1] - N
   hvalues.append(h)
   z = zvalues[-1] + h
   zvalues.append(z)
   height = arange((z)*dz,0,dz)
   for z,when in enumerate(height):
   nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence
diffusivity m**2/s
   nu.append(num + nuh[z])



I'm afraid I still don't know what the arange function is. Is that a function 
you have written yourself? However, I can see that it doesn't actually get used!


You create an arange object, and call it "height".

height = arange((z)*dz,0,dz)

You should insert a print statement after this line to see what value height 
is given, and check that it is what you expect it to be.


Presumably height is some sort of list or sequence of values, because you next 
use it in a for-loop:


for z,when in enumerate(height):
...

So now we know that z takes on the values 0, 1, 2, 3, ... and when takes on 
the values from height, whatever they are. But in the rest of your code, you 
don't use when at all:


nuh.append(0.001 * exp(-0.005*(z+200.0))*dz)
nu.append(num + nuh[z])

No when, hence the values from height aren't actually used. Strange.

Also, what are dz and num? You use them both, but I can't see where they are 
defined or what value they have. Likewise nuh and nu, although I can guess 
they are probably lists because you append to them.


Because I don't know what values to use, and I don't know what arange is, I 
can't run your code to see what it does. So I'm reduced to guessing.


If I take a wild stab in the dark that dz is a small number, say, 0.01, I can 
see what values nuh gets:



py> from math import exp
py> dz = 0.01
py> nuh = []
py> for z in range(10):
... nuh.append(0.001 * exp(-0.005*(z+200.0))*dz)
...
py> from pprint import pprint
py> pprint(nuh)
[3.6787944117144236e-06,
 3.6604463480401533e-06,
 3.6421897957152333e-06,
 3.624024298324903e-06,
 3.6059494017307832e-06,
 3.587964654059516e-06,
 3.5700696056914737e-06,
 3.5522638092495153e-06,
 3.5345468195878014e-06,
 3.5169181937806692e-06]

Is that the sort of behaviour you expect for nuh?

Since the nuh values are changing, num+nuh[z] should also be changing, which 
implies nu should be changing.


Unless num is so large that rounding error wipes out the nuh values.



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


Re: [Tutor] pass tuples to user defined function(beginner)

2011-11-29 Thread Steven D'Aprano

Peter Otten wrote:


And here's the lazy-bastard version:

[...]

... print ast.literal_eval(line.strip())


Nice!


--
Steven




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


[Tutor] problem with msg widget & button

2011-11-29 Thread Cranky Frankie
OK, I've stripped out all the comments and put it here:

http://www.pastie.org/2938751


This works but the button doesn't put the next comment in the window.
The only way I could figure to get the next comment in the window is
to add the msg_widget line to the disp_quote function, but when I do
that, it puts out *another* msg-widget! That is not what I want at
all. I just want the next quote button to put the next quote in the
box.

-- 
Frank L. "Cranky Frankie" Palmeri
Risible Riding Raconteur & Writer
“How you do anything is how you do everything.”
- from Alabama Crimson Tide training room
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] python webservice suds

2011-11-29 Thread 贾晓磊
hi, all:

is someone familiar to suds.

I'm making a webservice client, and meet some problems.
I try to ask helps from s...@python.org, li...@libertylost.org,
python-torn...@googlegroups.com, while, the problem still exist.


part 1: how do you think the xml in the url:

"http://211.137.45.104:9006/LnXxtCpInterface/services/LNXxtSyncService?wsdl";









part 2: in fact, the server is made by Axis, which is a web service
framework in Java.
Before i develop the client, there already have a java client for the
server.
the code  are below:

if (temp.length % MTINFO_LENGTH != 0) {
String[] remainBlock = new String[temp.length - jMark];
 for (int i = 0; i < remainBlock.length; i++) {
remainBlock[i] = temp[jMark];
 jMark++;
}

mark = lnxss.sendMt(remainBlock);

After read the code,  we know that the the inparams of sendMt is String[].
In fact, the purpose of senMt() is to send some shotmessage to a mobile
phone. you can find remobile in the parameters.

part 3: Besides, the server has some check, which i have add it in the
newest code.

servicecode: PABB4BEIJING
passwd: QWERTPABB
namespace: service.global.v1_0.wsdl.protocol.xxt (you can see it in the url)

I have tried  to add the service code and passwd in the code.
 while,  what  still puzzled me is that in suds, how to add the namespace
to the client.
how to use the ArrayOf_soapen_string is a problem. in my code, i provide a
list which contains some string. in my view, i should provide a object like
your code,
aoss = client.factory.create('ArrayOf_soapen_string')
then, what should i do next?  how to assign a value for the parameter of
aoss?

part 4:
# the newest code :

import suds
def test_sms4():
import logging
logging.basicConfig(level=logging.ERROR)
url = "
http://211.137.45.104:9006/LnXxtCpInterface/services/LNXxtSyncService?wsdl";
from suds.transport.https import HttpAuthenticated
credentials = dict(username='PABB4BEIJING', password='QWERTPABB')
t = HttpAuthenticated(**credentials)
client =
suds.client.Client(url,transport=t,cache=None,xstq=False,faults=False)
#client = suds.client.Client(url,cache=None,xstq=False)
aoss = client.factory.create('ArrayOf_soapenc_string')
#client.set_options(namespace='service.global.v1_0.wsdl.protocol.xxt')
print 'client', client
item1 =
"{'msgid':'1234567890','bizcode':'15140237310','serviceId':'1234567','recomobile':'15110791945','sendtime':'1322573860','content':'hi,
this is just a test. you can ignore it. --jiaxiaolei'}"
item2 =
"{'msgid':'1234567891','bizcode':'15140237310','serviceId':'1234567','recomobile':'15110791946','sendtime':'1322573870','content':'hi,
this is just a test. you can ignore it. --jiaxiaolei'}"
req = [item1, item2]

#client.service.sendMt(aoss)
output = client.service.sendMt(mtinfo=req)
print 'output', output



# output:

w_jiaxiaolei@drone-009:~/tornadows-0.9.1/demos$ python suds_client.py
client
Suds ( https://fedorahosted.org/suds/ )  version: 0.3.7 GA  build:
R580-20091016

Service ( LNXxtSyncServiceService )
tns="service.global.v1_0.wsdl.protocol.xxt"
   Prefixes (3)
  ns0 = "http://common.v1_0.obj.protocol.xxt";
  ns1 = "http://schemas.xmlsoap.org/soap/encoding/";
  ns2 = "service.global.v1_0.wsdl.protocol.xxt"
   Ports (1):
  (LNXxtSyncService)
 Methods (5):
sendMo(ArrayOf_soapenc_string moInfo, )
sendMt(ArrayOf_soapenc_string mtInfo, )
syncCorp(ArrayOf_tns2_GroupOrderInfo orderInfo, )
syncResponseRpt(ArrayOf_soapenc_string rpt, )
syncStaff(ArrayOf_tns2_UserOrderInfo orderInfo, )
 Types (54):
ns1:Array
ArrayOf_soapenc_string
ArrayOf_tns2_GroupOrderInfo
ArrayOf_tns2_UserOrderInfo
...

ERROR:suds.client:
http://schemas.xmlsoap.org/soap/encoding/"; xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"; xmlns:SOAP-ENV="
http://schemas.xmlsoap.org/soap/envelope/"; SOAP-ENV:encodingStyle="
http://schemas.xmlsoap.org/soap/encoding/";>
   
   
  
 
  
   

output (500, (detail){
   fault =
  (fault){
 _href = "#id0"
  }
   exceptionName = "xxt.protocol.obj.v1_0.common.ServiceException"
   hostname = "ln_xxt_mh01"
 })


-- jiaxiaolei







2011/11/29 xin zou 

> Sorry that I used many "should" as my subjective judgment, you can try to
> test with the closed correct args of "*array_soapenc_str*" refer the
> related document.
>
> Thanks,
> Xin
>
> 在 2011年11月29日 下午8:20,xin zou 写道:
>
> Hi,
>>
>> Here are my testing code with your supplied service:
>>
>> ===
>> from suds.client import Client
>> import logging
>>
>> #logging.basicConfig(level=logging.DEBUG)
>>
>> url = '
>> http://211.137.45.104:9006/LnXxtCpInterface/services/LNXxtSyncService?wsdl
>> '
>> client = Client(url)
>>
>> array_soapenc_str = client.factory.create('ArrayOf_soapenc_string')
>> array_soapenc_str._arrayType = 'test'
>> 

[Tutor] Making a function run every second.

2011-11-29 Thread Mic

Hi

I want a function to run every second , how do I do that?

Say that the function look like this:

def hi():
   print("hi")


Thanks! 



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


[Tutor] Creating a line in a text file every time a button is pressed.

2011-11-29 Thread Mic

Hey again.

I figured I would first post this piece of code and then ask my questions.

FREE = "green"
OCCUPIED = "red"

class Mainwindow(Frame):
def __init__(self,master):
super(Mainwindow,self).__init__(master)
self.grid()
self.create_mainwidgets()

def create_mainwidgets(self):
self.klicka=Button(self, text="Press the button",
   command=self.uppdatera)
self.klicka.grid()

def uppdatera(self):
SeatWindow(root)

class SeatButton(tk.Button):
def __init__(self, master, index):
text = str(index+1)
super(SeatButton, self).__init__(master,
 text=text, bg=FREE,
 command=self.clicked)
self.filename = "Germany_France{}.txt".format(index+1)
self.occupied = False
if os.path.exists(self.filename):
 self["bg"]=OCCUPIED

def clicked(self):
self.occupied = not self.occupied
if self.occupied:
self["bg"] = OCCUPIED
text_file=open(self.filename,"w")
text_file.write(self.filename)
text_file.close()
else:
self["bg"] = FREE
os.remove(self.filename)

class SeatWindow(tk.Toplevel):
 def __init__(self, master):
 super (SeatWindow, self).__init__(master)
 self.grid()
 self.create_widgets()

 def create_widgets(self):
 for index in range(20):
 button = SeatButton(self, index)
 row, column = divmod(index, 4)
 button.grid(row=row, column=column)

root=Tk()
root.title("testV2")
app=Mainwindow(root)
root.mainloop()




I am now writing another program. It turned out just fine, but I have one 
question.


If button one is pressed I want the program to write, say hi_1, on the first 
line in a text file.

If button one is pressed again, the first line should be empty.

If button two is pressed I want the program to write hi_2 in the second line 
in the text file.
If button two is pressed again, the second line in the text file should be 
empty.


If button three is pressed I want the program to write hi_3 in the third 
line in the text file.
if button three is pressed again, the third line in the text file should be 
empty.


There shouldn't be any other changes to the program other than this above. 
There is already a text file

created, the program doesn't need to create one. We can call that file "Hi".


I hope you understand what I want to do here. I have tried the entire 
evening yesterday to get this to work, I tried using writeline() but I can't 
get it to work.

What are your suggestions to this?



Thank you for your help and time!


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


Re: [Tutor] How to handle try and except in this case

2011-11-29 Thread Mic
Could you explain what's unclear about it?  Andreas couldn't get more 
specific, since you didn't say how these 10 names are provided.



Yes, it was probably my fault. Sorry about that. I have come up with a new 
way of working around
a problem in my main program so I only need two files to be tested if they 
exist instead of say 10 files.


So, the program should check if two text files exist. If neither of them 
exist, and only if neither of them,

then the program should print say "hi".

If only one of them exist, the program should continue to run without 
crashing.



I hope this was more easy to understand!




I thought I could co along those lines earlier

try:
   text_file=open("Hey","r") and text_file1=open("Hey","r")


Unfortunately this isn't valid Python syntax.  The equal sign has a 
specific statement syntax, and the only time you can have more than one of 
them in one statement, is the chained assignments, where they all get bound 
to the same object.  You wouldn't want to do this anyway, since it would 
leave all those open files in an unspecified state.


Thanks for the information. I figured that it was a little strange what I 
wrote.



Mic


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


Re: [Tutor] Making a function run every second.

2011-11-29 Thread delegbede
In my opinion, you probably have to think of how many times it has to run. If 
you want to run forever, you can just make an infinite loop. 

Here's my try. 

import time

def myloop():
while True:
print 'Hi'
time.sleep(1)


This would run forever and print Hi after every 1 second when you run the 
program. 

What exactly are you trying to achieve. 
Sent from my BlackBerry wireless device from MTN

-Original Message-
From: "Mic" 
Sender: tutor-bounces+delegbede=dudupay@python.org
Date: Tue, 29 Nov 2011 15:54:59 
To: 
Subject: [Tutor] Making a function run every second.

Hi

I want a function to run every second , how do I do that?

Say that the function look like this:

def hi():
print("hi")


Thanks! 


Mic
___
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] Making a function run every second.

2011-11-29 Thread bodsda
You won't get it exactly on because the time it takes to call the function will 
affect your trigger time.

I would use something like an infinite loop with a 1 second sleep after the 
function call

Bodsda 
Sent from my BlackBerry® wireless device

-Original Message-
From: "Mic" 
Sender: tutor-bounces+bodsda=googlemail@python.org
Date: Tue, 29 Nov 2011 15:54:59 
To: 
Subject: [Tutor] Making a function run every second.

Hi

I want a function to run every second , how do I do that?

Say that the function look like this:

def hi():
print("hi")


Thanks! 


Mic
___
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] How to handle try and except in this case

2011-11-29 Thread Dave Angel
(You top-posted again.  Try to put your remarks AFTER the part you're 
quoting, so that the message is self-descriptive)


On 11/29/2011 10:16 AM, Mic wrote:

Could you explain what's unclear about it? Andreas couldn't get more
specific, since you didn't say how these 10 names are provided.



Yes, it was probably my fault. Sorry about that. I have come up with a
new way of working around
a problem in my main program so I only need two files to be tested if
they exist instead of say 10 files.

So, the program should check if two text files exist. If neither of them
exist, and only if neither of them,
then the program should print say "hi".

If only one of them exist, the program should continue to run without
crashing.


I hope this was more easy to understand!



The os.path.exists(filename) returns a boolean, and doesn't tie up 
resources, so you are welcome to use it in an if expression.


if not (os.path.exists(file1) and os.path.exists(file2)):
 print "hi"


--

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


Re: [Tutor] problem with msg widget & button

2011-11-29 Thread Peter Otten
Cranky Frankie wrote:

> OK, I've stripped out all the comments and put it here:
> 
> http://www.pastie.org/2938751
> 
> 
> This works but the button doesn't put the next comment in the window.
> The only way I could figure to get the next comment in the window is
> to add the msg_widget line to the disp_quote function, but when I do
> that, it puts out *another* msg-widget! That is not what I want at
> all. I just want the next quote button to put the next quote in the
> box.

Hm, your description doesn't match with the code you posted which only 
creates one Message.

Also you still initialize the command parameter with the function result

Button(..., command=f()) # wrong

instead of the function itself

Button(..., command=f) # correct.

Here's a fixed version:


#!/usr/bin/python3

import random  
from tkinter import *   

quote_dict = {
1:["Kahlil Gibran", "A candle loses nothing of its light when lighting 
another."],
# ...
}

def choose_quote():
rand_quote = (random.randrange(len(quote_dict))+1)  
quote = quote_dict[rand_quote][1]
author = quote_dict[rand_quote][0]   
return (quote+"\n\n"+author)   

def display_quote():
msg_widget["text"] = choose_quote()

root = Tk()
win = Frame()   
win.pack() 

label_widget = Label(win, text="Welcome to Quote of the Day")   
label_widget.pack(side = TOP, expand=YES, fill=BOTH)   

msg_widget = Message(
win, anchor=NW, justify=LEFT, width=1000, bd=2,
bg="white", relief=SOLID, text=choose_quote())
msg_widget.pack()   

next_button = Button(win, text="Next Quote", command=display_quote) 
next_button.pack(side=LEFT)

quit_button = Button(win, text="QUIT", fg="red", command=quit) 
quit_button.pack(side=RIGHT)

root.mainloop()


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


Re: [Tutor] Making a function run every second.

2011-11-29 Thread Peter Otten
Mic wrote:

> I want a function to run every second , how do I do that?
> 
> Say that the function look like this:
> 
> def hi():
> print("hi")

For a console app you could use a for-loop with time.sleep() or
http://docs.python.org/dev/py3k/library/sched.html

For a script that uses tkinter there's the after() method.
Example:

root = Tk()

def hi():
print("ho")

def hi_reschedule():
hi()
# make tkinter call it again after 1000 milliseconds
root.after(1000, hi_reschedule) 

hi_reschedule() # call it manually the first time

http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html


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


Re: [Tutor] Making a function run every second.

2011-11-29 Thread Dave Angel
(You put your response in the wrong place;  it belongs after the part 
you're quoting.)

he
On 11/29/2011 10:19 AM, bod...@googlemail.com wrote:

You won't get it exactly on because the time it takes to call the function will 
affect your trigger time.

I would use something like an infinite loop with a 1 second sleep after the 
function call

Bodsda
Sent from my BlackBerry® wireless device

-Original Message-
From: "Mic"
Sender: tutor-bounces+bodsda=googlemail@python.org
Date: Tue, 29 Nov 2011 15:54:59
To:
Subject: [Tutor] Making a function run every second.

Hi

I want a function to run every second , how do I do that?

Say that the function look like this:

def hi():
 print("hi")


Thanks!


Mic
Without a clearer spec, there are too many possible answers.  As Bobsda 
says, you can't get it exactly one second apart.  But you also have the 
problem of whether a drift is okay.  For example, if you have a global 
you're incrementing each time that function runs, and you want it to 
represent the total time the program has been running, then a simple 
sleep() is totally wrong.


What I was concerned about is that perhaps this is for one of the 
tkinter programs Mic is writing.  For an event-driven program, sleep() 
calls of even a second are unaccepable.  And if you literally write a 
while loop like that, your whole program would stop responding.


So Mik:
Tell us more about the real requirements.  Is drift acceptable, is this 
a console program or some gui environment, are there any other hidden 
assumptions?


--

DaveA

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


Re: [Tutor] Making a function run every second.

2011-11-29 Thread Mic



-Ursprungligt meddelande- 
From: bod...@googlemail.com

Sent: Tuesday, November 29, 2011 4:19 PM
To: Mic ; tutor-bounces+bodsda=googlemail@python.org ; Tutor - python 
List

Subject: Re: [Tutor] Making a function run every second.

You won't get it exactly on because the time it takes to call the function 
will affect your trigger time.


Alright, but that doesn't matter. About every second would be good.

I would use something like an infinite loop with a 1 second sleep after the 
function call


I see, could you explain a little more detailed?


Thanks you for your reply!




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


Re: [Tutor] How to handle try and except in this case

2011-11-29 Thread Mic



-Ursprungligt meddelande- 
From: Dave Angel 
Sent: Tuesday, November 29, 2011 4:25 PM 
To: Mic 
Cc: tutor@python.org 
Subject: Re: [Tutor] How to handle try and except in this case 

(You top-posted again.  Try to put your remarks AFTER the part you're 
quoting, so that the message is self-descriptive)


I did? I thought I posted this: 


"""

Could you explain what's unclear about it?  Andreas couldn't get more 
specific, since you didn't say how these 10 names are provided.



Yes, it was probably my fault. Sorry about that. I have come up with a new 
way of working around
a problem in my main program so I only need two files to be tested if they 
exist instead of say 10 files. """



Is that top posting?

The os.path.exists(filename) returns a boolean, and doesn't tie up 
resources, so you are welcome to use it in an if expression.



if not (os.path.exists(file1) and os.path.exists(file2)):

 >print "hi"


Thank you! What do you mean with that it "doesn't tie up resources"?


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


Re: [Tutor] why doesn't python show error

2011-11-29 Thread Max gmail
In some cases, it is a useful fact that Python only shows error messages when 
they are encountered.  For example, I can test a program while keeping away 
from an area that still doesn't work, rather than having to make it work 
flawlessly before my first test.

Python *can* generate executables with py2exe, though if you use Python 3 
you'll need to learn to convert your code to Python 2.  Or, as Blender does, 
you could include Python in the download of your program, so that the user 
installs both your program and Python.

On Nov 28, 2011, at 4:53 AM, surya k wrote:

> 
> 1. Why doesn't python show error(description given below) at the beginning 
> when we use functions which aren't present in the standard modules...
> 
> Example: 
> 
> TheString = raw_input('enter a string')lengthofStr = strlen(TheString)Look 
> closely, I used a wrong function to find length of the string. [ strlen( ) 
> belongs to C ].When I run the program, it didn't show any error but when 
> entered input, it then showed up!.Why python doesn't show error at the 
> beginning just like C does?2. Why doesn't python create executable file (.exe 
> ) when we run the code.. If this doesn't do, how can I share my program.. 
> does everyone need to have python to check others code and know what it does? 
> 
> ___
> 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] How to handle try and except in this case

2011-11-29 Thread Dave Angel

On 11/29/2011 10:35 AM, Mic wrote:



-Ursprungligt meddelande- From: Dave Angel Sent: Tuesday,
November 29, 2011 4:25 PM To: Mic Cc: tutor@python.org Subject: Re:
[Tutor] How to handle try and except in this case

(You top-posted again. Try to put your remarks AFTER the part you're
quoting, so that the message is self-descriptive)


  

Is that top posting?



No, you're absolutely right.  I don't know what I was looking at.  Maybe 
I had your message scrolled when I was reading it.  I am sorry.



The os.path.exists(filename) returns a boolean, and doesn't tie up
resources, so you are welcome to use it in an if expression.



if not (os.path.exists(file1) and os.path.exists(file2)):

 >print "hi"


Thank you! What do you mean with that it "doesn't tie up resources"?


If you do multiple opens in the same expression, you can't easily* 
capture all the file objects, especially in the case of an exception. 
So there may be files left open that will get closed an indeterminate 
amount of time in the future.  That sort of thing is probably acceptable 
if the program is short-lived, but even then you can run into 
file-sharing conflicts.  Note that current CPython versions are pretty 
good about closing files if you don't save the object, but other 
versions might not get around to it for a while.





Mic



* (you can partially solve this if you put the open inside a list 
comprehension or equivalent, but exceptions still rear their ugly heads)


--

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


Re: [Tutor] Making a function run every second.

2011-11-29 Thread Mic



-Ursprungligt meddelande- 
From: Dave Angel

Sent: Tuesday, November 29, 2011 4:33 PM
To: bod...@googlemail.com
Cc: Mic ; Tutor - python List
Subject: Re: [Tutor] Making a function run every second.


(You put your response in the wrong place;  it belongs after the part

you're quoting.)

Okay, thanks.


On 11/29/2011 10:19 AM, bod...@googlemail.com wrote:
You won't get it exactly on because the time it takes to call the 
function will affect your trigger time.


I would use something like an infinite loop with a 1 second sleep after 
the function call



Bodsda

Sent from my BlackBerry® wireless device


-Original Message-
From: "Mic"
Sender: tutor-bounces+bodsda=googlemail@python.org
Date: Tue, 29 Nov 2011 15:54:59
To:
Subject: [Tutor] Making a function run every second.



Hi



I want a function to run every second , how do I do that?



Say that the function look like this:



def hi():

 print("hi")


Without a clearer spec, there are too many possible answers.  As Bobsda 
says, you can't get it exactly one second apart.  But you also have the 
problem of whether a drift is okay.  For example, if you have a global 
you're incrementing each time that function runs, and you want it to 
represent the total time the program has been running, then a simple 
sleep() is totally wrong.


Okay, I undestand. Hmm, what is a drift?

What I was concerned about is that perhaps this is for one of the tkinter 
programs Mic is writing.  For an event-driven program, sleep() calls of 
even a second are unaccepable.  And if you literally write a while loop 
like that, your whole program would stop responding.


Yes, this is one of my tkinter programs :) Why would the program stop 
responding using a sleep()?



So Mik:
Tell us more about the real requirements.  Is drift acceptable, is this a 
console program or some gui environment, are there any other hidden 
assumptions?


Okay, this function approximately runs every second and check what the time 
is.
(Well, every 30 second or every minute would be okay if that makes it 
easier)
If the time is 15:00 it is supposed to remove a file. That should be all 
requirements!


I have figured out how to make the function check what time it is and how to
remove the file when the time is 15:00, but I don't know how to make it run 
every

second or something like that.


Thanks!

Mic 


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


[Tutor] problem with msg widget & button

2011-11-29 Thread Cranky Frankie
Peter Otten <__pete...@web.de> wrote:

snip

<>

What I meant to say was, yes, I only want one message object, but I
want that same object to be updated each time the next quote button is
pressed.

<>

snip again

OK, I think I tried it several ways and couldn't get any of them to
work, but I tried your version and the button now works! My only
question is this line, which is what I was missing:

def display_quote():
   msg_widget["text"] = choose_quote()

Isn't msg_widget an object, like everything else in Python. If so, why is it not

def display_quote():
   msg_widget.text = choose_quote()

That is one of the things I tried. I don't understand why the ["test"]
pair works above.

Now my only problem is the msg_widget box resizing. I'm using the
.pack frame manager like the examples I've been reading say. I know
there's a grid manager as well. I'll have to try that. All I want is
the msg_widget to display the same size each time, no matter what size
string is in it.

Thanks Peter!








-- 
Frank L. "Cranky Frankie" Palmeri
Risible Riding Raconteur & Writer
“How you do anything is how you do everything.”
- from Alabama Crimson Tide training room
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Making a function run every second.

2011-11-29 Thread Mic


Mic wrote:


I want a function to run every second , how do I do that?

Say that the function look like this:

def hi():
print("hi")




For a script that uses tkinter there's the after() method.
Example:



root = Tk()



def hi():

   >print("ho")


def hi_reschedule():

  > hi()
   ># make tkinter call it again after 1000 milliseconds
   >root.after(1000, hi_reschedule)

hi_reschedule() # call it manually the first time




http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html


Nice!

Thank you!




--

Message: 3
Date: Tue, 29 Nov 2011 10:33:41 -0500
From: Dave Angel 
To: bod...@googlemail.com
Cc: Tutor - python List , Mic 
Subject: Re: [Tutor] Making a function run every second.
Message-ID: <4ed4fb55.1000...@davea.name>
Content-Type: text/plain; charset=windows-1252; format=flowed

(You put your response in the wrong place;  it belongs after the part
you're quoting.)
he
On 11/29/2011 10:19 AM, bod...@googlemail.com wrote:
You won't get it exactly on because the time it takes to call the function 
will affect your trigger time.


I would use something like an infinite loop with a 1 second sleep after 
the function call


Bodsda
Sent from my BlackBerry? wireless device

-Original Message-
From: "Mic"
Sender: tutor-bounces+bodsda=googlemail@python.org
Date: Tue, 29 Nov 2011 15:54:59
To:
Subject: [Tutor] Making a function run every second.

Hi

I want a function to run every second , how do I do that?

Say that the function look like this:

def hi():
 print("hi")


Thanks!


Mic

Without a clearer spec, there are too many possible answers.  As Bobsda
says, you can't get it exactly one second apart.  But you also have the
problem of whether a drift is okay.  For example, if you have a global
you're incrementing each time that function runs, and you want it to
represent the total time the program has been running, then a simple
sleep() is totally wrong.

What I was concerned about is that perhaps this is for one of the
tkinter programs Mic is writing.  For an event-driven program, sleep()
calls of even a second are unaccepable.  And if you literally write a
while loop like that, your whole program would stop responding.

So Mik:
Tell us more about the real requirements.  Is drift acceptable, is this
a console program or some gui environment, are there any other hidden
assumptions?

--

DaveA



--

Message: 4
Date: Tue, 29 Nov 2011 16:35:22 +0100
From: "Mic" 
To: 
Cc: tutor@python.org
Subject: Re: [Tutor] How to handle try and except in this case
Message-ID: 
Content-Type: text/plain; format=flowed; charset="iso-8859-1";
reply-type=response



-Ursprungligt meddelande- 
From: Dave Angel

Sent: Tuesday, November 29, 2011 4:25 PM
To: Mic
Cc: tutor@python.org
Subject: Re: [Tutor] How to handle try and except in this case


(You top-posted again.  Try to put your remarks AFTER the part you're
quoting, so that the message is self-descriptive)


I did? I thought I posted this:

"""


Could you explain what's unclear about it?  Andreas couldn't get more
specific, since you didn't say how these 10 names are provided.



Yes, it was probably my fault. Sorry about that. I have come up with a new
way of working around
a problem in my main program so I only need two files to be tested if they
exist instead of say 10 files. """


Is that top posting?


The os.path.exists(filename) returns a boolean, and doesn't tie up
resources, so you are welcome to use it in an if expression.



if not (os.path.exists(file1) and os.path.exists(file2)):

 >print "hi"


Thank you! What do you mean with that it "doesn't tie up resources"?


Mic


--

Message: 5
Date: Mon, 28 Nov 2011 09:47:06 -0500
From: Max gmail 
To: surya k 
Cc: Python Tutor 
Subject: Re: [Tutor] why doesn't python show error
Message-ID: 
Content-Type: text/plain; charset=iso-8859-1

In some cases, it is a useful fact that Python only shows error messages 
when they are encountered.  For example, I can test a program while keeping 
away from an area that still doesn't work, rather than having to make it 
work flawlessly before my first test.


Python *can* generate executables with py2exe, though if you use Python 3 
you'll need to learn to convert your code to Python 2.  Or, as Blender does, 
you could include Python in the download of your program, so that the user 
installs both your program and Python.


On Nov 28, 2011, at 4:53 AM, surya k wrote:



1. Why doesn't python show error(description given below) at the beginning 
when we use functions which aren't present in the standard modules...


Example:

TheString = raw_input('enter a string')lengthofStr = strlen(TheString)Look 
closely, I used a wrong function to find length of the string. [ strlen( ) 
belongs to C ].When I run the program, it didn't show any error but when 
entered input, it then showed up!.Why python doesn't show error at the 
beginning just like C does?2. Why doesn't p

Re: [Tutor] problem with msg widget & button

2011-11-29 Thread Wayne Werner
On Tue, Nov 29, 2011 at 9:54 AM, Cranky Frankie wrote:

> Peter Otten <__pete...@web.de> wrote:
>
> 

Isn't msg_widget an object, like everything else in Python. If so, why is
> it not
>
> def display_quote():
>   msg_widget.text = choose_quote()
>
> That is one of the things I tried. I don't understand why the ["test"]
> pair works above.
>

Just because msg_widget is an object doesn't automatically give it a .text
attribute. Just like the following dictionary (which is an object):

>>> knights = {'Aurthur': 'King of the Britons', 'Robin':'The Brave'}
>>> knights['Robin']
'The Brave'
>>> knights['Robin'] = 'The Coward'
>>> knights.Robin
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'dict' object has no attribute 'Robin'

They simply made a design choice to allow access to the data via index (in
this case "text" is the index), rather than by object attribute.

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


Re: [Tutor] Making a function run every second.

2011-11-29 Thread Dave Angel

On 11/29/2011 10:52 AM, Mic wrote:



-Ursprungligt meddelande- From: Dave Angel
Sent: Tuesday, November 29, 2011 4:33 PM



-Original Message-
From: "Mic"
Sender: tutor-bounces+bodsda=googlemail@python.org
Date: Tue, 29 Nov 2011 15:54:59
To:
Subject: [Tutor] Making a function run every second.



Hi



I want a function to run every second , how do I do that?



Say that the function look like this:



def hi():

print("hi")



Without a clearer spec, there are too many possible answers. As Bobsda
says, you can't get it exactly one second apart. But you also have the
problem of whether a drift is okay. For example, if you have a global
you're incrementing each time that function runs, and you want it to
represent the total time the program has been running, then a simple
sleep() is totally wrong.


Okay, I undestand. Hmm, what is a drift?


What I was concerned about is that perhaps this is for one of the
tkinter programs Mic is writing. For an event-driven program, sleep()
calls of even a second are unaccepable. And if you literally write a
while loop like that, your whole program would stop responding.


Yes, this is one of my tkinter programs :) Why would the program stop
responding using a sleep()?



I'm not that familiar with tkinter details.  But like all (almost??) 
GUI's it relies on an event loop.  Each event has to be "quick" for some 
definition of quick.  In the case of tkinter, I believe that eventloop 
is called mainloop().  That loop won't return till you hit the X button 
in the corner, or do something else that triggers program cancellation. 
 That loop is the thing that interacts with the OS, and calls various 
event handlers as things happen.   If you were to do a loop of  sleep() 
before you got to the mainloop() call, the GUI would never start.  If 
you do it inside some event, then the mainloop() never gets control again.


tkinter provides a couple of specific timer events, and I now see your 
reply to a message that said to use the after() method, which is a 
one-shot.  I believe there's another one that sets a periodic timer so 
you don't have to do an after() call each time it fires.



So Mik:
Tell us more about the real requirements. Is drift acceptable, is this
a console program or some gui environment, are there any other hidden
assumptions?


Okay, this function approximately runs every second and check what the
time is.
(Well, every 30 second or every minute would be okay if that makes it
easier)
If the time is 15:00 it is supposed to remove a file. That should be all
requirements!

I have figured out how to make the function check what time it is and
how to
remove the file when the time is 15:00, but I don't know how to make it
run every
second or something like that.


Thanks!

Mic




--

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


Re: [Tutor] Making a function run every second.

2011-11-29 Thread Wayne Werner
On Tue, Nov 29, 2011 at 10:09 AM, Dave Angel  wrote:

> tkinter provides a couple of specific timer events, and I now see
> your reply to a message that said to use the after() method, which is a
> one-shot.  I believe there's another one that sets a periodic timer so you
> don't have to do an after() call each time it fires.
>

Not in Tkinter - you have to do what Peter Otten suggested:


> For a script that uses tkinter there's the after() method.
> Example:
> root = Tk()
> def hi():
>print("ho")
> def hi_reschedule():
>hi()
># make tkinter call it again after 1000 milliseconds
>root.after(1000, hi_reschedule)
> hi_reschedule() # call it manually the first time



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


Re: [Tutor] useful function or reinventing the wheel??

2011-11-29 Thread Emile van Sebille

On 11/28/2011 8:30 PM Mark Lybrand said...


I am a habitual wheel re-inventor,


For anyone who hasn't yet discovered effbot's guide to the python 
library, it's a good place to start as you expand your python skills.


see http://effbot.org/librarybook and in particular for your current 
question, you'll find makedirs with sample code at


http://effbot.org/media/downloads/librarybook-core-modules.pdf

Although dated, it's still a great place to start as most internal 
functions have changed little over the years.


Emile


so it would not surprise me, but I

made this little function that I was kinda proud of (seeing that I have
only been learning python like a week now):

It just takes a directory and checks to see if all the directories,
sub-directories exist and creates them if they don't:

def insure_exists_dir(dir):
   grow_path = [dir]
   while not os.path.ismount(grow_path[0]):
 part_tuple = os.path.split(grow_path[0])
 grow_path.insert(0, part_tuple[0])

   del(grow_path[0])
   while grow_path:
 if not os.path.exists(grow_path[0]):
   os.mkdir(grow_path[0])
 del(grow_path[0])
   return(dir)


Opinions?  What should I really be using?

--
Mark :)


___
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] Making a function run every second.

2011-11-29 Thread Dave Angel

On 11/29/2011 11:09 AM, Dave Angel wrote:

On 11/29/2011 10:52 AM, Mic wrote:



Okay, I undestand. Hmm, what is a drift?

I just noticed I hadn't answered that one.  It doesn't matter any more 
since you're running tkinter.


But for completeness:

If you had a non-event driven program (eg. a console app), and you had a 
loop like the following:



SLEEPTIME = 1
while True:
sleep(SLEEPTIME)
myfunc()

myfunc() would  be called about once a second.  However, in a heavily 
loaded system, it might be 1.2 seconds one time, and 1.1 the next.  So 
it might be called only 50 times in that minute, rather than 60.  I 
believe that in some OS's, it might be called 75 times in a minute.  
Anyway, if drift is to be avoided, you need to keep track of the time 
that the next call should be made, compare it to "now", and calculate 
what to pass as a parameter to sleep().


In untested approx. code,

import time
import itertools
starttime = float(now())
SLEEPTIME = 1   (for one second)

for intervalnum in itertools.count():
  delayneeded = starttime + SLEEPTIME*intervalnum - now()
  time.sleep(delayneeded)
  myfunc()

if this drifts, it tries to compensate on the next iteration.  Note that 
there are cleverer implementations of this fundamental scheme, depending 
on other requirements or goals.


--

DaveA

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


[Tutor] tkinter message & button questions

2011-11-29 Thread Cranky Frankie
I changed the quote program to use the grid manager:

http://www.pastie.org/2939778

Still, the message widget box keeps resizing based on the length of
the quote. I'm thinking it has to be something to do with the message
widget itself, not the pack vs. grid manager.

When I research this I find that a lot of the information on the
message widget does not work in Python 3.1 - for example, the height
parameter does not work in 3.1.

-- 
Frank L. "Cranky Frankie" Palmeri
Risible Riding Raconteur & Writer
“How you do anything is how you do everything.”
- from Alabama Crimson Tide training room
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to write lines in a text file (GUI)

2011-11-29 Thread Mic

Hey again.

I figured I would first post this piece of code and then ask my questions.

FREE = "green"
OCCUPIED = "red"

class Mainwindow(Frame):
def __init__(self,master):
super(Mainwindow,self).__init__(master)
self.grid()
self.create_mainwidgets()

def create_mainwidgets(self):
self.klicka=Button(self, text="Press the button",
   command=self.uppdatera)
self.klicka.grid()

def uppdatera(self):
SeatWindow(root)

class SeatButton(tk.Button):
def __init__(self, master, index):
text = str(index+1)
super(SeatButton, self).__init__(master,
 text=text, bg=FREE,
 command=self.clicked)
self.filename = "Germany_France{}.txt".format(index+1)
self.occupied = False
if os.path.exists(self.filename):
 self["bg"]=OCCUPIED

def clicked(self):
self.occupied = not self.occupied
if self.occupied:
self["bg"] = OCCUPIED
text_file=open(self.filename,"w")
text_file.write(self.filename)
text_file.close()
else:
self["bg"] = FREE
os.remove(self.filename)

class SeatWindow(tk.Toplevel):
 def __init__(self, master):
 super (SeatWindow, self).__init__(master)
 self.grid()
 self.create_widgets()

 def create_widgets(self):
 for index in range(20):
 button = SeatButton(self, index)
 row, column = divmod(index, 4)
 button.grid(row=row, column=column)

root=Tk()
root.title("testV2")
app=Mainwindow(root)
root.mainloop()




I am now writing another program. It turned out just fine, but I have one
question.

If button one is pressed I want the program to write, say hi_1, on the first
line in a text file.
If button one is pressed again, the first line should be empty.

If button two is pressed I want the program to write hi_2 in the second line
in the text file.
If button two is pressed again, the second line in the text file should be
empty.

If button three is pressed I want the program to write hi_3 in the third
line in the text file.
if button three is pressed again, the third line in the text file should be
empty.

There shouldn't be any other changes to the program other than this above.
There is already a text file
created, the program doesn't need to create one. We can call that file "Hi".


I hope you understand what I want to do here. I have tried the entire
evening yesterday to get this to work, I tried using writeline() but I can't
get it to work.
What are your suggestions to this?



Thank you for your help and time!

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


Re: [Tutor] How to write lines in a text file (GUI)

2011-11-29 Thread Dave Angel

On 11/29/2011 01:02 PM, Mic wrote:

Hey again.

I figured I would first post this piece of code and then ask my 
questions.



How is this different from the question you posted 3 hours ago, with

subject:   "[Tutor] Creating a line in a text file every time a button 
ispressed."


I'm working on a response to that one, but I wanted to wait for my lunch 
hour.  Don't forget that everyone here's a volunteer.  If you don't get 
a response for a couple of days, reply to the original message to add 
some more information, or to get people's attention.  If it's the same 
question, keep it in the same thread.


--

DaveA


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


Re: [Tutor] Creating a line in a text file every time a button is pressed.

2011-11-29 Thread Dave Angel

On 11/29/2011 10:09 AM, Mic wrote:

Hey again.





root=Tk()
root.title("testV2")
app=Mainwindow(root)
root.mainloop()




What's that code got to do with the question below?


I am now writing another program. It turned out just fine, but I have 
one question.


If button one is pressed I want the program to write, say hi_1, on the 
first line in a text file.

If button one is pressed again, the first line should be empty.

If button two is pressed I want the program to write hi_2 in the 
second line in the text file.
If button two is pressed again, the second line in the text file 
should be empty.


You can't in general write randomly to a text file, especially if the 
line length changes.


If button three is pressed I want the program to write hi_3 in the 
third line in the text file.
if button three is pressed again, the third line in the text file 
should be empty.


There shouldn't be any other changes to the program other than this 
above. There is already a text file
created, the program doesn't need to create one. We can call that file 
"Hi".



I hope you understand what I want to do here. I have tried the entire 
evening yesterday to get this to work, I tried using writeline() but I 
can't get it to work.

What are your suggestions to this?


You have at least three choices:
   1)  abandon the notion of a text file for this purpose.  Make it a 
structured (binary) file, with fixed length fields.
   2)  same thing, but fake it in a text file, either by changing the 
contents so it's always the same size, or putting in redundant blanks.
   3)  reconstruct the entire file every time you want to change a line 
(other than the last one) to something larger or smaller.



For #3,
If the file is only about 3 lines, keep a list in memory, and dump the 
whole list to the file every time you change one of the items.


For #1 and #2, you should look up the seek() method of the file class.


--

DaveA

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


Re: [Tutor] How to write lines in a text file (GUI)

2011-11-29 Thread bodsda
Hi,

This is a very simple objective to achieve, so instead of giving you a straight 
up solution, I will just nudge your train of thought in the right direction.

Note: I'm struggling to follow your code whilst reading on my phone so the 
following suggestions make no reference to your particular codebase

Let's first assume that all buttons could be pressed in any order, therefore 
given the following presses: but1, but2, but2, but3, we will have the first 
line with hi_1, the second line empty and the third line hi_3. Now I also 
assume that there is no 'update file' button, therefore each press of a button 
needs to update the file making a change to a single line. That sounds to me 
like a good use for an update_file function that accepts a parameter of which 
line should be updated. So the main challenge is to write a function that can 
read/write to a file certain data depending on the argument passed. The 
function should:

Read file
Identify line to be changed
If line empty
Change line to hi_#
Write file

When you open a file, you could then use the read function to read the whole 
file, or you could use the readlines function to read the file line by line. 
Experiment with both, see what data types they both return and decide which is 
most suitable. Bear in mind you need to easily differentiate each line and 
access them individually.

If your still struggling to write this function, show us how far you get and we 
can go from there.

Hope this helps,
Bodsda 
Sent from my BlackBerry® wireless device

-Original Message-
From: "Mic" 
Sender: tutor-bounces+bodsda=googlemail@python.org
Date: Tue, 29 Nov 2011 19:02:52 
To: 
Subject: [Tutor] How to write lines in a text file (GUI)

Hey again.

I figured I would first post this piece of code and then ask my questions.

FREE = "green"
OCCUPIED = "red"

class Mainwindow(Frame):
 def __init__(self,master):
 super(Mainwindow,self).__init__(master)
 self.grid()
 self.create_mainwidgets()

 def create_mainwidgets(self):
 self.klicka=Button(self, text="Press the button",
command=self.uppdatera)
 self.klicka.grid()

 def uppdatera(self):
 SeatWindow(root)

class SeatButton(tk.Button):
 def __init__(self, master, index):
 text = str(index+1)
 super(SeatButton, self).__init__(master,
  text=text, bg=FREE,
  command=self.clicked)
 self.filename = "Germany_France{}.txt".format(index+1)
 self.occupied = False
 if os.path.exists(self.filename):
  self["bg"]=OCCUPIED

 def clicked(self):
 self.occupied = not self.occupied
 if self.occupied:
 self["bg"] = OCCUPIED
 text_file=open(self.filename,"w")
 text_file.write(self.filename)
 text_file.close()
 else:
 self["bg"] = FREE
 os.remove(self.filename)

class SeatWindow(tk.Toplevel):
  def __init__(self, master):
  super (SeatWindow, self).__init__(master)
  self.grid()
  self.create_widgets()

  def create_widgets(self):
  for index in range(20):
  button = SeatButton(self, index)
  row, column = divmod(index, 4)
  button.grid(row=row, column=column)

root=Tk()
root.title("testV2")
app=Mainwindow(root)
root.mainloop()




I am now writing another program. It turned out just fine, but I have one
question.

If button one is pressed I want the program to write, say hi_1, on the first
line in a text file.
If button one is pressed again, the first line should be empty.

If button two is pressed I want the program to write hi_2 in the second line
in the text file.
If button two is pressed again, the second line in the text file should be
empty.

If button three is pressed I want the program to write hi_3 in the third
line in the text file.
if button three is pressed again, the third line in the text file should be
empty.

There shouldn't be any other changes to the program other than this above.
There is already a text file
created, the program doesn't need to create one. We can call that file "Hi".


I hope you understand what I want to do here. I have tried the entire
evening yesterday to get this to work, I tried using writeline() but I can't
get it to work.
What are your suggestions to this?



Thank you for your help and time!

___
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] How to write lines in a text file (GUI)

2011-11-29 Thread Mic



How is this different from the question you posted 3 hours ago, with


subject:   "[Tutor] Creating a line in a text file every time a button is 
pressed."



Sorry about the repost. My Email-client is set to resend the mail if it is 
marked
as spam by the reciever. So, it wasn't the case, you didn't get it as spam 
mail?


Hmm, this is the second time it happens today, could it be that I am sending 
from
an hotmail address, perhaps they think that these addresses are more likely 
to

be spam?


I'm working on a response to that one, but I wanted to wait for my lunch
hour.  Don't forget that everyone here's a volunteer.  If you don't get
a response for a couple of days, reply to the original message to add
some more information, or to get people's attention.  If it's the same
question, keep it in the same thread.

Oh, where are you living if you are waiting for lunch?  It's past dinner 
here,
so that's why I got mails in the middle of the night! I thought most people 
were

from UK!

Mic



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


Re: [Tutor] tkinter message & button questions

2011-11-29 Thread Peter Otten
Cranky Frankie wrote:

> I changed the quote program to use the grid manager:
> 
> http://www.pastie.org/2939778
> 
> Still, the message widget box keeps resizing based on the length of
> the quote. I'm thinking it has to be something to do with the message
> widget itself, not the pack vs. grid manager.


I've no experience with the place layout manager, but the following seems to 
be what you want:

root = Tk()
win = Frame(root)
win.place(relheight=1, relwidth=1)

label_widget = Label(win, text="Welcome to Quote of the Day")
label_widget.pack(side=TOP, expand=YES, fill=BOTH)

msg_widget = Message(
win, anchor=NW, justify=LEFT, width=1000, bd=2,
bg="white", relief=SOLID, text=choose_quote())
msg_widget.pack(fill=BOTH)

next_button = Button(win, text="Next Quote", command=display_quote)
next_button.pack(side=LEFT)

quit_button = Button(win, text="QUIT", fg="red", command=quit)
quit_button.pack(side=RIGHT)

root.geometry("400x100")
root.mainloop()


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


Re: [Tutor] How to write lines in a text file (GUI)

2011-11-29 Thread Mic



Note: I'm struggling to follow your code whilst reading on my phone so the 
following suggestions make no reference to your particular codebase


Okay I understand. Perhaps it doesn't matter.

Let's first assume that all buttons could be pressed in any order, 
therefore given the following presses: but1, but2, but2, but3, we will have 
the first line with hi_1, the second line empty and the third line hi_3. 
Now I also assume that there >is no 'update file' button, therefore each 
press of a button needs to update the file making a change to a single 
line. That sounds to me like a good use for an update_file function that 
accepts a parameter of which line should be updated. >So the main challenge 
is to write a function that can read/write to a file certain data depending 
on the argument passed. The function should:



Read file
Identify line to be changed
If line empty
Change line to hi_#
Write file


When you open a file, you could then use the read function to read the 
whole file, or you could use the readlines function to read the file line 
by line. Experiment with both, see what data types they both return and 
decide which is most >suitable. Bear in mind you need to easily 
differentiate each line and access them individually.


If your still struggling to write this function, show us how far you get 
and we can go from there.


Actually, I nearly know how do to solve this problem. I just have one 
problem. Can I use writeline() to write text into line 3 or line 5 for 
example?
Say that I want to write the text "hi" into line five of a text file, can I 
do this using writeline(), if so, how ?


Thanks for the response!


Hope this helps,
Bodsda
Sent from my BlackBerry® wireless device

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


[Tutor] list, tuple or dictionary

2011-11-29 Thread ADRIAN KELLY

i am trying to create a program that will allow users to enter items and their 
prices; should i be looking at a list, tuple or what?
many thanksadrian

 

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


Re: [Tutor] How to write lines in a text file (GUI)

2011-11-29 Thread bodsda
I'm not sure, I also don't have access to the python docs atm, but the simplest 
method would be to read the whole file into a list, edit the correct item 
(remembering to count from 0 not 1) and then writing the whole list back to the 
file.

Bodsda 
--Original Message--
From: Mic
To: bod...@googlemail.com
To: tutor-bounces+bodsda=googlemail@python.org
To: Tutor - python List
Subject: Re: [Tutor] How to write lines in a text file (GUI)
Sent: 29 Nov 2011 19:24



>Note: I'm struggling to follow your code whilst reading on my phone so the 
>following suggestions make no reference to your particular codebase

Okay I understand. Perhaps it doesn't matter.

>Let's first assume that all buttons could be pressed in any order, 
>therefore given the following presses: but1, but2, but2, but3, we will have 
>the first line with hi_1, the second line empty and the third line hi_3. 
>Now I also assume that there >is no 'update file' button, therefore each 
>press of a button needs to update the file making a change to a single 
>line. That sounds to me like a good use for an update_file function that 
>accepts a parameter of which line should be updated. >So the main challenge 
>is to write a function that can read/write to a file certain data depending 
>on the argument passed. The function should:

>Read file
>Identify line to be changed
>If line empty
>Change line to hi_#
>Write file

>When you open a file, you could then use the read function to read the 
>whole file, or you could use the readlines function to read the file line 
>by line. Experiment with both, see what data types they both return and 
>decide which is most >suitable. Bear in mind you need to easily 
>differentiate each line and access them individually.

>If your still struggling to write this function, show us how far you get 
>and we can go from there.

Actually, I nearly know how do to solve this problem. I just have one 
problem. Can I use writeline() to write text into line 3 or line 5 for 
example?
Say that I want to write the text "hi" into line five of a text file, can I 
do this using writeline(), if so, how ?

Thanks for the response!


Hope this helps,
Bodsda
Sent from my BlackBerry® wireless device


Sent from my BlackBerry® wireless device
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list, tuple or dictionary

2011-11-29 Thread bodsda
You could use any of them, but a dict would be the most logical assuming no 
duplicate items

Bodsda 
Sent from my BlackBerry® wireless device

-Original Message-
From: ADRIAN KELLY 
Sender: tutor-bounces+bodsda=googlemail@python.org
Date: Tue, 29 Nov 2011 20:31:56 
To: 
Subject: [Tutor] list, tuple or dictionary

___
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] list, tuple or dictionary

2011-11-29 Thread Wayne Werner
On Tue, Nov 29, 2011 at 2:31 PM, ADRIAN KELLY wrote:

>  i am trying to create a program that will allow users to enter items and
> their prices; should i be looking at a list, tuple or what?
>

The entering part isn't as important as how you want to display the data.
For instance, here's a program that allows the user to input an unlimited
amount of data (using Python 3.x):

while input("Enter q to quit, or an item: ").lower() not in ('q', 'quit',
'goodbye'):
 input("Enter the price: ")

Of course it doesn't store the data, so it's pretty useless. But it does
allow the user to input whatever they want.

If you wanted to simply create a collection of items you could do it as a
list with alternating values:

inventory = ['Crunchy Frog', 4.13, 'Anthrax Ripple', 12.999,
'Spring Surprise', 0.00]
for x in range(0, len(inventory)-1, 2):
  print(inventory[x], inventory[x+1])

Or as a list of tuples:

inventory = [('Norwegian Blue', 500.00), ('Slug', 500.00), ('Cage',
50.00)]
for item in inventory:
print(item[0], item[1])

Or a dictionary:

inventory = {'Spam':5.00, 'Spam on eggs':10.00, 'Spam on Spam':7.50}
for item, price in inventory.items():
print(item, price)

Or if you wanted to get ridiculous, you could go with a list of classes:

class Item:
def __init__(self, desc='', price=0.00):
self.desc = desc
self.price = price
def __repr__(self):
return str(self)
def __str__(self):
return "{0} - {1}".format(self.desc, self.price)

inventory = [Item('Lumberjack', 5.5), Item('Tree', 50), Item('Flapjack',
0.5)]
for item in inventory:
print(item)


It just depends on how complex you want to get!
HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list, tuple or dictionary

2011-11-29 Thread ADRIAN KELLY

thanks guy, i was thinking of using a dictionary:- Stock_list = {"White Bread": 
1.24,"Biscuits": 1.77,"Banana" : 0.23,"Tea 
Bags" : 2.37,"Eggs" : 1.23,"Beans" : 0.57}
how would i go about adding, for example tea and eggs to get a subtotal? 

  

Adrian Kelly 
1 Bramble Close

Baylough

Athlone

County Westmeath

0879495663


From: waynejwer...@gmail.com
Date: Tue, 29 Nov 2011 14:49:00 -0600
Subject: Re: [Tutor] list, tuple or dictionary
To: kellyadr...@hotmail.com
CC: tutor@python.org

On Tue, Nov 29, 2011 at 2:31 PM, ADRIAN KELLY  wrote:







i am trying to create a program that will allow users to enter items and their 
prices; should i be looking at a list, tuple or what?
The entering part isn't as important as how you want to display the data. For 
instance, here's a program that allows the user to input an unlimited amount of 
data (using Python 3.x):


while input("Enter q to quit, or an item: ").lower() not in ('q', 'quit', 
'goodbye'):

 input("Enter the price: ")
Of course it doesn't store the data, so it's pretty useless. But it does allow 
the user to input whatever they want.


If you wanted to simply create a collection of items you could do it as a list 
with alternating values:


inventory = ['Crunchy Frog', 4.13, 'Anthrax Ripple', 12.999, 
'Spring Surprise', 0.00]

for x in range(0, len(inventory)-1, 2):  print(inventory[x], 
inventory[x+1])
Or as a list of tuples:  

inventory = [('Norwegian Blue', 500.00), ('Slug', 500.00), ('Cage', 50.00)] 
   for item in inventory:print(item[0], item[1])
Or a dictionary:


inventory = {'Spam':5.00, 'Spam on eggs':10.00, 'Spam on Spam':7.50}for 
item, price in inventory.items():print(item, price)


Or if you wanted to get ridiculous, you could go with a list of classes:
class Item:def __init__(self, desc='', price=0.00):self.desc = desc

self.price = pricedef __repr__(self):return str(self)
def __str__(self):return "{0} - {1}".format(self.desc, self.price)


inventory = [Item('Lumberjack', 5.5), Item('Tree', 50), Item('Flapjack', 
0.5)]for item in inventory:print(item)

It just depends on how complex you want to get!

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


Re: [Tutor] list, tuple or dictionary

2011-11-29 Thread Wayne Werner
On Tue, Nov 29, 2011 at 3:04 PM, ADRIAN KELLY wrote:

>  thanks guy, i was thinking of using a dictionary:-
>  Stock_list = {"White Bread": 1.24,
> "Biscuits": 1.77,
> "Banana" : 0.23,
> "Tea Bags" : 2.37,
> "Eggs" : 1.23,
> "Beans" : 0.57}
>
> how would i go about *adding, *for example tea and eggs to get a subtotal?
>

Why, you would add tea and eggs, of course!

print("Subtotal: ", Stock_list["Tea Bags"] + Stock_list["Eggs"])


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


Re: [Tutor] list, tuple or dictionary

2011-11-29 Thread ADRIAN KELLY

Sound Wayne, thank you

 

 

From: waynejwer...@gmail.com
Date: Tue, 29 Nov 2011 15:11:46 -0600
Subject: Re: [Tutor] list, tuple or dictionary
To: kellyadr...@hotmail.com
CC: tutor@python.org

On Tue, Nov 29, 2011 at 3:04 PM, ADRIAN KELLY  wrote:







thanks guy, i was thinking of using a dictionary:- Stock_list = {"White Bread": 
1.24,"Biscuits": 1.77,"Banana" : 0.23,"Tea 
Bags" : 2.37,

"Eggs" : 1.23,"Beans" : 0.57}
how would i go about adding, for example tea and eggs to get a subtotal?


Why, you would add tea and eggs, of course!
print("Subtotal: ", Stock_list["Tea Bags"] + Stock_list["Eggs"]) 


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


Re: [Tutor] pass tuples to user defined function(beginner)

2011-11-29 Thread Mayo Adams
Apologies for my numerous offenses to protocol, and gratitude for  the
suggestions all around.And yet...  as to the notion of a tuple
existing in some non-Platonic sense, I suspect I will have carry my
confusion away in order to dispel it by further reading.
"Wrong on both counts?" Hey, you win! I WAS wrong. But if it is not a
tuple that is in the file, it would be helpful to know what it is.
Presumably, a string representing a tuple. And as to the matter of
representation,  I cant immediately see how anything in a script is
anything other than a representation of some kind, hence the
distinction between representamen and object does no work for me.

Yes, I should have been clearer as to what I was trying to achieve,
but I underestimated the good will of this community(in most cases)and
their willingness to help.  For which, as I said, much thanks.

On Tue, Nov 29, 2011 at 8:02 AM, Steven D'Aprano  wrote:
> Peter Otten wrote:
>
>> And here's the lazy-bastard version:
>
> [...]
>>
>> ...     print ast.literal_eval(line.strip())
>
> Nice!
>
>
> --
> Steven
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Mayo Adams


287 Erwin Rd.
Chapel Hill, NC 27514
(919)-968-7889
mayoad...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pass tuples to user defined function(beginner)

2011-11-29 Thread Wayne Werner
On Tue, Nov 29, 2011 at 3:40 PM, Mayo Adams  wrote:

>  I cant immediately see how anything in a script is
> anything other than a representation of some kind, hence the
> distinction between representamen and object does no work for me.
>

That's exactly it - when you have something like this in a file named, say
data.txt:

("This", 'is', 'a', 'silly', 'tuple')

Then that's all it is - just text data. I happens to *look* like a tuple,
but it's not. If you rename that file to data.py... well, it's still text
data. If you add an assignment operation to the line:

data = ("This", 'is', 'a', 'silly', 'tuple')

Then you could actually import it with `from data import data`. Once the
data is actually evaluated, then it's "live" - it really is a tuple, and it
can be used in tuple-ish ways.

I think the main reason to make a distinction like that is that if you
encounter a .py file with data like this:

> "__import__('os').system('echo i got you now rm-rf')"

You know it's probably going to do some bad things to your system if you
run it. If you open that in a text editor, on the other hand, it's unlikely
to do anything painful.

I think there's also some use in making the distinction between data and
code. Python provides you with /ridiculously/ easy ways to read in data. So
if you have a bunch of strings that you want in a tuple you should do
something like:

data = tuple(f.open('data.txt').readlines())

Which has the added advantage of *just* reading in strings. If you want to
convert that data into other types (integer, float, etc.) then you can
easily do it explicitly, and explicit is better than implicit.

In reality of course, all the data is just 1's and 0's floating out there,
but I think it's helpful to develop these abstractions.
HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to write lines in a text file (GUI)

2011-11-29 Thread Dave Angel

On 11/29/2011 02:24 PM, Mic wrote:






Actually, I nearly know how do to solve this problem. I just have one 
problem. Can I use writeline() to write text into line 3 or line 5 for 
example?
Say that I want to write the text "hi" into line five of a text file, 
can I do this using writeline(), if so, how ?




This is why you should stick to one thread for one problem.  Read my 
reply on your original thread.  You cannot safely update intermediate 
lines in a text file unless you're positive they're the same length.  
And even then, using seek() to position yourself is fraught with 
problems, especially if you have to work on Windows.


Either use a binary file, or write the whole file out each time.

--

DaveA

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


Re: [Tutor] pass tuples to user defined function(beginner)

2011-11-29 Thread Dave Angel

On 11/29/2011 04:40 PM, Mayo Adams wrote:

Apologies for my numerous offenses to protocol, and gratitude for  the
suggestions all around.And yet...  as to the notion of a tuple
existing in some non-Platonic sense, I suspect I will have carry my
confusion away in order to dispel it by further reading.
"Wrong on both counts?" Hey, you win! I WAS wrong. But if it is not a
tuple that is in the file, it would be helpful to know what it is.
Presumably, a string representing a tuple. And as to the matter of
representation,  I cant immediately see how anything in a script is
anything other than a representation of some kind, hence the
distinction between representamen and object does no work for me.

Yes, I should have been clearer as to what I was trying to achieve,
but I underestimated the good will of this community(in most cases)and
their willingness to help.  For which, as I said, much thanks.


Nicely worded.  We appreciate your confusion, but please realize  that 
each of us comes from a different  background, computing-wise.


In traditional (compiled) languages, there was a sharp and uncrossable 
division between the stuff in source files and the stuff in data files.  
The former got compiled (by multi-million dollar machines) into machine 
code, which used the latter as data, both input and output.  The data 
the user saw never got near a compiler, so the rules of interpreting it 
were entirely different.  A file was just a file, a bunch of bytes made 
meaningful only by the particular application that dealt with it.  And 
the keyboard, screen and printer (and the card punch/reader) were in 
some sense just more files.


This had some (perhaps unforeseen) advantages in isolating the differing 
parts of the application.  Source code was written by highly trained 
people, who tried to eliminate the bugs and crashes before releasing the 
executable to the public.  Once debugged, this code was extremely 
protected against malicious and careless users (both human and virus, 
both local and over the internet) who might manage to corrupt things.  
The operating systems and hardware were also designed to make this 
distinction complete, so that even buggy programs couldn't harm the 
system itself.  I've even worked on systems where the code and the data 
weren't even occupying the same kind of memory.  When a program crashed 
the system, it was our fault, not the users' because we didn't give him 
(at least not on purpose) the ability to run arbitrary code.


then came the days of MSDOS, which is a totally unprotected operating 
system, and scripting languages and interpreters, which could actually 
run code from data files, and the lines became blurry.  People were 
writing malicious macros into word processing data, and the machines 
actually would crash from it.  (Actually things were not this linear, 
interpreters have been around practically forever, but give me a little 
poetic license)


So gradually, we've added protection back into our personal systems that 
previously was only on mainframes.  But the need for these protections 
is higher today than ever before, mainly because of the internet.



So to Python.  Notice that the rules for finding code are different than 
those for finding data files.  No accident.  We WANT to treat them 
differently.  We want data files to be completely spec'ed out, as to 
what data is permissible and what is not.  Without such a spec, programs 
are entirely unpredictable.  The whole Y2K problem was caused because 
too many programmers made unwarranted assumptions about their data (in 
that case about the range of valid dates).  And they were also saving 
space, in an era where hard disks were available for maybe three 
thousand dollars for 10 megabytes.


Ever filled in a form which didn't leave enough room for yout town name, 
or that assumed that city would not have spaces?  Ever had software that 
thought that apostrophes weren't going to happen in a person's name?  Or 
that zip codes are all numeric (true in US, not elsewhere).  Or that 
names only consist of the 26 English letters.  Or even that only the 
first letter would be capitalized.


Anyway, my post was pointing out that without constraining the data, it 
was impractical/unsafe/unwise to encode the data in a byte stream(file), 
and expect to decode it later.


In your example, you encoded a tuple that was a string and an integer.  
You used repr() to do it, and that can be fine.  But the logic to 
transform that string back into a tuple is quite complex, if you have to 
cover all the strange cases.  And impossible, if you don't know anything 
about the data.


A tuple object in memory doesn't look anything like the text you save to 
that file.  It's probably over a hundred bytes spread out over at least 
three independent memory blocks.  But we try to pretend that the 
in-memory object is some kind of idealized tuple, and don't need to know 
the details.  Much of the space is taken up by pointers, and point

Re: [Tutor] list, tuple or dictionary

2011-11-29 Thread Steven D'Aprano

ADRIAN KELLY wrote:

i am trying to create a program that will allow users to enter items and their 
prices; should i be looking at a list, tuple or what?
many thanksadrian



Translated to a version more familiar in the "real world":

   "I'm looking to build a wooden wardrobe that will allow
the user to store their clothes. Should I be using a saw,
a hammer, a drill, or what?"

The only correct answer is "Yes you should."

Lists, tuples and dicts are all basic tools in your programming toolbox, you 
should ALWAYS be looking at using them. But you use them for different purposes.


Perhaps if you narrow your question down to something more specific we can 
give a more useful answer.


Or... just try it! Don't be scared to write some code to throw it away. 
Especially when learning, there is no better way to learn than to write some 
code, discover what you can and can't do with the tools, learn the limitations 
by trying it, and then using that knowledge to write better code.



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


Re: [Tutor] pass tuples to user defined function(beginner)

2011-11-29 Thread emile

Dave Angel wrote:



> The whole Y2K problem was caused because
too many programmers made unwarranted assumptions about their data (in 
that case about the range of valid dates).  


Well, yes.  But we knew then that the stuff we were writing wouldn't 
still be in play 25 years out.  :)


And they were also saving 
space, in an era where hard disks were available for maybe three 
thousand dollars for 10 megabytes.


I remember it well... if not fondly.  5Mb internal and 5Mb removable. 
Eventually (by 1980) we could buy 80Mb drives dumbed down to 35Mb for 
$20k.  Quite a bit better than the IBM mag-card system I started with, 
itself a step up from single use punch cards...


Emile


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


Re: [Tutor] pass tuples to user defined function(beginner)

2011-11-29 Thread Dave Angel

On 11/29/2011 06:40 PM, emile wrote:

Dave Angel wrote:



 > The whole Y2K problem was caused because

too many programmers made unwarranted assumptions about their data (in
that case about the range of valid dates).


Well, yes. But we knew then that the stuff we were writing wouldn't
still be in play 25 years out. :)


And they were also saving space, in an era where hard disks were
available for maybe three thousand dollars for 10 megabytes.


I remember it well... if not fondly. 5Mb internal and 5Mb removable.
Eventually (by 1980) we could buy 80Mb drives dumbed down to 35Mb for
$20k. Quite a bit better than the IBM mag-card system I started with,
itself a step up from single use punch cards...

Emile



I also started on punched cards, for maybe the first 30,000 "lines" of 
code.  I also had to deal with paper tape for object file transport. 
Talk about unreliable.


Any chance you were a customer or vendor of Wang?  That 80mb drive, 
dumbed down, for prices around $20k, rings a bell.


--

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


Re: [Tutor] why doesn't python show error

2011-11-29 Thread Alan Gauld

On 28/11/11 10:31, surya k wrote:

Thanks for that information. I understood what you are saying but in
general when python doesn't give us executable files (whether its in
Mac/ Linux/ Windows).. how could people develop programs ?.
At some point of time people need to provide a file that runs without
the help of a python interpreter..


As Stephen pointed out many programs run in interpreted environments
including almost every web client side program.

But even if you compile the code to a native exe it will usually still 
not be truly standalone. Any Windows program will rely on the existence 
of the standard Windows DLLs and libraries such as msvcrt. Unix 
programs expect the standard libc and other libraries to be there.


Unless you are in the extremely unusual position of writing software for 
an embedded device without any OS support then your code needs support 
files. What difference does it make whether they are in the form of 
shared libraries or an interpreter like .NET or  the Java JVM or the 
Python interpreter?


--
Alan G
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


[Tutor] Treating lists as lists

2011-11-29 Thread Mark Lybrand
I am pretty sure I saw this somewhere but now I can't.  Here's the problem:
list = ['hello', 'world']
template = '%s %s'
print template % list

But it appears that list is just one (list) when I want to treat it as two
(items).  I can do that right?  How, pretty please?

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


Re: [Tutor] Treating lists as lists

2011-11-29 Thread Hugo Arts
On Wed, Nov 30, 2011 at 2:09 AM, Mark Lybrand  wrote:
> I am pretty sure I saw this somewhere but now I can't.  Here's the problem:
> list = ['hello', 'world']
> template = '%s %s'
> print template % list
>
> But it appears that list is just one (list) when I want to treat it as two
> (items).  I can do that right?  How, pretty please?
>
> Mark
>

The % operator doesn't work with lists, you need to make that a tuple.
It should work then.

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


Re: [Tutor] pass tuples to user defined function(beginner)

2011-11-29 Thread Alan Gauld

On 29/11/11 21:40, Mayo Adams wrote:


tuple that is in the file, it would be helpful to know what it is.
Presumably, a string representing a tuple.


Exactly so, everything in the file is a string. If it's a binary file it 
is a string of bytes, if it is a text file a string of characters. The 
interpretation of those bytes or characters is down to the reading 
program. The program must convert the string into data. The string 
represents the data that will be eventually created in the computer's 
memory within the interpreter's execution environment.



representation,  I cant immediately see how anything in a script is
anything other than a representation of some kind, hence the
distinction between representamen and object does no work for me.


While it is in the file it is just a string. a string representation of 
a program. The interpreter reads that string and converts it into symbol 
tables, executable objects and data structures. Your program, when it 
reads a file must do exactly the same, it must convert the string read 
from the file into whatever data structure it represents and, if 
necessary, assign that data to a variable for future reference.


The process of reading a string and interpreting its meaning as data is 
what's known as parsing. There are several parsers available in Python 
to help with that task, as well as some tools to help you write your own 
parser. Examples are the csv module, HTMLParser, xpat and ElementTree. 
But even with these you will often have to do the final type conversion 
from string to integer or Boolean etc yourself.


The other option is to use binary files where the data is stored in 
strings of bytes. In this case you still need to interpret the string
but you do so by reading the exact number of bytes needed to store the 
particular data type, for example 4 bytes for a 32 bit integer. You then 
have to convert those 4 bytes into an integer. Again Python offers some 
help in the form of the struct module. Binary files are usually more 
compact than text files storing the same information, but they are far 
harder to interpret. There are other standard types of binary file and 
Python offers support for some, most notably there are libraries to read 
Excel files, various databases and PDF documents. Most of these 
libraries will also contain functions that help you write data back out 
to the files in the same format as well.


The goal of all of these libraries is to make it comparatively easy to 
read a string representation from a file and convert it into real data 
that we can manipulate in our programs.


HTH,

--
Alan G
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] Treating lists as lists

2011-11-29 Thread Dave Angel

On 11/29/2011 08:09 PM, Mark Lybrand wrote:

I am pretty sure I saw this somewhere but now I can't.  Here's the problem:
list = ['hello', 'world']
template = '%s %s'
print template % list

But it appears that list is just one (list) when I want to treat it as two
(items).  I can do that right?  How, pretty please?

Mark



print template % tuple(list)




--

DaveA

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


Re: [Tutor] Making a function run every second.

2011-11-29 Thread Alan Gauld

On 29/11/11 14:54, Mic wrote:


I want a function to run every second , how do I do that?

Say that the function look like this:

def hi():
print("hi")


The answer depends on whether you want to do it in a GUI or in a command 
line program.


Since your other posts have included GUI code I'd suggest you check out 
the documentation for the after() method in Tkinter.


If it's for command line look at time.sleep()

--
Alan G
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] How to write lines in a text file (GUI)

2011-11-29 Thread Alan Gauld

On 29/11/11 18:29, Mic wrote:


Oh, where are you living if you are waiting for lunch? It's past dinner
here, so that's why I got mails in the middle of the night! I thought most
people were from UK!


You are on the internet, its global! :-)
Most tutor subscribers are actually US based I suspect, but we literally 
have subscribers in every continent.


But I'm in the UK and it's way past midnight :-)

And I'm off to bed now, got a 8:30am start tomorrow... :-(

--
Alan G
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] pass tuples to user defined function(beginner)

2011-11-29 Thread bob gailer

On 11/29/2011 6:40 PM, emile wrote:

Dave Angel wrote:

... single use punch cards...

You didn't have an IBM 719 CARD punch? (ChAd Restoration Device). Made 
reuse of punch cards very easy.



--
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] Treating lists as lists

2011-11-29 Thread Mark Lybrand
Thanks everyone. Right before quitting time my brain froze up :)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Programming Collective Intelligence Study Group

2011-11-29 Thread Rodney Lewis
Sounds like an awesome idea to me.  I'm on board.  Keep the list
informed about that please.

And thanks for the links to the machine learning and nlp resources!

http://www.squidoo.com/introductiontopython

On Tue, Nov 29, 2011 at 12:42 AM, Mark Lybrand  wrote:
> Over on the Machine Learning Class, I mentioned the idea of setting up some
> online resources to go through the Programming Collective Intelligence book
> as a group. This would include a group or discussion board of some type,
> maybe a Google+ or Facebook page, and a wiki.  Then we would set a pace and
> work through the book.  Since it is in Python, I thought this group would be
> interested.  Am I wrong?  If it works out pretty good, we will probably
> continue with Natural Language Processing (also Python) after we finish.
> So, what is the interest like here?  Let me know and I will give you guys a
> heads up when I get everything all set up.
>
> --
> Mark :)
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

-- 
Rodney Lewis
Please Visit My Homepage:
http://www.squidoo.com/dotcomboy
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Programming Collective Intelligence Study Group

2011-11-29 Thread bob gailer

On 11/29/2011 3:42 AM, Mark Lybrand wrote:
Over on the Machine Learning Class, I mentioned the idea of setting up 
some online resources to go through the Programming Collective 
Intelligence book as a group. This would include a group or discussion 
board of some type, maybe a Google+ or Facebook page, and a wiki. 
 Then we would set a pace and work through the book.  Since it is in 
Python, I thought this group would be interested.  Am I wrong?  If it 
works out pretty good, we will probably continue with Natural Language 
Processing (also Python) after we finish.


So, what is the interest like here?  Let me know and I will give you 
guys a heads up when I get everything all set up.

I'm interested too.


--
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] Programming Collective Intelligence Study Group

2011-11-29 Thread Mark Lybrand
Before I launch in on my master scheme.  I have come across another couple
of interesting Machine Learning/Python books:

Mining the Social Web by Matthew Russell. O'Reilly ISBN-13: 978-1449388348

Machine Learning: An Algorithmic Perspective by Stephen Marsland. ISBN-13:
978-1420067187


Okay, this is what I am thinking of trying out:

1. I will read through a chapter and try to provide a write up of the
material with the algorithms. Hopefully enough that even those without the
book can follow the source code and our discussions.

2. This will be communicated to Twitter, Google+ (I will make a page) and
Google Groups (I will make a group)

3. I will put a Wiki on my website and give anyone who wants it edit access
(just contact me).  There we can store notes and links and general
resources, with the idea that it could be a good Python/Machine Learning/AI
resource for us and others.

I will try to get up an initial post in the next week our two and announce
it here to allow folks to hook in via their preferred media.

This post is being made at the Machine Learning forum and to the Python
Tutor mailing list.  If you think of anywhere else to get the word out,
just holler.  I am thinking maybe the AI reddit group, AIQUS and the forum
on the AI class site. Others?

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