Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7 using the input to a function as a string and variable

I would like to do the following:

print "CC =",CC

but as a function so that i only have to write the variable CC once. I can't work out how to do this in a function as it always evaluates CC as a floating point number (which it is).... Is there a way to accept the input to a function as both a string and floating point number?

I tried this:

def printme(a): 
    b='%s' % a
    print b
    return b

but of course it only prints the value of a, not its name.

like image 836
malby Avatar asked Jul 02 '12 10:07

malby


1 Answers

You could use the inspect module (see also this SO question):

def printme(x):
    import inspect
    f = inspect.currentframe()
    val = f.f_back.f_locals[x]
    print x, '=', val


CC = 234.234    
printme('CC') # <- write variable name only once
# prints: CC = 234.234
like image 125
catchmeifyoutry Avatar answered Sep 30 '22 20:09

catchmeifyoutry