If satement in one line with 2 variables

Question:

How can you put this if satement in a single line?

if long_old != long_new:
      long = 'yes'
      counter_changes +=1

I’ve tried something like this:

long, counter_changes = ('yes',counter_changes +=1) if long_old != long_new

Syntax error…

Asked By: KROLN

||

Answers:

You could do:

if long_old != long_new: long = 'yes'; counter_changes += 1

By putting a semicolon between the two statements, python lets you put them on one line. (However, this isn’t recommended.)

You could also do:

long, counter_changes = ("yes", counter_changes + 1) if long_old != new_old else (long, counter_changes)

Which sets long and counter_changes to "yes" and counter_changes + 1 if the condition is true, but otherwise sets them to their previous values.

However, if long doesn’t exist, you could just set it to another default value, such as an empty string:

long, counter_changes = ("yes", counter_changes + 1) if long_old != new_old else ("", counter_changes)
Answered By: sbottingota
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.