A, Python Introduction
Python is an interpreted, object-oriented, dynamic data type of high-level programming language, Python Guido van Rossum by the invention at the end of 1989, the first public release was released in 1991, the same language like Perl, Python source code is likewise follow GPL (GNU General Public License) protocol.
Version 3.0 of ython, often referred to as Python 3000, or simply Py3k, relative to earlier versions of Python, which is a major upgrade, in order not to bring too much burden, Python 3.0 is not considered in the design down compatible.
Python installation:
Download Python installer:
https://www.python.org/ftp/python/2.7.14/python-2.7.14rc1.amd64.msi
download python, be sure to download the corresponding own version of the system
Pip
And yum, apt-get the same, from the server to automatically install python library
comes in python linux system, but there is no program pip, ubuntu use sudo apt install python-pip or python3-pip (yum install pip)
editor
sublime text
pycharm
Chinese garbled solve
garbled python script, the script in python front plus
#coding:utf-8
Adjust the windows command line garbled
chcp 65001
Second, identify the indentation
Note
Note the use of single-line # beginning python
python multi-line comments using three single quotation marks ( '' '), or three double quotation marks ( "" ")
in the preparation of python program, preferably written comment, easy to modify the code, debugging
Identification (variable)
Identification (variable) naming rules
1. In Python, identified by letters, numbers and underscores
2. In Python, all identifiers may include English, numbers and underscores (_), but not starting with a digit
3.Python identifier is case sensitive write
4. underscore to the beginning of the identifier is of special significance. _Foo begin single underline represent can not directly access the class attributes, class provides the interface through the access, can not be introduced from xxx import *
The private member starts with a double underscore __foo representative of the class; double-underlined __foo__ representative of the beginning and end of the Python in particular specific identification method, such as __init __ () constructor class representatives
Identifiers and can not retain the same name when 6. Name
Python保留标识符:
and exec not assert finally or break for pass class from print continue global raise def if return del import elif in while else is with except lambda yield
Logo indentation
Learning Python and the biggest difference is in other languages, the Python code blocks without using braces {} class controlled, functions, and other logic determination, is to use the most characteristic Python indentation (space) to write modules indented blank the number is variable, but all of the code block statement must contain the same number of spaces to indent, this must be strictly enforced.
Python statements generally a newline character to the end of the statement, but we can use the slash (\) line will be divided into multiple lines of statements
Python can use multiple statements on the same line, use a semicolon between the statements ( ;) segmentation, different rows do not need to write a semicolon
Third, input and output
Export
print
outputting content
print,
outputting content and does not wrap
print type ()
Output Data Type
Entry
the raw_input
Python use this function receives the contents of the command line (interactive)
Fourth, data types
numbers (Digital)
Int (signed integer)
A = 100
a float (float)
B = 1.29
Long (Long [may also represent octal and hexadecimal])
C = 111111111111111111111111
Complex (plural)
D = + 2J. 1
string (string)
definition
Single line : str = "sadasd"
Multi-line:
str1 = '' '
12 is
34 is
' ''
Subscript
The default start index 0 from left to right, the maximum range is a little string length
from right to left at -1 default index, the maximum range of the beginning of the string
slice
Cut for data (numeric character string extracted) by the variable name
print str [0: 3: 2 ]
the first index number is which starts from the second number is the index at the end of which, the third number is the step (a taken every few number)
CRUD
Increase (string concatenation)
using stitching +
Note: not possible to assemble different types, such as strings and numbers, the numbers required function str cast string, or formatted using
puncturing
del, recommended slicing
Change
before a string of str name
str.strip ()
to remove the spaces on both sides, if the specified character is to remove the specified character
str.lstrip ()
to remove spaces left, if the specified character is to remove the specified character
str.rstrip ()
to remove the right of spaces, if the specified character is to remove the specified character
Charles
str ago. A string name
str.find ()
to find the string from the beginning to the index to find the first occurrence of the return position, did not find returns -1
str.rfind ()
to find the string from end to subscript, find returns the position of the first occurrence (number from the beginning), did not find returns -1
Escapes
format
Specific format specifier
Python supports formatted string, although this can include complex expressions, the most basic usage is to insert a value into a string format character string% s
Formatting symbols:
use:
Inserting a single
print "Sada Sada% s"% "Ada"
inserting a plurality of
print "This is the% s% d"% (str4,555 )
using variables may be entered directly
format () function formats Format
Python2.6 started, a new function of formatting str.format string (), which enhances the function of a formatted string, through the basic syntax (} and: instead of the previous%, format function can accept Any parameter, the position may not be in sequence.
Use:
1. Do not set the specified location, default order
print "Ada extranet} {} {" the format ( "22 is", "asdas").
2. designated position (zero)
print "Ada external network {{1} 0} ". format (" 22 "," asdas ")
may be used variables may be entered directly
list (list)
Introduction
List (list) is the most frequently used Python data types
list can most complete set of data structures class implementation that supports the characters, numbers, strings may even contain a list (ie, nested).
List with [] identified python is the most common complex data type
a = ['fff', 2434, ['erwr', 242 ] ]
slice
The first value taken from a specified location to another specified location intermediate
sublist = list1[0:3]
print sublist
Extract the specified value of the location
print list1[2]
List CRUD
By:
the append ()
additional elements after list1
list1.append(1)
print list1
insert ()
Append the specified position of the element after the list1
list1.insert(1,'b')
print list1
extend ()
is added to another array behind a list1
list2=[5,5]
list1.extend(list2)
print list1
Delete:
del List1 []
Delete the value specified position
del list1[0]
print list1
list1.pop ()
to delete the last value
list1.pop()
print list1
list1.remove ()
to delete the first specified value
list1.remove(1)
print list1
Change: =
Direct assignment corresponding position
list1[2]=10
print list1
Check
in
to determine whether the elements in the list
print 9 in list1
print 2 in list1
tuple (tuple)
Introduction
Tuple is another data type, similar List (lists), tuples with "()" identifies the internal element with a comma, but not the second tuple assignment corresponding to read-only list
in addition to modifying data, use of other with a list of list
dictionary (dictionary)
Introduction
Dictionary (dictionary) python is in addition to being outside the list of the most flexible type of built-in data structures, combined with the object list is ordered, dictionaries are unordered collections of objects.
The difference between the two is that: among the elements of the dictionary is accessed by a key, rather than by offsetting the accessing
dictionary as "{}" identified by the Dictionary index (key) value and a value corresponding to its composition
dict = {"name":"lp","age":"24"}
Dictionary key requirements
do not allow the same key appears twice. When you create is assigned if the same key twice, the value will be remembered for a
key to be immutable, so you can use numbers, strings, or act as a tuple, so the list will not work with
Value Added
dict = {"name":"lp","age":"24"}
dict["a"]="bbb"
Fifth, operators
Arithmetic Operators
Suppose the following variables: A = 10, B = 20 is:
+
two objects are added
a + b output 30
-
obtained by subtracting a negative number or a number of other
a- b output -10
*
multiply two numbers or If a return is repeated thousand string
a * b output 200 is
/
x is divided by y
B / a output results 2
%
return of the remainder of the division
b% a 0 output
**
return power of y x
a ** b is 10 to the power 20, the output 1000000000000000000
//
take divisible - returns the quotient of an integer part
9 // 2 output 4, output 4.0 2.0 9.0 @
Comparison Operators
The following is assumed as 10 variables a, variable b is 20:
==
equal to - if the comparison is equal to
(a == b) returns False
! =
Not equal to - compare two objects are not equal
(! A = b) returns to true
<>
is not equal to - compare two objects are not equal
(a <> b) returns true, similar to this operator! =
>
greater than - returns x y is greater than
(a> b) returns False
<
less than - returns whether x is smaller than y. All comparison operators return 1 for true, 0 for false returns. True and False, respectively, which is equivalent to the special variables. Note the capitalization of these variable names.
(a <b) returns true
> =
greater than or equal - Returns whether x is greater than equal to Y
(A> = B) returns False
<=
Less than or equal - Returns whether x is less than or equal Y
(A <= B) returns true
Assignment Operators
The following assumptions variable a is 10, the variable b is 20:
=
simple assignment operator
C = a + b a a + b calculation result assigned to C
==
C + = a is equivalent to the C = C + a
adder assignment operator
_ =
subtraction assignment operator
c- = a is equivalent to CA = C
* =
multiplication assignment operator
C * = a * is equivalent to A C = C
/ =
division assigned; operators as
c / = a is equivalent to C = C / A
% =
modulo assignment operator
C% = a% C is equivalent to A = C
** =
exponentiation assignment operator
C ** = a C ** is equivalent to A = C
// =
taking assignment operator divisible symbol
c // = a is equivalent to the C = C // a
Bitwise Operators
&
Bitwise AND operator: two values involved in operations, if the corresponding two bits are 1, the result of 1 bit, otherwise 0
(A & B) output 12, a binary interpretation: 0000 1100 is
|
press bitwise oR operator: as long as the corresponding two binary bit a is 1, the result bit is set to 1
(a | B) output 61, a binary interpretation: 00111101
^
bitwise exclusive oR operator: when two corresponding to two when the carry different, the result is a 1
(a ^ B) output 49, a binary interpretation: 00110001
~
bitwise operators: for each binary data bit inverse, i.e., the 1 to 0, the variable 0 is 1, ~ x. 1-like the -X-
(~ a) -61 output, binary interpreter: 11000011, in the form of a complement to unsigned binary number.
<<
left Mobile Operator: each binary operand to the left a number of bits of all, the number of bits of a mobile "<<" specifies the right, discarding the upper, lower 0s.
output a << 2 240, the binary interpretation: 11110000
>>
right movements of the operator: the respective binary operand is ">>" All right a number of bits left, ">>" specifies the number of bits to the right of movement number
a >> 2 15 output, binary interpretation:
Logical Operators
The following assumptions variable a is 10, b is variable 20 is:
and
x and y
Boolean "and" - if x is False, x and y returns False, otherwise it returns calculated value of y.
(a and b) return 20 is
or
x or y
Boolean "or" - If x is non-zero, it returns the value of x. Otherwise, it returns the calculated value of y.
(a or b) return 10
not
not x
Boolean "NOT" - If x is True, returns False, if x is False, it returns True.
not (a and b) returns False
Member operator
In addition to some of the above operators, Python member also supports the operator, the test example contains a series of members, including a string, or a list of tuples
in
if the found value in the specified sequence returns True, otherwise return False
X in y sequence, returns True if x in y sequence
not in
If you do not find value in the specified sequence returns True, otherwise return False
x is not y sequence, if X is not in the sequence y returns True
Sixth, loop
Conditional statements
Python by a conditional statement or statements of the execution result (True or False) to determine the execution of the code block
usage
if the judgment condition:
execute a statement ......
elif judgment conditions:
execute a statement ......
the else:
execute a statement ......
loop statement
In general, the program is executed sequentially, the programming language provides various control structures allows more complex execution paths loop allows us to perform a statement or group of statements times
While Loop
while statement for executing a program loop, i.e., under certain conditions, implementation of certain program loop, the same processing task needs to repeat the process.
usage
Basic
while judgment conditions:
execute statement ......
Python and can be used with the while the else
while judgment conditions:
execute statement ......
the else:
execute statement ......
for loop
Python for loop can iterate any sequence of items, such as a list, a string or a tuple, Dictionary
usage
for x in range(1,100,2):
print x
NOTE: range (1,100,2) 1 to 100 and 2 to take a number of compartments (the list can be freely replaced, strings, etc.)
Loop control
skipping continue this cycle, the next cycle continues
pass is a special feature of the python, the statement is empty pass, in order to maintain the integrity of the program structure (footprint)
for x in range(1,99):
pass
break statement to terminate a loop statement, i.e., False condition or loop condition has not yet been fully recursive sequence completed, will stop the execution loop. break statement used in a while and for loop