這是我正在處理的代碼。它應該從用戶那里獲取一個數字,如果它是一個完美的數字,它會這樣說,但如果不是,它會要求輸入一個新數字。當我到達輸入新數字部分時,它不會記錄我的輸入。有人可以幫我嗎?
def isPerfect(num):
if num <= 0:
return False
total = 0
for i in range(1,num):
if num%i== 0:
total = total i
if total == num:
return True
else:
return False
def main():
num = int(input("Enter a perfect integer: "))
if isPerfect(num) == False:
op = int(input(f"{num} is not a perfect number. Re-enter:"))
isPerfect(op)
elif isPerfect(num) == True:
print("Congratulations!",num, 'is a perfect number.')
if __name__ == '__main__':
main()
uj5u.com熱心網友回復:
你可以像這樣將 while True 回圈放入你的 main 函式中:
def main():
first_run = True
perfect_num_received = False
while not perfect_num_received:
if first_run:
num = int(input("Enter a perfect integer: "))
first_run = False
if isPerfect(num) == False:
num = int(input(f"{num} is not a perfect number. Re-enter:"))
elif isPerfect(num) == True:
perfect_num_received = True
print("Congratulations!",num, 'is a perfect number.')
但也已經有一個內置函式來檢查變數的資料型別,所以你可以做這樣的事情:
if type(num) == int:
...
uj5u.com熱心網友回復:
根據問題描述,我假設程式應該在找到完全數后終止。可以添加兩件事,一個是每次用戶輸入數字時檢查輸入提示的回圈,另一個是找到完美數字后的中斷條件。這是一個有效的實作。
def main():
while True:
num = int(input("Enter a perfect integer: "))
if isPerfect(num) == False:
num = int(input(f"{num} is not a perfect number. Re-enter: "))
isPerfect(num)
elif isPerfect(num) == True:
print("Congratulations! ",num, ' is a perfect number.')
break
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/537909.html
上一篇:網站加載在FireFox上未完成