Skip to content

Commit 02af73d

Browse files
Improving the program, making it more modular, real world, pragmatic, renamed it to snake_case, etc...
1 parent 05ac4be commit 02af73d

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

sum_of_digits_of_a_number.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import sys
2+
3+
def get_integer_input(prompt, attempts):
4+
for i in range(attempts, 0, -1):
5+
try:
6+
n = int(input(prompt))
7+
return n
8+
except ValueError:
9+
print("Enter an integer only")
10+
print(f"{i-1} {'chance' if i-1 == 1 else 'chances'} left")
11+
return None
12+
13+
def sum_of_digits(n):
14+
total = 0
15+
while n > 0:
16+
total += n % 10
17+
n //= 10
18+
return total
19+
20+
chances = 3
21+
number = get_integer_input("Enter a number: ", chances)
22+
23+
if number is None:
24+
print("You've used all your chances.")
25+
sys.exit()
26+
27+
result = sum_of_digits(number)
28+
print(f"The sum of the digits of {number} is: {result}")

0 commit comments

Comments
 (0)