Sum of Digits
Calculate sum of digits of a number.
IntermediatePhase 2 - Level 2: Number-based Looping LogicExample 4 of 14
sum-of-digits.py
1# Take number2num = int(input("Enter a number: "))34# Sum of digits5digit_sum = 06temp = abs(num)78while temp > 0:9 digit = temp % 1010 digit_sum += digit11 temp //= 101213print(f"Sum of digits: {digit_sum}")
Output
Enter a number: 1234 Sum of digits: 10
What's going on
Extract digits and add them.
Key Concepts:
Extract last digit using modulo
Add to sum
Remove last digit using integer division
🔗Related Content
- 📖
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- 📝
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- 💻
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- 🎓
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- 🧠
Logic Building Overview
Learn about the complete logic building curriculum