In this example, You can find the sum of digits of a number that given by user using while loop statement
Python Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | # Get input from the user num = input("Enter a number:") # Import the array module (although not used in the current code) import array # Initialize variables to store the sum of digits and the loop counter sumDigits = 0 i = 0 # Iterate through each digit in the input number while i < len(num): # Convert the current digit to an integer and add it to the sum sumDigits = sumDigits + int(num[i]) # Increment the loop counter i = i + 1 # Print the total sum of digits print("The total sum of digits is %s" % int(sumDigits)) |
Output:

This code prompts the user to enter a number and then calculates the sum of the digits in that number.
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.