Tips to help you write clean python scripts

Tips to help you write clean python scripts

ยท

5 min read

Python's very popular for it's simplicity and readability, In this article I'll be showing you some useful tips & tricks on how you can write clean and readable code.

1. Using python's built-ins isn't a good idea, doing so overrides the default value it contained, which makes them unavailable for their initial purpose or you'd most likely get an error.

# bad
id = 2
zip = 567890
class = "physics"

if you're tempted to use names like this you should add an underscore or use a more detailed name

# use this instead
user_id  = 2
zip_code = 567890
class_   = "physics"

2. For long variable names, apply naming conventions correct, this improves readability. Use camel case or underscore naming convention. Camel case names have the next word written in Upper case letters while underscore names are separated with an underscore.

# bad
secondary_Title= "hello world"
Name = "rubbie" # write in lowercase instead

#better
secondaryTitle = "hello world"    # ... or
secondary_title = "hello world"

# Name stylings
# use titled-camelCase to name classes & exceptions

class ProximitySensor:

    def read(self):
        """
        1. use triple-quotes for doc strings
        2. purpose of this function should be
        well explained here.
        """
        pass

# name constants with uppercase underscore
PI = 3.141392
OPERATIONAL_EFFICIENCY = 0.67

# name functions like variables
# make sure not to mix between camel case and underscore naming

def open_database(filename):
    pass

3. Use spaces instead of tabs. using tabs can get your code looking weird on some other editors with different tab size... really bad experience when working with teams. although it's not always like this, but its best to leave your code looking readable anywhere it's opened. for better readability, set to 4 spaces per tab.

4. I see this in a lot of people's code, cases where conditional statements are used to return Boolean values

# poor
if True:
    is_active = True
else:
    is_active = True

boys, girls = 5, 19
...
if boys == girls:
    equal = True
else:
    equal = False

do these instead...

is_active = True

boys, girls = 5, 19
...
equal = boys == girls

It saves you a lot of time and makes you code look simple.

5. Use python tunary conditions to solve small conditional problems.

is_active = False

if is_active:
    x = 1
else:
    x = -1
...
# do this instead.

x = 1 if is_active else -1

6. Working with large numbers. seeing digits like 10000000000 always get me counting the zeros ๐Ÿ˜ญ... I'm sure it's not just me. On paper we can write like 10,000,000,000 it gives you a better overview on how big the number is exactly. luckily we can do the same in python without getting errors.

connections_accepted = 1_000_000_000_000
connections_rejected = 1000
connections_total = connections_accepted + connections_rejected
# it's totally safe :)

7. Resource management using context managers.

file = open("text.txt")
content = file.read()
file.close()

ok... that's bad practice. a better way to do this is to use the with context.

with open("text.txt") as file:
    content = file.read()

the context manager closes the resources once the code is done reading it or when there's an error automatically.

8. keeping track of index while looping through lists.

items = ["apple",  "pear", "papaya", "mango"]
index = 0

for item in items:
    print(index, item)
    index += 1

this should print the index of the items in list as so:

Output:
0 apple
1 pear
2 papaya
3 mango

it's a common practice in a beginner's world (i did it ๐ŸŒš). well there's a better way to track index while looping.

items = ["apple",  "pear", "papaya", "mango"]

for index, item in enumerate (items):
    print(index, item)
Output:
0 apple
1 pear
2 papaya
3 mango

if you want to start from index 1, just add start=1 as an argument to the enumerate function.

...
for index, item in enumerate (items, start=1):
...
Output:
1 apple
2 pear
3 papaya
4 mango

9. looping through multiple lists at once. i know what you might be thinking ๐Ÿ˜‚... let's see:

names = ["rubbie", "jerome", "carlie", "angie"]
hobbies = ["painting", "surfing", "cycling", "singing"]

index = 0

for name in names:
    print(f"{name} loves {hobbies[index]}")
    index += 1

Well... while this actually works, it's not always the best way to get this done. a more resourceful approach is the use of the zip function. the zip function allow you to loop through multiple lists at once. let's see how this goes:

names = ["rubbie", "jerome", "carlie", "angie"]
hobbies = ["painting", "surfing", "cycling", "singing"]

for name, hobby in zip(names, hobbies):
    print(f"{name} loves {hobby}")

10. Use underscore when dealing with variables that are useless in most cases, but are pretty much necessary.

for i in range(6):
    do_somthing()

as seen we only wanted to call do_somthing 6 times and not to use the variable i. simply replace it with an underscore, like so;

for _ in range(6):
    do_somthing()

And that's it! A couple of points you should put into consideration while writing your next script, there's more than i could come up with, but I think this is a good start.

If you enjoyed this article, don't forget to leave a like and thanks for reading!