Python basic grammar notes 2

-------------------------------------------------------------------------------

 

 

Constant and Pylint specifications

1. Constants: constant value can not be changed. There is no concept of constant Python, Python because there is no mechanism to change the value of a constant, so constant in Python does not exist, but there are constants defined. All named constants in uppercase.

2.Pylin constants defined rules: If you define a variable does not belong to the category or function, are considered to be constant. It should be a function of variables encapsulated scattered directly on the module where the variable is bad coding habits.

3. Module: A module is a file. A Python project consists of multiple modules. Python recommended that each module has a detailed explanation.

4. Syntax Identifier (colon) before and no spaces.

5. The end of the program to extra blank line.

6. The logical operators left and right sides to a space.

7. indentation is four spaces, not all IDE a tab equal to four spaces.

 

-------------------------------------------------------------------------------

 

 

S nippet branch code block embedding concepts

snippet (fragment): Helps rapidly build snippet

For example, in the coding region of the input if, election if / else in the drop-down menu that automatically appears in, IDE will fill in the template

if code:

    pass

else:

    pass

Pass code and then simply replace specific function or variable.

1. tab key to automatically switch from the code sequence input to each pass, the reverse operation (a back pass) is shift + tab shortcut

2. pass called the empty statement / placeholder statement so that the code does not complain, you can fill in later.

3. The same block of code execution, other code will be executed, because the code is the same level

   Not recommended code is nested too many levels, it will affect the reading sense. Function may be used instead.

-------------------------------------------------------------------------------

 

 

Elif usage

elif expression:

Pass

 

 

That simplification reduces the appearance of nested wording

 

 

a = input () a resultant string type, which is a drawback of dynamic languages, where there is no error, it is strong for rotation

-------------------------------------------------------------------------------

-------------------------------------------------------------------------------

-------------------------------------------------------------------------------

 

 

W hile circulation and usage scenarios

More suitable for use in a recursive scenario

 

 

F or cycle

 

 

1.for mainly used to iterate / or cyclic sequence set dictionary.

2. printing lateral print (y, end = '' ) single quotes various characters may be spaced

3.for else loop again after execution else for complete traversal

4 out of the loop: break out force if the break (interrupt) is not executed else statements

a = [1,2,3]

for x in a:

    if x == 2:

        break

    print(x)

5. Skip cycle: Continue performs else statements

a = [1,2,3]

for x in a:

    if x == 2:

        continue

print(x)

 

 

for common errors jump out of circulation

 

 

Two for nesting inside the orange y = the first sublist out, but still the second tuple is traversed in the output element has a tuple

 

B reak out the internal circulation, but external circulation not bounce

 

 

 

 

How P the Y implementations for  (I = 0; I <= 10; I ++) {

} This statement

 

Range(start, start, step)

For x in range(0,10):

Print(x)

 

For x in range (0, 10 , 2): // each step is 2, corresponding to an interval of 2

Print(x)

 

Decreasing the number of columns of this output is 10 | 8 | 6 | 4 | 2 | 0

For x in range (0, 10 , -2): // represents from zero a total of ten digits, each step is 2, corresponding to an interval of 2

Print(x, end = ‘|’)

 

 

a=[1,2,3,4,5,6,7,8,]

for i in range(0,len(a),2):

    print(a[i],end='|')

Output 1 | 3 | 5 | 7

 

 

With a slice sequence to achieve:

b = a [0: only the (a): 2]

   print(b)

Output [1,3,5,7]

 

 

 

 

-------------------------------------------------------------------------------

-------------------------------------------------------------------------------

-------------------------------------------------------------------------------

 

 

 

 

 

Python organizational structure

 

 

import module name as the name of this syntax can solve the problem of excessive namespace.

如:import t.c7 as m print(m.a)

The I Mport entire module is introduced, from Import single variable introduced  

(1) introducing a variable from moudle import a, def

Does not require calling a namespace (moduel.a)

(2) * represents the variable introduced by batch

Control functions and variables can be referenced, as _all_ (built-in variable modules, built-in properties).

In the module defined in _all_

__all__ = [ 'a', 'c'] so that when the module from import *, other modules can only be introduced into a, c variables (module can be forced from forcibly introduced import b) from more flexible usage Import module can be introduced from the package

 

-init-.py usage

1. Code wrap is preferably a (), may also end with a backslash \

2.__init__.py role:

(1) When the module is introduced into the variable in the packet or packets when the file is automatically executed, and the package can also be used for initialization module

(2) can be defined in __init__.py __all__ variables may be defined in other modules which modules referenced in this packet (from package import *)

  (3) can be used to do batch import file __init__.py

  In sub-package module __init__.py file name needs to import, and then import the child on a treasure name, batch import module

Note: when referring to the attention of the namespace  sub-package name .def

3.__init__.py file name is the package name

 

 

 

 

Avoid circulation import

For example: direct cycle

P1.py

 

 

P2.py

 

 

Indirect cycle

In p1 import P2 , P2 introduced P3 , P3 introduced p1, a closed loop is formed

 

 

 

-------------------------------------------------------------------------------

-------------------------------------------------------------------------------

-------------------------------------------------------------------------------

 

 

 

 

Module built-in variables

info = dir ()

print(infos)

dir () built-in variables can be viewed , if want to see built-in variables specified module can be written in brackets need to write on the value of

1. __name__: the complete name of the module, the module includes a namespace name.

2. __package__: bag module located

3. __file__: full physical path of the file where the windows path

4. __doc__: annotation module described in the content

 

Py is not TRINOCULAR expression

 

 

 

 

 

 

 

Python common module must have a package, when you want to put an executable file to run as a common module, you can use the -m parameter

Such as  : python -m namespace (package) . Module name

Here is the c 15 as a module to run

As a general packet must have a run-time module as carrier

So space before retreated forward to look for the package . Module 

 

 

Add to

if __name__='__main__':

     pass

Meaning: the Make A both-importable Script and Executable ( let the script either as a common module be imported into other modules or as an executable module )

Action: determining whether the current module entry file

 

 

 

Absolute and relative imports import

 

1. Top package and import documents at the same level

2. (1) absolute path: from top-module package until this path, for example package2.package4.m2

   ( 2) the relative path: one path would then correspond to absolute relative path is the path in front of the module the module those bells and whistles folder name to be removed, the remaining light point

3. Absolute path at the entrance of the import file module or other modules can be used when you import the module, while the relative path can only be used when other modules import module, the relative path is used as follows: We import the module to an unknown m2 another ordinary m3 as an example of the module

(1) If the m3 and m2 in the same folder, then add a point

(2) if a higher than m2 m3, plus the two points, and so on

4. The ultimate rule: import module package must be below the top

 

 

 

 

 

 

 

 

Entrance files can be imported using an absolute path.

But may not use a relative path to import , the relative path to find the corresponding module is built-in module according to __name__ variable positioning, the file is executed __name__ inlet is not a so-called module name but is to be changed __main__ python, __main__ module does not exist, you can not use a relative path to import. If you want to import opposite is also possible, in the form of the module, the return module is a python -m demo.main

 

 

 

function

round (a, 2) function after a two decimal places

You can also perform the function of rounding

 

 

 

 

How to quickly learn how to function built-in functions

python --- help (round) Enter

Enter keystrokes can flip

import this print out the Zen of python

Function features:

1, functional

2, hide the details

3, avoid writing duplicate code, organization code

 

 

 

1, the structure of the function: def funcname (parameter_list), indent function body

1) parameter list can not;

2) the function body can return the results to return; if not the return key, and Python that the function returns a null value so None.

 

2, several features of the function:

After 1) function definition, we must call this function to work.

After 2) calls must be placed in the function definition, not before.

3) Default 995 recursive, beyond the error. Available import sys, sys.setrecursionlimit (1000000) to set the recursion; in fact reach millions of recursion.

4) defining a function or variable, and to avoid built-in functions of the same name Python.

 

 

 

 

How to make function returns multiple results

Behind the return statement will not be executed

def damage(skill1,skill2):

  damage1 = skill1*3

  damage2 = skill*2+8

   return damage1,damage2

 

damages = damage (3,6) //  a number indicating the result is a very bad habit

 

print(type(damages))

Good way is:

skill1_damage , skill2_damage=damage(3,6)

print(skill1_damage , skill2_damage)

Unpack the sequence: a meaningful variable names to the return value of the function

Chain sequence assignment and unpacking

What is the sequence unpacking

d = 1,2,3

a, b, c = d

print(a, b, c)

Unpack the sequence: A sequence according to which the number of disassembled into a number of elements to achieve the desired result of our process is called unpacking sequence

When unpacking the sequence, the number of variables and the number of values ​​must coincide

python multiple assignment mode

a = 1

b = 2

c = 3

 

a, b, c = 1, 2, 3

 

Chain assignment:

a = b = c = 1

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Parameters (key is to define the function call instead):

① must Parameters: Parameter list of functions must be defined assignment. It must be placed in front of the argument list.

② keyword arguments: the argument can be made clear that the reference is not necessarily the order in which the shape parameter passed in the function call. Such as:

def add(x, y):

    ...

    return result

c = add(y = 3, x = 2)

 

③ default parameters: the parameter is not set the default value of the argument must be passed.

 

 

Is the default parameters of gender and age and college years in advance to set a good

The default parameters and actual parameters can not be defined the same as their own

 

④ variable parameters. Such as:

def demo(*param):

    print(param)

    print(type(param))

demo(1,2,3,4,5)

The results are:

1,2,3,4,5

tuple type

That python automatically variable parameter argument converted to the corresponding tuple type.

 

variable parameter

 

 

Function 1) has defined a variable parameter: the parameter front brackets asterisk *

2) Python automatically corresponding to the variable parameter argument list be assembled into a tuple;

3) direct transmission when you call a tuple, the result returned is a two-dimensional tuple; if we are not forming a two-dimensional array can be used when calling *, it will tuple element tile passed to the function. At this time, * the role of tuples tile elements inside out, passed to the function;

4) The variable parameters can be combined with other types of parameters remember. As can be coupled when defining the parameters, but must be placed behind the variable parameter;

5) The function parameter is mandatory parameters, variable parameters, default parameters must be the last ; when the need to change the default parameter values must be assigned to a keyword parameter default parameters;

6) In view of this, the arguments in favor of such a complex design category .

 

 

 

Keyword variable parameters:

format:

 

 

def demo(**param):

    pass

So that when a plurality of keywords can pass call parameters, this time will be converted to the python dictionary type dict. If you not want to pass a dictionary into a multi-dimensional array, plus the time required to call **.

Tips:

Dictionary type data traversing method:

for key,value in param.items():

    print(key, ':', value)

 

 

 

The scope chain

1) Local variables are preferentially used in the scope;

2) local variable relative. The variable c = 2 in func1 () function is a local variable, but func2 () function, but it is the one it is therefore not local variables, may be func2 () is referenced;

3) layer by layer to find out stepwise variable definitions, like a chain, so there is scope chain properties;

4) If you are looking for loop variables to the body of the function, the scope chain count it? It is not. The reason is not a for loop scope, calling it part of the normal cycle of in vitro variable function in vivo behavior of variable call.

The scope chain step by step to find variables, but does not include a for loop

 

 

 

 

 

G lobal keyword

global keyword:

Action: internal variable reference function outside the function, i.e., the external variables into local variables can be referenced functions.

def demo():

     Global c

     c = 2

demo()

print(c)

ps: import module after import module can use global variables.

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/flowercatnice/p/11875606.html