Ask Your Question
0

Printing variable name

asked 7 years ago

anonymous user

Anonymous

How would I return a variable name in a function. E.g. If I have the function:

def mul(a,b):
   return a*b

a = mul(1,2); a
b = mul(1,3); b
c = mul(1,4); c

This would return:

2
3
4

I would like it to return:

a = 2
b = 3
c = 4

How would I do this?

Preview: (hide)

Comments

One answer could be:

print """a = 2
b = 3
c = 4"""

(Sorry, but this is strictly speaking a valid answer.)

If something else is needed, something "more general", and this is certainly the case, than please describe this generality. Note also that the name of the variables "live" only in the "namespace of the code", it is not a good idea to let them live also "outside", as output... For testing purposes one may try something like...

print "a = %s" % a
print "b = %s" % b
print "c = %s" % c

(using this old fashioned string formatter, that may become soon obsolete, but it is the most simple one...)

(So what is the reason for such prints? Three prints as above can be understood also in the

2
3
4

form...)

dan_fulea gravatar imagedan_fulea ( 7 years ago )

1 Answer

Sort by » oldest newest most voted
0

answered 7 years ago

tmonteil gravatar image

updated 7 years ago

I am not sure about your request, does the following solve your issue ?

sage: def mul(a,b):
....:    return a*b
sage: a = mul(1,2); print('a = {}'.format(a))
sage: b = mul(1,3); print('b = {}'.format(b))
sage: c = mul(1,4); print('c = {}'.format(c))
a = 2
b = 3
c = 4
Preview: (hide)
link

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 7 years ago

Seen: 905 times

Last updated: Jan 29 '18