give me python code to ask for confirmation interactively in a CLI program
- User
give me python code to ask for confirmation interactively in a CLI program
Assistant
Below is a simple Python function that asks for confirmation interactively in a Command-Line Interface (CLI) program. This function will prompt the user with a yes/no question and return
Trueif the user confirms (enters 'yes', 'y', etc.) andFalseotherwise.pythondef ask_for_confirmation(prompt="Are you sure?"): """ Ask for confirmation from the user. :param prompt: The question to ask the user. :return: True if user confirms, False otherwise. """ while True: # Get user input user_input = input(f"{prompt} (yes/no): ").strip().lower() # Check for yes if user_input in ['yes', 'y']: return True # Check for no elif user_input in ['no', 'n']: return False # If neither yes nor no, ask again else: print("Please respond with 'yes' or 'no' (or 'y'/'n').\n") # Example usage: if __name__ == "__main__": confirmed = ask_for_confirmation("Do you want to proceed with the operation?") print(f"Confirmed: {confirmed}")Key Points:
- Functionality: The
ask_for_confirmationfunction takes apromptas an argument (defaulting to "Are you sure?"), asks the user for confirmation, and returns a boolean based on the user's response. - User Input Handling: The function converts user input to lowercase and strips any leading or trailing whitespace to make the response check case-insensitive and robust against extra spaces.
- Response Validation: It ensures the user responds with either a confirmation ('yes', 'y') or a denial ('no', 'n'), prompting again for invalid inputs.
- Example Usage: Demonstrates how to call the function with a custom prompt and handle the returned confirmation boolean.
- Functionality: The
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.