DEV Community

BHUVANESH M
BHUVANESH M

Posted on • Edited on

Write Python Code Like a Ninja : Shrink 4 Lines into 1!

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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.


πŸ“– For more tips and tricks in Python 🐍, check out

Packed with hidden gems, Python's underrated features and modules are real game-changers when it comes to writing clean and efficient code.


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

Top comments (2)

Collapse
 
ceir profile image
Eric Garcia

Nice tip for beginners! It reminded me of how nice are list comprehensions in python ⭐ (although they don't have much to do with the topic).
Maybe I could write something about niche python techniques that beginners may not know πŸ€”.

Collapse
 
anitaolsen profile image
Anita Olsen

I code as a ninja in my sleep so I was already aware of this but thank you for sharing with us! ✨