Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python function not working properly it doesn't return the values that user should be getting

Tags:

python

def divisors(n):
    ans =0
    for i in range(n):
        i += 1
        k=n%i
        if k!=1:
            ans=i
    return ans
print(20)

I have a function that's not working properly when I run it prints the n value instead of printing out the divisors.

like image 664
user4574134 Avatar asked Nov 17 '25 04:11

user4574134


1 Answers

Three key issues are:

  1. k=n%i returns the remainder - if the remainder != 1 it doesn't mean that i is a divisor!
  2. in the for-loop you keep overriding ans and at the end of the function you return the value that was found on the last iteration that satisfied the if condition. What you want to do instead is to accumulate all the anss into a list and return that list.
  3. The print at the end is not calling the function - it simply prints the number 20.

I'm not posting a corrected solution because I think that it will be a good exercise for you to fix these bugs by yourself, good luck!

like image 157
Nir Alfasi Avatar answered Nov 18 '25 19:11

Nir Alfasi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!