Home > OS >  How to execute if and else in a single line
How to execute if and else in a single line

Time:12-15

Using python I was trying to execute if and else in a single line as below

expr = "no remainder" if 5% 2 == 0 else pass
print(expr)

output:

SyntaxError: invalid syntax

Expected output:

It should pass condition without printing anything

Please help me on how to overcome the above issue

CodePudding user response:

When you use if and else in the same line what you are actually using is a conditional ternary operator. This is a way of selecting a value from two possible values based on a condition, not choosing whether to run a line based on a condition. So pass is not valid. Perhaps what you want instead is None or "" or "there is a remainder". Here is the correct code:

expr = "no remainder" if 5% 2 == 0 else "there is a remainder"
print(expr)

CodePudding user response:

You aren't using pass correctly. You should return a value in the else block. The pass statement is a null operation; nothing happens when it executes, so you're variable would be empty when the condition is not met. You might want to return something like None instead.

CodePudding user response:

As others mentioned, pass is not supposed to be used like this. If you want to execute the print() statement conditionally, do something like this:

expr = "no remainder" if 5 % 2 == 0 else None

if expr:
    print(expr)

CodePudding user response:

s = 12 if 3 < 4 else 32

assign 12 if 3 is less than 4,else assign 32.

Putting a simple if-then-else statement on one line

  • Related