Skip to content

Commit

Permalink
Code - sum of digits of a number
Browse files Browse the repository at this point in the history
  • Loading branch information
sarayusreeyadavpadala committed Aug 20, 2023
1 parent bc55e2a commit 9899eab
Showing 1 changed file with 28 additions and 8 deletions.
36 changes: 28 additions & 8 deletions Sum of digits of a number.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,33 @@
q=0 # Initially we assigned 0 to "q", to use this variable for the summation purpose below.
# The "q" value should be declared before using it(mandatory). And this value can be changed later.
# Python code to calculate the sum of digits of a number, by taking number input from user.

n=int(input("Enter Number: ")) # asking user for input
while n>0: # Until "n" is greater than 0, execute the loop. This means that until all the digits of "n" got extracted.
import sys

r=n%10 # Here, we are extracting each digit from "n" starting from one's place to ten's and hundred's... so on.
def get_integer():
for i in range(3,0,-1): # executes the loop 3 times. Giving 3 chances to the user.
num = input("enter a number:")
if num.isnumeric(): # checks if entered input is an integer string or not.
num = int(num) # converting integer string to integer. And returns it to where function is called.
return num
else:
print("enter integer only")
print(f'{i-1} chances are left' if (i-1)>1 else f'{i-1} chance is left') # prints if user entered wrong input and chances left.
continue


q=q+r # Each extracted number is being added to "q".
def addition(num):
Sum=0
if type(num) is type(None): # Checks if number type is none or not. If type is none program exits.
print("Try again!")
sys.exit()
while num > 0: # Addition- adding the digits in the number.
digit = int(num % 10)
Sum += digit
num /= 10
return Sum # Returns sum to where the function is called.

n=n//10 # "n" value is being changed in every iteration. Dividing with 10 gives exact digits in that number, reducing one digit in every iteration from one's place.

print("Sum of digits is: "+str(q))

if __name__ == '__main__': # this is used to overcome the problems while importing this file.
number = get_integer()
Sum = addition(number)
print(f'Sum of digits of {number} is {Sum}') # Prints the sum

0 comments on commit 9899eab

Please sign in to comment.