import random def guess_number(): def get_difficulty(): while True: difficulty = input("Choose a difficulty level (easy, medium, hard): ").lower() if difficulty in ['easy', 'medium', 'hard']: return difficulty else: print("Invalid difficulty level. Please choose from easy, medium, or hard.") def play_again(): return input("Do you want to play again? (yes/no): ").lower() == 'yes' while True: difficulty = get_difficulty() if difficulty == 'easy': max_number = 50 max_attempts = 8 elif difficulty == 'medium': max_number = 100 max_attempts = 6 else: max_number = 200 max_attempts = 4 secret_number = random.randint(1, max_number) print(f"Welcome to the {difficulty.capitalize()} Number Guessing Game!") print(f"I have chosen a number between 1 and {max_number}. Try to guess it!") for attempt in range(1, max_attempts + 1): guess = int(input("Enter your guess: ")) if guess == secret_number: print(f"Congratulations! You guessed the number in {attempt} attempts.") break elif guess < secret_number: print("Too low! Try again.") else: print("Too high! Try again.") else: print(f"Sorry, you've run out of attempts. The correct number was {secret_number}.") if not play_again(): break if __name__ == "__main__": guess_number()