Refactored code into a function for the loop, a parsed user-entered number, and input validation