From 47dd9840dac6ec8e835693373d80b396bf4a47e9 Mon Sep 17 00:00:00 2001 From: Tithi Joshi Date: Sat, 14 Feb 2026 11:28:09 +0530 Subject: [PATCH] refactor: extract input normalization into helper function Added input normalization function and improved input validation. --- Animal-Guess/animalguess.py | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/Animal-Guess/animalguess.py b/Animal-Guess/animalguess.py index 62dbd77..5d30926 100644 --- a/Animal-Guess/animalguess.py +++ b/Animal-Guess/animalguess.py @@ -1,5 +1,10 @@ +def normalize_input(text): + """ + Normalize user input for comparison. + Strips whitespace and converts to lowercase. + """ + return text.strip().lower() -# Improved version with modular structure, input validation, and typo fixes def check_guess(guess, answer): """ @@ -8,17 +13,20 @@ def check_guess(guess, answer): Returns 1 if correct, 0 otherwise. """ attempt = 0 + while attempt < 3: - if guess.lower().strip() == answer.lower(): + if normalize_input(guess) == normalize_input(answer): print("āœ… Correct Answer!") - return 1 # increment score + return 1 else: attempt += 1 if attempt < 3: - guess = input("āŒ Wrong answer. Try again: ").strip() + guess = input("āŒ Wrong answer. Try again: ") + print("The correct answer is:", answer) return 0 + def main(): """ Main game function. Loops through all questions and calculates the total score. @@ -33,12 +41,15 @@ def main(): score = 0 for question, answer in questions: - guess = input(question + " ").strip() - while not guess: - guess = input("Please enter a valid guess: ").strip() + guess = input(question + " ") + + while not guess.strip(): + guess = input("Please enter a valid guess: ") + score += check_guess(guess, answer) print(f"\nšŸ† Your Total Score is: {score} out of {len(questions)}") + if __name__ == "__main__": main()