Posted on

I am writing code in Python these days and these are a few practices that I am definitely avoiding!!

  1. Using manual string formatting (+ signs) instead of f strings

Instead of

    print("Wow" + name + "!")

use

    print(f"Wow {name}!")
  1. Using bare except clause.

This is wrong:

    try:
        break
    except:

This is because user-interrupts in Python are propogated as exceptions. So if you Ctrl+C for such code, it wont really exit, it will execute whatever is in the except block

So use

     try:
        break
    except Exception:
  1. Using == to check if None, True or False

Instead of:

     if x == None:

     if x == True:

     if x == False:

use:

     if x is None:

     if x is True:

     if x is False:

Use Identity instead of Equality!

  1. Checking bool or len

Instead of:

     if bool(x):

     if len(x)!=0:

you can directly use:

     if x:
  1. Don't use range-length for for loops

Instead of:

    a = [1, 2, 3]
    for i in range(len(a)):
        v = a[i]
        print(v)

simply use:

    a = [1, 2, 3]
    for v in a:
        print(v)

and in case you want indices use enumerate:

    a = [1, 2, 3]
    for i, v in enumerate(a):
        print(i) #index
        print(v) #value