DEV Community

Cover image for PYTHON TRICKS FOR WRITING CLEAN AND EASY READABLE CODE.
Sam Sonter
Sam Sonter

Posted on

PYTHON TRICKS FOR WRITING CLEAN AND EASY READABLE CODE.

Hello everybody, Today I am going state and explain few python tricks with examples.

        TERNARY OPRATORS/CONDITIONALS
Enter fullscreen mode Exit fullscreen mode

Ternary oprators/conditionals evaluate code on True or False. It allows a single line replacing multi-line if and else statements. This basicaily replaces multi-line code but still makes the code understandable.

Image description

Re-write using Ternary

Image description

Now we have both if/else statement on a single line. Making the code simple and easier to read.

          ENUMERATE FUNCTION
Enter fullscreen mode Exit fullscreen mode

This is a built-in python function that eases the task of interating through lists/tuples.
Enumerated objects can be used directly in loops or converted into tuples using list() method. Here is an example:

Image description

I am now going to state a cleaner code using Enumerate function

Image description

      WRITING SIMPLIFIED NUMERIC LITERALS
Enter fullscreen mode Exit fullscreen mode

I will show use to use _ to simplify large numeric literals in code.
In the following example i will use an underscore help read large numeric values and an f string for easy read of its output.

Image description

Top comments (0)