TheChetan TheChetan - 2 years ago 155
Python Question

Using ternary operator in python?

Consider the following code snippet. It flags a syntax error at the break statement.

digits = list(str(102))
dummy = list(str(102/2))
for j in digits:
dummy.remove(j) if j in dummy else break

How do I fix this?(I want to still use the ternary operator)

Ian Ian
Answer Source


(see my conversation with Stefan Pochmann in the comments)

Ternary operator is not for only statement, but rather for assignment or for expression (and break is an only statement):

a = 5 if cond else 3 #OK
do() if cond else break #not OK

use normal if-else statement to do statements:

if cond:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download