10 Quick Clean Coding Hacks in Python | by Normaler Mensch | Towards Data Science

Hey all! Thanks to Python’s beautiful simplicity, it offers multiple ways to do the same task. It is also a very intuitive and easy language to read and write. That said, it is easy to get carried away with Python and make things appear more complex than they need to be. PEP8, the python style guide provides some guidelines to stay clean on python. Here is a quick list of 10 that you can immediately start doing in your code.
Use “““Triple double quotes””” to write docstrings that clearly explain the purpose of your function, module and the script in all, even if you are commenting it otherwise. Remember to end your docstrings with a period. (.)
def get_percent_sales(product,sales,region):“““Return the product Sales volumes in percent of total in country.Get percentage of product sales of the region.This function gets the product and corresponding sales by region and returns a percent sales of the region by total sales in that country. Region input is accepted only by city. Districts are not accepted. If city name is not found, exception is thrown.         Parameters:              product (str) : Product name             sales (int) : Sales Volume         Returns:              percent_sales (float): Percent of total sales of                                        product."""
Don't
if is_white == Falseif not is_white == False
Do
is_white = Trueif is_white:else: 
Don't
my_name = ‘firstname’+ ‘ ‘ + ‘lastname’
Do
my_name = " ".join(['firstname','lastname'])
numbers = [1,2,3,4,5,6,7,8,9,10]
Don’t
even_halves = [ ]for num in numbers:    if num%2 == 0:       even_halves.append(num/2)print(even_halves)
Do:
even_halves = [num/2 for num in numbers if num%2==0]
Save the lambda functions for calculation inside of expressions.
Don’t
squared = lamdba x: x**2
Do
def squared(x):   return x**2
Pay attention to the text wrap line. Stay Inside your wrap line on the editor.
Don’t
df = pd.read_excel('This/extremely/long/file/path/that/extends/ /to/the/next/line/and/screws/with/indentation.xlsx')mylist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20000,30000,3100000320000]
do backslash and implicit continuation:
filepath = "this/sweet/line/" \           "continued/prettily/"\           "looksbetter.xlsx"df = pd.read_excel(filepath)my_list = [1,2,3,4,5,6,7,8,9,10,11,          12,13,14,15,16,17,18,19,          20000,30000,3100000,320000]if this_happens or that_happens \   or these_happen:      print('blah')else:   print('the other blah')
Don’t
indices = [0,2,4,6,8,10]for idX in indices:    print(name[idX])
do
for idX in range(0,12,2):    print(name[idX])
Don’t
try:   names = get_data(students, classroom)   numbers = get_scores(students, classroom)   return names,numbersexcept KeyError: 
Do:
try:    names = get_data(students, classroom)    numbers = get_scores(students, classroom)except KeyError:    print('That's not a student in this classroom!')return names, numbers
Sets offer performance over functionality. If you don’t need a lot of functionality in the current situation, prefer sets to other data structures.
data = {‘find_this’, ‘among’, ‘all_the’,'other',’data’}if‘find_this’ in data:   print(‘this exists!’)long_stuff = [‘this’,’list’,’list’,’is’,             ’enormous’,’oh’,’my’,’god’,             ’god’,’what’,’is’,             ’unique’,’unique’]unique_values = set(long_stuff) 
students = [‘tom’,’dick’,’harry’,’larry’,’tim’,’benny’]scores = [100,20,40,60,30,40]
Don’t:
for i in range(len(students)):    print(student[i],scores[i]
Do
for student,score in zip(students,scores):    print(student,score)
That’s about some basic ways you can improve your script with python. Follow the style guide and be a friendly programmer!