tm1rbrt tm1rbrt - 5 months ago 22
Python Question

Python inline elif possible?

'Hello ' + ('there' if name is None else name)


Is the equivalent of

msg = 'Hello '
if name is None:
msg += 'there'
else:
msg += name


What is the equivalent of this:

msg = 'Hello '
if name is None:
msg += 'there'
elif name == 'Mr Anderson'
msg += 'Neo'
else:
msg += name


EDIT: for reference here is the code I wanted to shrink

srepr = '\'Modify '
if self.register == 'p':
srepr += 'Pointer'
elif self.register == 'v':
srepr += 'Value'
else
srepr += 'Unknown'
srepr += ' By ' + str(self.delta) + '\''

Answer
msg = "Hi " + ("there" if not name else ("Neo" if name == "Anderson" else name))

Personally I find this is unreadable and I would never use it myself nor advice anyone to use it.