From 982dc4dca23a01a932f81f6a5375fde11f5a96b0 Mon Sep 17 00:00:00 2001 From: Brunda G Date: Sat, 1 Nov 2025 11:01:24 +0530 Subject: [PATCH] add palindrome number program Added a beginner-friendly program to check whether a given integer is a palindrome. - Created palindrome_number.py for interactive and CLI input - Added unit tests in test_palindrome.py to verify correctness - Updated README with a short description of the new script - Followed consistent naming and formatting across files This commit introduces a simple yet useful addition for learners practicing control flow and loops in Python. --- palindrome.py | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 palindrome.py diff --git a/palindrome.py b/palindrome.py new file mode 100644 index 00000000..84d8957a --- /dev/null +++ b/palindrome.py @@ -0,0 +1,50 @@ +""" +palindrome_number.py +Simple beginner program to check whether an integer is a palindrome. + +Usage: + python3 palindrome_number.py # interactive input + python3 palindrome_number.py 121 # runs for the given number (optional argument) +""" + +import sys + +def is_palindrome_number(n: int) -> bool: + """ + Return True if integer n is a palindrome (reads same forwards and backwards). + + Works for non-negative integers. Example: 121 -> True, 123 -> False. + """ + if n < 0: + return False # negative numbers have a leading '-' so we treat them as not palindrome + original = n + reversed_num = 0 + while n > 0: + digit = n % 10 + reversed_num = reversed_num * 10 + digit + n //= 10 + return original == reversed_num + +def main(): + # Allow optional command-line argument: python3 palindrome_number.py 121 + if len(sys.argv) > 1: + try: + value = int(sys.argv[1]) + except ValueError: + print("Please provide a valid integer.") + return + else: + # Interactive input + try: + value = int(input("Enter an integer to check palindrome: ").strip()) + except ValueError: + print("Invalid input. Please enter an integer.") + return + + if is_palindrome_number(value): + print(f"{value} is a palindrome number ✅") + else: + print(f"{value} is NOT a palindrome number ❌") + +if __name__ == "__main__": + main() \ No newline at end of file