Basic knowledge of Python (1)

One, coding standards

PEP-8 coding standard

Python Enhancement Proposals: Python improvement plan

One of Guido's key points is that the code is more for reading than writing. The coding standards aim to improve the readability of Python code.

The style guide emphasizes consistency. It is important to keep the project, module or function consistent.

Second, the grammar specification

1.1、 Comment

The so-called comment is to add explanations in the program, which can greatly enhance the readability of the program. The content in the comment is not the actual program to be executed, and serves as an auxiliary explanation

Single line comment

Start with #, and everything on the right of # is used as an explanation

# I am a comment, you can write some function descriptions in it.
print('hello world')

Multi-line comments

Use 3 quotes, 3 single quotes or 3 double quotes

'''
I am a multi-line comment, I can write many, many lines of function description
  This is what I pointed out
  Hahaha. . .
'''

"""
I am also multi-line comments, Barabara. .
"""

1.2、 Indentation

Use 4 spaces for each level of indentation

Python does not use {} to organize code and relies entirely on indentation, so the format of indentation is very important.

Use 4 spaces for indentation, don't use tab, and don't mix tab with spaces.

When using spaces, always use 4 spaces, and other spaces cannot be used, otherwise the syntax is wrong.

It is recommended to change the tab of the development tool to 4 spaces.

Sublime is set as follows: In addition, pycharm has replaced tab with 4 spaces by default

# Align left parenthesis
foo =long_function_name(var_one, var_two,
       var_three, var_four)

# Do not align the opening parenthesis, but add an extra layer of indentation to distinguish it from the following content.
def long_function_name(
  var_one, var_two, var_three,
  var_four):print(var_one)

# Hanging indentation must add an extra layer of indentation.
foo =long_function_name(
 var_one, var_two,
 var_three, var_four)

note:

Use vertical implicit indentation or hanging indentation in parentheses. For the latter, it should be noted that the first line must have no parameters, and the subsequent lines must be indented.

1.3、 Semicolon

Python does not strictly require the use of semicolons (;).

In theory, you should put one code per line. After each line of code, you can add a semicolon ; or not add a semicolon ;

Try not to put multiple lines of code on one line, if you put them on one line, you need to add a semicolon to separate them.

1.4、 Line length

Each line does not exceed 80 characters (the maximum line width is 79 characters, and for long blocks of text, such as document strings or comments, the line length should be limited to 72 characters.)

Except in the following cases:

  1. Long import module statement
  2. URL in comments

Do not use backslashes to connect lines. If a text string does not fit on one line, you can use parentheses to achieve implicit line concatenation:

x =('This is a very long very long very long very long''Very long very long very long very long very long very long string')

1.5、 Blank line

Two blank lines separate the definitions of top-level functions and classes. The method definition of the class is separated by a single blank line. Extra blank lines can be used to separate different function groups when necessary, but should be used sparingly. Extra blank lines can be used to separate different logic blocks in the function when necessary, but they should be used sparingly.

###1.6、 Source file encoding

Code published in core Python should always use UTF-8 (ASCII in Python 2).

# Python recommended
#- *- coding:utf-8-*-
# Simplified writing
# encoding: utf-8

Python 3 (default UTF-8) should not have an encoding declaration.

1.7、 Import in a single line

import os
import sys
from subprocess import Popen, PIPE

Imports are always at the top of the file, after module comments and docstrings, and before module global variables and constants.

The import sequence is as follows: standard library import, related third-party library, local library. There must be a blank line between the imports of each group.

Wildcard import is prohibited.
Wildcard import (from import *) should be avoided because it is not clear which names exist in the namespace, which confuses readers and many automated tools.

**1.8、 Brackets **

It is better to use parentheses unless it is used to implement line joins. Don't use parentheses in return statements or conditional statements. However, it is possible to use parentheses on both sides of tuples.

Avoid spaces in parentheses

# Avoid spaces in parentheses
# Yes
spam(ham[1],{eggs:2})
# No
spam( ham[1],{ eggs:2})

1.9、 Space

Use the spaces on both sides of the punctuation in accordance with the standard typesetting conventions

1.9.1、 There should be no spaces in the brackets.

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

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

1.9.2、 Don't put spaces before commas, semicolons, and colons, but you should add them after them (except at the end of the line).

Yes:if x ==4:
   print x, y
  x, y = y, x

No:if x ==4:
   print x , y
  x , y = y , x

1.9.3、 There should be no spaces before the opening parenthesis of parameter lists, indexes or slices.

Yes:spam(1)

no:spam(1)

Yes: dict['key']= list[index]

No:  dict ['key']= list [index]

**1.9.4、 Add a space on both sides of the binary operator, **

Such as assignment (=), comparison (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Boolean (and, or, not). As for arithmetic operations How to use the spaces on both sides of the character requires your own judgment. But both sides must be consistent.

Yes: x ==1

No:  x<1

But note: When'=' is used to indicate keyword parameters or default parameter values, do not use spaces on both sides.

Yes: def complex(real, imag=0.0):returnmagic(r=real, i=imag)

No:  def complex(real, imag =0.0):returnmagic(r = real, i = imag)

Do not use spaces to vertically align the marks between multiple lines, because this will become a maintenance burden (applicable to:, #, =, etc.):

Yes:
  foo =1000  #Comment
  long_name =2  #Notes do not need to be aligned

  dictionary ={"foo":1,"long_name":2,}

No:
  foo       =1000  #Comment
  long_name =2     #Notes do not need to be aligned

  dictionary ={"foo":1,"long_name":2,}

**It is strongly not recommended to use compound statements (Compound statements: write multiple statements on the same line). **

if foo =='blah':print(100)

1.10、 Identifiers and keywords

Identifiers are character sequences used when naming variables, constants, classes, methods, and parameters in a program.

Keywords are reserved in Python and have special meanings.

Python keywords:

and as assert breakclasscontinue def del elif else except 
exec finallyforfrom global ifinimport is lambda not or pass
print raise returntrywhilewithyield

The naming rules are as follows

  1. The identifier consists of letters, underscores, and numbers, and the number cannot start
  2. Python is case sensitive. a and A are completely different.
  3. It cannot be a python keyword.

Coding habits:

  1. See the name know the meaning, use meaningful, English words or phrases, never use Chinese pinyin.
  2. Underscore naming and camel case naming
    Underscore: student_name
    Little hump: studentName
    Big hump: StudentNameTable

Three, input and output

1、 Output (see supplement)

**2、 Enter **

1.1、 Introduction

Input and output, in simple terms, is to get data from standard input and print data to standard output. It is often used in an interactive environment. In Python, input() is used to input standard data.

1.2、 Syntax format

Format: input()
Function: Accept a standard input data,
Return: return string type. ctrl+z end input

1.2、 Sample code

Waiting for an arbitrary character input

input('please enter user name:\n')

Accept multiple data inputs, use the eval() function, the spacer must be a comma

a,b,c=eval(input())

The public account "FunTester", an interesting test development, the article records learning and insights, welcome to pay attention and grow together.

Recommended Posts

Basic knowledge of Python (1)
Basic syntax of Python
Python basic knowledge question bank
​Full analysis of Python module knowledge
Python basic syntax (1)
Python3 basic syntax
7 features of Python3.9
Python basic summary
Python knowledge points
Python basic operators
Basic analysis of Python turtle library implementation
Summary of knowledge points about Python unpacking
Knowledge points of shell execution in python
Python basic syntax generator
Python3 supplementary knowledge points
Python basic drawing tutorial (1)
Python advanced knowledge points
Python function basic learning
Basics of Python syntax
python_ crawler basic learning
Python basic data types
Prettytable module of python
Python basic data types
09. Common modules of Python3
Python basic syntax iteration
Consolidate the foundation of Python(7)
In-depth understanding of python list (LIST)
Subscripts of tuples in Python
Python analysis of wav files
Consolidate the foundation of Python(6)
Analysis of JS of Python crawler
2020--Python grammar common knowledge points
python king of glory wallpaper
Python basic syntax list production
Python implementation of gomoku program
Analysis of Python Sandbox Escape
Some new features of Python 3.10
Deep understanding of Python multithreading
Python basic drawing tutorial (two)
Analysis of Python object-oriented programming
Python version of OpenCV installation
9 feature engineering techniques of Python
matplotlib of python drawing module
Python method of parameter passing
Consolidate the foundation of Python (3)
Collection of Python Common Modules
The usage of wheel in python
Summary of logarithm method in Python
Detailed explanation of python backtracking template
Python introductory notes [basic grammar (on)]
Analysis of usage examples of Python yield
Use of Pandas in Python development
Detailed implementation of Python plug-in mechanism
Detailed explanation of python sequence types
Python implementation of IOU calculation case
Magic methods and uses of Python
In-depth understanding of Python variable scope
Python preliminary implementation of word2vec operation
Python entry notes [basic grammar (below)]
Python handles the 4 wheels of Chinese
Python calculation of information entropy example