Python Forum

Full Version: how to return False in ternary condition
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
Other than for style, why do you want to do that?
You can achieve this with semicolons. You dont ordinarily see ; in python, but you can use them.

print("hi");print("hi again")
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.
Semicolons just make linters angry. One statement per line please. Why do people like to write dense, unreadable code?
return statement can only be used in a function, not elsewhere
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.
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'.