Ask Your Question
0

Printing variable name

asked 2018-01-29 19:05:32 +0100

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?

edit retag flag offensive close merge delete

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 ( 2018-01-29 19:35:16 +0100 )edit

1 Answer

Sort by ยป oldest newest most voted
0

answered 2018-01-29 19:32:39 +0100

tmonteil gravatar image

updated 2018-01-29 19:32:52 +0100

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
edit flag offensive delete link more

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: 2018-01-29 19:05:32 +0100

Seen: 857 times

Last updated: Jan 29 '18