You can calculate the sum of the digits of a number by converting the number to a string, traversing each character in the string, and converting it to an integer to add.
For example:
num = twelve thousand three hundred and forty-five str_num = str (num)
sum = zero
for ch in str_num:
sum += int (ch)
print ( sum )
In the above code, we first put the number twelve thousand three hundred and forty-five
Convert to string and assign to variable str_num
。 Then, use the for
Circular traversal str_num
Convert each character in to an integer and add it to get the sum of the digits. Finally, use the print()
The function outputs the result.
Note that if the number entered may be negative, you need to use abs()
The function takes its absolute value for operation. In addition, in practical applications, user input needs to be properly verified and processed to ensure that the input content meets expectations.