Basic Python Question: Shortening If Statements

28 views Asked by At

I understand that a ternary conditional operator can be used to shorten the following:

if x > a:
   y += 12
else:
   y += 10

re-written as:

y += 12 if x > a else 10

Is there something to shorten a statement if it's just the if portion with no else?

i.e.:

if x > a:
   y += 12

can be re-written as:

y += 12 if x > a else 0

due to decrementing 0 resulting in the same value as the initial value.

But I'm curious if there is an operator that doesn't add an else condition to a simple if statement with no else block. The ternary operator works in this case due to using an equivalent decrementing value of 0 vs. not changing the value in the first place, but having an equivalent operation may not always exist.

I was thinking of something similar to the idea of:

y += 12 if x > a

even though I know this is syntactically incorrect.

0

There are 0 answers