-1

I have a lot of variables. Say for example, I wanted to print each variable everytime it was computed with. How would I do this. I will illustrate below:

def mul(a,b):
    return a*b
a = mul(1,2)
b = mul(1,3)
c = mul(1,4)
b = mul(1,5)

How would I print so it displays both computations of b, as shown below:

a = 2
b = 3
c = 4
b = 5

Would I have to store the variables in a list and use a for loop? Quite new to python so I am unsure.

AdilRay
  • 1
  • 1
  • 1
    Welcome to SO. Unfortunately this isn't a discussion forum or tutorial. Please take the time to read [ask] and the other links on that page. Invest some time with [the Tutorial](https://docs.python.org/3/tutorial/index.html) practicing the examples. It will give you an idea of the tools Python offers to help you solve your problem. You should try something. – wwii Jan 25 '18 at 18:24

1 Answers1

0

If you store both variables in a list, you could use this idiom:

def mul(x, y):
    return x * y

xs = [1,2,3,4,5]
ys = [10,20,30,40,50]

for args in zip(xs, ys):
    print "mul({}, {}) = {}".format(args[0], args[1], mul(*args))

mul(1, 10) = 10
mul(2, 20) = 40
mul(3, 30) = 90
mul(4, 40) = 160
mul(5, 50) = 250

zip() takes two lists, and returns a list of 2-tuples:

>>> zip(xs, ys) 
>>> [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50)]

str.format() takes a string, and injects the arguments you supply into the curly braces:

>>> "hello {}".format('world')
>>> "hello world"
fraczles
  • 81
  • 3