Skip to content

Instantly share code, notes, and snippets.

@AkshuAgarwal
Created July 16, 2021 10:06
Show Gist options
  • Save AkshuAgarwal/c43074b97589586d963fdb9d7c38147f to your computer and use it in GitHub Desktop.
Save AkshuAgarwal/c43074b97589586d963fdb9d7c38147f to your computer and use it in GitHub Desktop.
A simple Switch-case class for python
class Switch:
def __init__(self, input_message: str, *, response: dict):
self._input_msg: str = input_message
if any(isinstance(i, str) for i in response.keys()):
raise ValueError('response keys can only be of str type')
self._response = response
self._input = None
def start(self):
self._input = input(self._input_msg)
return self.check()
def check(self):
if self.input in self.response:
return self.response[self.input]
else:
raise KeyError('user response not in valid responses.')
# Example:
import Switch
my_switch = Switch(
"Please enter your choice: ",
response={
'1': 'Fine! Your input has been recorded as 1',
'2': 'Fine! Your input has been recorded as 2',
'exit': 'Exiting...',
}
)
my_switch.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment