Output should be 4 and 1 but it's returning 4 and 5?

Viewed 22

In the following code i am try to find kth factor of given number it's works fine until i created function and pass value to it can anyone tell me why it's returning wrong output. when you call function only ones no matter what number you pass it shows correct output but when call function two time it returning wrong output.

#Code

fact = []
def factor(N,k):
   for i in range(1,N+1):
     if N % i == 0:
        fact.append(i)

   if len(fact)<k:
        print(1)
  
   else:
       print(fact[k])

factor(12,3)
factor(30,9)
1 Answers

You have defined the fact variable of type list outside your function. So it is being referenced and used by both functions calls when you call it twice.

If you declare fact inside the function the scope of the variable will not persist and the number of times it is called will not be an issue.

def factor(N,k):
   fact = []
   for i in range(1,N+1):
     if N % i == 0:
        fact.append(i)

   if len(fact)<k:
        print(1)

   else:
       print(fact[k])
Related