【发布时间】:2014-10-30 04:24:53
【问题描述】:
我正在处理的函数应该告诉用户他们给出的数字是否是完美数字(即等于其因子总和的一半)。如果用户给出数字 8,则输出应如下所示:
8 is not a perfect number
但我不知道要在 return 语句中放入什么来使 int(根据用户输入而变化)与字符串一起打印出来。到目前为止的代码如下所示:
#代码在另一个更大的函数中,这就是 elif 的原因
elif(message == 2):
num1 = int(input("""Please enter a positive integer :"""))
while(num1 <= 0):
print("Number not acceptable")
num1 = int(input("""Please enter a positive integer :"""))
thisNum = isPerfect(num1)
if(thisNum == True):
return num1, is a perfect number
elif(thisNum == False):
return num1 is not a perfect number
def isPerfect(num1):
sumOfDivisors = 0
i = 0
listOfDivisors = getFactors(num1)
for i in range(0, len(listOfDivisors) - 1):
sumOfDivisors = sumOfDivisors + listOfDivisors[i]
i += 1
if(sumOfDivisors / 2 == num1):
return True
else:
return False
如果我要返回(num1,“不是一个完美的数字”)它会像 (8, '不是一个完美的数字')
【问题讨论】:
-
return '{} is not a perfect number'.format(num1) -
顺便说一下,你的求和操作是错误的。您从
0 - len(listOfDivisors) - 1迭代,但每次在循环内递增i,使 i 在每次通过时增加 2。考虑使用sum函数,例如sumOfDivisors = sum(getFactors(num1))
标签: python string int return-value