Writing If-else multiple ways in Python 3

Learn different ways to write if else statement in Python 3.

Writing If-else multiple ways in Python 3

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:

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.

Subscribe to Pylenin

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.