Python Forum

Full Version: is this a bug or not with if...else...?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
platform.python_version()
'3.5.1'
a=None; b='abc'; c = b if a == None else a + ' & ' + b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'


I thought that the rest part after 'else' would not be interpreted since a==None.

Any thought please? Thank you.
If I copy and paste the same line of code in my python 3.5.2 interpreter, there is no error...
looks like it violates PEP 20, but runs.
I don't see where the else is being interpreted as the 1st condition is satisfied.
reversed will give syntax error, because forced to run else code of first statement
a=None; b='abc'; a + ' & ' b if a != None else c = b
Output:
a=None; b='abc'; a + ' & ' b if a != None else c = b ^ SyntaxError: invalid syntax
@Larz60+ You forgot a + in the reversed version, and you cannot inverse the assignment statement. The reversed version is
a=None; b='abc'; c = a + ' & ' + b if a != None else b
and it also works.
Accepted (and more efficient) form of None value check is is/is not

if a is None:
.....
if b is not None:
.....