Python

Python Program to Find Sum of Digits Using for Loop2 min read

In this python program finds the sum of digits using for loop statement.

Example 1, Here is a simple example of how you can find the sum of the digits of a number in Python using a for loop:




In this example, we first define a function called sum_digits that takes in a single argument num. The function converts the number to a string and then iterates over each character in the string. For each character, we convert it back to an integer and add it to the sum variable. Finally, we return the sum of the digits.

We can then test the function by calling it with a few different numbers and printing the result.

Example 2:

Python Code:

This code will prompt the user to enter a number, then it will iterate over each digit in the number and add it to the sum variable. Finally, it will print the sum of the digits.

Here is a step-by-step explanation of the code:

  1. The user is prompted to enter a number using the input function. The user’s input is stored in the num variable as a string.
  2. A variable called sum is initialized to 0. This variable will be used to store the sum of the digits.
  3. A for loop is used to iterate over each character (digit) in the num string. The loop variable n is set to each character in turn.
  4. Inside the for loop, the value of n is converted to an integer using the int function, and then added to the sum variable.
  5. After the for loop completes, the sum of the digits is printed using the print function.

For example, if the user enters the number 123, the output will be 6. If the user enters 1234, the output will be 10.

Output:

2 Comments

    • It sounds like you’re encountering a common issue. When using ‘int’ for the user but not specifying ‘int’ for ‘sum,’ it can lead to a type mismatch error. Make sure the data types match to avoid such errors. If you have specific code snippets or more details, I’d be happy to help troubleshoot!

Leave a Comment