Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error when trying to use pass keyword in one line if statement

Tags:

python

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
like image 386
Derek Krantz Avatar asked Apr 19 '13 21:04

Derek Krantz


People also ask

Can we use pass in if statement in Python?

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.

What does pass do in if-else Python?

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.

Are one line if statements Pythonic?

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.

Can we write if-else into one line in?

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.


1 Answers

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.

like image 73
Lev Levitsky Avatar answered Oct 21 '22 17:10

Lev Levitsky