avatarSruthi Korlakunta

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

4706

Abstract

"hljs-number">1,2,3,4</span>,<span class="hljs-number">5,6,7,8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">10</span>]</pre></div><p id="9a57">Don’t</p><div id="18cc"><pre><span class="hljs-attr">even_halves</span> = [ ]</pre></div><div id="daa2"><pre><span class="hljs-attribute">for</span> num in numbers: <span class="hljs-attribute">if</span> num%<span class="hljs-number">2</span> == <span class="hljs-number">0</span>: <span class="hljs-attribute">even_halves</span>.append(num/<span class="hljs-number">2</span>)</pre></div><div id="9143"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(even_halves)</span></span></pre></div><p id="6151">Do:</p><div id="5655"><pre>even_halves <span class="hljs-operator">=</span> [num/<span class="hljs-number">2</span> for num in numbers if num%<span class="hljs-number">2</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-number">0</span>]</pre></div><h2 id="c32d">5. If you are assigning a value to a variable, use def functions instead of lambda</h2><p id="dc3c">Save the lambda functions for calculation inside of expressions.</p><p id="5e61">Don’t</p><div id="6e4b"><pre><span class="hljs-attr">squared</span> = lamdba x: x**<span class="hljs-number">2</span></pre></div><p id="d1e2">Do</p><div id="1d21"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">squared</span>(<span class="hljs-params">x</span>): <span class="hljs-keyword">return</span> x**<span class="hljs-number">2</span></pre></div><h2 id="50ae">6. Break those long lines</h2><p id="93d9">Pay attention to the text wrap line. Stay Inside your wrap line on the editor.</p><p id="6587">Don’t</p><div id="c15a"><pre>df <span class="hljs-operator">=</span> pd.read_excel('<span class="hljs-type">This</span><span class="hljs-regexp">/extremely/</span>long<span class="hljs-regexp">/file/</span>path<span class="hljs-regexp">/that/</span>extends<span class="hljs-operator">/</span> <span class="hljs-regexp">/to/</span>the<span class="hljs-regexp">/next/</span>line<span class="hljs-regexp">/and/</span>screws<span class="hljs-regexp">/with/</span>indentation.xlsx')</pre></div><div id="9491"><pre>mylist = [<span class="hljs-number">1,2,3,4</span>,<span class="hljs-number">5,6,7,8</span>,<span class="hljs-number">9,10,11,12</span>,<span class="hljs-number">13,14,15,16</span>,<span class="hljs-number">17</span>,<span class="hljs-number">18,19,20000</span>,<span class="hljs-number">30000</span>,<span class="hljs-number">3100000320000</span>]</pre></div><p id="4e1b">do backslash and implicit continuation:</p><div id="3dfe"><pre><span class="hljs-attribute">filepath</span> <span class="hljs-operator">=</span> <span class="hljs-string">"this/sweet/line/"</span>
<span class="hljs-string">"continued/prettily/"</span>
<span class="hljs-string">"looksbetter.xlsx"</span></pre></div><div id="0bb6"><pre><span class="hljs-attribute">df</span> <span class="hljs-operator">=</span> pd.read_excel(filepath)</pre></div><div id="c841"><pre>my_list = [<span class="hljs-number">1,2,3,4</span>,<span class="hljs-number">5,6,7,8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">10</span>,<span class="hljs-number">11</span>, <span class="hljs-number">12,13,14,15</span>,<span class="hljs-number">16,17,18,19</span>, <span class="hljs-number">20000,30000</span>,<span class="hljs-number">3100000</span>,<span class="hljs-number">320000</span>]</pre></div><div id="eaed"><pre><span class="hljs-variable"><span class="hljs-keyword">if</span></span> <span class="hljs-variable">this_happens</span> <span class="hljs-variable"><span class="hljs-keyword">or</span></span> <span class="hljs-variable">that_happens</span>
<span class="hljs-variable"><span class="hljs-keyword">or</span></span> <span class="hljs-variable">these_happen</span>: <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-string">'blah'</span>)</span> <span class="hljs-variable"><span class="hljs-keyword">else</span></span>: <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-string">'the other blah'</span>)</span></pre></div><figure id="4bcf"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*o3Hg2AxFB3StvmJceiiobw.png"><figcaption></figcaption></figure><h2 id="3750">7. Use range instead of a list where possible</h2><p id="c073">Don’t</p><div id="dbc5"><pre><span class="hljs-attr">indices</span> = [<span class="hljs-number">0</span>,<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span cla

Options

ss="hljs-number">6</span>,<span class="hljs-number">8</span>,<span class="hljs-number">10</span>]</pre></div><div id="72e3"><pre><span class="hljs-keyword">for</span> idX <span class="hljs-keyword">in</span> <span class="hljs-built_in">indices</span>:</pre></div><div id="b932"><pre> <span class="hljs-built_in">print</span>(<span class="hljs-keyword">name</span>[idX])</pre></div><p id="d158">do</p><div id="a7b7"><pre><span class="hljs-attribute">for</span> idX in range(<span class="hljs-number">0</span>,<span class="hljs-number">12</span>,<span class="hljs-number">2</span>):</pre></div><div id="5ad8"><pre> <span class="hljs-built_in">print</span>(<span class="hljs-keyword">name</span>[idX])</pre></div><h2 id="0c76">8. Keep a minimum amount of code under Try blocks</h2><p id="ae6b">Don’t</p><div id="ef3f"><pre><span class="hljs-keyword">try</span>:</pre></div><div id="92cf"><pre> <span class="hljs-attr">names</span> = get_data(students, classroom)</pre></div><div id="1a46"><pre> <span class="hljs-attr">numbers</span> = get_scores(students, classroom)</pre></div><div id="f8b5"><pre> <span class="hljs-keyword">return</span> names,numbers</pre></div><div id="0c4c"><pre><span class="hljs-keyword">except</span> KeyError: </pre></div><p id="0b6a">Do:</p><div id="5530"><pre><span class="hljs-keyword">try</span>:</pre></div><div id="8596"><pre> <span class="hljs-attr">names</span> = get_data(students, classroom)</pre></div><div id="e530"><pre> <span class="hljs-attr">numbers</span> = get_scores(students, classroom)</pre></div><div id="6c5f"><pre>except KeyError: <span class="hljs-keyword">print</span>(<span class="hljs-string">'That'</span>s not a student <span class="hljs-keyword">in</span> <span class="hljs-keyword">this</span> classroom!<span class="hljs-string">')</span></pre></div><div id="41ac"><pre><span class="hljs-keyword">return</span> names, numbers</pre></div><h2 id="2074">9. Use sets a little more than you already do</h2><p id="ef48">Sets offer performance over functionality. If you don’t need a lot of functionality in the current situation, prefer sets to other data structures.</p><div id="de29"><pre><span class="hljs-class"><span class="hljs-keyword">data</span> = {‘<span class="hljs-title">find_this</span>’, ‘<span class="hljs-title">among</span>’, ‘<span class="hljs-title">all_the</span>’,'<span class="hljs-title">other'</span>,’<span class="hljs-title">data</span>’}</span></pre></div><div id="5fef"><pre><span class="hljs-title">if</span>‘find_this’ <span class="hljs-keyword">in</span> <span class="hljs-class"><span class="hljs-keyword">data</span>:</span></pre></div><div id="a79a"><pre> <span class="hljs-keyword">print</span>(‘<span class="hljs-keyword">this</span> <span class="hljs-keyword">exists</span>!’)</pre></div><div id="2cdb"><pre>long_stuff = [‘<span class="hljs-keyword">this</span>’,’list’,’list’,’<span class="hljs-keyword">is</span>’, ’enormous’,’oh’,’my’,’god’, ’god’,’what’,’<span class="hljs-keyword">is</span>’, ’unique’,’unique’]</pre></div><div id="1f41"><pre><span class="hljs-attr">unique_values</span> = set(long_stuff) </pre></div><figure id="ef97"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*eBeih_I9YMGj5sF7WSgVhg.png"><figcaption></figcaption></figure><h2 id="cef0">10. use zip to iterate over multiple lists</h2><div id="062a"><pre><span class="hljs-attr">students</span> = [‘tom’,’dick’,’harry’,’larry’,’tim’,’benny’]</pre></div><div id="fdc7"><pre><span class="hljs-attr">scores</span> = [<span class="hljs-number">100</span>,<span class="hljs-number">20</span>,<span class="hljs-number">40</span>,<span class="hljs-number">60</span>,<span class="hljs-number">30</span>,<span class="hljs-number">40</span>]</pre></div><p id="0dbb">Don’t:</p><div id="b121"><pre><span class="hljs-keyword">for</span> <span class="hljs-selector-tag">i</span> <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-built_in">len</span>(students)):</pre></div><div id="aafb"><pre> <span class="hljs-built_in">print</span>(student<span class="hljs-selector-attr">[i]</span>,scores<span class="hljs-selector-attr">[i]</span></pre></div><p id="5536">Do</p><div id="ae04"><pre><span class="hljs-keyword">for</span> student,<span class="hljs-keyword">score</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">zip</span>(students,scores): <span class="hljs-keyword">print</span>(student,<span class="hljs-keyword">score</span>)</pre></div><p id="5d48">That’s about some basic ways you can improve your script with python. Follow the style guide and be a friendly programmer!</p></article></body>

10 Quick Clean Coding Hacks in Python

Make your Python script pretty and readable

Photo by Chris Ried on Unsplash

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.

1. Do your co-developer a favor and use docstrings

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.
"""

2. Make your logic statements intuitive to read

Don't

if is_white == False
if not is_white == False

Do

is_white = True
if is_white:
else: 

3. Use .join instead of + to perform string concatenation

Don't

my_name = ‘firstname’+ ‘ ‘ + ‘lastname’

Do

my_name = " ".join(['firstname','lastname'])

4. Use List Comprehension for readable for loops

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]

5. If you are assigning a value to a variable, use def functions instead of lambda

Save the lambda functions for calculation inside of expressions.

Don’t

squared = lamdba x: x**2

Do

def squared(x):
   return x**2

6. Break those long lines

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')

7. Use range instead of a list where possible

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])

8. Keep a minimum amount of code under Try blocks

Don’t

try:
   names = get_data(students, classroom)
   numbers = get_scores(students, classroom)
   return names,numbers
except 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

9. Use sets a little more than you already do

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) 

10. use zip to iterate over multiple lists

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!

Python
Clean Code
Data Science
Coding
Towards Data Science
Recommended from ReadMedium