How do you write python code?
If someone ask you to write a python program which return the square of the number then most of us will come with the following solution:
def pow(a):
return a*a
a=17
p=pow(a)
print("the power of ",a," is:",p)
This program will run without any error and also give the right answer which is 289.
However let me give some insight picture of this program.
If we execute this program with pylint and pychecker then we will come to know following bug in this program.
- pow() is inbuilt function of python.
- Local variable in function pow i.e. a and the global variable a is of the same name.
- No doc string for the function.
- No unit case for the parameter pass in pow function.
- User define variable a,b should follow upper case naming style.
- Space required between = operator and exactly one space required after ,.
def foo_pow(foo_x):
"""return pow of number"""
return foo_x*foo_x
FOO_A = 17
FOO_P = foo_pow(FOO_A)
print("The power of ", FOO_A, " is:", FOO_P)
Now I change code in above style. At pylint this code score 6/10 while the previous code score was -24 /30.
Conclusion:
- Function name should be different from inbuilt function of python.
- Name of global variable and local variable should be different.
- Write some unit case because there is no power if the parameter is string or Boolean value in function
- Follow upper case naming style for variable in python.
- Leave blank before and after assignment operator and one space after every comma (,).
- Write a doc string with the function.
This little improvement is very impactful if you extend your code to make a complex application. So it is better to start with the clean code.