How would you handle a default case in this?
default
My though is to add || defaultValue at the end since a failure to match any property will return undefined. Thoughts?
|| defaultValue
undefined
That would be handy using a try except:
def my_switcher(x): switches = { 'a': 1, 'b': 2, } default = 3 try: result = switches[x] except KeyError: result = default return result print(my_switcher('a')) print(my_switcher('b')) print(my_switcher('c'))
I added the extra default variable just to make the code self explanatory.
EDIT: Bad solution, look at the other comments.
You can also use defaultdict in the standard library :D
This is clean :D
This is the answer to this entire thread.
@rhymes and @pedromendes96 got it better than me 😁
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
How would you handle a
default
case in this?My though is to add
|| defaultValue
at the end since a failure to match any property will returnundefined
. Thoughts?That would be handy using a try except:
I added the extra
default
variable just to make the code self explanatory.EDIT: Bad solution, look at the other comments.
You can also use defaultdict in the standard library :D
This is clean :D
This is the answer to this entire thread.
@rhymes and @pedromendes96 got it better than me 😁