[Tutor] Re: Tutor digest, Vol 1 #965 - 15 msgs

Charlie Clark Charlie Clark <charlie@begeistert.org>
Thu, 19 Jul 2001 19:11:55 +0200


>From:	kromag@nsacom.net [SMTP:kromag@nsacom.net]
>> def filter(cc,rpm,type):
>> 	cid=cc/16.387
>> 	ocg=(cid*rpm)/20839
>> 	foam=ocg*1.3767
>> 	paper=ocg*1.2181
>> 	if type==paper:
>> 		return paper,
>> 	elif type==foam:
>> 		return foam,
>> 	else:
>> 		return ocg
> 
Gives the error 
Traceback (innermost last):
  File "<pyshell#1>", line 1, in ?
    filter(1800,7000,foam)
NameError: There is no variable named 'foam'

It took me a second to spot this. Paper and foam are values for type 
("paper", "foam") but also variables in their own right (paper, foam). But 
they are also local variables - they are confined to the function. 
Furthermore, you are trying to feed a variable (foam) to the function before 
it has been initialised. If you had written foam = "" or anything like that 
you would have generated different errors. It is very easy to make this kind 
of mistake as well as type errors - at least I do it all the time.

Also you don't need the comma after a return. I don't know if it's just me 
but if you're taking the trouble to generate the intermediate local and thus 
hidden values like "cid" I'd introduce a special "return_value" in the 
conditions and just return that. I do this when I really need to be able step 
through my functions.

It might also be an idea not to use "type" as a name as it is a built in 
function.

So my solution would be
def filter_type(cc,rpm,material):
	cid = cc/16.387
	return_value = ocg = (cid*rpm)/20839 # assign the default value to be
                                         # returned
	foam_value = ocg*1.3767
	paper_value = ocg*1.2181

	if material == "paper":
		return_value = paper_value
	elif material == "foam":
		return_value = foam_value
	return return_value

using it
print filter_type(1800,7000,'water')
print filter_type(1800,7000,'paper')
print filter_type(1800,7000,'foam')
gives respectively:
36.8972685137
44.9445627765
50.7964695628


>BTW, are you using tabs to indent your code? Don't! Use spaces instead.
I noticed there was a heated discussion on the newsgroup about this a while 
back and I'm sure it crops up often. And the consensus seemed to be that 
spaces are the way to do things. But tabs are allowed. Maybe there is a page 
somewhere that presents the arguments? That would be useful to know.

Charlie

PS: I enjoyed working through this!