Writing If-else multiple ways in Python 3

By Lenin Mishra

We all know about if else clauses in Python 3. Probably we use them on a daily basis.

In this article, I will show you different ways to write if else clause.

  • Most Readable Way
  score = 46
  
  if score > 35:
    print("Passed")
  else:
    print("Fail")
  • A little shorter
  score = 46
  
  result = "Passed" if scored > 35 else "Fail"

You would usually see such forms while writing list comprehensions in Python 3. However, you could still use them in other ways.

  • Code Golf Suitable
  score = 46
  
  result = scored > 35 and "Passed" or "Fail"

As we progress, we see that the readability keeps going down. According to Zen of Python, your code should always be readable. Hence, I wouldn’t recommend using this form of if else clause.

However, it is still pretty useful for Code Golf.

To learn more about if else clause in Python 3, check out this video.



Don't forget to subscribe to the Pydrools Newsletter