Home > Blockchain >  My function not returning any result in python?
My function not returning any result in python?

Time:02-24

so I was doing a little math study and decided to recreate a simple assignment in python which is to find the factor pairs of a number. I did that quite easily but now I have a little issue which I have tried to figure out but to no avail. Here's the code:

# Find the factor pairs of a given number

def getFactorPairs(n=0):
    num = n
    factors = []
    pair = None

    for p in range(1, num   1):
        for r in range(1, num   1):
            if p * r == num:
                pair = (p, r)
                if (r, p) not in factors:
                    factors.append(pair)
                else:
                    continue
    return factors

print(getFactorPairs(120)) # Works fine

getFactorPairs(120) # This doesn't give any result. Why?

When I use the print(getFactorPairs()) and pass in a number, the result is as expected but when I just call the function getFactorPairs() and input a number, it doesn't give me any result. I will be glad if someone can show me where I am doing something wrong. Thanks.

CodePudding user response:

Replace

getFactorPairs(120) # This doesn't give any result. Why?

with

temp = getFactorPairs(120)
print(temp)

The reason

When a function return value/values it is not automatically displayed by python.

CodePudding user response:

The print function will display the values. if you assign the result of the getFactorPairs() to a variable and display the variable using print it will display the result

def getFactorPairs(n=0):
    num = n
    factors = []
    pair = None

    for p in range(1, num   1):
        for r in range(1, num   1):
            if p * r == num:
                pair = (p, r)
                if (r, p) not in factors:
                    factors.append(pair)
                else:
                    continue
    return factors
result = getFactorPairs(120)
print(result)

You are simply executing the function without displaying the result

  • Related