Python Forum
how to return False in ternary condition - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: how to return False in ternary condition (/thread-31397.html)



how to return False in ternary condition - KEYS - Dec-08-2020

The code below is running inside a while True loop
if play=='y':
    print('ok')
else:
    return False
I would like to write those lines in a ternary form.
Problem with my code is it seems you cannot return in ternary conditions.

print('ok') if play=='y' else return False
Is there a way to achieve this?


RE: how to return False in ternary condition - jefsummers - Dec-08-2020

Other than for style, why do you want to do that?


RE: how to return False in ternary condition - MrBitPythoner - Dec-08-2020

You can achieve this with semicolons. You dont ordinarily see ; in python, but you can use them.

print("hi");print("hi again")



RE: how to return False in ternary condition - bowlofred - Dec-08-2020

The ternary syntax is a special form of an expression, and is limited to expressions only. It isn't a full control flow like a real "if" statement. You can't put statements like "return" into those expressions.


RE: how to return False in ternary condition - deanhystad - Dec-10-2020

Semicolons just make linters angry. One statement per line please. Why do people like to write dense, unreadable code?


RE: how to return False in ternary condition - MK_CodingSpace - Dec-10-2020

return statement can only be used in a function, not elsewhere


RE: how to return False in ternary condition - deanhystad - Dec-10-2020

Quote:return statement can only be used in a function, not elsewhere
This may or may not be a problem here. We have no context provided for the code in question. But this is invalid Python if it is in a function or not. "return" is not an expression. A ternary expression is "expression condition expression". In
answer = 'odd' if x % 2 else 'even'
'even' and 'odd' are expressions and 'if x % 2 else' is the condition.

An expression is something that evaluates to a value. A string is an expression. An equation is an expression. A function call is an expression. A "return", ironically, is not an expression because it does not evaluate to a value.


RE: how to return False in ternary condition - perfringo - Dec-10-2020

Some additional tidbits. In Python there is conditional expression set forth in PEP308.

Guido in Python-Dev list:

Quote:Pleas stop calling it 'ternary expression'. That doesn't explain
what it means. It's as if we were to refer to the + operator as
'binary expression'.