Program 1
Program 1
The code we’ve written is functional and handles basic input validation, but there are some
potential areas for improvement:
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %
(levelname)s - %(message)s')
def check_number(number):
"""
Function to check if a number is even or odd and log the result.
"""
if number % 2 == 0:
logging.info(f"{number} is an even number.")
return f"{number} is an even number."
else:
logging.info(f"{number} is an odd number.")
return f"{number} is an odd number."
def main():
while True:
try:
# Step 1: Get input from the user
user_input = input("Enter a number (or type 'exit' to
quit): ")
# Exit condition
if user_input.lower() == 'exit':
print("Goodbye!")
break
except ValueError:
logging.warning("Invalid input. Please enter a valid
integer.")
print("Please enter a valid integer.")
Improvements Made:
1. Enhanced User Feedback:
– Added a logging mechanism to track user inputs and results. When the user
enters an invalid integer, the program logs the event and provides feedback.
2. Handling Negative Numbers:
– The code can handle negative numbers as even or odd without additional
changes. However, if you want to explicitly differentiate positive and
negative numbers, that logic can be added.
3. Handling Special Characters and Large Numbers:
– Added a try-except block to catch non-numeric inputs and provide
feedback, ensuring the program doesn’t crash.
4. Looping for Continuous Input:
– Introduced a loop to allow the user to check multiple numbers without
restarting the program. The user can exit the loop by typing “exit”.
5. Modular Code Structure:
– The logic to check if a number is even or odd has been separated into a
function (check_number). This makes the code more modular and easier to
extend.
6. Logging:
– Added logging to record inputs and results, which is useful for debugging and
auditing.
7. Unit Tests:
– To add unit tests, you could use a framework like unittest or pytest. This
wasn’t included in the script, but here’s an example of how you might write a
simple unit test for the check_number function:
import unittest
class TestNumberCheck(unittest.TestCase):
def test_even_number(self):
self.assertEqual(check_number(2), "2 is an even number.")
def test_odd_number(self):
self.assertEqual(check_number(3), "3 is an odd number.")
def test_negative_even_number(self):
self.assertEqual(check_number(-4), "-4 is an even number.")
def test_negative_odd_number(self):
self.assertEqual(check_number(-5), "-5 is an odd number.")
if __name__ == '__main__':
unittest.main()
This structure should make the code more robust, user-friendly, and scalable for future
enhancements.