Home > Article > Backend Development > How to find the sum of three digits in python
Python inputs three digits to find the sum of each digit. Steps: 1. Get the three digits input by the user through the input function and save it in the num variable; 2. Use the len function to determine whether the input is three digits. number, if not, print an error message and exit the program; 3. Use the int function to convert the input string into an integer type; 4. Use the integer division operator // and the remainder operation % to obtain the hundreds, tens and individuals digits, and add them to get the sum of each digit; 5. Use the print function to output the result of the sum of each digit.
The operating environment of this article: Windows 10 system, Python 3.11.4 version, Dell G3 computer.
Python can use string operations and mathematical operations to find the sum of a three-digit number. The following is a code example written in Python:
# 输入一个三位数 num = input("请输入一个三位数:") # 判断输入是否为三位数 if len(num) != 3: print("输入的不是三位数,请重新输入!") exit() # 将输入的字符串转换为整数 num = int(num) # 求各位之和 digit_sum = num // 100 + (num % 100) // 10 num % 10 # 输出各位之和 print("各位之和为:", digit_sum)
In this example, first obtain the three-digit number entered by the user through the input function and save it in the num variable. Then use the len function to determine whether the input is a three-digit number. If not, print an error message and exit the program.
Use the int function to convert the input string to an integer type. This makes it easy to perform mathematical operations.
Find the sum of each digit through mathematical operations. We use the integer division operator // and the remainder operator % to get the numbers in the hundreds, tens and ones digits, and add them to get the sum of each digit.
Use the print function to output the result of the sum.
In this way, we can find the sum of a three-digit number in Python.
The above is the detailed content of How to find the sum of three digits in python. For more information, please follow other related articles on the PHP Chinese website!