diff --git a/Sum of digits of a number.py b/Sum of digits of a number.py index 68aea397b25..c000547c7bc 100644 --- a/Sum of digits of a number.py +++ b/Sum of digits of a number.py @@ -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