Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

print(f"{i-1} {'chance' if i-1 == 1 else 'chances'} left")

This is better readability I think.
But, your is fine, too!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @NitkarshChourasia

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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also use doc-string on the main function.
To explain it when.
print(function.__doc__ ) is used.

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