• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Finding the Sum of Digits of a Number in Python with explanation

  • July 6, 2023
  • CODE OF GEEKS
  • 0
What’s here -:
  • Step 1: Understanding the Problem
  • Step 2: Developing the Algorithm
  • Step 3: Writing the Python Code
  • Step 4: Code Explanation
  • Step 5: Dry Run the Code
Python Program to print sum of digits of a number
Python Program to print sum of digits of a number


Step 1: Understanding the Problem

To find the sum of digits, we need to extract each digit from the given number and sum them together. For example, the sum of digits in the number 123 would be 1 + 2 + 3 = 6.

Step 2: Developing the Algorithm

To solve the problem, we’ll use a loop to iterate through each digit of the number. We’ll extract the digits by performing modulo 10 operations and divide the number by 10 to move to the next digit. We’ll keep adding each digit to a running sum until all digits have been processed.

Step 3: Writing the Python Code

Let’s write the Python code to find the sum of digits:

def sum_of_digits(number):
    # Initialize the sum variable
    sum = 0

    # Iterate through each digit of the number
    while number > 0:
        # Extract the last digit using modulo 10
        digit = number % 10

        # Add the digit to the sum
        sum += digit

        # Remove the last digit from the number
        number = number // 10

    # Return the final sum
    return sum

# Test the function
number = 12345
result = sum_of_digits(number)
print("The sum of digits in", number, "is:", result)

O/P

The sum of digits in 12345 is: 15



Step 4: Code Explanation

Let’s go through the code step by step and explain how it finds the sum of digits in a given number:

1. The sum_of_digits function is defined, which takes a number as an argument.

2. Inside the function, we initialize a variable sum to 0. This variable will store the running sum of digits.

3. We enter a while loop that continues as long as the number is greater than 0.

4. Inside the loop, we extract the last digit of the number using the modulo (%) operator. For example, if the number is 123, number % 10 will give us the remainder 3.

5. We add the extracted digit to the sum variable.

6. We update the number by integer division (//) to remove the last digit. For example, if the number is 123, number // 10 will give us 12, effectively removing the last digit.

7. The loop continues until all digits have been processed, extracting each digit, adding it to the sum, and removing it from the number.

8. Once the loop completes, we return the final value of the sum.

9. Outside the function, we test the code by assigning a number (12345) to the number variable.

10. We call the sum_of_digits function with number as an argument and store the result in the result variable.

Finally, we print the result, which displays the sum of digits in the given number.

By using the modulo operator and integer division, the code effectively extracts the last digit from the number, adds it to the sum, and removes it from the number in each iteration. This process continues until all the digits have been processed, resulting in the sum of digits.

Step 5: Dry Run the Code

Certainly! Here’s a step-by-step explanation of the iteration process for n = 1235:

Iteration 1:

  • Current number: 1235
  • Extracted digit: 5
  • Sum: 5
  • Remaining number: 123

Iteration 2:

  • Current number: 123
  • Extracted digit: 3
  • Sum: 5 + 3 = 8
  • Remaining number: 12

Iteration 3:

  • Current number: 12
  • Extracted digit: 2
  • Sum: 8 + 2 = 10
  • Remaining number: 1

Iteration 4:

  • Current number: 1
  • Extracted digit: 1
  • Sum: 10 + 1 = 11
  • Remaining number: 0

The loop ends because there are no more digits left in the number.

The final sum of digits for n = 1235 is 11.

I hope this clarifies the iteration-wise explanation for calculating the sum of digits.

Feel free to modify and experiment with the code to gain a better understanding of how it works and explore other variations or optimizations.





Tags: Calculate sum of digits in PythonCalculate the sum of digits in Python programFinding sum of digits in PythonFinding the sum of digits using PythonHow to calculate the sum of digits in PythonHow to find the sum of digits in PythonPython algorithm for finding the sum of digitsPython code for digit sum with explanationPython code to find the sum of digits in a numberPython code to sum digits of a numberPython function to calculate sum of digitsPython function to find the sum of digitsPython program for digit sum calculationPython program to compute the sum of digits in a numberPython program to find sum of digitsPython sum of digits algorithm explainedPython sum of digits in a numberSum of digits in a number Python programSumming the digits of a number Python tutorialSumming the digits of a number using Python
  • Previous Printing Fibonacci Series in Python: A Step-by-Step Tutorial
  • Next Node.js follows non-blocking I/O model, Know why

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Advertise with us

Table of Content – Python

  1. Introduction to Python ▼
    • Python and its features
    • Key Differences : C vs Python
    • Key Differences : Java vs Python
    • Python Flavors
    • PVM and Memory Management in Python

  2. Python Fundamentals ▼
    • 'Hello World' using Python
    • Comments in Python
    • Variables and Garbage Collection in Python
    • Datatypes in Python
    • Determining the Datatype of Literal | type() method
    • Tokens in Python
    • Keywords in Python
    • Identifiers and Naming Convention in Python
    • Literals in Python

  3. Python Operators ▼
    • Operators in Python
    • Python Mathematical Functions

  4. Python User Inputs ▼
    • Taking Inputs | input() function in Python

  5. Python Control Statements ▼
    • Control Statements in Python
    • if-elif-else Statements in Python
    • Looping in Python
    • while loop in Python
    • while-else loop in Python
    • for loop in Python
    • for-else loop in Python
    • Infinite loops in Python
    • Nested loops in Python
    • break Statement in Python
    • continue Statement in Python
    • pass Statement in Python
    • assert Statement in Python
    • return Statement in Python

  6. Python Functions ▼
    • Introduction to Python Functions
    • Python Functions vs Python Methods
    • Local and Global Variables in Python
    • Formal and Actual Arguments in Python
    • Recursion in Python Functions
    • Lambda Functions in Python
    • Function Decorators in Python
    • Function Generators in Python

  7. Python Strings ▼
    • Strings in Python and Basic Operations
    • String Immutability Explained
    • strip() method in Strings
    • find() method in Strings
    • count() method in Strings
    • replace() method in Strings
    • split() method in Strings
    • Switching Cases in Strings
    • startswith() method in Strings
    • endswith() method in Strings

  8. Python Lists ▼
    • Python Lists Basics
    • index() method in list
    • append() method in list
    • insert() method in list
    • copy() method in list
    • remove() method in list
    • pop() method in list
    • sort() method in list
    • reverse() method in list
    • clear() method in list
    • Nested Lists in Python
    • List Comprehensions in Python

  9. Python Sets ▼
    • Python Sets and Basic Operations
    • Adding Elements in Python Sets
    • Removing Elements in Python Sets
    • Union in Python Sets
    • Intersection in Python Sets

  10. Python Tuples ▼
    • Python Tuple Basics
    • Python Tuples Immutability Explained
    • Python Tuples Methods
    • Python Nested Tuples

  11. Python Dictionary ▼
    • Python Dictionary Basics
    • Python Dictionary Sorting
    • Python Dictionary List to Dictionary Conversion
    • Passing Dictionary to Function

  12. Python Classes and Objects ▼
    • Classes and Objects
    • self variable in Python
    • __init__() method in Python
    • Inner Classes
    • Instance variable and methods
    • Class variable and methods

  13. Python OOPs ▼
    • Inheritance and its types
    • super() method in Python
    • Abstract class| Abstract method in Python

  14. Python Exception Handling ▼
    • Errors in Python and its types
    • Exception Handling in Python
    • Types of Exceptions in Python
    • Custom Exceptions in Python

  15. Python File Handling ▼
    • File Handling in Python
    • with statement in Python

  16. Python DateTime Modules ▼
    • datetime module in Python

  17. Python MultiThreading ▼
    • Multithreading in Python

  18. Python Requests Module ▼
    • Python GET Request
    • Python POST Request
    • Python PUT Request

Python Programs

  1. Fibonacci Series till 'N' Numbers

  2. Sum of Digits of a Number

  3. Checking Prime Number

  4. Checking Armstrong Number

  5. Finding Reverse Number (Traditional)

  6. Finding Reverse Number (Pythonic)

  7. Finding Prime Numbers within Range

  8. Finding Prime Numbers within Range Using SOE

  9. Checking Leap year

  10. Calculating Simple Interest

  11. Generate Random Numbers

  12. Calculate Compound Interest

  13. Area of Circle

  14. ASCII Value of Character
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.