Sum of Digits Recursively
Calculate sum of digits recursively.
IntermediatePhase 3 - Level 1: Basic RecursionExample 10 of 10
sum-of-digits-recursively.py
1def sum_digits(n):2 # Base case3 if n == 0:4 return 056 # Recursive case7 return (n % 10) + sum_digits(n // 10)89# Test10num = int(input("Enter a number: "))11result = sum_digits(abs(num))12print(f"Sum of digits: {result}")
Output
Enter a number: 1234 Sum of digits: 10
What's going on
Extract last digit and recurse on remaining.
Key Concepts:
Base case: n == 0, return 0
Extract last digit: n % 10
Recurse on remaining: n // 10
Add digit to recursive result
🔗Related Content
- 📖
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- 📝
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- 💻
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- 🎓
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- 🧠
Logic Building Overview
Learn about the complete logic building curriculum