Re: [Tutor] My code works but it is a little bit broken.

2011-09-26 Thread Alan Gauld

On 26/09/11 03:25, brandon w wrote:

This code calculates money. The problem is that in the first field after
the mouse enters a second time updates itself with the value from the
last field. I don't want it to do that.
I think that the problem is in the "callback" method.



I haven't gone through this in depth but one thing that
looked odd to me was:



def calculateAmount():
 field1 = varText.get()
...
 field2 = varText.get()
...
 field3 = varText.get()
...
 field4 = varText.get()
...
 field5 = varText.get()


Are all fields supposed to be getting the same value?
And if so why not just do it once at the start of the function?

But as I say I didn't read it all in depth so maybe you
have some magic going on that changes the value between reads...

--
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] execute a function

2011-09-26 Thread Sajjad
Hello forum,


It has been two days that i have started with python and i am stuck with the
following simple issue:

i have created a python file and inside the file i have defined a function
as follows:


def greeting():
  print "Welcome to python"

///

I am following the Book named - "Rapid GUI programming with Python and Qt"

In the book they mentioned that  in the command line if i type

greeting() i should get the output "Welcome to python"

But i get nothing.


Any hint on this?


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


Re: [Tutor] execute a function

2011-09-26 Thread Steven D'Aprano

Sajjad wrote:

Hello forum,


It has been two days that i have started with python and i am stuck with the
following simple issue:

i have created a python file and inside the file i have defined a function
as follows:


def greeting():
  print "Welcome to python"

///

I am following the Book named - "Rapid GUI programming with Python and Qt"

In the book they mentioned that  in the command line if i type

greeting() i should get the output "Welcome to python"

But i get nothing.


"Nothing"? Are you sure?

You shouldn't get nothing. You should get either "Welcome to python", or 
an error message. But you shouldn't get nothing at all.



First off, you need to launch the Python interactive interpreter from 
the command line. I don't know what operating system you are using, but 
this is how I do it from Linux:



Start menu > System > Terminal

(terminal window opens)

At the $ prompt, type: "python" and then press the Enter key. The 
terminal shows:


[steve@sylar ~]$ python
Python 2.5 (r25:51908, Nov  6 2007, 16:54:01)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>


Now, I don't know what you have called your Python file, so I will make 
up a name: "myfile.py". Make sure it is saved in your home directory.


At the >>> prompt, type "import myfile" (WITHOUT the .py) and then hit 
Enter. The terminal shows:


>>> import myfile
>>>


At the >>> prompt, type "myfile.greeting() and hit Enter:

>>> myfile.greeting()
Welcome to python
>>>


Now type "from myfile import greeting", Enter, then "greeting()", Enter:

>>> from myfile import greeting
>>> greeting()
Welcome to python
>>>


Remember to change the word "myfile" to whatever the actual name of your 
file is. The file MUST have a .py extension, but inside Python you never 
use the .py.



If you get any errors, please COPY AND PASTE them and send them to the 
mailing list. Don't type them by memory, paraphrase them, or otherwise 
edit them.


Good luck!



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


Re: [Tutor] execute a function

2011-09-26 Thread Dave Angel

On 09/26/2011 06:53 AM, Sajjad wrote:

Hello forum,


It has been two days that i have started with python and i am stuck with the
following simple issue:

i have created a python file and inside the file i have defined a function
as follows:


def greeting():
   print "Welcome to python"

///

I am following the Book named - "Rapid GUI programming with Python and Qt"

In the book they mentioned that  in the command line if i type

greeting() i should get the output "Welcome to python"

But i get nothing.


Any hint on this?


Regards
Sajjad

A little more precision would be helpful.  You never told us what you 
called that source file.  And there are several possible "command line" 
you might be referring to.   The most likely are the shell, and the 
interpreter prompt.  if you had shown us your session (via cut 'n 
paste), we might have been able to guess.


If you get nothing, then you must be somewhere else, since each of those 
will give you some response, depending on which shell you're running.  
So for example, if you're running Python 2.7 on Linux 10.04, with Bash 
as your shell, you might get


davea@think:~$ greeting()
>


That > prompt means you haven't finished the command line, and bash is 
waiting for the rest.  Use Ctrl-C to get out of that one.  Greeting is 
not a program from bash's point of view.


or if I'm running in the interpreter, I might get:

Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> greeting()
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'greeting' is not defined
>>>

And this would be because two errors have occurred.  In the above 
session I didn't import the source file, and I didn't qualify the name 
greeting so the interpreter could look in that module.


I would normally just add the greeting() call to the bottom of the 
source file  firstprogram.py, and then run the whole thing with


davea@think:~$ python firstprogram.py

But your tutorial may have other ideas, so you'd best tell us what 
you've tried, and exactly what happened.





--

DaveA

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


[Tutor] Review my code

2011-09-26 Thread Chanakya Mitra
 

I wrote a short script that tries to check if an email address exists or
not.

 

It takes the domain of the inputted email and looks up the registered
mail exchange.

 

It then connects via smtp and attempts the "RCPT TO:"
command and based on the response decides if the email exists or not.

 

I was trying to be more OOP in my approach but not sure I've been
entirely successful.

 

Thanks for your time.

 

Chan

 

Code:

 

 

import DNS, socket, string, re, sys

servers = []

myserver = 'mailgate..com'

mymail = 'maywedt...@.com'

CRLF="\r\n"

def mailxch(hname):

mxhosts = DNS.mxlookup(hname)

return mxhosts

 

def prompt(prompt):

return raw_input(prompt).strip()

 

class smtsock(object):

response = None

def getmsg(self):

self.response = self.msock.makefile('rb')

while 1:

try:

   line = self.response.readline()

   return line[:3], line[4:]   

except socket.error:

self.msock.close()

return "socket Error"

def put(self,cmd,args=""):

if args == "":

str = '%s%s' % (cmd, CRLF)

else:

str = '%s %s%s' % (cmd, args, CRLF)

try:

self.msock.send(str)

except socket.error:

self.msock.close()

return "socket Error"

def pr(self,cmd,args=""):

self.put(cmd, args) 

return self.getmsg()

def conn(self,server):

try:

self.msock = socket.create_connection((server,25))

(hand, msg) = self.getmsg()

return hand, msg

except:

err = sys.exc_info()[1]

return err

def helo(self, server): 

(hand, msg) =  self.pr("HELO",server)

return hand, msg

def vrfy(self, hname):

cstr =  "<%s>"% hname

(hand, msg) = self.pr("VRFY", cstr)

return hand, msg

def mailfrm(self, emf):

cstr =  "<%s>"% emf

(hand, msg) = self.pr("MAIL FROM:", cstr)

return hand, msg

def rcptto(self,hname):

cstr =  "<%s>"% hname

(hand, msg) = self.pr("rcpt to:", cstr)

return hand, msg

def cls(self):

self.msock.close()

 

   

 

rcpt_handlers = {

"250":"  \n#--# \n\tE-mail
Exists\n#--# \n",

"251":"  User not local; will forward to ",

"550":"  \n#--# \n\tNo Such
Address\n#--# \n",

"551":"  User not local; please try ",

"552":"  Requested mail action aborted: exceeded storage allocation",

"553":"  Requested action not taken: mailbox name not allowed",

"450":"  Requested mail action not taken: mailbox unavailable",

"451":"  Requested action aborted: local error in processing",

"452":"  Requested action not taken: insufficient system storage",

"500":"  Syntax error, command unrecognised",

"501":"  Syntax error in parameters or arguments",

"503":"  Bad sequence of commands",

"521":"   does not accept mail [rfc1846]",

"socket Error":"Socket Error: Connection closed.",

"421":"   Service not available, closing transmission channel"

}

 



em =
re.compile(r"(?:^|\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)",r
e.IGNORECASE)

 

while True:

hname = prompt("E-Mail Address(or XX to quit): ")

if hname == "XX":

break

if em.match(hname) == None:

print "Email incorrect format"

else:

s = smtsock()

servers = mailxch(hname.split("@")[1])

print servers

i = 0

for i in range(len(servers)):

print "Trying mailserver: %s"% servers[i][1]

(reply, msg)= s.conn(servers[i][1])

if reply != '220':

break

(reply, msg) = s.helo(myserver)

if reply != '250':

break

(reply, msg) = s.mailfrm(mymail)

if reply != '250':

break

(reply, msg) = s.rcptto(hname)

print rcpt_handlers.get(reply)

if reply == '250':

break

s.cls()

 



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


[Tutor] taking input for a list in a list

2011-09-26 Thread surya k
Hi,

Actually my programming language is C.. learning python.

I'm trying to write sudoku program for which I need to take input.
This is what I did merely

*list = []
for i in range (0,4) :
  for j in range (0,4) :
   list[i][j].append (" int (raw_input("Enter") ) )

*
This is completely wrong.. but I couldn't handle this kind of.. how do I..
Actually I need a list in a list to handle sudoku.

for a simple list to get input.. this would obviously work..
*list.append ( int(raw_input("Enter") )*


Can you tell me how do I do this correctly ?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] taking input for a list in a list

2011-09-26 Thread Joel Goldstick
On Mon, Sep 26, 2011 at 8:46 AM, surya k  wrote:

> Hi,
>
> Actually my programming language is C.. learning python.
>
> I'm trying to write sudoku program for which I need to take input.
> This is what I did merely
>
> *list = []
> for i in range (0,4) :
>   for j in range (0,4) :
>list[i][j].append (" int (raw_input("Enter") ) )
>
> *
> This is completely wrong.. but I couldn't handle this kind of.. how do I..
> Actually I need a list in a list to handle sudoku.
>
> for a simple list to get input.. this would obviously work..
> *list.append ( int(raw_input("Enter") )*
>
>
> Can you tell me how do I do this correctly ?
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
> because list is a built in data type you should name your list something
else.  What does your code do? does it give traceback errors?  After you
change list to, say my_list what do you get?


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


Re: [Tutor] taking input for a list in a list

2011-09-26 Thread Peter Otten
surya k wrote:

> Actually my programming language is C.. learning python.
> 
> I'm trying to write sudoku program for which I need to take input.
> This is what I did merely
> 
> *list = []
> for i in range (0,4) :
>   for j in range (0,4) :
>list[i][j].append (" int (raw_input("Enter") ) )
> 
> *
> This is completely wrong.. but I couldn't handle this kind of.. how do I..
> Actually I need a list in a list to handle sudoku.
> 
> for a simple list to get input.. this would obviously work..
> *list.append ( int(raw_input("Enter") )*
> 
> 
> Can you tell me how do I do this correctly ?

Break the problem down to one you already know how to solve: if you add a 
new inner list for the columns to the outer list of rows adding an entry to 
the row means just appending an integer to the inner list:

def input_int():
return int(raw_input("Enter an integer "))

square = []
N = 4
for i in range(N):
row = []
square.append(row)
for k in range(N):
row.append(input_int())


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


Re: [Tutor] Review my code

2011-09-26 Thread Steven D'Aprano

Chanakya Mitra wrote:
 


I wrote a short script that tries to check if an email address exists or
not.



Some brief comments:

When you send code by HTML email, you mess up the formatting of the 
code. Please don't do that in the future.




def mailxch(hname):
mxhosts = DNS.mxlookup(hname)
return mxhosts


That can be re-written as:

def mailxch(hname):
return DNS.mxlookup(hname)

but why bother calling the function? Instead of:

x = mailxch("some host name")

why not just call the actual function that does the work?

x = DNS.mxlookup("some host name")


If all you want is to use a different name, because you don't like 
"mxlookup", then:


mailxch = DNS.mxlookup

will bind the mxlookup function to the name "mailxch" without the cost 
of an extra function call.





def prompt(prompt):
return raw_input(prompt).strip()


Another function which may be simple enough to just call inline. But 
that's a matter of taste.




class smtsock(object):
response = None


This class has no initialiser (no __init__ method). Is that deliberate?

Also, it is normal for classes to be named in CamelCase.




def getmsg(self):
self.response = self.msock.makefile('rb')
while 1:


The more Pythonic idiom is to say "while True" rather than "while 1", 
although again that's a matter of taste.




try:
   line = self.response.readline()
   return line[:3], line[4:]   
except socket.error:

self.msock.close()
return "socket Error"


Generally speaking, this is poor design. Now you have a method which 
sometimes returns a tuple of lines, and sometimes a string. So you can't 
do this:


alines, blines = smtsock().getmsg()

because it will break if there is a socket error. So you have to do this:


result = smtsock().getmsg()
if result == "socket error":  # oops, I spelled it wrong...
# how do I recover from this?
pass  # ???
else:
alines, blines = result


Ugly and fragile! Don't write code like this. Instead, errors should 
raise an exception. The caller can always catch the exception if they 
know how to deal with it, or they can ignore it and let it bubble up to 
the top, then they will get a nice traceback.


So something like this is probably better:

try:
line = self.response.readline()
return line[:3], line[4:]
finally:
# Always close the socket, even if an error occurred.
self.msock.close()


If an error occurs, you will get an exception, but the socket will still 
be closed.





def put(self,cmd,args=""):
if args == "":
str = '%s%s' % (cmd, CRLF)
else:
str = '%s %s%s' % (cmd, args, CRLF)
try:

self.msock.send(str)
except socket.error:
self.msock.close()
return "socket Error"


Same here. Never return a magic error code when you can use an exception 
instead.




def pr(self,cmd,args=""):
self.put(cmd, args) 
return self.getmsg()


def conn(self,server):
try:
self.msock = socket.create_connection((server,25))
(hand, msg) = self.getmsg()
return hand, msg
except:


Never catch a bare except! (Well, truth be told there are situations 
where catching a bare except is useful, but they're rare.) Bare excepts 
catch too much -- they mask bugs in your code, they prevent the user 
from interrupting the script with Ctrl-C. You should only ever catch the 
smallest set of exceptions that you know you can deal with.




err = sys.exc_info()[1]
return err


Again, don't return magic error codes.


def helo(self, server): 
(hand, msg) =  self.pr("HELO",server)

return hand, msg

def vrfy(self, hname):
cstr =  "<%s>"% hname
(hand, msg) = self.pr("VRFY", cstr)
return hand, msg

def mailfrm(self, emf):
cstr =  "<%s>"% emf
(hand, msg) = self.pr("MAIL FROM:", cstr)

return hand, msg

def rcptto(self,hname):
cstr =  "<%s>"% hname
(hand, msg) = self.pr("rcpt to:", cstr)

return hand, msg

def cls(self):
self.msock.close()


Apart from the painfully terse method names ("cls"? Would typing "close" 
break your keyboard?), nothing looks too bad there.






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


Re: [Tutor] Review my code

2011-09-26 Thread Chanakya Mitra
Hi Steve,
>Some brief comments:
>
>When you send code by HTML email, you mess up the formatting of the 
>code. Please don't do that in the future.

Noted and sorry about that.

Someone also pointed out I should have said 'please' in my original email, so 
apologies if I came across as rude and demanding.

Thanks for the feedback and critique, I'll be reworking the script with all 
your points in mind.

Chan



-Original Message-
From: tutor-bounces+chanakya=optirisk-systems@python.org on behalf of 
Steven D'Aprano
Sent: Mon 26/09/2011 16:42
To: Tutor@python.org
Subject: Re: [Tutor] Review my code
 
Chanakya Mitra wrote:
>  
> 
> I wrote a short script that tries to check if an email address exists or
> not.





> def mailxch(hname):
> mxhosts = DNS.mxlookup(hname)
> return mxhosts

That can be re-written as:

def mailxch(hname):
 return DNS.mxlookup(hname)

but why bother calling the function? Instead of:

x = mailxch("some host name")

why not just call the actual function that does the work?

x = DNS.mxlookup("some host name")


If all you want is to use a different name, because you don't like 
"mxlookup", then:

mailxch = DNS.mxlookup

will bind the mxlookup function to the name "mailxch" without the cost 
of an extra function call.



> def prompt(prompt):
> return raw_input(prompt).strip()

Another function which may be simple enough to just call inline. But 
that's a matter of taste.


> class smtsock(object):
> response = None

This class has no initialiser (no __init__ method). Is that deliberate?

Also, it is normal for classes to be named in CamelCase.



> def getmsg(self):
> self.response = self.msock.makefile('rb')
> while 1:

The more Pythonic idiom is to say "while True" rather than "while 1", 
although again that's a matter of taste.


> try:
>line = self.response.readline()
>return line[:3], line[4:]   
> except socket.error:
> self.msock.close()
> return "socket Error"

Generally speaking, this is poor design. Now you have a method which 
sometimes returns a tuple of lines, and sometimes a string. So you can't 
do this:

alines, blines = smtsock().getmsg()

because it will break if there is a socket error. So you have to do this:


result = smtsock().getmsg()
if result == "socket error":  # oops, I spelled it wrong...
 # how do I recover from this?
 pass  # ???
else:
 alines, blines = result


Ugly and fragile! Don't write code like this. Instead, errors should 
raise an exception. The caller can always catch the exception if they 
know how to deal with it, or they can ignore it and let it bubble up to 
the top, then they will get a nice traceback.

So something like this is probably better:

 try:
 line = self.response.readline()
 return line[:3], line[4:]
 finally:
 # Always close the socket, even if an error occurred.
 self.msock.close()


If an error occurs, you will get an exception, but the socket will still 
be closed.



> def put(self,cmd,args=""):
> if args == "":
> str = '%s%s' % (cmd, CRLF)
> else:
> str = '%s %s%s' % (cmd, args, CRLF)
> try:
> self.msock.send(str)
> except socket.error:
> self.msock.close()
> return "socket Error"

Same here. Never return a magic error code when you can use an exception 
instead.


> def pr(self,cmd,args=""):
> self.put(cmd, args) 
> return self.getmsg()
> 
> def conn(self,server):
> try:
> self.msock = socket.create_connection((server,25))
> (hand, msg) = self.getmsg()
> return hand, msg
> except:

Never catch a bare except! (Well, truth be told there are situations 
where catching a bare except is useful, but they're rare.) Bare excepts 
catch too much -- they mask bugs in your code, they prevent the user 
from interrupting the script with Ctrl-C. You should only ever catch the 
smallest set of exceptions that you know you can deal with.


> err = sys.exc_info()[1]
> return err

Again, don't return magic error codes.


> def helo(self, server): 
> (hand, msg) =  self.pr("HELO",server)
> return hand, msg
> 
> def vrfy(self, hname):
> cstr =  "<%s>"% hname
> (hand, msg) = self.pr("VRFY", cstr)
> return hand, msg
> 
> def mailfrm(self, emf):
> cstr =  "<%s>"% emf
> (hand, msg) = self.pr("MAIL FROM:", cstr)
> return hand, msg
> 
> def rcptto(self,hname):
> cstr =  "<%s>"% hname
> (hand, msg) = self.pr("rcpt to:", cstr)
> return hand, msg
> 
> def cls(self):
> self.msock.close()

Apart from the painfully terse method names ("cls"? Would typing "close" 
br

Re: [Tutor] Funtions, modules & global variables

2011-09-26 Thread questions anon
Thanks for your feedback. I might be asking the wrong questions.
I have written a number of scripts that do various things for each step:
1. get data (e.g. Dec-jan-feb, only januarys, all data)
2. summary stats(e.g. max, min, frequency)
3. plot data (e.g. plot with time, plots subplots, plot with particular
projection)

I would like to then be able to choose which script for each step and
somehow feed the data/variables written in earlier functions through to then
be able to run something like:

def main():
 getdataDJF()
 calculatemean()
 plotmean()
main()

Is this possible? Is this the correct way to do things?
My main problem is not being able to feed the output from one function into
the next.
Thanks
Sarah


On Mon, Sep 26, 2011 at 10:35 AM, Alan Gauld wrote:

> On 26/09/11 00:21, questions anon wrote:
>
>> Hi All,
>> I am trying to move from writing one long script each time I need to do
>> a new thing but I do not quite understand how functions work, even after
>> reading many manuals.
>>
>
> Can you be more specific about what you dpn;t understand.
>
> For example can you understand how this function works?
>
> def square(x):
>return x*x
>
> If not what is the area of difficulty?
>
>
>  My first attempt is to create a python file where I have defined a
>> number of functions that get data in various ways.
>> I have also made another python file where I want to plot the data in
>> different ways. but I am having trouble getting that data to run in my
>> python plotting file.
>>
>
> It may be easier to keep all the functions in a single file initially. It
> just eliminates an extra layer of complexity until we get things working.
> Once you know your functions work we can think about moving them into
> separate files.
>
>
>  I have made the variable I require 'global' but that doesn't seem to be
>> working. I keep receiving:
>> /
>> UnboundLocalError: local variable 'TSFC' referenced before assignment/
>>
>
> global in Python means global within the current file. It does not mean
> across all files.
>
>
>
>> Below is a some of the script for both folder, just note that their will
>> be many functions in each folder
>>
>
> I'm not sure I understand that bit. So I'll just ignore it for now! :-)
>
>
>
>  #selectdata.py
>> def selectalldata():
>> for (path, dirs, files) in os.walk(MainFolder):
>> for dir in dirs:
>> print dir
>> path=path+'/'
>> for ncfile in files:
>> if ncfile[-3:]=='.nc':
>> print "dealing with ncfiles:", path+ncfile
>> ncfile=os.path.join(path,**ncfile)
>> ncfile=Dataset(ncfile, 'r+', 'NETCDF4')
>> global TSFC
>>
>
> Normally globals are defined at the top of the function. Its not necessary
> but its where most readers will look for it. In this case there is no
> existing global variable TSFC so it gets created in your module space on the
> assignment.
>
>
> >  TSFC=ncfile.variables['T_SFC']**[:,:,:]
>
> I'm not familiar with the [:,:,:] style? What does it do?
> Are you sure you want the commas?
>
>
> But since that happens inside an if block, if the block doesn't get
> executed the global variable will never get created. Any attempt to access
> the variable before the if block is executed will result in your error.
>
>
>  LAT=ncfile.variables['**latitude'][:]
>> LON=ncfile.variables['**longitude'][:]
>> TIME=ncfile.variables['time'][**:]
>> fillvalue=ncfile.variables['T_**SFC']._FillValue
>> ncfile.close()
>>
>
> And since there are no other functions in this file nobody else can see the
> TSFC variable you created. And since the function does not return any data
> it will be hard for other modules to use this function.
>
>
>
>
>>
>> #plotdata.py
>>
>> from selectdata import selectalldata
>> selectalldata()
>>
>
> This will (msometimes) create a TSFC variable in the selectdata module, but
> you will not be able to access it here because you have not imported
> selectdata. If you had you could have done
>
> TSFC = selectdata.TSFC
>
> But since you didn't I suspect that
>
>
>  def plotncfilewithtime():
>> for TSFC, TIME in zip((TSFC[1::3]),(TIME[1::3]))**:
>>
>
> This will fail when it tries to slice TSFC which it can't see.
> Even if it did work it would be bad practice to do this sin e from the next
> line onwards the original TSFC would be masked by the new TSFC variable you
> are creating. Better to use unique names for the two values.
>
>
>  #convert time from numbers to date and prepare it to have no
>> symbols for saving to filename
>>
> 
> I ignored the techie stuff :-)
>
>
>  print "end of processing"
>> plotncfilewithtime()
>>
>
> Again, this is not the best way to use functions, better to get the
> function to return the output to be displayed by the other program.
>
> HTH

Re: [Tutor] Funtions, modules & global variables

2011-09-26 Thread Dave Angel

(Don't top-post.  Put your new remarks after whatever you're quoting)

On 09/26/2011 08:26 PM, questions anon wrote:

Thanks for your feedback. I might be asking the wrong questions.
I have written a number of scripts that do various things for each step:
1. get data (e.g. Dec-jan-feb, only januarys, all data)
2. summary stats(e.g. max, min, frequency)
3. plot data (e.g. plot with time, plots subplots, plot with particular
projection)

I would like to then be able to choose which script for each step and
somehow feed the data/variables written in earlier functions through to then
be able to run something like:

def main():
  getdataDJF()
  calculatemean()
  plotmean()
main()

Is this possible? Is this the correct way to do things?
My main problem is not being able to feed the output from one function into
the next.
Thanks
Sarah


If multiple functions need to share data, it should be done by passing 
parameters, and returning results.  If you can understand how to do that 
within a single source file, you'll be ready to extend the concept to 
multiple source files.


But if you just want to skip to a solution, without worrying about 
whether it makes sense, read on.


You have multiple files, how do they relate to each other?  What is the 
kind of data you're trying to share?


I'll make a crazy guess, since you still give no clue.

Perhaps each of your multiple files, called external1.py, external2.py 
defines three functions, called getdataDJF(), calculatemean(), and 
plotmean().  They're defined as follows:


getdataDJF - takes arg1, arg2 and arg3 as parameters, and returns 
results as   (res1, res2)
calculatemean - takes  arg1 and arg2 as parameters, and returns mydata 
as result
plotmean  - takes mydata and device as parameters, and doesn't return 
anything


So your script could do a conditional import to get various 
implementations of the functions.


import sys
if (something):
   from   external1 import getdataDJF, calculateman, plotmean
else:
   from   external2 import getdataDJF, calculateman, plotmean


def main(argv):
  (res1, res2) = getdataDJF(argv[1], argv[2], argv[3])
  buffer = calculatemean(res1, res2)
  plotmean(buffer, argv[4])

main(sys.argv, "printer")

Another approach if this guess is wrong:use classes.  Keep all the 
data as attributes of a class instance, and the methods can share data 
by stuffing it in those attributes.


--

DaveA

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


Re: [Tutor] My code works but it is a little bit broken.

2011-09-26 Thread brandon w
The fields take the initial value and multiply it to get the amount.
The problem in in the callback function. It uses the  event to clear
a field, but when the mouse enters a second time it adds a numeric value.
This is a semantic error. It is not doing what I want it to do.

On Mon, Sep 26, 2011 at 4:03 AM, Alan Gauld wrote:

> On 26/09/11 03:25, brandon w wrote:
>
>> This code calculates money. The problem is that in the first field after
>> the mouse enters a second time updates itself with the value from the
>> last field. I don't want it to do that.
>> I think that the problem is in the "callback" method.
>>
>>
> I haven't gone through this in depth but one thing that
> looked odd to me was:
>
>
>  def calculateAmount():
>> field1 = varText.get()
>> ...
>> field2 = varText.get()
>> ...
>> field3 = varText.get()
>> ...
>> field4 = varText.get()
>> ...
>> field5 = varText.get()
>>
>
> Are all fields supposed to be getting the same value?
> And if so why not just do it once at the start of the function?
>
> But as I say I didn't read it all in depth so maybe you
> have some magic going on that changes the value between reads...
>
> --
> 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 maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor