Benetha Thambi
Benetha Thambi

Reputation: 47

my program shows unexpected token error. why?

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)

Upvotes: 0

Views: 1292

Answers (2)

Pravitha V
Pravitha V

Reputation: 3308

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

Upvotes: 0

Md. Rezwanul Haque
Md. Rezwanul Haque

Reputation: 2950

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

Upvotes: 1

Related Questions