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.
π 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)
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 π€.
I code as a ninja in my sleep so I was already aware of this but thank you for sharing with us! β¨