Python is such an expressive language because there are so many different ways to represent the same idea. Hence, while Python code can be abhorrently messy, it’s not hard to write beautiful code. Using these five tricks will help make your Python code more clean, readable, and elegant!


1 | Replacing nested ifs with if/continue

Consider the following setup: we want to loop through each element in a 3 by 3 matrix, which is done with two for loops (one looping through each row, one looping through each column — element — in each row). If the element satisfies a certain condition, we’ll do something with the numbers.

Although the example is watered down, writing an if statement this way can make your code a lot less readable. Especially if there are already many indents before and after, it’s safe to say that it is almost always better to reduce the amount of indenting necessary in our code.

If there is only an if statement and not an elif/else component, we can write the code another way: if the condition is not true, we call the continue keyword, which skips anything left in the iteration and continues to the next.

This is very helpful in making complex code more readable!

2 | Place values for large numbers

If I were to ask you to tell me the number below, which one would you be able to say and understand faster?

  • 5683273847
  • 1,984,738,928

Obviously, the answer is the second, because the number is broken down into thirds. Everyone knows that the fourth chunk is the billions, so the number is one billion, nine hundred eighty four million, seven hundred thirty eight thousand, nine hundred twenty eight. It’s so much faster than having to figure out the place values from the very start.

In Python, you can place underscores anywhere in numbers, and they will be treated as valid, which means that you can also use it for some other notation besides thirds (for whatever reason you would need to).

  • var = 394_293_103
  • print(var*2 + 98_293)
  • i = (3_5_7_8) #don’t know why you would do this

#computer-science #coding #development #python #programming

5 Essential Python Tricks to Make Your Code More Clean, Readable, & Elegant
1.50 GEEK