1

The function do_math() is supposed to iterate over the lists numbers and operations. Each operations element is defined in do_math and is supposed to be applied to the corresponding numbers element. The loop however runs only once and then stops. Any ideas?

from math import sqrt

def do_math(numbers, operations):
    for i, j in list(zip(numbers, operations)):
        if j == "Root":
            return sqrt(i)
        elif j == "Square":
            return i**2
        elif j == "Nothing":
            return i

numbers = [2, 9, 25, 6, -3]
operations = ["Square", "Root", "Square", "Root", "Nothing"]

print(do_math(numbers, operations))
  • 2
    Most of your branches `return` something, which will immediately end the loop and exit the calling function. You probably want something like `result = []`, `result.append(sqrt(i))`, etc., `return result`. – 0x5453 Jun 04 '21 at 15:55

1 Answers1

1

You are using return which will exit your loop once it has reached that statement. So I think you are looking for the beloved yield.

from math import sqrt

def do_math(numbers, operations):
    for i, j in zip(numbers, operations):
        if j == "Root":
            yield  sqrt(i)
        elif j == "Square":
            yield  i**2
        elif j == "Nothing":
            yield  i

numbers = [2, 9, 25, 6, -3]
operations = ["Square", "Root", "Square", "Root", "Nothing"]
#generated is an object at the moment: <generator object do_math at 0x7fe3c0561d60>
generated = do_math(numbers, operations)
#iterate through that
for i in generated:
    print(i)

output

4
3.0
625
2.449489742783178
-3

Also note: for x,y in list(zip(a,b)) is the same as for i, j in zip(numbers, operations)

Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
  • Does that mean zip already creates a list (of tuples) on its own and i, j correspond to the two tuple elements? I thought I had to use list() first as I saw that in another thread (although the problem was not exactly the same). –  Jun 04 '21 at 17:25
  • [how does `zip` work?](https://realpython.com/python-zip-function/) – Buddy Bob Jun 04 '21 at 18:10