我正在工作的功能應該告訴用戶他們給出的數字是否是完美數字(即等於它的因子總和的一半)。如果用戶給出數8,輸出應該是這樣的:我怎樣才能返回一個在Python中的字符串中更改int?
8 is not a perfect number
,但我想不出該怎麼把在return語句,使int,它的變化取決於用戶的輸入,打印與字符串。到目前爲止的代碼看起來是這樣的:
#the代碼是另一大功能是,如果我是這樣做的回報(NUM1爲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
的原因中,「是不是一個完美的數字」 ),它會出來像 (8「是不是一個完美的數字」)
'return'{}不是一個完美的數字'.format(num1)' – 2014-10-30 04:29:35
順便說一下,你的求和操作是錯誤的。你從'0 - len(listOfDivisors) - 1'迭代,但是你每次都在你的循環中遞增'i',使得每次遞增2。考慮使用'sum'函數,比如'sumOfDivisors = sum(getFactors(num1))' – sberry 2014-10-30 04:43:12