< >
The following three parts are used to gradually master and familiarize yourself with Python scripts from the perceptual knowledge of rational command code testing. What is important is the third part, you must test it in person and display the correct results. If you are familiar with it, OK!
========================================================== ============================
Part 1: Current python application instance
Google web Crawler and search engine
Yahoo, managing discussion groups
Youtobe, sharing service
The frontend, backend, and server of Douban.com use python.
Part 2: General Introduction to the concept of Python
Location: Explanatory, object-oriented programming language with dynamic semantics
Python features
Script Language
Advanced Dynamic Programming Language
Easy to learn
Interpretability & Compilation: you do not need to mutate binary data, but you need an interpreter. You can also compile the data faster.
Object-oriented: process-oriented programming and Object-Oriented Programming
Scalability, nesting, can be embedded into c/c ++ programs, provides script functions, and some programs can also be written in c
Portability: All programs can run on any platform without any modification.
Rich libraries: password system, GUI, TK, document generation, unit test, thread, CGI, email
Other high-quality libraries: wxPython, Twisted, and Python image Libraries
Automated memory management
Free, open-source
Rapid development with other languages, also called the glue Language
Three types of recognition files:
1. Source Code: With the. py extension, which is explained by a python program and does not need to be compiled
2. byte code: After compilation, a file with the extension of. pyc is generated.
Import py_compile
Py_compile.compile ("hello. py ")
3. Optimization code: optimized source file with the extension. pyo
The preceding three methods can be run directly.
Part 3: test the execution of commands and codes in Python
1. py
Print ("hello, world ")
Run python 1.py
==> Hello, world
2. py
Import py_compile
Py_compile.compile ('1. py ')
Generate file _ pycache _/1. cpython-33.pyc
Run python 1. cpython-33.pyc
==> Hello, world
Generate optimization code:
Run python-O-m py_compile 1.py
Generate file _ pycache _/1. cpython-33.pyo
Run python 1. cpython-33.pyo
==> Hello, world
Python variable
========================================================== ===
> A1 = 123
> A2 = 123
> Id (a1)
505912912
> Id (a2)
505912912
Different from the C language, the C language opens up space for variable names to store numeric values. python is the opposite. Numeric values exist in the memory.
Different variables can point to the value of the same address space.
Python operators & Expressions
========================================================== =====
Value assignment operator
-----------------------
= + =-= * =/= % =
Arithmetic Operators
-----------------------
+-* // (Integer division) % (remainder) ** (power)
> 4/3
1.33333333333333
> 4 // 3
1
Relational operators
-----------------------
<><=>=! ===
> A = 1
> B = 1.0
> A = B
True
> A = "hello"
> B = "hello"
> A = B
True
Logical operators
------------------------
And or not
Priority (low to high)
======================================
Or
And
Not
Member: in, not in
Identity: is, is not
<, <=,>, >= ,! =, =
By bit or |
By bit or ^
Bitwise AND &
Shift <,>
+ ,-
*,/, %
Plus and minus signs + x,-x
Flip by bit ~ X
Index **
Data Type
======================================
Numeric type
2. x is divided into integer, long integer, floating point, and plural type.
Atmosphere in version 3.x: integer, floating point, and plural
You can use the type function to view types.
> A = 111
> Type ()
Int
> A = 1.23
> Type ()
Float
> A = 12j
> Type ()
Complex
String type
> "Let's go" # correct
> 'Let's go '# error
Escape
> A = "let's \" go \""
> Print ()
Let's "go"
Newline \ n
Use the triple quotation marks '''xxxxxxxx''' instead of line breaks '''
> Str = 'abc'
> Str [0]
A
> Str = "abc"
> Str [0]
A
Slice & Index operations:
& Gt; a = "123456"
> A []
1234
> A [2:]
3456
> A [: 4]
1234
> A [-1]
6
> A [: 1] returns a value at an interval of 0.
123456
> A [: 2] returns one value at an interval.
135
> A [:]
123456
> A [:]
123456
Sequence
Lists, tuples, and strings are all sequences.
Two main features of sequences: Index operators and slice Operators
Basic sequence operations:
Len ()
> Len ("abcdef ")
*
> 5 * ""
+
> "Abc" + "bcd"
In
> "A" in "abc"
Max ()
> Max ("adfe ")
F
Min ()
> Min ("dfa ")
A
Cmp (tuple1, tuple2)
Tuple1> tuple2 ==> 1
Tuple1 <tuple2 ==>-1
Tuple1 = tuple2 => 0
What is cmp ("abc", "123 ")?
Cmp does not exist in version 3.x.
Tuples
The tuples are very similar to the list, but the tuples and strings are the same and immutable, that is, they cannot be modified.
It is usually used when statements or user-defined functions can safely adopt a set of values.
Create tuples ()
Null tuples a = ()
A = ("",)
A = ("a", "B ")
> A = ()
> B = (2 ,)
> C = (1, 2)
> Type (a) ==> tuple
> Type (B) ==> tuple
> Type (c) ==> tuple
Incorrect syntax
> D = (2)
> Type (d) => int
> D = ("ss ")
> Type (d) => str
The value of the tuples cannot be modified.
> A = (2, 3)
> A [1] = 4 # error TypeError: 'tuple' object does not support item assignment
Assignment
> Name, age, sex = ("zhang", 20, "man ")
> Name => "zhang"
> Age => 20
> Sex => "man"
# List []
Variable list element
> A = [1]
> Type (a) ==> list
Basic operations
Index list [index]
Slice list [:]
Add list. append ()
Find var in list
Delete list. remove () # Delete the first element that appears
> A = [1, 2, 3, 2]
> A. remove (2) ==> [1, 3, 2]
System Method del
> Del (a [0]) ==> [3, 2]
Note: after the list is assigned a value again, the address space remains unchanged.
> List = [1, 3]
>>Id (list) => 85445
> List [0] = 2
>>Id (list) => 85445
Conditional expressions
Python uses indentation as the grouping method of its language
If the indentation is inconsistent, the program reports an error.
If 1> 2:
Print ("OK ")
Print ("OK ")
Print ("xx ")
Print ("no ")
==> No
If 1> 2:
Print ("OK ")
Print ("OK ")
Print ("xx ")
Print ("no ")
==> IndentationError: unindent does not match any outer indentation level
X = 99
If x> 90:
Print ("")
Elif x> 80:
Print ("B ")
Elif x> 70:
Print ("C ")
Else:
Print ("D ")
Not. It cannot be used!
If not 0
Print ("OK ")
Loop traversal:
For I in range (10 ):
Print ("hello, world ")
For I in [1, 3, 4, 5, 5]:
Print (I)
For I in range (1, 10 ):
Print (I)
==> 1, 2, 3... 10
For I in range (1, 10, 2 ):
Print (I)
==> 1, 3, 5, 7, 9
List traversal:
D = {, 5: 666}
For k, v in d. items ():
Print (k)
Print (v)
Else:
Print ("ending ")
Result =>
2
333
4
444
5
666
Ending
-------------------------------
Specifically, the for Loop in python can be connected to else. After the loop is executed normally
Execute the statements in else. If the loop is interrupted, the else statement will not be executed.
D = {, 3: 666, 4: 444, 5: 777}
For k, v in d. items ():
If k = 2:
Break
Else:
Print (k)
Print (v)
Else:
Print ("ending ")
Result =>
1
333
Pass code pile, do nothing
Continue
Exit () exit the program
---------------------------------------
D = {, 3: 666, 4: 444, 5: 777}
For k, v in d. items ():
If k = 3:
Break
If k = 2:
Pass
Continue
If k = 5:
Exit ()
Else:
Print (k)
Print (v)
Else:
Print ("ending ")
While loop:
--------------------------------------------
$ Cat while. py
The statement in else is executed only when the while condition is false.
X = ""
While x! = "Q ":
Print ("hello ")
X = input ("input something, q for quit :")
If not x:
Break
Else:
Print ("ending ")
Function:
------------------------------
A = 2
B = 3
Def add ():
C = a + B
Print (c)
Add ()
==> 5
This is a bit insecure. If the variable in the function body is not small and the variable name is duplicated outside the function, isn't it a problem?
Def new_add (x, y ):
Z = x + y
Print (z)
Add ()
New_add (3, 4)
Passing Parameters
----------------------------------
Def add (x = 3, y = 4 ):
C = x + y
Print (c)
Add ()
Add (y = 5) # You can pass parameters separately, but it won't work if x has no default value.
Global Variables
-------------------------
$ Cat global. py
X = "global var"
Def change ():
X = 100
Print (x)
==> "Global var"
------------------------------
$ Cat global. py
X = "global var"
Def change ():
Global x
X = 100
Change () # after the change () method is executed, global x is equivalent to re-assigning a value to x.
Print (x)
===> 100
Tuples as parameters
-------------------------
$ Cat function1.py
Def add (x, y ):
Print ("% s: % s" % (x, y ))
Add ("hello", "world ")
A = ("hello", "world ")
B = ("hello", "pthon", "world ")
Add (a) # error. a is passed to x as a whole, and a parameter error is reported.
Add (* a) # correct. If the number of elements in the tuples is the same as the number of function parameters, x = a [0], y = a [1]
Add (* B) # error. When the number of elements in the tuples is not equal to the number of function parameters, a parameter error is reported.
Add (y = "world", x = "hello") # correct. You can specify the parameter to pass the value. That is, the order is irrelevant.
Dictionary as a parameter
-------------------------------------
Def add (x, y ):
Print ("% s: % s" % (x, y ))
D = {"y": "world", "x": "hello "}
D1 = {"y": "world", "x": "hello", "z": "python "}
Add (** d) # correct output => hello, world
Add (** d1) # error, add () got an unexpected keyword argument 'Z'
Accept redundant Parameters
------------------------------------------------------
* Args (the remaining parameters are used as tuples) and ** args (the remaining parameters are used as dictionaries)
$ Cat function2.py
Def p (x, * args ):
Print (x)
Print (args)
P (1)
P (1, 2, 3)
==> 1
==> ()
==> 1
==> (2, 3)
P (x = 1, y = 3)
==> P () got an unexpected keyword argument 'y'
Y = 3 cannot be saved as redundant parameters in args. You can use ** args to save
-----------------------------------------------------
$ Cat function2.py
Def p (x, ** args ):
Print (x)
Print (args)
P (1)
P (x = 2, y = 4)
==> 1
==> {}
==> 2
==>{ 'Y': 4}
P (1, x = 3) # error. The first parameter is paid to x, which is equivalent to wearing x = 1, x = 3.
==> P () got multiple values for argument 'X'
Accept the situation of * args and ** args at the same time
------------------------------------------------------
Def p (x, * args, ** other_args ):
Print (x)
Print (args)
Print (other_args)
P (1)
==> 1
==> ()
==> {}
P (3, 3, z = 5)
==> 3
==> (3 ,)
==>{ "Z": 5}
Parameter order cannot be changed
P (y = 3, 3, 5) # error, SyntaxError: non-keyword arg after keyword arg
P (3, 4, y = 4, 5) # error, SyntaxError: non-keyword arg after keyword arg
Lambda expressions
----------------------------------
Lambda is a minimum function that quickly defines a single row. It is borrowed from lisp and can be used in any
Where functions are needed
G = lambda x, y: x + y
G (1, 2) => 3
Benefits of lambda:
1. Write some execution scripts to save the function definition process and make the code more concise.
2. Saving the trouble of naming Abstract Functions
3. Make the code easier to understand (sometime)
Swtich. swtich is not in python. You can use a dictionary to implement switch.
------------------------------------------------------
X = 1
Y = 4
Dd = {
"+": X + y,
"-": X-y
}
Print (dd)
Print (dd. get ("+ "))
Print (dd. get ("-"))
Built-in functions
----------------------------------------------------
View the document:
Help (str. replace)
Str. capilize ()
Str. split ()
Str. replace ()
Exception Handling
--------------------------------------------
Contents = {"tomato": 4, "banana": 3}
Try:
If contents ["apple"]> 3:
Print ("I have apples ")
Except T (KeyError) as error:
Print ("I have no % s" % error)
==> I have no 'apple'