In this example, You can find the sum of digits of a number that given by user using while loop statement
# Get input from the user
num = input("Enter a number:")
# Import the array module (although not used in the current code)
# 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))
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.