-1

Can anyone tell me why this only prints one value?

Range = [1,2,3,4]
def MyFunction(Var1,Var2,RangeValues):
        for x in RangeValues:
                if (x-1-Var1) <= 0: 
                  return 1-Var2
                else: 
                    return 1+Var2
print(MyFunction(1,3,Range))

I was expecting to see 4 printed results, one for each value in Range. However it seems like only evaluates the first term since it finds that 1-1-1 <= 0, and gives up there. Why doesn't it keep going for each value in Range?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
JZ1987
  • 99
  • 4
  • so I changed return to yield, and now it's telling me: "generator object MyFunction at 0x00000252F03237C8" – JZ1987 Oct 06 '19 at 17:17
  • If you use `yield`, you also have to call the function in a loop context, i.e. `for result in MyFunction(...):`, or `results = list(MyFunction(...))` – John Gordon Oct 06 '19 at 17:20

2 Answers2

2

After checking the if - else condition for the first element in the list, the return statement is causing the function to stop executing. Hence, the function is printing only one value. You can try the following code:

Range = [1,2,3,4]
def MyFunction(Var1,Var2,RangeValues):
    for x in RangeValues:
        if (x-1-Var1) <= 0: 
            print(1-Var2)
        else: 
            print(1+Var2)
MyFunction(1,3,Range)

You can also try returning a list:

Range = [1,2,3,4]
def MyFunction(Var1,Var2,RangeValues):
    li = []
    for x in RangeValues:
        if (x-1-Var1) <= 0: 
            li.append(1-Var2)
        else: 
            li.append(1+Var2)
    return li
print(MyFunction(1,3,Range))
Sultan Singh Atwal
  • 810
  • 2
  • 8
  • 19
1

return causes the function to exit as soon as its reached. You cannot return from a single call of a function multiple times.

The most straightforward solution is just to use a list comprehension, and return the result from it:

def MyFunction(Var1,Var2,RangeValues):
    return [1-Var2 if (x-1-Var1) <= 0 else 1+Var2 for x in RangeValues]

or, make the function a generator using yield:

def MyFunction(Var1,Var2,RangeValues):
    for x in RangeValues:
        if (x-1-Var1) <= 0: 
            yield 1-Var2
        else: 
            yield 1+Var2

# Need to force the generator into a list to easily see the results
print(list(MyFunction(1,3,Range)))

Just learn how to use list comprehensions though (the first version), since they're the simplest. Once you begin advancing, generator functions (the second version) are a good topic to take up. I wouldn't use the second until you have a better understanding of Python. I showed it here because it's the closest to what you already have.


Also, don't use capitalized names for arbitrary variables. Plain variable names should be in lower case, separated by an underscore ("snake_case").

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117