diff --git a/Sum of digits of a number.py b/Sum of digits of a number.py index ce141531e66..1eac9578497 100644 --- a/Sum of digits of a number.py +++ b/Sum of digits of a number.py @@ -1,32 +1,28 @@ -# Python code to calculate the sum of digits of a number, by taking number input from user. +""" +Module Name: Addition of Digits +Description: Calculates the sum of digits of a user-input integer (supports negative numbers). +Author: Mohammad Arham Javed +Date: 2026-07-18 +""" import sys - def get_integer(): - for i in range( - 3, 0, -1 - ): # executes the loop 3 times. Giving 3 chances to the user. + 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 + # .lstrip('-') allows negative numbers to pass the numeric check + if num.lstrip('-').isnumeric(): + return int(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 + print(f"{i - 1} chances are left" if (i - 1) > 1 else f"{i - 1} chance is left") + return None def addition(num): """ Returns the sum of the digits of a number. - Negative numbers are handled using the absolute value. + Negative numbers are handled gracefully. Examples: >>> addition(123) @@ -34,24 +30,17 @@ def addition(num): >>> addition(-784) 19 """ - Sum = 0 - if type(num) is type( - None - ): # Checks if number type is none or not. If type is none program exits. + if num is None: print("Try again!") sys.exit() - num = abs(num) # Handle negative numbers - 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. + + # Strip the minus sign if present, and sum the integer values + return sum(int(digit) for digit in str(num).replace('-', '')) -if ( - __name__ == "__main__" -): # this is used to overcome the problems while importing this file. +if __name__ == "__main__": number = get_integer() - Sum = addition(number) - abs_display = f" (absolute value: {abs(number)})" if number < 0 else "" - print(f"Sum of digits of {number}{abs_display} is {Sum}") # Prints the sum + if number is not None: + Sum = addition(number) + abs_display = f" (absolute value: {abs(number)})" if number < 0 else "" + print(f"Sum of digits of {number}{abs_display} is {Sum}") \ No newline at end of file diff --git a/sum_of_digits_of_a_number.py b/sum_of_digits_of_a_number.py index f17fd6bcf41..7f4f88ad87f 100644 --- a/sum_of_digits_of_a_number.py +++ b/sum_of_digits_of_a_number.py @@ -1,61 +1,31 @@ """ -A simple program to calculate the sum of digits of a user-input integer. - -Features: -- Input validation with limited attempts. -- Graceful exit if attempts are exhausted. -- Sum of digits computed iteratively. - -Doctests: - >>> sum_of_digits(123) - 6 - >>> sum_of_digits(0) - 0 - >>> sum_of_digits(999) - 27 - >>> sum_of_digits(-123) - 6 +Module Name: Sum of Digits +Description: A simple program to calculate the sum of digits of a user-input integer. +Author: Mohammad Arham Javed +Date: 2026-07-18 """ import sys - -def get_integer_input(prompt: str, attempts: int) -> int | None: - """ - Prompt the user for an integer input, retrying up to a given number of attempts. - - Args: - prompt: The message shown to the user. - attempts: Maximum number of input attempts. - - Returns: - The integer entered by the user, or None if all attempts fail. - - Example: - User input: "12" -> returns 12 - """ - for i in range(attempts, 0, -1): +def get_integer_input(prompt: str, attempts: int): + """Prompt the user for an integer with a limited number of attempts.""" + while attempts > 0: try: - # Attempt to parse user input as integer - n = int(input(prompt)) - return n + return int(input(prompt)) except ValueError: - # Invalid input: notify and decrement chances - print("Enter an integer only") - print(f"{i - 1} {'chance' if i - 1 == 1 else 'chances'} left") + attempts -= 1 + print(f"Invalid input. You have {attempts} attempt(s) left.") return None - def sum_of_digits(n: int) -> int: """ Compute the sum of the digits of an integer. Args: - n: Non-negative integer. - If the integer is negative, it is converted to positive before computing the sum. + n: Integer (negative signs are ignored). Returns: - Sum of digits of the number. + Sum of digits of the absolute value of the number. Examples: >>> sum_of_digits(123) @@ -65,13 +35,7 @@ def sum_of_digits(n: int) -> int: >>> sum_of_digits(-789) 24 """ - n = abs(n) # FIX: handle negative numbers - total = 0 - while n > 0: - # Add last digit and remove it from n - total += n % 10 - n //= 10 - return total + return sum(int(digit) for digit in str(n).replace('-', '')) def main() -> None: