Cheap VPS host selection
Provide server host evaluation information

Example demonstration of using python to find the sum of each digit of a number

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) #Convert a number to a string
 sum = zero
 for ch in str_num: #Traverse every character in the string
     sum += int (ch) #Convert characters to integers and add
 print ( sum ) #Output the sum of each digit

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.

Do not reprint without permission: Cheap VPS evaluation » Example demonstration of using python to find the sum of each digit of a number