\'Hello \' + (\'there\' if name is None else name)
Is the equivalent of
msg = \'Hello \'
if name is None:
msg += \'there\'
else:
Firstly, run 'pip install pyswitch'
Then:
import pyswitch
mySwitch = pyswitch.Switch()
@mySwitch.case(None):
def gotNone(value):
return 'Hello there'
@mySwitch.case('Mr. Anderson')
def gotMrAnderson(value):
return 'Hello Neo'
@mySwitch.default
def gotDefault(value):
return 'Hello %s' % value
msg = mySwitch.switch(None) # Returns 'Hello there'
msg = mySwitch.switch('Mr. Anderson') # Returns 'Hello Neo'
msg = mySwitch.switch('OoglyMoogly') # Returns 'Hello OoglyMoogly'
Use a dictionary to perform a mapping:
srepr = "'Modify " + {"p": "Pointer", "v": "value"}.get(self.register, "Unknown")
(by the way, instead of '\'...'
you can use "'...
for a bit more clarity.
'Hello ' + \
('there' if name is None else \
'Neo' if name == 'Mr Anderson' else \
name)
I recommend against this; if your conditions become this complex, stick it in a function.
msg = "Hi " + ("there" if not name else ("Neo" if name == "Anderson" else name))
I think that's pretty unreadable, though.
You could also do this:
msg= 'Hello ' + {name is None: 'there', name == 'Mr Anderson': 'Neo'}.get(True, name)
So either of name is None
or name == 'Mr Anderson'
is True
, or none of them is True, then name
will be used.
msg = 'Hello ' + (
'there' if name is None else
'Neo' if name == 'Mr Anderson' else
name
)
This is a reiteration of several other answers, but with nicer formatting. I consider this most readable, and this is the approach I would use.