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 calldigit_sum(inputNum / 10)but don't return the result of this call (plus the current digit). Without areturnhere, the function defaults to returningNoneonce this branch finishes executing. That's exactly why your output showsNonefor multi-digit numbers. - Incorrect division type: Using
/performs floating-point division (e.g.,123 / 10gives12.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 // 10gives12).
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:
digit_sum(123)calculates3 + digit_sum(12)digit_sum(12)calculates2 + digit_sum(1)digit_sum(1)hits the base case and returns1- Working back up:
2 + 1 = 3, then3 + 3 = 6 - The final result
6is 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
相关产品推荐
相关产品推荐

