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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | def sum_digits(num): # Initialize a variable to store the sum of digits sum = 0 # Iterate over each digit in the number for digit in str(num): # Add the current digit to the sum sum += int(digit) # Return the sum of digits return sum # Test the function print(sum_digits(123)) # 6 print(sum_digits(1234)) # 10 print(sum_digits(1234567890)) # 45 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # Get the number from the user num = input("Enter a number: ") # Initialize a variable to store the sum of digits sum = 0 # Iterate over each digit in the number for n in num: # Add the current digit to the sum sum += int(n) # Print the sum of digits print(sum) |
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:
- The user is prompted to enter a number using the
input
function. The user’s input is stored in thenum
variable as a string. - A variable called
sum
is initialized to 0. This variable will be used to store the sum of the digits. - A for loop is used to iterate over each character (digit) in the
num
string. The loop variablen
is set to each character in turn. - Inside the for loop, the value of
n
is converted to an integer using theint
function, and then added to thesum
variable. - 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:
i had an doubt if we put int in user not putting int in sum its showing error
whyyy
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!