[Tutor] variables within function - wha?

Hans Nowak hnowak@cuci.nl
Fri, 20 Jul 2001 07:15:23 +0200


On 19 Jul 01, at 10:17, kromag@nsacom.net wrote:

> I am trying to get a function to perfrom simple calculations based on 3
> values.
> 
> -----------------------------------
> 
> 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
> 
> -----------------------------------
> 
> I can't figure out why:
> 
> >>> filter(1800,7000,foam)
> Traceback (innermost last):
>   File "<pyshell#1>", line 1, in ?
>     filter(1800,7000,foam)
> NameError: There is no variable named 'foam'
> >>> 
> 
> occours. Have I been inhaling too much brake cleaner?

If you call 
 
    filter(1800, 7000, foam)

then this only works if a variable 'foam' already exists outside of the 
'filter' function. If it's an argument you call the function with, then it 
shouldn't be done like this. A possible variant (although I'm not sure what 
the function is doing, so I might be wrong) is:

FOAM, PAPER = 1, 2	# just dummy values for the 'type' argument
	
def filter(cc, rpm, type):
	cid = cc / 16.387
	ocg = (cid * rpm) / 20839
	if type == PAPER:
		return ocg * 1.2181,
	elif type == FOAM:
		return ocg * 1.3767,
	else:
		return ocg
	
print filter(1800, 7000, FOAM)
# (50.796469562756506,)

A few side notes: did you mean to use a tuple for the return value? (As 
said, I don't know much about what this function does and what your 
intentions are, so you might have perfectly good reasons for it. But it 
strikes me as a bit odd that filter called with FOAM and PAPER will return 
a singleton tuple, while calling it with another value for 'type' will 
return a number.

Also, note that this code overrides the built-in functions 'filter' and 
'type'. If this code is part of a large program, you might want to consider 
renaming at least 'filter'.

HTH,

--Hans Nowak (zephyrfalcon@hvision.nl)
You call me a masterless man. You are wrong. I am my own master.
May Chickenlittle stab you in your your jugular!