Re: [Tutor] no loops

2006-07-11 Thread Alan Gauld
> def increment(time, seconds):
>  time.seconds = time.seconds + seconds
> 
>  while time.seconds >= 60:
>time.seconds = time.seconds - 60
>time.minutes = time.minutes + 1

Tale a look at what this loop is doing.
Think about its purpose. If you werre doing this 
with paper and pencil would you really use iteration?
Think division

> As an exercise, rewrite this function so that it
> doesn't contain any loops.
> 
> I have been staring at this function and drawing a
> blank.  Something tells me that I need to use
> iteration, but I am not sure how I could implement it.

The loops are implementing a mathematical function 
which doesn't need a loop. Look at the division and 
modulo operators.

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

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


Re: [Tutor] How do I get my machine to run an SMTP server?

2006-07-11 Thread Luke Paireepinart
[snip code]
> *When I run the program using IDLE, I get the following:*
>  
> Send the contents of a directory as a MIME message.
>  
> Usage: dirmail [options] from to [to ...]*
>  
> Options:
> -h / --help
> Print this message and exit.
>  
> -d directory
> --directory=directory
> Mail the contents of the specified directory, otherwise use the
> current directory.  Only the regular files in the directory 
> are sent,
> and we don't recurse to subdirectories.
>  
> `from' is the email address of the sender of the message.
>  
> `to' is the email address of the recipient of the message, and multiple
> recipients may be given.
>  
> The email is sent by forwarding to your local SMTP server, which then 
> does the
> normal delivery process.  Your local machine must be running an SMTP 
> server.
>  
> Traceback (most recent call last):
>   File "C:\Documents and Settings\User\Desktop\EB2.py", line 125, in ?
> main()
>   File "C:\Documents and Settings\User\Desktop\EB2.py", line 65, in main
> usage(1)
>   File "C:\Documents and Settings\User\Desktop\EB2.py", line 48, in usage
> sys.exit(code)
> SystemExit: 1
>  
> *I guess that my first question is how do I get my machine to run an 
> SMTP server?*
That's not what's causing the error.  It's raising an error because your 
program expects arguments to be passed to it.
Did you know that?
Other than that, if you're on Linux, Sendmail is an SMTP server that 
comes with most/all flavors of Linux, I believe.
If you're on Windows, I have no idea what kind of SMTP server you should 
use.
Sorry I can't be of more help.
> ** 
> *Also, I'd like to say that I greatly appreciate all of the help that 
> I've gotten in the past.*
>  
> Grady Henry
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>   

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


Re: [Tutor] Need Help

2006-07-11 Thread Luke Paireepinart
[snip]
> It would be very cruel to not address the core reason why the student's 
> struggling.  That's why we don't "answer" homework questions: it doesn't 
> address what's often a much bigger problem with the student's concepts of 
> programming.
Thank you for this explanation, Danny.  I thought there was a 
zero-tolerance policy on homework, not that we were supposed to give 
them more general help than a specific answer.
I agree my original choice of words was harsh.  It didn't sound that way 
to me when I wrote it, and I apologize to the OP.
It's also better that they tell us it's a homework problem than trying 
to mislead us, I reckon.
Anyway, does the Original Poster have any more questions or have we 
answered them all?
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How do I get my machine to run an SMTP server?

2006-07-11 Thread Grady Henry



This is a program that I wrote using the 
third example at 12.2.13 Examples at python.org.
 
#!/usr/bin/env python
 
"""Send the contents of a directory as a MIME 
message.
 
Usage: dirmail [options] from to [to 
...]*
 
Options:    -h / 
--help    Print this message and 
exit.
 
    -d 
directory    
--directory=directory    Mail the 
contents of the specified directory, otherwise use 
the    current directory.  Only 
the regular files in the directory are 
sent,    and we don't recurse to 
subdirectories.
 
`from' is the email address of the sender of the 
message.
 
`to' is the email address of the recipient of the 
message, and multiplerecipients may be given.
 
The email is sent by forwarding to your local SMTP 
server, which then does thenormal delivery process.  Your local machine 
must be running an SMTP server."""
 
import sysimport osimport getoptimport 
smtplib# For guessing MIME type based on file name extensionimport 
mimetypes
 
from email import Encodersfrom email.Message 
import Messagefrom email.MIMEAudio import MIMEAudiofrom email.MIMEBase 
import MIMEBasefrom email.MIMEMultipart import MIMEMultipartfrom 
email.MIMEImage import MIMEImagefrom email.MIMEText import 
MIMEText
 
COMMASPACE = ', '
 
def usage(code, msg=''):    print >> 
sys.stderr, __doc__    if 
msg:    print >> sys.stderr, 
msg    sys.exit(code)
 
def main():    
try:    opts, args = 
getopt.getopt(sys.argv[1:], 'C:', ['help', 'directory='])    
except getopt.error, msg:    usage(1, 
msg)
 
    dir = os.curdir    for opt, arg in 
opts:    if opt in ('-h', 
'--help'):    
usage(0)    elif opt in ('-d', 
'--directory'):    
dir = arg
 
    if len(args) < 
2:    usage(1)
 
    sender = args[0]    recips = 
args[1:]
 
    # Create the enclosing (outer) 
message    outer = MIMEMultipart()    
outer['Subject'] = 'Contents of directory %s' % os.path.abspath('C:\Documents 
and Settings\User\\My Documents')    outer['To'] = 
COMMASPACE.join('[EMAIL PROTECTED]')    
outer['From'] = '[EMAIL PROTECTED]'    
outer.preamble = 'You will not see this in a MIME-aware mail 
reader.\n'    # To guarantee the message ends with a 
newline    outer.epilogue = ''
 
    for filename in os.listdir('C:\Documents and 
Settings\User'):    path = 
os.path.join('C:\Documents and Settings\User', 'My 
Documents')    if not 
os.path.isfile('C:\Documents and 
Settings\User'):    
continue    # Guess the content type 
based on the file's extension.  
Encoding    # will be ignored, 
although we should check for simple things 
like    # gzip'd or compressed 
files.    ctype, encoding = 
mimetypes.guess_type('C:\Documents and Settings\User\\My 
Documents')    if ctype is None or 
encoding is not 
None:    # No 
guess could be made, or the file is encoded (compressed), 
so    # use a 
generic bag-of-bits 
type.    
ctype = 'application/octet-stream'    
maintype, subtype = ctype.split('/', 
1)    if maintype == 
'text':    fp 
= open('C:\Documents and Settings\User\\My 
Documents')    
# Note: we should handle calculating the 
charset    
msg = MIMEText(fp.read(), 
_subtype=subtype)    
fp.close()    elif maintype == 
'image':    
fp = open('C:\Documents and Settings\User\\My Documents', 
'rb')    msg 
= MIMEImage(fp.read(), 
_subtype=subtype)    
fp.close()    elif maintype == 
'audio':    
fp = open('C:\Documents and Settings\User\\My Documents', 
'rb')    msg 
= MIMEAudio(fp.read(), 
_subtype=subtype)    
fp.close()    
else:    fp = 
open('C:\Documents and Settings\User\\My Documents', 
'rb')    msg 
= MIMEBase(maintype, 
subtype)    
msg.set_payload(fp.read())    
fp.close()    
# Encode the payload using 
Base64    
Encoders.encode_base64(msg)    # Set 
the filename parameter    
msg.add_header('Content-Disposition', 'attachment', 
filename=filename)    
outer.attach(msg)
 
    # Now send the message    s = 
smtplib.SMTP()    s.connect()    
__init__(self, host='', port=25, local_hostname=None)    
s.sendmail('[EMAIL PROTECTED]', '[EMAIL PROTECTED]', 
outer.as_string())    s.close()
 
if __name__ == '__main__':    main()
When I run the program using IDLE, I get the 
following:
 
Send the contents of a directory as a MIME message.
 
Usage: dirmail [options] from to [to ...]*
 
Options:    -h / 
--help    Print this message and 
exit.
 
    -d directory    
--directory=directory    Mail the 
contents of the specified directory, otherwise use 
the    current directory.  Only 
the regular files in the directory are 
sent,    and we don't recurse to 
subdirectories.
 
`from' is the email address of the sender of the message.
 
`to' is the email address of the recipient of the message, and 
multiplerecipients may be given.
 
The email is sent by forwarding to your local SMTP

Re: [Tutor] no loops

2006-07-11 Thread Bob Gailer
Christopher Spears wrote:
> I am working on another problem from "How To Think
> Like A Computer Scientist".  Here is a function:
>
> def increment(time, seconds):
>   time.seconds = time.seconds + seconds
>
>   while time.seconds >= 60:
> time.seconds = time.seconds - 60
> time.minutes = time.minutes + 1
>
>   while time.minutes >= 60:
> time.minutes = time.minutes - 60
> time.hours = time.hours + 1 
>
> Here is the function in action:
>
>   
 from time import *
 atime = Time()
 atime.hours = 1
 atime.minutes = 60
 atime.seconds = 120
 printTime(atime)
 
> 1:60:120
>   
 increment(atime,1)
 printTime(atime)
 
> 2:2:1
>
> Now the exercise is:
> As an exercise, rewrite this function so that it
> doesn't contain any loops.
>
> I have been staring at this function and drawing a
> blank.  Something tells me that I need to use
> iteration, but I am not sure how I could implement it.
>   
take a look at the divmod built-in function.
>   


-- 
Bob Gailer
510-978-4454

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


Re: [Tutor] quickie: a better dynamic dictionary update?

2006-07-11 Thread John Fouhy
On 12/07/06, Marcus Goldfish <[EMAIL PROTECTED]> wrote:
> # 1st, find the 'stale' items in our dictionary to delete
> # lstKeepers is a list of current pictures
> # Note: if I try to iterate over the keys of the dict and
> # remove-as-I-go, I get an exception (dict size changed
> # during iteration)

Try this:

for key in myDict.keys():
  if key not in lstKeepers:
del myDict[key]

The difference here is that myDict.keys() creates a list containing
the keys of myDict at the start of the loop, and then iterates over
the list.

If lstKeepers is big, it might be more efficient to make it into a set first ---

keepSet = set(lstKeepers)
for key in myDict.keys():
  if key not in keepSet:
del myDict[key]

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


Re: [Tutor] quickie: a better dynamic dictionary update?

2006-07-11 Thread Terry Carroll
On Tue, 11 Jul 2006, Terry Carroll wrote:

> On Tue, 11 Jul 2006, Marcus Goldfish wrote:
> 
> > # 1st, find the 'stale' items in our dictionary to delete
> > # lstKeepers is a list of current pictures
> > # Note: if I try to iterate over the keys of the dict and
> > # remove-as-I-go, I get an exception (dict size changed
> > # during iteration)
> > lstRemove = []
> > for key in myDict:
> >if key not in lstKeepers:
> >lstRemove.append(key)
> > 
> > # 2nd, remove them
> > for oldKey in lstRemove:
> >del myDict[oldKey]
> 
> [snip code]
> It's still a two-passer, but I don't see straightforward any way around
> that, if you want to update the dictionary (as opposed to making a new
> dictionary with the result, which could probably be done with an
> excessively clever list comprehension).

Actually, it turns out not to be excessively clever at all (if I could do
it):

myDict = dict([(key, myDict[key]) for key in myDict.keys()
   if key in lstKeepers])

I'm not sure it's any nicer looking, though, than my first suggestion 
(although my first suggestion is probably a little slower).


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


Re: [Tutor] quickie: a better dynamic dictionary update?

2006-07-11 Thread Terry Carroll
On Tue, 11 Jul 2006, Marcus Goldfish wrote:

> # 1st, find the 'stale' items in our dictionary to delete
> # lstKeepers is a list of current pictures
> # Note: if I try to iterate over the keys of the dict and
> # remove-as-I-go, I get an exception (dict size changed
> # during iteration)
> lstRemove = []
> for key in myDict:
>if key not in lstKeepers:
>lstRemove.append(key)
> 
> # 2nd, remove them
> for oldKey in lstRemove:
>del myDict[oldKey]


lstDeleters = [key for key in myDict.keys() if key not in lstKeepers]
for key in lstDeleters:
del myDict[key]

It's still a two-passer, but I don't see straightforward any way around
that, if you want to update the dictionary (as opposed to making a new
dictionary with the result, which could probably be done with an
excessively clever list comprehension).

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


Re: [Tutor] Need Help

2006-07-11 Thread Marc Poulin

--- Terry Carroll <[EMAIL PROTECTED]> wrote:

> On Tue, 11 Jul 2006, Michael P. Reilly wrote:
> 
> >   Another aspect of your assignment will be to be
> able to use this
> > functionality from the "command-line".  This
> means: without asking questions
> > from the user, but input is being passed as
> arguments.  
> 
> John should get clarification from his instructor,
> but I did not read it 
> that way.  I read that requirement to "support a
> command line query" as 
> meaning the program should prompt the user to enter
> a query command; as 
> opposed to hard-coding the transactions in the coe
> itself (as is sometimes 
> done at an intro level).
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

This may be the most important lesson to learn from
this exercise: even experienced programmers can (and
do) interpret requirements differently. When in doubt,
ask!



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


Re: [Tutor] no loops

2006-07-11 Thread Marc Poulin

--- John Fouhy <[EMAIL PROTECTED]> wrote:

> On 12/07/06, Christopher Spears
> <[EMAIL PROTECTED]> wrote:
> > Now the exercise is:
> > As an exercise, rewrite this function so that it
> > doesn't contain any loops.
> >
> > I have been staring at this function and drawing a
> > blank.  Something tells me that I need to use
> > iteration, but I am not sure how I could implement
> it.
> 
> Hi Chris,
> 
> You are using iteration.  That's what loops are :-)
> 
> Perhaps you meant to say "recursion", which is where
> a function calls
> itself.  You could solve this recursively, but I
> think Gregor's
> comment is closer to what they want you to do.
> 
> -- 
> John.

I agree with Gregor and John. What makes the problem
difficult is the fact that time is represented using 3
different units of measure: hours, minutes, and
seconds. The math becomes much simpler if you convert
the time value to a single unit (such as seconds).

But it doesn't have to be seconds. I recall seeing one
 database that stores time as fractional hours where a
minute is worth 1/60 of an hour and a second is worth
1/3600 of an hour. 

In other words, 1:15 is stored as 1.25 hours, 4:30 is
stored as 4.5 hours, and so forth. Converting from
(hours, minutes, seconds) to fractional hours is
pretty easy, but going the other way is not so simple.




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


[Tutor] quickie: a better dynamic dictionary update?

2006-07-11 Thread Marcus Goldfish
Hi,I need to keep an updated dictionary of pictures in my application.  I have a function which takes snapshots of the current pictures available.  Some of the pictures in my dictionary have been deleted, so their dict entry needs to be removed.  Here is a snippet of very ugly code I have which works.  I'm looking for quick suggestions for a better implementation-- all nice replies welcomed!
Thanks,Marcus-- code snippet# 1st, find the 'stale' items in our dictionary to delete# lstKeepers is a list of current pictures# Note: if I try to iterate over the keys of the dict and
# remove-as-I-go, I get an exception (dict size changed# during iteration)lstRemove = []for key in myDict:   if key not in lstKeepers:       lstRemove.append(key) # 2nd, remove themfor oldKey in lstRemove:
   del myDict[oldKey]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need Help

2006-07-11 Thread Terry Carroll
On Tue, 11 Jul 2006, Michael P. Reilly wrote:

>   Another aspect of your assignment will be to be able to use this
> functionality from the "command-line".  This means: without asking questions
> from the user, but input is being passed as arguments.  

John should get clarification from his instructor, but I did not read it 
that way.  I read that requirement to "support a command line query" as 
meaning the program should prompt the user to enter a query command; as 
opposed to hard-coding the transactions in the coe itself (as is sometimes 
done at an intro level).


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


Re: [Tutor] no loops

2006-07-11 Thread John Fouhy
On 12/07/06, Christopher Spears <[EMAIL PROTECTED]> wrote:
> Now the exercise is:
> As an exercise, rewrite this function so that it
> doesn't contain any loops.
>
> I have been staring at this function and drawing a
> blank.  Something tells me that I need to use
> iteration, but I am not sure how I could implement it.

Hi Chris,

You are using iteration.  That's what loops are :-)

Perhaps you meant to say "recursion", which is where a function calls
itself.  You could solve this recursively, but I think Gregor's
comment is closer to what they want you to do.

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


Re: [Tutor] no loops

2006-07-11 Thread Gregor Lingl
Christopher Spears schrieb:

IF you know that it's 2 seconds after midnight,
how many hours, minutes, seconds after midnight ist this.

If you should compute this by hand, how would you proceed?

Best wishes,
Gregor

> I am working on another problem from "How To Think
> Like A Computer Scientist".  Here is a function:
>
> def increment(time, seconds):
>   time.seconds = time.seconds + seconds
>
>   while time.seconds >= 60:
> time.seconds = time.seconds - 60
> time.minutes = time.minutes + 1
>
>   while time.minutes >= 60:
> time.minutes = time.minutes - 60
> time.hours = time.hours + 1 
>
> Here is the function in action:
>
>   
 from time import *
 atime = Time()
 atime.hours = 1
 atime.minutes = 60
 atime.seconds = 120
 printTime(atime)
 
> 1:60:120
>   
 increment(atime,1)
 printTime(atime)
 
> 2:2:1
>
> Now the exercise is:
> As an exercise, rewrite this function so that it
> doesn't contain any loops.
>
> I have been staring at this function and drawing a
> blank.  Something tells me that I need to use
> iteration, but I am not sure how I could implement it.
>
> -Chris
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   

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


[Tutor] no loops

2006-07-11 Thread Christopher Spears
I am working on another problem from "How To Think
Like A Computer Scientist".  Here is a function:

def increment(time, seconds):
  time.seconds = time.seconds + seconds

  while time.seconds >= 60:
time.seconds = time.seconds - 60
time.minutes = time.minutes + 1

  while time.minutes >= 60:
time.minutes = time.minutes - 60
time.hours = time.hours + 1 

Here is the function in action:

>>> from time import *
>>> atime = Time()
>>> atime.hours = 1
>>> atime.minutes = 60
>>> atime.seconds = 120
>>> printTime(atime)
1:60:120
>>> increment(atime,1)
>>> printTime(atime)
2:2:1

Now the exercise is:
As an exercise, rewrite this function so that it
doesn't contain any loops.

I have been staring at this function and drawing a
blank.  Something tells me that I need to use
iteration, but I am not sure how I could implement it.

-Chris

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


Re: [Tutor] Need Help

2006-07-11 Thread Kent Johnson
Shappell, John J CW2 wrote:
>
> Here is the assignment
>
>  1. You've been given an assignment by your supervisor to
> program a small application to monitor the current status
> of the cash account in the firm's petty cash fund (the
> amount of cash kept on hand in the office for incidental
> purchases). The requirements for the program are to allow
> users to input the amount of cash deposited, the amount of
> cash withdrawn and to get a report of the balance at any
> given time. You will need to also add the date of each
> deposit and the date of each withdrawal and provide a date
> with the balance returned upon a given query. The program
> should be able to provide a printed report and support a
> command line query.
>
> You are to use the object oriented properties of Python to
> accomplish this task.
>
> This is where I am at so far.  I don't understand how to get the 
> Account class into the program. Can you help a little,  Just looking 
> for an idea or some guidance
>
> #!/usr/bin/python
> # Filename: petty cash.py
>
> print "Welcome to the petty cash account"
> print "Did you deposit or withdrawl money today"
> print
>
> # print out menu
> print "please select a number"
> print "1 for deposit"
> print "2 for withdrawl"
>
> # Get user's choice:
> number = input (">")
> #
> if number == 1:
> deposit = input ("how much?")
> print "I deposited:", deposit
>
> elif number == 2:
> withdrawl = input ("How Much?")
> print "I withdrew:", withdrawl
>
> print "what is today's date?"
> # Get date from user
> date = input (">")
>
> *This is where I get stuck. The program will allow me to input the 
> deposit or withdrawl ammount and the date but does nothing ownce it 
> gets here*
>
> class Account:
>  def __init__(self, initial):
>  self.balance = initial
>  def deposit(self, amt):
>  self.balance = self.balance + amt
>  def withdraw(self,amt):
>  self.balance = self.balance - amt
>  def getbalance(self):
>  return self.balance
>

Hi John,

You need to create an instance of Account and post the transactions to 
it by calling instance methods on the account. The Account class may 
need to keep track of the individual postings as well as the total balance.

There is a lot to the assignment - is this one of your first assignments 
or a later one? Without a bit of context of where you are in the course 
it's hard to know what is expected. It sounds like you may need some 
kind of persistent storage like a database but I don't know if you have 
learned anything about that yet.

Kent

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


Re: [Tutor] Need Help

2006-07-11 Thread Michael P. Reilly
On 7/10/06, Shappell, John J CW2 <[EMAIL PROTECTED]> wrote:









Here is the assignment


You've been given an assignment by your supervisor to program a small application to monitor the current status of the cash account in the firm's petty cash fund (the amount of cash kept on hand in the office for incidental purchases). The requirements for the program are to allow users to input the amount of cash deposited, the amount of cash withdrawn and to get a report of the balance at any given time. You will need to also add the date of each deposit and the date of each withdrawal and provide a date with the balance returned upon a given query. The program should be able to provide a printed report and support a command line query.


You are to use the object oriented properties of Python to accomplish this task. 


This is where I am at so far.  I don't understand how to get the Account class into the program. Can you help a little,  Just looking for an idea or some guidance

#!/usr/bin/python
# Filename: petty cash.py


print "Welcome to the petty cash account"
print "Did you deposit or withdrawl money today"
print


# print out menu
print "please select a number"
print "1 for deposit"
print "2 for withdrawl"


# Get user's choice:
number = input (">")
#
if number == 1:
    deposit = input ("how much?")
    print "I deposited:", deposit
    
elif number == 2:
    withdrawl = input ("How Much?")
    print "I withdrew:", withdrawl
    
print "what is today's date?"
# Get date from user
date = input (">")


This is where I get stuck. The program will allow me to input the deposit or withdrawl ammount and the date but does nothing ownce it gets here

class Account:
 def __init__(self, initial):
 self.balance = initial
 def deposit(self, amt):
 self.balance = self.balance + amt
 def withdraw(self,amt):
 self.balance = self.balance - amt
 def getbalance(self):
 return self.balance 
John,  Another aspect of your assignment will be to be able to use this functionality from the "command-line".  This means: without asking questions from the user, but input is being passed as arguments.  You will eventually have to think how this will affect the structure of your program.
  -Arcege-- There's so many different worlds,So many different suns.And we have just one world,But we live in different ones.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] modbus communication with python?

2006-07-11 Thread Jeff Peery
okay, yes thank you! I have seen this, although I looked a the code and it appears that this is actually a modbus server (please correct me if I am wrong, I am really new to modbus and PLC's). We are already using a modbus server (KEPDirect for PLC's, automation direct) and I beleive we are using a Koyo PLC. but I simply want to read and write values stored on the modbus server, I don't actually want to create a new server. I'm not sure that this module is the way to go (although again I might be wrong), what might be my other options and where should I go to learn about this? thanks!JeffJason Massey <[EMAIL PROTECTED]> wrote: Googling for modbus python turned up:https://lintouch.org/repos/lintouch/lsp-modbus/trunk/tests/ On 7/5/06, Jeff Peery <[EMAIL PROTECTED]> wrote: Hello, I need to talk read write to a modbus so that I can work with a PLC. I have not a clue how this all works. does python have a modbus module or where might I look to find how to do this? thanks. JeffHow low will we go? Check out Yahoo! Messenger's low   PC-to-Phone call rates. ___Tutor maillist  -  Tutor@python.org http://mail.python.org/mailman/listinfo/tutor  
		Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls.  Great rates starting at 1¢/min.___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How can I copy files recursively?

2006-07-11 Thread Alan Gauld
>> Or you could just use mv on the top level folder.
>>
> But I don't want the sub folders to come along with the copy. I'd 
> like to
> grab the mp3 files out of a set of subfolders and place them all 
> into a
> single folder somewhere else.

Ah, sorry, I misunderstood the question.

In that case os.walk and shutil.copy provide a fairly easy solution.
Take a look at the findfile() function in the OS tutor topic.

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


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


Re: [Tutor] Need Help

2006-07-11 Thread Danny Yoo
> By posting the entire homework problem, John Shappell did give the 
> impression that he wanted us to do the problem for him, but as John 
> Montgomery notes he is just looking for a hint in an area where he is 
> stuck. That is fine for the tutor list. Since we know it is homework we 
> can use a light touch and avoid giving the entire solution.


The idea is to try attacking the core of the problem the questioner has. 
In that sense, I try not to look at the details of the homework problem.


As a concrete example, if someone comes up and says:

 I don't know how to get my name-asking program to stop when the user
 enters "quit".  Help!


I'll translate this to:

 1.  I might not know how to use boolean conditionals.

 2.  I might not know how to use loops.

 3.  I might not know how to use these two things together.

 4.  I don't understand the question I'm being asked, or why
 this is useful.


That is, I'd ignore the surface details about asking about string 
comparison, but concentrate on figuring out which of these things the 
questioner is confused with.  Or there may be something that hasn't been 
accounted for... The questions we ask from then on are meant to probe.

It would be very cruel to not address the core reason why the student's 
struggling.  That's why we don't "answer" homework questions: it doesn't 
address what's often a much bigger problem with the student's concepts of 
programming.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need Help

2006-07-11 Thread Alan Gauld
> [snip assignment]
> Please don't ask about homework in the future.  Did your professor 
> tell you to submit queries to this list?  If so, could you ask him 
> not to? it's against the policies of the tutor mailing list to give 
> homework help.

Thats a bit extreme. We don't mind giving help on specific queries
where an attempt has been made to do the work.
We will rarely give a direct answer but might ask questions or
make suggestions to lead you towards the answer.

What we will not do is accept a simple query saying, in effect,
"here is the assignment, how do I do it?"

>> This is where I am at so far.  I don't understand how to get the 
>> Account class into the program. Can you help a little,  Just 
>> looking for an idea or some guidance

Do you understand the difference between classes and objects?
Do you understand how to create an object, as opposed to a class?
Do you know how to call the methods of an object once created?

If not find almost any Python tutorial. They all answer those 
questions.

>> class Account:
>>  def __init__(self, initial):
>>  self.balance = initial
>>  def deposit(self, amt):
>>  self.balance = self.balance + amt
>>  def withdraw(self,amt):
>>  self.balance = self.balance - amt
>>  def getbalance(self):
>>  return self.balance
>>
> What you have there is a class, not an instance of a class.  read 
> more about the difference at 
> http://www.python.org/doc/2.2.3/tut/node11.html
> or some other tutorial site.

Seconded.

> Also, make it clear to your instructor that you had trouble here. 
> If he doesn't know what's hanging people up he won't be able to help 
> you with it.

But I think Luke is being a wee bit hard here, you clearly have
tried to solve it, you just need some direction. I'd say that was
within the tutor list rules.

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


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


Re: [Tutor] Help IDLE Compile Problem

2006-07-11 Thread Bob Gailer
Bugra Cakir wrote:
> Hi,
>
> I have two Python source files within editing them via IDLE.
> I have a problem. The second file is used by the first file. Some parts
> i mean from the second file is used. But when i change the contents of 
> the
> second file and while i'm running the first file with F5, change 
> doesnt reflect
> to the runtime. If i close two IDLE windows and delete .pyc of the 
> second file
> then it is ok. What is the problem ?
Your question is hard to address because we don't know what you mean by 
"The second file is used by the first file". I will assume you are 
importing it. Import runs the imported module once. Subsequent 
executions of import do NOT rerun the module. Therefore any changes you 
make to it are not showing up. To work around this "problem", after 
importing, use the reload function:
import foo
reload(foo)

-- 
Bob Gailer
510-978-4454

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


Re: [Tutor] How can I copy files recursively?

2006-07-11 Thread Richard Querin
On 7/11/06, Alan Gauld <[EMAIL PROTECTED]> wrote:
Things which are easy in the shell are usually less easy in Python.In your case a simple cp -r will copy the files and an rm -rf willdelete the originals.Or you could just use mv on the top level folder.
But I don't want the sub folders to come along with the copy. I'd like to grab the mp3 files out of a set of subfolders and place them all into a single folder somewhere else. I'm completely lost when it comes to bash scripting, so I may take Michael P. Reilly's suggestion as a starting point since it's the only one I understand at first glance ;).
I'm really a newbie to python programming so readability and understanding it is first on my list. Efficiency and speed is secondary to me at the moment.Thanks to all for the help.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How can I copy files recursively?

2006-07-11 Thread Alan Gauld
> subfolders. I'd like to write a quick script to move (not copy) all 
> the mp3
> files in those folders into a single destination folder. I was 
> thinking I
> could do it easily from the linux command line (cp -r copies the 
> subfolders
> out as well) but I can't figure out how to do it. Is there an easy 
> way to
> achieve this using Python? I am assuming this would be something 
> Python was
> designed to make easy..

Things which are easy in the shell are usually less easy in Python.
In your case a simple cp -r will copy the files and an rm -rf will
delete the originals.

Or you could just use mv on the top level folder.

However the OS topic in my tutor provides all the bits you need
to write a python script if you really need to.

Alan G. 


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


[Tutor] Help IDLE Compile Problem

2006-07-11 Thread Bugra Cakir
Hi,I have two Python source files within editing them via IDLE.I have a problem. The second file is used by the first file. Some partsi mean from the second file is used. But when i change the contents of the
second file and while i'm running the first file with F5, change doesnt reflectto the runtime. If i close two IDLE windows and delete .pyc of the second filethen it is ok. What is the problem ?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need Help

2006-07-11 Thread Kent Johnson
John or Margaret Montgomery wrote:
> On Tue, 11 Jul 2006 06:41:23 -0500
> Luke Paireepinart <[EMAIL PROTECTED]> wrote:
>
>   
>> Hi.
>> Shappell, John J CW2 wrote:
>> 
>>> Here is the assignment
>>>
>>>   
>> [snip assignment]
>> Please don't ask about homework in the future.  Did your professor tell 
>> you to submit queries to this list?  If so, could you ask him not to? 
>> it's against the policies of the tutor mailing list to give homework 
>> help.  However, I can give you a few hints about python in general.  The 
>> rules may be different but my impression was that there was no homework 
>> to be submitted here.  If I'm wrong please correct me.
>> 
>
> Perhaps I am wrong, Luke but my impression was that this request was fine. He 
> openly stated it was homework and he did considerable work on it before 
> getting stuck. Also he specifically did not ask for a solution but wished to 
> be nudged in the right direction.
>
> I am sorry that I do not have the knowledge to help but perhaps your tip did 
> the trick.
>
> Perhaps Danny or Kent would clarify this situation.

By posting the entire homework problem, John Shappell did give the 
impression that he wanted us to do the problem for him, but as John 
Montgomery notes he is just looking for a hint in an area where he is 
stuck. That is fine for the tutor list. Since we know it is homework we 
can use a light touch and avoid giving the entire solution.

Kent

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


Re: [Tutor] tempfile and passing files around

2006-07-11 Thread Kent Johnson
Gabriel Farrell wrote:
> On Tue, Jul 11, 2006 at 03:04:02PM -0400, Kent Johnson wrote:
>   
>> Try bob.flush() instead of bob.read(), my guess is the read() is forcing 
>> a flush().
>> 
>
> That works!  Thanks, Kent.  If I understand flush (looking at [1]), I
> got no output because the data for the stream wasn't written to the
> file before I tried to read it.  Is that right?

Yes, that's right.

Kent

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


Re: [Tutor] tempfile and passing files around

2006-07-11 Thread Gabriel Farrell
On Tue, Jul 11, 2006 at 03:04:02PM -0400, Kent Johnson wrote:
> Try bob.flush() instead of bob.read(), my guess is the read() is forcing 
> a flush().

That works!  Thanks, Kent.  If I understand flush (looking at [1]), I
got no output because the data for the stream wasn't written to the
file before I tried to read it.  Is that right?

[1] http://www.opengroup.org/pubs/online/7908799/xsh/fflush.html
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need Help

2006-07-11 Thread John or Margaret Montgomery
On Tue, 11 Jul 2006 06:41:23 -0500
Luke Paireepinart <[EMAIL PROTECTED]> wrote:

> Hi.
> Shappell, John J CW2 wrote:
> >
> > Here is the assignment
> >
> [snip assignment]
> Please don't ask about homework in the future.  Did your professor tell 
> you to submit queries to this list?  If so, could you ask him not to? 
> it's against the policies of the tutor mailing list to give homework 
> help.  However, I can give you a few hints about python in general.  The 
> rules may be different but my impression was that there was no homework 
> to be submitted here.  If I'm wrong please correct me.
> >

Perhaps I am wrong, Luke but my impression was that this request was fine. He 
openly stated it was homework and he did considerable work on it before getting 
stuck. Also he specifically did not ask for a solution but wished to be nudged 
in the right direction.

I am sorry that I do not have the knowledge to help but perhaps your tip did 
the trick.

Perhaps Danny or Kent would clarify this situation.

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


Re: [Tutor] tempfile and passing files around

2006-07-11 Thread Kent Johnson
Gabriel Farrell wrote:
> I have an issue with the tempfile module that I can't figure out.
>
> Snippet of relevant script looks like so:
>
> 1   bob = tempfile.NamedTemporaryFile()
> 2   bob.write('Hallo!')
> 3   bob.read()
> 4   sam = tempfile.NamedTemporaryFile()
> 5   bobHandle = file(bob.name)
> 6   bobHandle.read()
>
> As you can see, I'm creating two NamedTemporaryFiles and then reading
> from the first.  Line 3 doesn't really do anything, there's no output
> because we're reading at the end of the file, but as long as I leave
> it in, line 6 will output the expected 'Hallo!'.  If I remove it,
> there's no output from line 6.
>   
Try bob.flush() instead of bob.read(), my guess is the read() is forcing 
a flush().

Kent


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


[Tutor] tempfile and passing files around

2006-07-11 Thread Gabriel Farrell
I have an issue with the tempfile module that I can't figure out.

Snippet of relevant script looks like so:

1   bob = tempfile.NamedTemporaryFile()
2   bob.write('Hallo!')
3   bob.read()
4   sam = tempfile.NamedTemporaryFile()
5   bobHandle = file(bob.name)
6   bobHandle.read()

As you can see, I'm creating two NamedTemporaryFiles and then reading
from the first.  Line 3 doesn't really do anything, there's no output
because we're reading at the end of the file, but as long as I leave
it in, line 6 will output the expected 'Hallo!'.  If I remove it,
there's no output from line 6.

I really stumbled upon this, and it looks like, if you create a
tempfile and write to it, then create another tempfile, you can only
open up the first to read it again if you do a read method on the
first file before you open it.  I dunno, just kinda baffled.

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


Re: [Tutor] How can I copy files recursively?

2006-07-11 Thread Michael P. Reilly
On 7/10/06, Richard Querin <[EMAIL PROTECTED]> wrote:
I know this is probably a dumb question:I've got mp3 files that are downloaded (by ipodder) into individual subfolders. I'd like to write a quick script to move (not copy) all the mp3 files in those folders into a single destination folder. I was thinking I could do it easily from the linux command line (cp -r copies the subfolders out as well) but I can't figure out how to do it. Is there an easy way to achieve this using Python? I am assuming this would be something Python was designed to make easy..
Python makes things easy, from a certain point of view.  You have to think that Python is a program language and not a command language (like Bourne shell).Others have a number of solutions that will move your files with 
os.walk and os.path.walk.  They are nice, but sometimes it's better to traverse the tree individually.  Also, you didn't specify if the destination "folder" structure already existed, or if it will need to be created (which cp -r will do).  The following should handle that case for you:
import fnmatch, osdef movetree(srcdir, dstdir, pattern=None):    # dstdir must exist first
    srcnames = os.listdir(srcdir)    for name in srcnames:
    srcfname = os.path.join(srcdir, name)    dstfname = os.path.join(dstdir, name)    if 
os.path.isdir(srcfname):    os.mkdir(dstfname, 00)    movetree(srcfname, dstfname)
    elif pattern is None or fnmatch.fnmatch(name, pattern):    os.rename(srcfname, dstfname)
You could do the same with 
os.walk or os.path.walk, but the recursive nature of the function takes care of itself a bit better, IMO.  -Arcege-- There's so many different worlds,So many different suns.And we have just one world,
But we live in different ones.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] printing 00

2006-07-11 Thread Shantanoo Mahajan
+++ Christopher Spears [10-07-06 21:34 -0700]:
| I'm working on a problem from "How To Think Like A
| Computer Scientist".  I created  a Time class:
| 
| class Time:
|   
|   def __init__(self, hours, minutes, seconds):
|   self.hours = hours
|   self.minutes = minutes
|   self.seconds = seconds
| 
| I created a function to print the Time object:
| 
| def printTime(time):
|   print "%d:%d:%d" % (time.hours, time.minutes,
| time.seconds)
|   
| However, when I type '00', I get the following:
| >>> time = Time(12,34.4,00)
| >>> printTime(time)
| 12:34:0
| >>> time.seconds
| 0

instead of %d you may use %02d.

Shantanoo
-- 
It's not what you look at that matters, it's what you see.  ~Henry David
Thoreau
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need Help

2006-07-11 Thread Luke Paireepinart
Hi.
Shappell, John J CW2 wrote:
>
> Here is the assignment
>
[snip assignment]
Please don't ask about homework in the future.  Did your professor tell 
you to submit queries to this list?  If so, could you ask him not to? 
it's against the policies of the tutor mailing list to give homework 
help.  However, I can give you a few hints about python in general.  The 
rules may be different but my impression was that there was no homework 
to be submitted here.  If I'm wrong please correct me.
>
> This is where I am at so far.  I don't understand how to get the 
> Account class into the program. Can you help a little,  Just looking 
> for an idea or some guidance
>
> #!/usr/bin/python
> # Filename: petty cash.py
>
> print "Welcome to the petty cash account"
> print "Did you deposit or withdrawl money today"
>
> print
>
> # print out menu
> print "please select a number"
> print "1 for deposit"
> print "2 for withdrawl"
>
> # Get user's choice:
> number = input (">")
>
I suggest doing something like
number = int(raw_input("> "))
I'm pretty sure the 'input' statement is a no-no, unless your Professor 
says, and then you should use it.
>
> #
> if number == 1:
> deposit = input ("how much?")
> print "I deposited:", deposit
>
> elif number == 2:
> withdrawl = input ("How Much?")
> print "I withdrew:", withdrawl
>
> print "what is today's date?"
> # Get date from user
> date = input (">")
>
> *This is where I get stuck. The program will allow me to input the 
> deposit or withdrawl ammount and the date but does nothing ownce it 
> gets here*
>
> class Account:
>  def __init__(self, initial):
>  self.balance = initial
>  def deposit(self, amt):
>  self.balance = self.balance + amt
>  def withdraw(self,amt):
>  self.balance = self.balance - amt
>  def getbalance(self):
>  return self.balance
>
What you have there is a class, not an instance of a class.  read more 
about the difference at http://www.python.org/doc/2.2.3/tut/node11.html
or some other tutorial site.
Also, make it clear to your instructor that you had trouble here.  If he 
doesn't know what's hanging people up he won't be able to help you with it.

>
> [EMAIL PROTECTED]
> [EMAIL PROTECTED]
>
What was your job in the Army, if you don't mind my asking?
Cheers.
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Need Help

2006-07-11 Thread Shappell, John J CW2
Title: [Tutor] Need Help





Here is the assignment


You've been given an assignment by your supervisor to program a small application to monitor the current status of the cash account in the firm's petty cash fund (the amount of cash kept on hand in the office for incidental purchases). The requirements for the program are to allow users to input the amount of cash deposited, the amount of cash withdrawn and to get a report of the balance at any given time. You will need to also add the date of each deposit and the date of each withdrawal and provide a date with the balance returned upon a given query. The program should be able to provide a printed report and support a command line query.

You are to use the object oriented properties of Python to accomplish this task. 


This is where I am at so far.  I don't understand how to get the Account class into the program. Can you help a little,  Just looking for an idea or some guidance

#!/usr/bin/python
# Filename: petty cash.py


print "Welcome to the petty cash account"
print "Did you deposit or withdrawl money today"
print


# print out menu
print "please select a number"
print "1 for deposit"
print "2 for withdrawl"


# Get user's choice:
number = input (">")
#
if number == 1:
    deposit = input ("how much?")
    print "I deposited:", deposit
    
elif number == 2:
    withdrawl = input ("How Much?")
    print "I withdrew:", withdrawl
    
print "what is today's date?"
# Get date from user
date = input (">")


This is where I get stuck. The program will allow me to input the deposit or withdrawl ammount and the date but does nothing ownce it gets here

class Account:
 def __init__(self, initial):
 self.balance = initial
 def deposit(self, amt):
 self.balance = self.balance + amt
 def withdraw(self,amt):
 self.balance = self.balance - amt
 def getbalance(self):
 return self.balance 


V/R


CW2 John Shappell
HHB 2-44 ADA BN
Work 270-798-6823
FAX 775-618-2455
[EMAIL PROTECTED]
[EMAIL PROTECTED]






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


Re: [Tutor] How can I copy files recursively?

2006-07-11 Thread Kent Johnson
John Fouhy wrote:
> On 11/07/06, Richard Querin <[EMAIL PROTECTED]> wrote:
>   
>> I know this is probably a dumb question:
>>
>> I've got mp3 files that are downloaded (by ipodder) into individual
>> subfolders. I'd like to write a quick script to move (not copy) all the mp3
>> files in those folders into a single destination folder. I was thinking I
>> could do it easily from the linux command line (cp -r copies the subfolders
>> out as well) but I can't figure out how to do it. Is there an easy way to
>> achieve this using Python? I am assuming this would be something Python was
>> designed to make easy..
>> 
>
> In python, you can use os.rename to move and os.walk to walk your
> directory structure.  Something like:
>
> source = '/ipodder'
> dest = '/foo/bar'
> for root, dirs, files in os.walk(source):
> for f in files:
> os.rename(os.path.join(root, f), os.path.join(dest, f))
This will copy all the files into the dest directory - it doesn't copy 
the folder structure.

I highly recommend Jason Orendorff's path module for any code involving 
walking directories. Something like this:

from path import path
source = path('/ipodder')
dest = '/foo/bar'

for mp3 in source.walkfiles('*.mp3'):
  relpath = source.relpathto(mp3)
  destmp3 = dest / relpath
  os.rename(mp3, destmp3)

http://www.jorendorff.com/articles/python/path/index.html
Kent

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