0

the program needs to return true if the factors of n other than n sum up to n. i need to use the function name during runtime. when i input

factors(45) 

it shows that there is an unexpexted token error. please check what is wrong with the program.

def factors(n):#unexpected token error
 factorlist = []
 for i in range(1,n):
  if n%i == 0:
    factorlist = factorlist + [i]
 return(factorlist)
def perfect(n):
 if sum(factorlist) == n:
  return(True)
 else :
  return(False)
8
  • factorlist not referenced in perfect(n) function. May be you wanted factorlist = factors(n) ? Commented Aug 6, 2017 at 9:27
  • can u do the correction in the program. i am not able to get it. im just beginning to learn python. please Commented Aug 6, 2017 at 9:37
  • 45 is not perfect number . so, it returns False. Commented Aug 6, 2017 at 9:40
  • People have answered below. Use one the answers ;) Commented Aug 6, 2017 at 9:44
  • 1
    Are you using Python 3? If so, to read a number from the user at runtime you can do n = int(input('Enter number ')). Commented Aug 6, 2017 at 10:01

2 Answers 2

1

You do not call factors(n) into the perfect(n) function. So, you have to use factorlist = factors(n) into the perfect(n) function.

and then try this way :

def factors(n):
  factorlist = []
  for i in range(1, n):
    if n % i == 0:
      factorlist = factorlist + [i]
  return (factorlist)


def perfect(n):
  factorlist = factors(n)  # use this line
  if sum(factorlist) == n:
    return (True)
  else:
    return (False)

print(perfect(45)) # Ouput : False
Sign up to request clarification or add additional context in comments.

1 Comment

Copy my code and run in the compiler. I think, this code is right and there is no bug.
0

Try :

def factors(n):
    factorlist = []
    for i in range(1,n):
        if n%i == 0:
            factorlist = factorlist + [i]
    print factorlist
    return factorlist

def perfect(n):
    factorlist = factors(n)
    if sum(factorlist) == n:
        return True
    else :
        return False

n = int(raw_input('Enter the number: '))
print(perfect(n))

Output:

enter image description here

8 Comments

it did not work. same error, how to use an argument in a function?
@ Benetha, both mine and Md. Rezwanul Haque answers are working and giving output, please try once again. Or post the exact error and code you are trying.
i need to input the number for what sum has to be calculated only during runtime. how should i change the print command
you can use "raw_input" to input values dynamically , see my updated answer
the runtime command should be>>> perfect(28) true
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.