Chapter III Python Basics

Source: Internet
Author: User

After spending more than one weeks watching "Learn Python's hard-to-go", you can only say that you have mastered fur, and today began to learn to see "core Python programming."

Also, share your own learning notes, push yourself, and motivate yourself.

  

3.1 Statements and syntax
There are some basic rules and special characters in the Python statement:
?? The pound sign (#) indicates that the following character is a Python comment
?? line break (\ n) is a standard line delimiter (usually one line of a statement)
?? backslash (\) to continue on line
?? Colon (:) separates the head and body of the code block
?? Statements (blocks of code) are expressed in the form of indented blocks
?? Different indentation depths separate different blocks of code
?? Python files are organized in a modular format

?? Semicolon (;) Connect two statements in one row

1 Print "  "  print  "  hiWorld"

?? backslash (\) to continue on line

Python statements, which are generally delimited by line breaks, that is, one statement at a line. A long line of statements can use a backslash
the bar (\) is decomposed into several lines, as in the following example:

if  and  = = 0): Send_goto_beach_mesg_to_pager ()

There are two exceptions to a statement that does not use backslashes or can span rows. When a closed operator is used, a single statement can
Spans multiple lines, for example: You can write multiple lines with parentheses, brackets, and curly braces. The other is the three quotation marks including the following words
String can also be written across lines.

3.2 Assigning values to variables

Note that the assignment does not directly assign a value to a variable, although you may have experience in other language programming that
This is the case. In the Python language, objects are passed by reference. When assigning a value, whether the object is newly created or
is an existing one that assigns a reference to the object (not a value) to the variable. If you're not 100% right now,
Clear the solution, do not worry. In the later part of this chapter, we will discuss this topic again, now you only need to have so????????????
a concept.

>>> x = 1
>>> y = (x = x + 1) # Assignments not expressions! File "<stdin>", line 1
y = (x = x + 1)
^
Syntaxerror:invalid syntax

Increment assignment hides the mathematical operation in the assignment process by using the assignment operator. If you have used C, C + + or
Java, you will find the following operators very familiar.
+= -= *= /= %= **=
<<= >>= &= ^= |=

"Multivariate" assignment
Another method of assigning multiple variables simultaneously is called multivariate Assignment (multuple). This is not the official Python technique.
We have built our own "mul-tuple" together. Because when you assign a value in this way, the object on either side of the equal sign
Are tuples (we say in section 2.8 that tuples are a Python basic data type).
>>> x, y, z = 1, 2, ' a string '

In the above example, two integer objects (values 1 and 2 respectively) and a string object are assigned to
x, y, and Z. Usually tuples need to be enclosed in parentheses (parentheses), although they are optional. We recommend always adding
Parentheses to make your code more readable.
>>> (x, y, Z) = (1, 2, ' a string ')

In the above C code fragment, the values of the variable x and the variable y are exchanged with each other. The TEMP variable, TMP, is used to assign Y
Save the value of x before the value to X. After assigning the value of Y to X, you can assign the value of x saved in the TMP variable to Y.
Python's multivariate assignment allows the value of two variables to be exchanged without the need for an intermediate variable.
# Swapping variables in Python
>>> x, y = 1, 2
>>> x
1
>>> y
2
>>> x, y = y, X
>>> x
2
>>> y
1
It is clear that Python has already computed the new values for x and y prior to assigning values.

3.3.4 Dedicated underscore identifier
PYTHON specifies special variables with underscores as variable prefixes and suffixes. Later, we will find that, for the program, its
Some of the variables are very useful, while others are unknown or useless. Here's a special usage of the underline in Python
Made a summary:

?? _xxx no ' from module import * ' Import
?? __xxx__ System Definition Name
?? Private variable names in the __xxx class
Core style: Avoid using underscores as the start of variable names
Because underscores have special meanings for the interpreter and are symbols used by built-in identifiers, we recommend that programmers avoid
Avoid underlining as the start of a variable name. In general, the variable name _xxx is considered "private" and not in a module or class outside
can be used. When a variable is private, it is good practice to use _xxx to represent variables. Because the variable name __xxx__
Python has a special meaning, which should be avoided for common variables.

Indent in
Because indentation alignment plays a very important role, you have to consider what indentation style makes the code easy to read. In the selection
Common sense also plays a big role in you want empty lattice numbers.
1 or 2 may not be enough, it's hard to determine which block the code statement belongs to
8 to 10 may be too many, and if the code is embedded in too many layers, it makes the code difficult to read. The four spaces are very
Popular, not to mention the creators of Python support this style. Five and six are not bad, but the text editor is usually not
Such a setting, so it is not often used. Three and seven are border conditions.

When using Tab tab, keep in mind that different text editors do not have the same settings. Recommend that you do not
With tab, if your code exists and runs on a different platform, or it is opened with a different text editor, push
I recommend you not to use tab.

3.5 Memory Management
So far, you've seen a lot of examples of Python code. Our topic in this section is variable and memory management
Details, including:
?? variable without prior declaration
?? Variable does not need to specify type
?? Programmers don't care about memory management
?? Variable names are "recycled"
?? Del statement can release resources directly

3.5.1 Variable definition
In most compiled languages, variables must be declared before they are used, and the C language is more demanding: the variable declaration must be bit
At the beginning of the code block and before any other statements. Other languages, like C + + and Java, allow "anywhere" to declare
variables, such as variable declarations, can be in the middle of a block of code, but must still declare the name of the variable before the variable is used and
Type. In Python, such explicit variable declaration statements are not required, and variables are declared automatically the first time they are assigned. and other large
In most languages, variables are created and assigned only to be used.

3.5.4 Reference count
To keep track of objects in memory, Python uses the simple technique of reference counting. In other words, Python internal
Records how many references each object in use has. You can think of it as a poker game "Blackjack" or "21 points."
An internal tracking variable, called a reference counter. As to how many references each object has, referred to as the reference count. When
When the object is created, a reference count is created when the object is no longer needed, that is, the object's
The reference count becomes 0 o'clock, and it is garbage collected. (Strictly speaking this is not 100% correct, but at this stage you can just
Think
Increase reference count

When an object is created and assigned to a variable (referencing it), the object's reference count is set to 1.
When the same object (a reference) is assigned to another variable, or passed as a parameter to a function, a method or class instance
, or is assigned a member of a Window object, a new reference to the object, or an alias, is created
(The reference count for the object is automatically added to 1).
Figure 3–2 the same object with two references
Take a look at the following statement:
x = 3.14
y = X
The statement x=3.14 creates a floating-point number object and assigns its reference to X. X is the first reference, so the
The reference count of the object is set to 1. Statement Y=x creates an alias y that points to the same object (see Figure 3-2). Thing
Instead of creating a new object for Y, the reference count of the object is incremented 1 times (2). This is the object
One of the ways to increase the reference count. There are other ways to increase the object's reference count, such as the object as a parameter
Number is called by a function or when the object is added to a container object.

In summary, the object's reference count
?? Object is created
x = 3.14
?? Or a different alias is created
y = X
?? Or passed as a parameter to a function (new local reference)
Foobar (x)

?? or become an element of a container object
MyList = [123, X, ' XYZ ']
Let's take a look at how the reference count gets less.
Reduce reference count
When a reference to an object is destroyed, the reference count is reduced. The most obvious example is when a reference leaves its scope,
This situation most often occurs at the end of the function run, all local variables are automatically destroyed, the object's reference count will be
The reduction.
When a variable is assigned to another object, the reference count of the original object is automatically reduced by 1:
foo = ' xyz '
bar = Foo
Foo = 123
When the string object "XYZ" is created and assigned to Foo, its reference count is 1. When an alias bar is added
, the reference count becomes 2. However, when Foo is re-assigned to the integer object 123, the reference count of the XYZ object is from
Minus 1 and turned 1 again.
Other ways to reduce the reference count of objects include using the DEL statement to delete a variable (see the next section), or
When an object is moved out of a Window object (or the reference count of the container object itself becomes 0 o'clock). To summarize,
The reference count for an object is reduced in the following cases:

The reference leaves its scope. such as Foobar () (see previous example) at the end of the function.
?? The alias of the object is explicitly destroyed.
Del y # or del x
?? An alias of an object is assigned to another object
x = 123
?? object is removed from a Window object
Mylist.remove (x)
?? The Window object itself is destroyed
Del myList # or goes Out-of-scope

Del statement
The Del statement deletes a reference to the object whose syntax is:
Del obj1[, obj2[,... Objn]]
For example, executing del y in the previous example produces two results:
?? Remove Y from the current namespace
?? The reference count of X minus one
In one step, executing del x deletes the last reference to the object, which means that the reference count of the object is reduced to
0, which causes the object to be "unreachable" or "unreachable" from this point. From this point on, the object becomes a garbage collection
The recovered object of the mechanism. Note that any trace or debug program adds an additional reference to an object, which delays the
The time that the object was reclaimed.

  

Chapter III Python Basics

Related Article

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.