Python basic tutorial-code specification

Before starting to learn Python, we need to understand the specifications of Python code. As the saying goes, "No rules can't make a circle", a line of code that does not conform to programming rules will bury you the hidden danger of constantly reporting errors.

Knowing the code specifications in advance can help you to be logically clear in the follow-up study, reduce the error rate, and develop good programming habits for you.

Don’t say much, let’s go to the catalog first.

coding

Code format

import statement

Space

Wrap

docstring

 

coding

Baidu’s interpretation of coding is a process of transforming information from a new style or format to another. In computer hardware, coding is the use of codes to represent groups of data so that the computer can read and understand this line of code. Information is analyzed and processed.

In the Python programming process, you need to pay attention to the following two points:

If there are no special circumstances, the file will use UTF-8 encoding

If there are no special circumstances, the file header must be added with #-*-coding:utf-8-*- logo

 

Code format

indentation

The same use 4 spaces for indentation, which is a Tab

 

Line width

Try not to exceed 80 characters per line of code (in special cases, it can exceed, but the longest cannot exceed 120)

If the code is too long, there may be three problems:

This is helpful when viewing side-by-side diffs

Convenient to view the code under the console

Too long may be a flawed design

 

quotation marks

In the encoding process, if the computer needs to directly output the information you want, we need to use quotation marks. Natural language uses double quotation marks, and machine labels use single quotation marks. Most of the code uses single quotation marks. For example:

Natural language uses double quotes "..."

For example, error message; directly use this method "error message"

Machine ID Use single quotes'...' such as the key in dict

Regular expressions use native double quotes r"..."

The docstring uses three double quotes """......"""

 

Blank line

Two blank lines between module-level functions and class definitions;

Blank line between class member functions;

class A:

 

def __init__(self):

pass

 

def hello(self):

pass

 

def main():

pass

You can use multiple blank lines to separate multiple sets of related functions

Blank lines can be used in functions to separate logically related codes

 

import statement

The correct way of writing should be branch writing

#Correct wording

import them

import sys

 

# Not recommended

import sys,os

# Correct writing

from subprocess import Popen, PIPE

 

The import statement should be placed at the head of the file, after the module description and docstring, and before the global variables;

Import statements should be arranged in order, separated by a blank line between each group

 

import them

import sys

 

import msgpack

import zmq

 

import foo

 

When importing class definitions of other modules, you can use relative import

from myclass import MyClass

 

Space

Leave a space on each side of the binary operator [=,-,+=,==,>,in,is not, and]:

# Correct writing

i = i + 1

submitted += 2

y = y * 2 - 1

hypot2 = x * x + y * y

c = (a + b) * (a - b)

 

# Not recommended

i=i+1

submitted +=2

y = y * 2 - 1

hypot2 = x * x + y * y

c = (a+b) * (a-b)

 

In the parameter list of the function, there must be a space after

 

# Correct writing

def complex(real, imag):

pass

 

# Not recommended

def complex(real,imag):

pass

 

In the parameter list of the function, do not add spaces around the default equal sign

 

# Correct writing

def complex(real, imag=0.0):

pass

 

# Not recommended

def complex(real, imag = 0.0):

pass

 

Do not add extra spaces after the left parenthesis and before the right parenthesis

# Correct writing

spam(ham[1], {eggs: 2})

 

# Not recommended

spam( ham[1], { eggs : 2 } )

 

No extra spaces before the opening parenthesis of the dictionary object

# Correct writing

dict['key'] = list[index]

 

# Not recommended

dict ['key'] = list [index]

 

Do not use extra spaces to align assignment statements

 

# Correct writing

x = 1

y = 2

long_variable = 3

 

# Not recommended

x = 1

y = 2

long_variable = 3

 

Wrap

If/for/while must wrap:

# Correct writing

if foo == 'blah':

do_blah_thing()

 

# Not recommended

if foo == 'blah': do_blash_thing()

 

Compound statements are prohibited, that is, multiple statements in one line:

# Correct writing

do_first()

do_second()

do_third()

 

# Not recommended

do_first();do_second();do_third();

 

Use backslash\newline, binary operator + ., etc. should appear at the end of the line; long strings can also be used for newlines

session.query(MyTable).\

filter_by(id=1).\

one()

 

print 'Hello, '\

'%s %s!' %\

('Harry', 'Potter')

 

docstring

docstring Docstring is an important tool for interpreting the documentation program, helping your program documentation to be more understandable.

The most important specifications are:

All public modules, functions, classes, and methods should be written in docstrings. Private methods are not necessarily required, but a block comment should be provided after def.

The ending """ of the docstring should be on its own line, unless the docstring has only one line.

An analogy

del function():

    '''say something here!

    '''

    pass

print(function.__doc__) # call doc

The output result is

say something here!

It is not difficult to find that the code specification is to ensure the simplicity and elegance of Python, to develop this kind of good programming habits, and to facilitate us to review and repair our own code in the future.

The above is a concise overview of the Python code specification shared today, and the comments in the code specification will be described tomorrow. After officially entering our Python learning, I will attach a small exercise at the back of the daily article and attach the source code. .

Of course, I still hope that you try to do it first, and then compare with the source code to check for omissions.

Finally, to help you succeed in your studies~

Original link: Python code specification-a concise overview

Welcome to pay attention to my princess "Python Little White Training Camp", daily updates of the tutorial and practical operation of the zero-based beginners introductory Python, reply keywords and get a Python learning gift package~

Guess you like

Origin blog.csdn.net/minzhisocute/article/details/112759665