Baham's Blog

Above all else, guard your heart.

6 Tips to Writing More Beautiful Python Codes(For Beginners)

Python is an easy-learning programming language. Its design philosophy emphasizes code readability. And if you did not know python, you can get the base knowledge on Wikipedia.

1 “”“ use Three quotes

In python 3 quotes is not just used to show mutiline strings, but also for doc in a function.

This will help users to understand this function.

Like:

def hw():
    """Output 'Hellow World'
    For example:
    >>> hw()
    Hellow World!
    """
    print("Hellow World")
    return "Hellow World"

And the strings between 2 three quotes, not just commits but also an introduction for the function.

You can get the strings by print(hw.__doc__)

    Output 'Hellow World'
    For example:
    >>> hw()
    Hellow World!

2 Use Return —functional programming

Not every function need a return(just like the function greet()below the title ‘use keywords as default parameter’), if you do not type a return, python consider you typed a return None.

But if you like functional programming, like Scale, R and so on. You need add return in every function.

2.1functional programming

There are not variables or side effect, you can only edit things by the `return`.

3 Use main()

You know main is not necessary. Using main()is just an agreement.

Just make python’s code more comfortable for who have learned Java or C++.

4 Use keywords as default parameter

  1. It will show the parameter’s value directly;
  2. The order of the parameter with keywords doesn’t matter.

Just like this:

def greet(name='Bob', greeting='Hellow'):
    print(greeting, name+'!')

5 Import Package name like import packagename

Cause when you import package like: from packagename import *

When there is a same name in your own code with in the packege, it will overwrite it.

So use import packagename insted of using from packagename import *.

And use packagename.functionname to use the function.

6 Using negative number for an index

a   p   p   l   e
0   1   2   3   4
-5  -4  -3  -2  -1

Maybe it will take more time to find the exact the negative index. But it will avoid some mistakes when you operate an array or string with delete.




The Original Link: http://baham.github.io/05_15_6-tips-to-writing-more-beautiful-python-codes.html
If you want to reprint it, please do under the CC BY-NC-SA 4.0

Comments