0

Lets say I have a variable name = "Jack". I can check it like this

if name:
    return name
else:
    name = None
    return name

Is there any way to handle it in one line like:

new_name = name if not return none Which simply return the variable value if available and if not then it should return None

varad
  • 5,407
  • 14
  • 45
  • 95
  • 4
    why not `return name if name else None`? – Ian May 19 '16 at 06:19
  • 1
    Sure it is possible in both Python 2.x (starting Python 2.5) and Python 3.x. See here: http://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator . For Python pre-2.5 workarounds are possible. – Artur Opalinski May 19 '16 at 06:21
  • 1
    In *this specific case* `return name or None` would also work, because you want to return `None` for any falsey value of name. – Martijn Pieters May 19 '16 at 06:22
  • If you want to assign the `name` to `None` before return in case it is `None`, you could do it in *two* lines: 1. `name = name or None` 2. `return name` – Ian May 19 '16 at 06:30
  • You don't need that `else` there at all. Without an explicit `return`, it'll already `return` the value `None`. – TigerhawkT3 May 19 '16 at 06:33

2 Answers2

3

Yes.

return name if name else None

It works:

>>> def test_name(name):
...     return name if name else None
... 
>>> print test_name("")
None
>>> print test_name("Jack")
Jack
Daniil Ryzhkov
  • 6,649
  • 2
  • 35
  • 55
3

Yes, you could do it in one line as shown in my comment:

return name if name else None

Or even simpler for this specific case (as pointed out by Martijn):

return name or None
Ian
  • 28,526
  • 18
  • 60
  • 94