In this post, I’ll show you how to find digits of a given. I’ll solve the problem two diffrent way.
First way; for loop statement and other; while loop statement.
For loop:
1 2 3 4 5 6 7 | num=input("Enter a number:") sum=0 for n in num: sum = sum + int(n) print(sum) |
This code prompts the user to enter a number and then calculates the sum of its digits.
Here’s a brief explanation of how the code works:
- The “num” variable is assigned the value of the number entered by the user.
- The “sum” variable is initialized to 0 and will be used to store the sum of the digits.
- The for loop iterates over the digits in “num”. For each iteration, the digit is added to “sum” using the assignment operator “+=”.
- When the loop finishes executing, the sum of the digits is printed to the console.
While loop:
1 2 3 4 5 6 7 8 9 10 11 12 | num=input("Enter a number:") import array sumDigits=0 i=0 while i < len(num): sumDigits=sumDigits + int(num[i]) i=i+1 print("The total sum of digits is %s" % int(sumDigits)) |
This code prompts the user to enter a number and then calculates the sum of its digits.
Here’s a brief explanation of how the code works:
- The “num” variable is assigned the value of the number entered by the user.
- The “sumDigits” variable is initialized to 0 and will be used to store the sum of the digits.
- The “i” variable is initialized to 0 and will be used as a counter in the while loop.
- The while loop iterates over the digits in “num”. For each iteration, the digit is added to “sumDigits” and “i” is incremented by 1.
- When the loop finishes executing, the sum of the digits is printed to the console.
Output: