Skip to content

Instantly share code, notes, and snippets.

@alaestor
Created February 3, 2025 21:58
Show Gist options
  • Select an option

  • Save alaestor/8027476e1ddbae549f089ad09c9a5c37 to your computer and use it in GitHub Desktop.

Select an option

Save alaestor/8027476e1ddbae549f089ad09c9a5c37 to your computer and use it in GitHub Desktop.
User confirmation with a message and optional default
def userConfirmation(msg: str = 'Confirm', default: bool|None = None) -> bool:
prompt = f"{msg} ({'y/n' if default is None else 'Y/n' if default else 'y/N'}): "
while True:
user_input = input(prompt).strip().lower()
if user_input in ['y', 'yes']:
return True
elif user_input in ['n', 'no']:
return False
elif default is not None:
return default
print("Invalid input. Please enter (Y)es or (N)o")
if __name__ == '__main__': # example usage
print('user said yes') if userConfirmation('owo?', default=True) else print('user said no')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment