In this, you'll get to learn how to add digits of a number in python (using different-different approaches) that is entered by a user at the runtime with examples. i.e. Let's say if the user entered 365, the output should be 14 (3+6+5=14).
This covers three different approaches:
Here are the different examples with different approaches to find the largest number among three numbers in python:
This example is to add digits of a number entered by a user at runtime using a for loop.
N = int(input("Enter the number: "))
sum = 0
var1 = N
for i in range(len(str(var1))):
rem = N%10
sum = sum+rem
num = int(N/10)
print(f"\nSum of Digits of {str(temp)+ } = {str(sum)}")
Here, the f-string is a string literal that is used as an f at the beginning and curly braces containing expression that will be replaced with its value.
Note:
str()
is used to convert an int value to a string-type valuelen()
is used to find the length of a string.Output:
Enter the number: 1997
Sum of Digits of 1997 = 26
This example is to add digits of a number entered by a user at runtime using a while loop.
N = int(input("Enter the number: "))
sum = 0
temp_var = N
while N > 0:
rem = N%10
sum = sum+rem
N = int(N/10)
print(f"\nSum of Digits of {str(temp_var)} = {str(sum)}")
Output:
Enter the number: 1997
Sum of Digits of 1997 = 26
This program uses a user-defined function named addDigits() to find the sum of digits of a given number. The function receives a number as its argument and returns the sum of its digits.
def addDigits(self, n):
sum = 0
while n > 0:
rem = n%10
sum = sum+rem
n = int(n/10)
return sum
N = int(input("Enter the number: "))
sum = 0
result = addDigits(N)
print(f"\nSum of Digits of {str(N)} = {str(result)}")
Output:
Enter the number: 1997
Sum of Digits of 1997 = 26
Adding digits of a number using the Class method is as follows:
class numberOperation:
def addDigits(self, n):
sum = 0
while n > 0:
rem = n%10
sum = sum+rem
n = int(n/10)
return sum
N = int(input("Enter the number: "))
sum = 0
obj = numberOperation()
result = obj.addDigits(N)
print(f"\nSum of Digits of {str(N)} = {str(result)}")
All properties of the class named numberOperations get assigned to an object named obj. Then the object can be used to access the member function of class numberOperations using dot (.) operator.
Output:
Enter the number: 1997
Sum of Digits of 1997 = 26
In this, we demonstrated different examples with different methods to add digits of a number -- using for loop
, using while loop
, using a function
, and using Class
.