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

Python递归实现输入数字各位求和时返回None的问题排查

Fixing Your Recursive Digit Sum Function in Python

Hey there! Let's break down why your recursive digit sum code is returning None and fix it up. I noticed two critical issues in your implementation:

Key Problems in Your Code

  • Missing return statement in the recursive branch: When inputNum >= 10, you call digit_sum(inputNum / 10) but don't return the result of this call (plus the current digit). Without a return here, the function defaults to returning None once this branch finishes executing. That's exactly why your output shows None for multi-digit numbers.
  • Incorrect division type: Using / performs floating-point division (e.g., 123 / 10 gives 12.3), but your function is designed to work with integers. You need integer division (//) to drop the last digit and get a whole number (e.g., 123 // 10 gives 12).

Corrected Code

Here's the fixed version of your code with clear explanations:

def run():
    inputNum = int(input("Enter an int: "))
    print(f"sum of digits of {inputNum} is {digit_sum(inputNum)}.")

def digit_sum(inputNum):
    # Base case: single-digit number, return the number itself
    if inputNum < 10:
        return inputNum
    # Recursive case: add last digit to sum of remaining digits
    else:
        last_digit = inputNum % 10
        remaining_digits = inputNum // 10
        return last_digit + digit_sum(remaining_digits)

if __name__ == "__main__":
    run()

How It Works

Let's walk through an example with input 123 to see the recursion in action:

  1. digit_sum(123) calculates 3 + digit_sum(12)
  2. digit_sum(12) calculates 2 + digit_sum(1)
  3. digit_sum(1) hits the base case and returns 1
  4. Working back up: 2 + 1 = 3, then 3 + 3 = 6
  5. The final result 6 is returned and printed correctly

Now if you run this code, multi-digit inputs will return the correct sum instead of None!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 12:32:30