Image description
You ever look at a few lines of code and think, "There has to be a shorter way to do this"? That's exactly how I felt when I wrote this:

if score >= 50:
    status = "Pass"
else:
    status = "Fail"

It’s straightforward, sure. But as someone who loves clean and compact code, I knew Python had a trick up its sleeve.

Enter the Ninja Move: Ternary Operator

With Python, you can make that same logic a one-liner:

status = "Pass" if score >= 50 else "Fail"

Boom. Just like that, you've turned four lines into one — without sacrificing clarity.

Why This is Cool

  • Concise: Fewer lines = cleaner code.
  • 🤠 Pythonic: This kind of expression is encouraged in Python.
  • 📈 Useful in functions: Handy when you just want to return something based on a quick condition.

Example:

def get_status(score):
    return "Pass" if score >= 50 else "Fail"

A Gentle Warning

This trick is awesome, but don't get carried away. For more complex logic, stick with the traditional if-else — readability always comes first.


Curious about shrinking your Python code more elegantly? Check out this post on Simplifying Dictionary Operations with defaultdict in Python https://bhuvaneshm.in/dev-post/1

Have any favorite one-liner tricks or code golf moments in Python? I'd love to hear them! Drop them below and let's share the ninja knowledge.

#python #coding #devto #oneliners #beginners #cleanCode