我的程序显示意外的令牌错误。为什么?

时间:2017-08-06 09:21:16

标签: python

如果除了n之外的n的因子总和为n,则程序需要返回true。我需要在运行时使用函数名称。当我输入

factors(45) 

它表明存在一个未解决的令牌错误。请检查程序有什么问题。

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)

2 个答案:

答案 0 :(得分:1)

您不能将factors(n)调用perfect(n)功能。所以,你必须使用 factorlist = factors(n)函数perfect(n)

然后尝试这种方式:

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

答案 1 :(得分:0)

尝试:

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))

输出:

enter image description here