stumped that this works:
if 5 % 2 == 0:
print "no remainder"
else:
pass
but not this:
print "no remainder" if 5% 2 == 0 else pass
SyntaxError: invalid syntax
As you can see in the official documentation, the pass statement does nothing. In Python, the contents cannot be omitted in the def statement of the function definition and the if statement of the conditional branch. You can use the pass statement when you need to write something, but you don't need to do anything.
The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. The pass statement is a null operation; nothing happens when it executes.
One Line If-Else Statements in PythonWriting a one-line if-else statement in Python is possible by using the ternary operator, also known as the conditional expression. This works just fine. But you can get the job done by writing the if-else statement as a neat one-liner expression.
Other programming languages like C++ and Java have ternary operators, which are useful to make decision making in a single line. Python does not have a ternary operator. But in python, we can use the if-else in a single line, and it will give the same effect as the ternary operator.
The latter is not an if
statement, rather an expression (I mean, print
is a statement, but the rest is being interpreted as an expression, which fails). Expressions have values. pass
doesn't, because it's a statement.
You may be seeing it as two statements (print or pass
), but the interpreter sees it differently:
expr = "no remainder" if 5% 2 == 0 else pass
print expr
and the first line is problematic because it mixes an expression and a statement.
A one-line if
statement is a different thing:
if 5 % 2 == 0: print "no remainder"
this can be called a one-line if
statement.
P.S. Ternary expressions are referred to as "conditional expressions" in the official docs.
A ternary expression uses the syntax you tried to use, but it needs two expressions and a condition (also an expression):
expr1 if cond else expr2
and it takes the value of expr1
if bool(cond) == True
and expr2
otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With