Python Learning notes (i)

Source: Internet
Author: User

This Python record is a bit messy, it is recorded in the electronic file when the data.

1. The biggest difference between learning Python and other languages is that Python's code block does not use curly braces ({}) to control classes, functions, and other logical judgments. Python's most distinctive feature is the use of indentation to write modules.

The amount of whitespace to indent is variable, but all code block statements must contain the same amount of indentation whitespace, which must be strictly enforced

2. In Python statements, the new line is generally used as the Terminator for the statement. However, you can use a slash (\) to divide a line of statements into multiple lines of display, but you do not need to use a multiline connector if you include [], {}, or () parentheses.

3. Python receives single quotation marks ('), double quotation marks ("), and three quotation marks (" ' "" ") to denote the string, the beginning and end of the quotation mark must be the same type. Where three quotation marks can be made up of multiple lines, the shortcut syntax for writing multiple lines of text

4, note using #, there is a special note of the document string. You can add a string to the beginning of a module, class, or function to function as an online document. Unlike regular annotations, a document string can be accessed at run time, or it can be used to automatically generate documents.

5. Variables in Python do not need to be declared, and the assignment of variables is not only the process of declaring and defining variables. Each variable is created in memory and includes information about the identity, name, and data of the variable. A value must be assigned before it is used, and the variable will not be created until the variable is assigned.

6, you can specify multiple variables for multiple objects: A, B, C = 1, 2, "John" is about 1 assigned to a,2 assigned to B,john c.

7. Python has five standard data types :

    • numbers (number): int  long (L)  float complex

    • string (String) the list of strings:p Ython has 2 order of values: starting from left to right index default 0, maximum range is 1 of string length, right-to-left index default-1, the maximum range is the beginning of the string. + is the string join operator, the asterisk (*) is a repeat operation (print str*2 output two str); [:] means part of the truncated string

    • list (list): list = [' ABCD ', 786, 2.23, ' John ', 70.2] lists can accomplish the data structure implementation of most collection classes. It supports characters, numbers, and even strings that can contain lists (so-called nesting).

    • tuple (tuple): with "()" identification. The inner elements are separated by commas. However, the element can not be assigned two times (cannot be modified or deleted), equivalent to a read-only list, only one element should be left with a comma a= (1,); You can use Del to delete the entire meta-ancestor

    • dictionary (dictionary): identified by the "{}", consisting of the index (key) and its corresponding value. struct-like JSON

List : is an ordered object combination, and the dictionary is a collection of unordered objects. The difference between the two is that the elements in the dictionary are accessed by keys, not by offsets.

After Python creates the object, the data type is not allowed to change, only del var1,var2 can be used to delete multiple objects.

Dictionary : A dictionary value can take any Python object without restriction, either as a standard object or as a user-defined one, but not a key. The same key is not allowed to appear two times. When created, if the same key is assigned two times, the latter value is remembered, the key must be immutable, can be used as a number, a string or a tuple, but not a list.

Python arithmetic operators

* *: Power operation 2**3=8

: Returns the integer part of the quotient of the integer 9.0//2.0=4.0

And: (A and B) returns true, similar to having or and not

In: Member operator x in Y if x is in Y, then true,not in is represented as x not in Y how true

is: The identity operator is to determine whether two identifiers are references from an object (return result 1), is not to determine whether a two identifier is referenced from a different object

Python Process Control

1. If judgment condition:

Execute statement ...

else: (Elif judgment Condition:)

Execute statement ...

Python does not support switch statements, so multiple criteria can be judged only by elif, and if you want multiple conditions to be judged simultaneously, use or OR and

2. While judging condition:

Execute statement ...

Else

In Python, for ... else means that the statement in for is no different from normal, while the statement in else is executed when the loop is executed normally (that is, for not breaking out by break), while ... else is the same. While can iterate over nested

3, for Itareting_var in sequence

Statement (s)

Python functions

    • The function code block begins with a def keyword followed by the function identifier name and parentheses ().

    • Any incoming parameters and arguments must be placed in the middle of the parentheses. Parentheses can be used to define parameters.

    • The first line of the function statement can optionally use the document string-for storing the function description.

    • The function contents begin with a colon and are indented.

    • Return[expression] End Function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.

    • Define an empty function that does nothing and can use the PASS statement

    • Function put back multi-value, is actually a tuple:x,y=myfun () = = R=myfun (), r= (x, y)

def functionname (parameters):   "Function _ Document String"   function_suite   return [expression]

All parameters (independent variables) are passed by reference in Python. If you modify the parameters in the function, the original parameters are changed in the function that called the function.

Default Parameters :

First define a function, pass in a list, add an end and return:

def add_end (l=[]):

L.append (' END ')

Return L

When you call normally, the result looks good:

>>> Add_end ([1, 2, 3])

[1, 2, 3, ' END ']

>>> add_end ([' X ', ' y ', ' z '])

[' x ', ' y ', ' z ', ' END ']

When you use the default parameter call, the result is also right at the beginning:

>>> Add_end ()

[' END ']

However, when you call Add_end () again, the result is incorrect:

>>> Add_end ()

[' End ', ' end ']

>>> Add_end ()

[' End ', ' End ', ' end ']

Many beginners are puzzled, the default parameter is [], but the function seems to "remember" the last time the "END" after the list.

The reasons are explained as follows:

When the Python function is defined, the value of the default parameter L is computed, that is, [] because the default parameter, L, is also a variable, which points to the object [], each time the function is called, if the content of L is changed, the contents of the default parameter will change the next time the function definition is no longer [].

So, one thing to keep in mind when defining default parameters: The default parameter must point to the immutable object!

To modify the above example, we can use the none of the immutable object to achieve:

def add_end (L=none):

If L is None:

L = []

L.append (' END ')

Return L

Now, no matter how many times it is called, there is no problem:

>>> Add_end ()

[' END ']

>>> Add_end ()

[' END ']

Why design an immutable object such as Str and none? Since immutable objects are created, the data inside the object cannot be modified, which reduces the error caused by modifying the data. In addition, because the object is not changed, the simultaneous reading of objects in a multitasking environment does not require locking, while reading a little bit of a problem. When we are writing a program, if we can design a constant object, we try to design it as an immutable object.

variable Parameters :

The number of arguments is not sure, you can put a,b,c ... Passed in as a list or tuple, the function is defined as follows:

def calc (numbers):

For I in numbers:

In the call, you need to assemble a list or tuple first:

>>> Calc ([1, 2, 3])

If a variable argument is used, the parameter of the function is changed to a mutable parameter:

Def calc (*numbers):

For N in numbers:

The way the function is called can be simplified into this:

>>> Calc (1, 2, 3)

When you define a mutable parameter and define a list or tuple parameter, just precede the parameter with an * number. Inside the function, the parameter numbers receives a tuple, so the function code is completely unchanged. However, when you call the function, you can pass in any parameter, including 0 parameters: Calc ()

What if you have a list or a tuple and you want to invoke a mutable parameter? You can do this:

>>> nums = [1, 2, 3]

>>> Calc (nums[0], nums[1], nums[2])

However, this is too cumbersome, you can precede the list or tuple with an * number, the list or tuple elements into a variable parameter to pass in:

>>> nums = [1, 2, 3]

>>> Calc (*nums)

keyword Parameters :

The keyword parameter allows you to pass in 0 or any parameter with parameter names that are automatically assembled inside the function as a dict.

def person (name, age, **kw):

The function person accepts the keyword parameter kw, in addition to the required parameter name and age. When you call this function, you can pass in only the required parameters:

>>> person (' Michael ', 30)

You can also pass in any number of keyword parameters:

>>> person (' Bob ', city= ' Beijing ')

Keyword parameters can extend the functionality of a function. For example, in the person function, you can guarantee that you can receive both the name and the age parameters, but the function can receive if the caller is willing to provide more arguments. Imagine a user registration function, in addition to user name and age is required, the other is optional, using the keyword parameters to define this function can meet the requirements of registration.

You can also assemble a dict, and then convert the dict into a keyword parameter:

>>> kw = {' City ': ' Beijing ', ' job ': ' Engineer '}

>>> person (' Jack ', "city=kw[' City '), job=kw[' job ') or person (' Jack ', ' **kw ')

parameter Combinations :

Combine the above three parameter combinations: def func (A, B, c=0, *args, **kw): The interpreter automatically passes the corresponding parameters according to the parameter position and argument name

So, for any function, it can be called by the form of a func (*args, **kw), regardless of how its arguments are defined.

anonymous functions : Lambda Lambda [arg1 [, Arg2, .... argn]: expression

Use lambda keywords to create small anonymous functions. This function is named after the standard procedure for declaring a function with DEF is omitted.

    • A lambda function can receive any number of arguments but can only return the value of an expression, and can only contain commands or multiple expressions.

    • Anonymous functions cannot call print directly, because lambda requires an expression.

    • The lambda function has its own namespace and cannot access parameters outside its own argument list or in the global namespace.

    • Although the lambda function appears to be only a single line, it is not equivalent to a C or C + + inline function, which is designed to call small functions without consuming stack memory to increase operational efficiency.

The module is a python file, and you can use the functions in the module only if you import the imported modules. When the interpreter encounters an import statement, the module is imported if it is in the current search path.

From ModName import funcname1,funcname2 .... Import a specific function in a module.

The module search path is stored in the Sys.path variable of the system module. The variable contains the current directory, PYTHONPATH (which is the path to Lib in Python) and the default directory that is determined by the installation process.

a A Python expression can access variables in the local namespace and in the global namespace. If a local variable and a global variable have the same name, the local variable overrides the global variable.

Name space

Each function has its own namespace. The scope rules of a method of a class are the same as the usual functions.

Python intelligently guesses whether a variable is local or global, and assumes that any variable that is assigned within the function is local.

Therefore, if you want to assign a value to a global variable in a function, you must use the global statement.

The expression for global varname tells Python that VarName is a global variable so that Python does not look for the variable in the local namespace.

a=0;

def sum ():

Global a #若将其注释掉将出现错误 unboundlocalerror:local variable ' a ' referenced before assignment

A +=1

Print a

Package

A package is a hierarchical directory structure, for example, you want to have three a1.py,a2.py,a3.py under the A folder. You can create a __init__.py file under a, and then use the imported statements that appear,

Import A1 from A1; Import A2 from A2;  Import A3 from A3;  These classes are all available when you import a package, import a; A.A1 (); This is how the package is used.

File I/O

RAW_INPUT (hint) function reads a line from the standard input and returns a string (minus the end of the line break)

The input (hint) function and the raw_input (hint) function are basically interchangeable, but input assumes that your input is a valid Python expression and returns the result of the operation.

Open (filename,mode,buffering): Opening a file

The write () method writes any string to an open file and does not add a newline character (' \ n ') at the end of the string.

The Read () method reads a string from an open file.

The tell () method tells you the current position within the file, in other words, the next read and write occurs after so many bytes at the beginning of the file:

The Seek (offset [, from]) method changes the position of the current file. The offset variable represents the number of bytes to move. The from variable specifies the reference position at which to begin moving bytes.

Object oriented

Data hiding in Python is very simple, do not need to add a keyword in front, as long as the class variable name or member function before adding two underscore the function of data hiding, so, for the class instance, its variable name and member function is not used, for its class inheritance class, is also hidden, so , its inheriting class can define its exact variable name or member function name without causing a naming conflict. Python does not allow instantiated classes to access hidden data, but you can use Object._classname__attrname to access properties.

The reference is on-line information

Python Learning notes (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.