You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何实现函数重调重启程序?完全数判断代码输入无响应求助

问题分析与修复方案

你的代码核心问题有两个:

  • 重新输入后仅调用了isPerfect(op),但没有对返回结果做判断,也没有触发循环逻辑,导致输入完就直接结束程序,不会继续验证或重新发起输入。
  • 缺少循环机制,无法让程序反复接收输入直到用户输入完全数。

下面是修复后的代码,同时优化了逻辑冗余:

def isPerfect(num):
    if num <= 0:                  
        return False
    total = 0                       
    for i in range(1, num):
        if num % i == 0:
            total += i
    return total == num  # 简化判断逻辑


def main():
    while True:  # 用while循环实现持续输入直到正确
        try:  # 处理非整数输入的异常
            num = int(input("Enter a perfect integer: "))
            if isPerfect(num):
                print(f"Congratulations! {num} is a perfect number.")
                break  # 输入正确,退出循环
            else:
                print(f"{num} is not a perfect number. Please re-enter.")
        except ValueError:
            print("Invalid input! Please enter an integer.")


if __name__ == '__main__':
    main()

关键修改点:

  • 用while True构建无限循环,直到用户输入完全数后执行break退出。
  • 简化isPerfect的返回逻辑,直接返回total == num的布尔值,去掉多余的if-else分支。
  • 添加try-except捕获非整数输入的异常,避免程序因输入格式错误崩溃。
  • 重新输入后自动回到循环开头,无需手动调用函数即可重启输入验证流程。

内容的提问来源于stack exchange,提问作者Ryan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 07:55:19