Skip to content

Commit 443465f

Browse files
author
“javearham2
committed
Fix: Handle negative numbers correctly in both sum of digits scripts
1 parent 11edb06 commit 443465f

2 files changed

Lines changed: 35 additions & 82 deletions

File tree

Sum of digits of a number.py

Lines changed: 22 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,46 @@
1-
# Python code to calculate the sum of digits of a number, by taking number input from user.
1+
"""
2+
Module Name: Addition of Digits
3+
Description: Calculates the sum of digits of a user-input integer (supports negative numbers).
4+
Author: Mohammad Arham Javed
5+
Date: 2026-07-18
6+
"""
27

38
import sys
49

5-
610
def get_integer():
7-
for i in range(
8-
3, 0, -1
9-
): # executes the loop 3 times. Giving 3 chances to the user.
11+
for i in range(3, 0, -1): # executes the loop 3 times. Giving 3 chances to the user.
1012
num = input("enter a number:")
11-
if num.isnumeric(): # checks if entered input is an integer string or not.
12-
num = int(
13-
num
14-
) # converting integer string to integer. And returns it to where function is called.
15-
return num
13+
# .lstrip('-') allows negative numbers to pass the numeric check
14+
if num.lstrip('-').isnumeric():
15+
return int(num)
1616
else:
1717
print("enter integer only")
18-
print(
19-
f"{i - 1} chances are left"
20-
if (i - 1) > 1
21-
else f"{i - 1} chance is left"
22-
) # prints if user entered wrong input and chances left.
23-
continue
18+
print(f"{i - 1} chances are left" if (i - 1) > 1 else f"{i - 1} chance is left")
19+
return None
2420

2521

2622
def addition(num):
2723
"""
2824
Returns the sum of the digits of a number.
29-
Negative numbers are handled using the absolute value.
25+
Negative numbers are handled gracefully.
3026
3127
Examples:
3228
>>> addition(123)
3329
6
3430
>>> addition(-784)
3531
19
3632
"""
37-
Sum = 0
38-
if type(num) is type(
39-
None
40-
): # Checks if number type is none or not. If type is none program exits.
33+
if num is None:
4134
print("Try again!")
4235
sys.exit()
43-
num = abs(num) # Handle negative numbers
44-
while num > 0: # Addition- adding the digits in the number.
45-
digit = int(num % 10)
46-
Sum += digit
47-
num //= 10
48-
return Sum # Returns sum to where the function is called.
36+
37+
# Strip the minus sign if present, and sum the integer values
38+
return sum(int(digit) for digit in str(num).replace('-', ''))
4939

5040

51-
if (
52-
__name__ == "__main__"
53-
): # this is used to overcome the problems while importing this file.
41+
if __name__ == "__main__":
5442
number = get_integer()
55-
Sum = addition(number)
56-
abs_display = f" (absolute value: {abs(number)})" if number < 0 else ""
57-
print(f"Sum of digits of {number}{abs_display} is {Sum}") # Prints the sum
43+
if number is not None:
44+
Sum = addition(number)
45+
abs_display = f" (absolute value: {abs(number)})" if number < 0 else ""
46+
print(f"Sum of digits of {number}{abs_display} is {Sum}")

sum_of_digits_of_a_number.py

Lines changed: 13 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,31 @@
11
"""
2-
A simple program to calculate the sum of digits of a user-input integer.
3-
4-
Features:
5-
- Input validation with limited attempts.
6-
- Graceful exit if attempts are exhausted.
7-
- Sum of digits computed iteratively.
8-
9-
Doctests:
10-
>>> sum_of_digits(123)
11-
6
12-
>>> sum_of_digits(0)
13-
0
14-
>>> sum_of_digits(999)
15-
27
16-
>>> sum_of_digits(-123)
17-
6
2+
Module Name: Sum of Digits
3+
Description: A simple program to calculate the sum of digits of a user-input integer.
4+
Author: Mohammad Arham Javed
5+
Date: 2026-07-18
186
"""
197

208
import sys
219

22-
23-
def get_integer_input(prompt: str, attempts: int) -> int | None:
24-
"""
25-
Prompt the user for an integer input, retrying up to a given number of attempts.
26-
27-
Args:
28-
prompt: The message shown to the user.
29-
attempts: Maximum number of input attempts.
30-
31-
Returns:
32-
The integer entered by the user, or None if all attempts fail.
33-
34-
Example:
35-
User input: "12" -> returns 12
36-
"""
37-
for i in range(attempts, 0, -1):
10+
def get_integer_input(prompt: str, attempts: int):
11+
"""Prompt the user for an integer with a limited number of attempts."""
12+
while attempts > 0:
3813
try:
39-
# Attempt to parse user input as integer
40-
n = int(input(prompt))
41-
return n
14+
return int(input(prompt))
4215
except ValueError:
43-
# Invalid input: notify and decrement chances
44-
print("Enter an integer only")
45-
print(f"{i - 1} {'chance' if i - 1 == 1 else 'chances'} left")
16+
attempts -= 1
17+
print(f"Invalid input. You have {attempts} attempt(s) left.")
4618
return None
4719

48-
4920
def sum_of_digits(n: int) -> int:
5021
"""
5122
Compute the sum of the digits of an integer.
5223
5324
Args:
54-
n: Non-negative integer.
55-
If the integer is negative, it is converted to positive before computing the sum.
25+
n: Integer (negative signs are ignored).
5626
5727
Returns:
58-
Sum of digits of the number.
28+
Sum of digits of the absolute value of the number.
5929
6030
Examples:
6131
>>> sum_of_digits(123)
@@ -65,13 +35,7 @@ def sum_of_digits(n: int) -> int:
6535
>>> sum_of_digits(-789)
6636
24
6737
"""
68-
n = abs(n) # FIX: handle negative numbers
69-
total = 0
70-
while n > 0:
71-
# Add last digit and remove it from n
72-
total += n % 10
73-
n //= 10
74-
return total
38+
return sum(int(digit) for digit in str(n).replace('-', ''))
7539

7640

7741
def main() -> None:

0 commit comments

Comments
 (0)