Python Learning notes (11)-syntax requirements (indentation, identifiers, variables)

Source: Internet
Author: User

Title of this node
1. Grammar Requirements
1.1. Indentation Specification
1.2. Variable Identifier specification
2. variables
2.1, the assignment of the variable is stored in the memory space, and then from the memory space to obtain
2.2, variable assignment, If the variable name in memory does not have to be equal to the assignment of a new variable, if the variable name is already in memory, it is re-overwrite the variable
2.3, the assignment of the variable is to the memory address, the variable 1 assignment variable 2, the variable 1 is re-assigned value does not change the value of the variable 2, because the variable 1 is re-assigned after the memory address changes, and no re-assigned variable 2 memory address Unchanged.
2.4. View the memory address of the variable, ID ()
2.5, python virtual machine to deal with the operating system, it is optimized for python, if the variable is assigned to 0-255 (python2.7 is actually -5~256) one of the numbers, then the same number of variables all point to the same memory space, to avoid wasting memory
2.6, multi-word splicing variable name style specification
2.7. assigning values to multiple variables
2.8. references to variables
2.9. multi-variable Reference


=============================================================================================================== =========

1. Grammar Requirements

1.1. Indentation Specification

Indent unity, space, tab, etc., try to use One. (four Spaces officially Recommended)
Flow control statement body to be indented, non-indented is parsed into a non-process-controlled statement body.

Example 1:
No indentation error:
#coding: Utf-8
A=1
b=2
if(b>=a):
Print"7, B is greater than or equal to a"
Else:
Print"7, B is less than a"

Run Result: (statement body does not indent will Error)
[email protected] script]# python bijiaoyunsuanfu.py
File "bijiaoyunsuanfu.py", Line 42
Print "7, B is greater than or equal to a"
^
Indentationerror:expected an indented block (indent one Piece)

Correct as Follows:
If (b>=a):
Print "7, B is greater than or equal to a"-at least one space or tab indent
Else
Print "7, b less than a"

More than a few spaces will be an error, pay attention!
--------------------------------------------------------------------------------------------------------------- -------------------------------
Example 2:
Name = Raw_input ("please Input your name:")
ifName = =' Alex ':
Print"he is the Python teacher."
Print"haha"
Print"xixi"

Run result 1: (a statement that is not indented will not be parsed into the statement body of the process structure, and no indent statement appears when the IF process has ended)
Please input your NAME:QQ
Qq
Xixi

Run result 2: (the indented statement will be parsed into the statement body of the process structure, the execution of the condition is fulfilled, and the execution of the statement body of the process structure continues to run down the other statements of the Program)
Please input your Name:alex
He is the Python teacher.
haha
Xixi
--------------------------------------------------------------------------------------------------------------- -------------------------------
Example 3:
Name = Raw_input ("please Input your name:")
ifName = =' Alex ':
Print"he is the Python teacher."
Print"haha"
Print"xixi"

Run Result: (the Indentation of the process statement body is not uniform will also error)
[email protected] ~]# python/root/xwr/my_python/script/node1/user_interactive.py
File "/root/xwr/my_python/script/node1/user_interactive.py", Line 9
Print "haha"
^
Indentationerror:unindent does not match no outer indentation level
--------------------------------------------------------------------------------------------------------------- -------------------------------
Example 4:
#coding: Utf-8
A=1
b=2
if(b>=a):
Print"7, B is greater than or equal to a"
Else:
Print"7, B is less than a"

Run Result: (if the statement body and else under the statement body is not the same layer, indentation is inconsistent, but it is recommended to indent as much as Possible)
7, B is greater than or equal to a

1.2. Variable Identifier specification

? The first character of an identifier must be a letter in the alphabet (uppercase or Lowercase) or an underscore (' _ ')
? Other parts of the identifier name can consist of a letter (uppercase or lowercase), an underscore (' _ '), or a number (0-9).
? The identifier name is Case-sensitive. For example, MyName and myname are not an identifier. Notice the lowercase n in the former and the uppercase N in the Latter.
? Identifier name cannot be a keyword, such as import, class, break, if, while and so on, with no error, but when the use of the keyword when the error, by your variables washed away the original keyword
? Examples of valid identifier names are i, __my_name, name_23, and a1b2_c3.
? Examples of invalid identifier names are 2things, this was spaced out, and My-name.

2. Variables

2.1, the assignment of the variable is stored in the memory space, and then from the memory space to obtain

The value that the variable is stored in Memory. This means that there is a space in memory when creating Variables.
Based on the data type of the variable, the interpreter allocates the specified memory and determines what data can be stored in memory.
therefore, variables can specify different data types, which can store integers, decimals, or Characters.

>>> name = "Zha"
>>> Name
' Zha '
>>>

2.2, Variable assignment, If the variable name in memory does not have to be equal to the assignment of a new variable, if the variable name is already in memory, it is re-overwrite the variable
>>> name = "Zha"
>>> Name
' Zha '
>>> name = "Zhong Yi"
>>> Name
' Zhong Yi '
>>>

2.3, the assignment of the variable is to the memory address, the variable 1 assignment variable 2, the variable 1 is re-assigned value does not change the value of the variable 2, because the variable 1 is re-assigned after the memory address changes, and no re-assigned variable 2 memory address Unchanged.
>>> name = "Zhong Yi"
>>> Name
' Zhong Yi '
>>> name2 = Name
>>> name2
' Zhong Yi '
>>> name = "jigongtou"
>>> Name
' Jigongtou '
>>> name2
' Zhong Yi '
>>>

2.4. View the memory address of the variable, ID ()
Example 1:
>>> ID (name)
140514571357472
>>> ID (name2)
140514571357520
>>> ID (name), ID (name2)
(140514571357472, 140514571357520)
>>>

Example 2:
>>> A = 10
>>> B = A
>>> ID (a), ID (b)
(29024400, 29024400)
>>>




Example 3:
Sometimes a fully independent variable assigns the same value, storing the memory address, and no additional memory space is opened
>>> A = 10
>>> B = A
>>> ID (a), ID (b)
(29024400, 29024400)
>>> C = 10
>>> ID (a), ID (b), ID (c)
(29024400, 29024400, 29024400)
>>>

2.5, python virtual machine to deal with the operating system, it is optimized for python, if the variable is assigned to 0-255 (python2.7 is actually -5~256) one of the numbers, then the same number of variables all point to the same memory space, to avoid wasting memory
>>> a =-6
>>> B = A
>>> C =-6
>>> ID (a), ID (b), ID (c)
(30048416, 30048416, 30048224)-------different
>>> del a,b,c
>>>
>>> a =-5
>>> B = A
>>> C =-5
>>> ID (a), ID (b), ID (c)
(29024760, 29024760, 29024760)--------same
>>> del a,b,c
>>>
>>> A = 256
>>> B = A
>>> C = 256
>>> ID (a), ID (b), ID (c)
(29030448, 29030448, 29030448)--------same
>>> del a,b,c
>>>
>>> A = 257
>>> B = A
>>> C = 257
>>> ID (a), ID (b), ID (c)
(30048224, 30048224, 30048392)-------different

2.6, multi-word splicing variable name style specification
>>> Eric_gf_name = "Erin"--recommendations
>>> Ericfgname = "Eric"--not recommended because the class name is also capitalized, which distinguishes
>>> Ericgfname = "Eric"--suggest
Style to unify, can not code for a moment with a style variable name, for a while for another variable name

2.7. assigning values to multiple variables
Python allows you to assign values to multiple variables at the same time. For example:
A = b = c = 1
The above example creates an integer object with a value of 1 and three variables allocated to the same memory space.
>>> a=b=c=1
>>> A,b,c
(1, 1, 1)
>>>

You can also specify multiple variables for multiple objects. For example:
a, b, C = 1, 2, "john"
For the above example, two integer objects 1 and 2 are assigned to variables a and b, and the string object "john" is assigned to variable C.
>>> a,b,c=1,2, "john"
>>> A,b,c
(1, 2, ' John ')
>>>


2.8. references to python2.x variables
The variable connects the object to itself (the pointer joins the object space), which is the Reference. When the reference is complete, the assignment is Realized.


% operator +% variable name used together to reference variable, operator of more type variablerefer to the section "data type/string/string formatting (% operator)"

>>> name = ' Alex '
>>> print "" "Welcome to Python,
...
... I am%s
... good bye.
... "" "%name
Welcome to Python,

I am Alex
Good Bye.

>>>

>>> age = 1
>>> print ' I am%d year old '%age
I am 1 year old



2.9, python2.x multi-variable Reference
>>> name = "Alex"
>>> Age = 18
>>> print "%s is%d years old."% (name,age)
Alex is years Old.
>>>

2.10. references to python3.x variables
(we'll Talk about string formatting (format () Function) later, this node skips)
Since python2.6, a new function Str.format () that formats the string has been added to the Power. so, What's the advantage of being compared to the previous% format string? Let us uncover the veil of its shy.
Grammar
It replaces% with {} And:.
Map sample
By location
In [1]: ' {0},{1} '. format (' kzc ', 18)
Out[1]: ' kzc,18 '
In [2]: ' {},{} '. format (' kzc ', 18)
Out[2]: ' kzc,18 '
In [3]: ' {1},{0},{1} '. format (' kzc ', 18)
Out[3]: ' 18,kzc,18 '
The Format function of the string can accept an unlimited number of parameters, the position can be out of order, can not be used or multiple times, but 2.6 can not be empty {},2.7.
--------------------------------------
by keyword parameter
In [5]: ' {name},{age} '. format (age=18,name= ' Kzc ')
Out[5]: ' kzc,18 '
--------------------------------------
Through object properties
Class Person:
def __init__ (self,name,age):
Self.name,self.age = Name,age
def __str__ (self):
Return ' This guy was {self.name},is {self.age} old '. format (self=self)

In [2]: str (person (' kzc ', 18))
Out[2]: ' This guy is Kzc,is
--------------------------------------
by subscript
In [7]: p=[' kzc ', 18]
In [8]: ' {0[0]},{0[1]} '. format (p)
Out[8]: ' kzc,18 '
With these convenient "mapping" methods, we have a lazy weapon. Basic Python knowledge tells us that list and tuple can be "broken" into normal parameters to the function, and dict can be broken into the keyword parameters to the function (through and *). So you can easily pass a list/tuple/dict to the format Function. Very flexible.
--------------------------------------
Format qualifier
It has a rich "format qualifier" (syntax is {} with:), such as:
Fill and align
Padding is used in conjunction with alignment
^, <, > center, align left, right, back with width
: The fill character after the number, only one character, not specified by default is filled with a space
Like what
In []: ' {: >8} '. format (' 189 ')
Out[15]: ' 189 '
In [+]: ' {: 0>8} '. format (' 189 ')
Out[16]: ' 00000189 '
In [+]: ' {: a>8} '. format (' 189 ')
Out[17]: ' aaaaa189 '
--------------------------------------
Accuracy and type F
Accuracy is often used in conjunction with Type F
In []: ' {:. 2f} '. format (321.33345)
Out[44]: ' 321.33 '
Where. 2 represents a precision of 2 length, and F represents a float type.
--------------------------------------
Other types
Mainly in the system, b, d, o, x are binary, decimal, octal, hexadecimal.
In [+]: ' {: b} '. format (17)
Out[54]: ' 10001 '
In []: ' {:d} '. format (17)
Out[55]: ' 17 '
In [+]: ' {: o} '. format (17)
Out[56]: ' + ' in []: ' {: x} '. format (out[57]: ' 11 '
--------------------------------------
use, The number can also be used to make the amount of thousands separator.
In [+]: ' {:,} '. format (1234567890)
Out[47]: ' 1,234,567,890 '













Python Learning notes (11)-syntax requirements (indentation, identifiers, variables)

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.