Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If satement in one line with 2 variables

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading