python – Putting a simple if-then-else statement on one line
python – Putting a simple if-then-else statement on one line
Thats more specifically a ternary operator expression than an if-then, heres the python syntax
value_when_true if condition else value_when_false
Better Example: (thanks Mr. Burns)
Yes if fruit == Apple else No
Now with assignment and contrast with if syntax
fruit = Apple
isApple = True if fruit == Apple else False
vs
fruit = Apple
isApple = False
if fruit == Apple : isApple = True
Moreover, you can still use the ordinary if
syntax and conflate it into one line with a colon.
if i > 3: print(We are done.)
or
field_plural = None
if field_plural is not None: print(insert into testtable(plural) {0}.format(field_plural))
python – Putting a simple if-then-else statement on one line
count = 0 if count == N else N+1
– the ternary operator. Although Id say your solution is more readable than this.