- How to find the sum of digits of a number in Python
- Sum of digits of a number in Python
- How to find the Sum of digits of a number in Python using str() and int()
- Sum of digits of a number in Python using recursion
- How to find the Sum of digits of a number in Python using iteration
- Sum of digits of a number in Python using sum()
- How to find the Sum of digits of a number in Python using brute force
- Sum of digits of a number in Python modulo operator
- Sum of digits of a number in Python without loop
- 3 способа найти сумму цифр числа в Python
- Введение
- Использование цикла for
- Использование цикла while
- Использование рекурсии
- Заключение
How to find the sum of digits of a number in Python
In this Python tutorial, we will discuss several methods to calculate the sum of a given number’s digits. Moreover, we’ll look at various examples to find the sum of a given number’s digits.
As a Developer, while making the Python Project, I got the requirement to calculate the Sum of Digits of a Number
- How to find the Sum of digits of a number in Python using str() and int()
- Sum of digits of a number in Python using recursion
- How to find the Sum of digits of a number in Python using iteration
- Sum of digits of a number in Python using sum()
- Sum of digits of a number in Python modulo operator
- Sum of digits of a number in Python without loop
- How to find the Sum of digits of a number in Python using brute force
Sum of digits of a number in Python
To calculate the sum of the digits of the number, first, we will take the input from the user. Next, we split the number into digits, and then we add each digit to the sum variable.
If we have the number 678, we can find the digit sum by adding 6 + 7 + 8 and the result will come to 21.
In Python, there are primarily three methods that are commonly used and important to understand when calculating the Sum of digits of a number in Python.
How to find the Sum of digits of a number in Python using str() and int()
- In this section, we will discuss how to find a Sum of the digits of a number in Python using str() and int().
- In Python, the int() method is used to convert the string value into an integer and the str() method is used to convert the integer number to a string.
Let’s take an example and check how to find the Sum of digits of a number in Python using str() and int().
Source Code:
USA_state_ZIPCode=int(input("Enter the value")) total=0 for i in str(USA_state_ZIPCode): total=total+int(i) print("Sum of digits of a number :",total)
In the following given code first, we will take the input from the user and then create a variable to store the total. Next, we converted the number to a string by using the str() method.
After that, we used the for loop to iterate each digit of a number and convert them into an integer by using the int() method.
Here is the implementation of the following given code
This is how to find the Sum of digits of a number in Python using str and int.
Sum of digits of a number in Python using recursion
- Now let us see how to calculate the sum of digits of a number in Python using recursion.
- Recursive functions are those that call themselves repeatedly. When a specific issue is defined in terms of itself, this approach is applied.
Here we will take an example and check how to calculate the sum of digits of a number in Python using recursion.
Source Code:
In the above code first, we defined the function “total_num” with parameter ‘i’ for calculating the sum. Next, we will check the condition if ‘i’ is less than 10 then it will return i. If not, calculate the remainder (n%10) by multiplying the number by 10.
Recursively call the function with (n/10) as an argument. and then add the function’s value with the remainder to get the sum. After that take the input from the user and call the function “total_num” and assign the input as an argument.
Here is the Screenshot of the following given code
In this example we have understood how to calculate the sum of digits of a number in Python using recursion.
How to find the Sum of digits of a number in Python using iteration
- Here we will discuss how to find the Sum of digits of a number in Python using iteration.
- To calculate the sum in this program, looping statements will be used. To run a certain part of the code repeatedly, use loops. Some looping statements include the for loop, while, and do-while.
- Divide a number by 10 to get the rightmost digit, which is 0, by the number. The rightmost digit will eventually make up the remainder. Use the remaining operator “%” to obtain the remainder. Divide the quotient by 10 to get a number’s entire digit count. Use “//” to obtain an integer quotient each time.
Let’s take an example and check how to find the Sum of digits of a number in Python using iteration.
Source Code:
def total_num(m): total_num = 0 while (m != 0): total_num = total_num + (m % 10) m = m//10 return total_num m=int(input("Enter the value")) print("Sum of digits of given number :",total_num(m))
In the given example first, we defined the function “total_num” with the parameter ‘m’ and then declare a variable “total_num” to contain the sum of digits.
Create a loop that continues until n is not 0 and then add the sum variable to the remainder (n%10) returned. Revision n to n/10 call the function Sum with the user’s input as an argument.
Print the sum value that was returned.
You can refer to the below screenshot.
This is How to find the Sum of digits of a number in Python using iteration.
Sum of digits of a number in Python using sum()
- In this section, we will discuss how to find the sum of digits of a number in Python using sum().
- Python’s sum() function is used to calculate a number’s digit sum in a list.
- Use the str() function to convert the number to a string, then the strip() and map() methods to turn the string into a list of numbers. After that, use the sum() method to calculate the total.
Here we will take an example and check how to find the sum of digits of a number in Python using sum().
Source Code:
def total_num(m): new_val = str(m) new_result = list(map(int, new_val.strip())) return sum(new_result) m = 456 print("Sum of numbers :",total_num(m))
In the above code first, we defined the function “total_num” with parameter ‘m’ for calculating the sum. Next, we converted the number to a string by using the str() method.
Here is the implementation of the following given code.
As you can see in the screenshot we have discussed sum of digits of a number in Python using sum().
How to find the Sum of digits of a number in Python using brute force
- In this section, we will discuss how to find the Sum of digits of a number in Python using brute force.
- Here, we extract each digit by calculating the modulus of the entire input multiplied by 10.
Let’s take an example and check how to find the Sum of digits of a number in Python using brute force.
Source Code:
USA_police_num=67232 total_number = 0 while USA_police_num!=0: new_char = int(USA_police_num%10) total_number += new_char USA_police_num = USA_police_num/10 print(total_number)
Here is the implementation of the following given code
Sum of digits of a number in Python modulo operator
Another way to calculate the sum of digits of a number in Python is to use the modulo operator. The modulo operator returns the remainder when one number is divided by another. We can use this operator to find the last digit of a number and then remove it from the number.
Here is an example of how to use this method.
# Function to calculate the sum of digits def sum_of_digits(n): # Initialize a variable to store the sum sum = 0 # Iterate until the number is not zero while n > 0: # Find the last digit digit = n % 10 # Add the digit to the sum sum += digit # Remove the last digit n = n // 10 return sum # Test the function print(sum_of_digits(123))
- Define a function called “sum_of_digits” and pass in a variable “n” as a parameter.
- Within the function, initialize a variable “sum” to store the sum of the digits and set it equal to 0.
- Use a while loop to iterate until the value of “n” is greater than 0.
- Within the while loop, use the modulo operator (n % 10) to find the last digit of the number “n” and store it in a variable “digit”.
- Add the value of “digit” to the “sum” variable.
- Use the floor division operator (n // 10) to remove the last digit from “n”.
- Return the final value of “sum” after the while loop has finished executing.
Sum of digits of a number in Python without loop
The sum of digits of a number in Python can be found without using loops as well. One way to achieve this is by converting the number to a string and then using the built-in sum() function.
Here’s an example of how it can be done.
number = 1234 number_string = str(number) sum_of_digits = sum(int(digit) for digit in number_string) print(sum_of_digits)
- Initialize a variable “number” with the number for which you want to find the sum of digits.
- Use the str() function to convert the number to a string.
- Use a list comprehension to iterate through the characters of the string, which are the digits of the number, and convert them to integers.
- Print the value of sum_of_digits, which is the sum of all digits of the number.
In this article, we have discussed How to find the Sum of digits of a number in Python and also we have covered the following given methods
- How to find the Sum of digits of a number in Python using str() and int()
- Sum of digits of a number in Python using recursion
- How to find the Sum of digits of a number in Python using iteration
- Sum of digits of a number in Python using sum()
- How to find the Sum of digits of a number in Python using brute force
Also, take a look at some more Python tutorials.
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.
3 способа найти сумму цифр числа в Python
Статьи
Введение
В данной статье разберём 3 способа найти сумму цифр числа в языке программирования Python.
Использование цикла for
Для начала создадим переменную number, в которой будет храниться число, сумму цифр которого нужно посчитать. Также создадим переменную равную нулю:
number = 11223344 sum_digits = 0
Создадим цикл, в котором благодаря функции str() преобразуем наше число в строку, и поэлементно пройдёмся по ней. Внутри цикла во время каждой итерации будем прибавлять итерабельное значение к переменной sum_digits:
number = 11223344 sum_digits = 0 for i in str(number): sum_digits += int(i) print(f"Сумма цифр числа: ") # Вывод: 20
Использование цикла while
В данном способе у нас также будет присутствовать переменная sum_digits равная нулю:
number = 11223344 sum_digits = 0
Создадим цикл while, который не закончит свою работу, пока number > 0. Внутри цикла к переменной sum_digits будем прибавлять последнюю цифру нашего числа, после чего путём целочисленного деления убирать его:
number = 11223344 sum_digits = 0 while number > 0: sum_digits += number % 10 number //= 10
Осталось вывести результат:
number = 11223344 sum_digits = 0 while number > 0: sum_digits += number % 10 number //= 10 print(f"Сумма цифр числа: ") # Вывод: Сумма цифр числа: 20
Использование рекурсии
Для начала создадим функцию, которую назовём sum_digits(). В качестве параметра укажем n. Внутри неё зададим условие, что если n равна нулю, то возвращаем её. Если же условие не сработало, то возвращаем сумму последней цифры числа, и рекурсивный вызов функции с её отбрасыванием путём целочисленного деления:
def sum_digits(n): if n == 0: return n else: return int(n % 10) + sum_digits(int(n / 10))
Вызовем функцию и передадим в неё число:
def sum_digits(n): if n == 0: return n else: return int(n % 10) + sum_digits(int(n / 10)) number = 11223344 print(f"Сумма цифр числа: ") # Вывод: Сумма цифр числа: 20
Также можно сократить условие внутри функции используя тернарный оператор:
def sum_digits(n): return 0 if n == 0 else int(n % 10) + sum_digits(int(n / 10)) number = 11223344 print(f"Сумма цифр числа: ") # Вывод: Сумма цифр числа: 20
Заключение
В ходе статьи мы с Вами разобрали 3 способа найти сумму цифр числа в языке программирования Python.Надеюсь Вам понравилась статья, желаю удачи и успехов! 🙂