-1

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

user10389226
  • 109
  • 3
  • 14

4 Answers4

2

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)
Lecdi
  • 2,189
  • 2
  • 6
  • 20
1

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.

DSteman
  • 1,388
  • 2
  • 12
  • 25
1

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)

donor
  • 41
  • 4
0

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

takudzw_M
  • 186
  • 1
  • 5