Table of contents
Introduction and Features of Python
Python supports multiple programming styles
Building a Python development environment
Get to know the Python interpreter
Introduction and Features of Python
Python supports multiple programming styles
Python supports a process-oriented programming style . If you are familiar with C language , you can write Python like CPython supports an object-oriented programming style . Numbers , strings , functions , modules ... are all " objects ".Python supports functional programming . In fact, there are only two programming languages in the world , C -like language and Lisp -like language . Python also supports functional programming.
explain run
Python is an interpreted programming language . Unlike C/C++ , it does not convert the source code file into an executable file before executing it ; instead, the Python interpreter reads the source code line by line . Execute one line . But strictly speaking, Python is a " semi-compiled , half-interpreted " language . On the one hand , the Python interpreter will read the source code file line by line , and then convert the source code to Python for interpretation The " bytecode " directly executed by the processor . Then execute the bytecode . For example, after we execute a .py file , a .pyc file with the same name will be generated . This .pyc file is Python The bytecode file generated by the interpreter . If the .pyc file already exists , then there is no need to " translate " it again , which also improves execution efficiency
Cross-platform
Python is executed based on a Python interpreter . As long as a Python interpreter can run on a certain operating system / platform , it can run perfectlyPython source code . Mainstream Windows, Linux, Mac and other operating systems can support Python very well
Scalable and strong
Python can easily call C/C++ language . If you feel that the logic performance does not meet the requirements , you can use C/C++ to reconstruct this part of the module and call it with Python.
Embeddable
Python code can also be easily embedded into C/C++ for execution
rich library
A gentleman's nature is not different , and he is good at falsehoods .The Python standard library is already very rich and powerful , and there are also very large third-party libraries . It can almost reach heaven and earth , and I can do whatever I want~
Python version selection
Python currently has two major version branches :
Python2: The latest version is Python2.7.14Python3: The latest version is Python3.6.2Although Python3 is an upgraded version of Python2 , many grammars are not compatible!Regarding compatibility:C++ is very compatible with C language ( code written in C language can be compiled directly with a C++ compiler ), but it also means that C++ bears a lot of historical baggage of C language .But Python3 and Python2 are incompatible in many places (the code written in Python2 cannot be executed smoothly on the Python3 interpreter ).This means that many codes already written in Python 2 will not be upgraded to Python 3 smoothly .But this also means that Python3 can drastically modify some unreasonable places without carrying the burden of history .The official statement is that Python2 will stop updating until 2020 at most .But the version of Python in some enterprises is also Python2.7 or even Python2.6 ( fortunately , there is not much difference between Python2.7 and 2.6 ).This book is mainly about the content of the Python3 version
Building a Python development environment
Windows/Linux: VSCode + Python plugin ( recommended )Windows/Linux: PyCharm ( recommended )Get to know the Python interpreter
Just type python on the command line to enter the Python interpreter . At this time we see a Python shell .First , we can use this interpreter as a basic calculator .Of course , arbitrary legal Python statements can also be executedPress ctrl+d to exit the python shell.Although we can execute some python statements through the Python shell , it is more to write the Python code into a file with a .py suffix , and interpret the .py file through the Python interpreter to execute the code
quick start
Variables and assignments
Variables in Python do not need to be declared , they can be defined directly . The " type " of the variable will be determined at the time of initializationUse = for initialization and assignment operations>>> counter = 0>>> miles = 1000.0>>> name = 'Bob'>>> kilometers = 1.609 * milesOperations like ++/-- are not supported in Python and can only be written as>>> n += 1dynamic type
The same variable can be assigned different types of values>>> a = 100>>> print a100>>> a = 'hehe'>>> print aheheVariable Naming Rules
Variable names must be letters , numbers , and underscores . But they cannot start with numbers ( the rules are the same as in C language ).Variable names are case-sensitive , case and Case are two different variables .Know " Numbers"
Python does not have int, float, such keywords , but in fact the type of number is to distinguish between types such as "int" and "float" . Use the built-in function type to view the type of the variable .>>> a = 1>>> type(a)<type 'int'>>>> a = 1.0>>> type(a)<type 'float'>The value range of the numeric variable in Python is not limited ( it depends entirely on how much memory your machine has ) , instead of being represented by 4 bytes like int in C language .There is also a " complex number " type in Python . It is the same concept as " complex number " in mathematics>>> a = 10 + 5j>>> print(a)(10+5j)Know " string "
Single quotes ('), double quotes ("), and triple quotes ('''/""") can be used in Python to represent strings . The differences between these three strings will be discussed later.>>> a = 'hehe'>>> b = "hehe">>> c = '''hehe'''The advantage of this is that if the string contains characters like " , there is no need to escape lamely>>> a = 'My name is "tangzhong"'>>> print aMy name is "tangzhong"But some invisible characters still have to be escaped , using \ to escape . For example, newline character \n>>> a = 'My name is \n "tangzhong"'>>> print(a)My name isUse the index operator [] or the slice operator [:] to get substrings ( the slice operation is a closed-before-open interval ).The indexing rules for strings are : the first character index is 0, and the last character index is -1 ( which can be understood as len-1).>>> pystr = 'hehe'>>> pystr[0]'h'>>> pystr[-1]'e'>>> pystr[1:3]'eh'>>> pystr[1:-1]'eh'>>> pystr[1:]'before'>>> pystr[:2]'he'>>> pystr[:]'hehe'+ for string concatenation , * for string repetition>>> a = 'hehe'>>> b = 'haha'>>> c = a + b>>> print(c)hahahahaha>>> d = a * 4>>> print(d)hehehehehehehe>>> e = a * bTraceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: can't multiply sequence by non-int of type 'str'Python has no such concept as " character type " . A single character is also a string>>> a = 'hehe'>>> type(a[0])<type 'str'>Use the built-in function len to get the length of a string>>> a = 'hehe'>>> print(len(a))4Format string , you can use % to replace the format .>>> a = 100>>> pystr = "a = %d">>> result = pystr % a>>> print(result)a = 100It can be simplified as follows>>>print("a = %d" % a)a = 100Know " Boolean type "
>>> a = True>>> print aTrue>>> print(type(a))<type 'bool'>Boolean variables are also a special integer type . When operating with integers , True is treated as 1, and False is treated as 0input Output
The print function outputs the result to standard output ( monitor ) .The input function takes user input from standard input>>> name = input('Enter name:')Enter name:aaa>>> print(name)aaaThe result returned by input is just a string . If you need to get a number , you need to use the int function to convert the string into a number .>>> num = input('Enter num:')Enter number: 100>>> print(num + 1)Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: cannot concatenate 'str' and 'int' objects>>> print int(num) + 1101note
Python uses # as a single-line comment . The content behind # is the content of the commenta = 1.0 # define aprint(type(a))When using Chinese comments , be careful ~~ Direct use may cause errors when running (Python3 does not have this problem at present , Python2 should pay attention)The source code of Python only supports ASCII by default , so if you want to include Chinese , you need to indicate # - * - coding: UTF- 8 - *- at the very beginning of the code fileoperator
Operators such as + - * / % are supported in Python . And their behavior is the same as that of C language ./ is " exact division ">>> a = 1>>> b = 2>>> print(a / b)0.5// is " divisible ". The result will be rounded>>> a = 1>>> b = 2>>> print a // b0Note that in Python2 / is traditional division , // is floor division , and the semantics of Python3 are completely different** Indicates the power operation ( remember that Python 's data has no upper limit )>>> a = 100>>> b = 100>>> print a ** b100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000Python also supports standard comparison operators . > < >= <= == != The result of the expression of these operators is a Boolean value>>> 2 < 4True>>> 2 == 4False>>> 2 > 4False>>> 2 != 4TruePython also supports logical operators . and or not>>> 2 < 4 and 2 == 4False>>> 2 > 4 or 2 < 4True>>> not 6.2 <= 6TrueIn Python , 3 < 4 < 5 is equivalent to 3 < 4 and 4 < 5 , which is different from most other programming languages .There is a distinction between high and low precedence between operators . Brackets should be used reasonably to increase the readability of the code .Operators can also be used between strings and strings , for example, + is used to connect strings>>> print 'haha' + 'hehe'hahahaYou can use == != between strings to determine whether the contents of the strings are the same>>> 'haha' != 'hehe'TrueThe size can also be compared between strings . The result of this size depends on the " lexicographical order " of the string>>> 'haha' < 'hehe'True
Scope and Lifecycle
In Python , def, class ( we will talk about it later ), lamda ( we will talk about it later ) will change the scope of variablesif, else, elif, while, for, try/except ( we'll talk about that later ) don't change the scope of variablesfor i in range(0, 10):print(i)print(i) #Even if the for loop statement block is out , the variable i can still access the i variable .def func():x = 1print(x)print(x) #Out of the def function statement block , the x variable can no longer be accessedThe built-in function globals() returns which variables are in the global scope , and the built-in function locals() returns which variables are in the local scopea = 100def Func():x = 0print(globals())print(locals())print 'In Gloabl'print(globals())print(locals())print('In Func')Func()#execution resultIn Gloabl{'a': 100, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'test.py','__package__': None, 'Func': <function Func at 0x7f9085d5b9b0>, '__name__': '__main__','__doc__': None}{'a': 100, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'test.py','__package__': None, 'Func': <function Func at 0x7f9085d5b9b0>, '__name__': '__main__','__doc__': None}In Func{'a': 100, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'test.py','__package__': None, 'Func': <function Func at 0x7f9085d5b9b0>, '__name__': '__main__','__doc__': None}{'x': 0}Regarding the life cycle of Python variables , this does not require programmers to worry about it . Python provides a garbage collection mechanism to automatically identify whether the life cycle of a variable has come to an end, and automatically release space ( we will talk about the details later ).
Python keywords
At present, we have come into contact with keywords such as while, if, else, for, continue, break, return, etc. In fact , there are many other keywords
list / tuple / dictionary
Lists and tuples are similar to arrays in C.
Use [] for lists and () for tuples .>>> alist = [1, 2, 3, 4]>>> alist[1, 2, 3, 4]>>> atuple = (1, 2, 3, 4)>>> atuple(1, 2, 3, 4)Lists and tuples can hold any number of Python objects of any type>>> a = [1, 'haha']>>> a[1, 'haha']You can use the subscript to access the elements inside , the subscript starts from 0. The last subscript is -1>>> a[0]1>>> a[1]'haha'>>> a[-1]'haha'You can use the [:] slice operation to get a subset of the list or tuple . This operation is the same as the string operation>>> a[:][1, 'haha']The only difference between a list and a tuple is that the elements in a list can be modified , but the elements in a tuple cannot be modified>>> a = [1, 2, 3, 4]>>> a[0] = 100>>> a[100, 2, 3, 4]>>> a = (1, 2, 3, 4)>>> a[0] = 100Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: 'tuple' object does not support item assignment>>>A dictionary is a mapping data type in Python . It stores key-value pairs (key-value).Almost any type of Python object can be used as a key . However, numbers and strings are generally the most commonly used .Use {} to represent a dictionary .>>> a = { 'ip' : '127.0.0.1'} #create dictionary>>> a['ip'] #Get the elements in the dictionary'127.0.0.1'>>> a['port'] = 80 #insert a new key-value pair>>> a{'ip': '127.0.0.1', 'port': 80}
understand " quote "
In Python, you can use the built-in function id to view the " address " of the variable>>> a = 100>>> id(a)24187568>>> a = 200>>> id(a)24191144>>> b = a>>> id(b)24191144>>> b = 300>>> id(b)25094648Reassigning a to 200 is equivalent to creating a new object like 200 , and then rebinding the variable name a to the object 200 .Assigning a to b is actually equivalent to creating a variable name b, and binding the name b to the object 200 .Modify the value of b again , and you can see that an object like 300 is actually created , and b is bound to the object of 300 .Variable names like a and b created are actually just an alias of an object . Or called a " reference " of a variable
Code Blocks and Indentation
Python uses indentation to represent code blocks . It is equivalent to naturally specifying the code style from a grammatical point of view .Python is unique in using indentation instead of { } , which avoids a partisan battle ~There are no curly braces . Therefore, there is no need to consider where the curly braces are placed
if statement
The standard if conditional statement syntax is as follows .If the value of the expression is non- zero or Boolean True, do_something is executed , otherwise the next jump statement is executed .if expression1:do_something1elif expression2:do_something2else:do_something3Python does not support statements such as switch/case . There is no need to support them . In fact, the switch/case syntax is not elegant .If there are too many conditional branches , you can consider using the " table-driven " method to organize the code . For details, please refer to Chapter 18 of << Code Encyclopedia >> .
while loop
The while loop statement is similar to the if statement syntax . As long as the value of the expression is not 0 or True, do_something will be executed in a loopwhile expression:do_something# Loop to execute print three timescounter = 0while counter < 3:print 'loop %d' % countercounter += 1
for loop
The for loop in Python is different from the traditional for loop .The for loop receives an iterable object ( sequence or iterator ) as a parameter , and iterates one element at a time#Loop through each character in the stringa = 'hehe'for c in a:print c#execution resulthehe#Loop through each element in the lista = [1, 2, 3, 4]for item in a:print item#execution result1z234#Loop through all key-values in the dictionarya = {'ip':'192.168.1.1', 'port':80}for key in a:print key, a[key]#execution resultip 127.0.0.1port 80The built-in function range can generate a list of numbers , which is convenient for for loop traversal# for loop executes three printsfor i in range(0, 3):print 'loop %d' % i#execution resultloop 0loop 1loop 2The range function actually has three parameters . The first two parameters represent an interval that is closed before opening and then opened . The third parameter represents step, the step size of each iteration# Traverse the even numbers in the interval [0, 100)for i in range(0, 100, 2):print i
break和continue
Use the break statement to break out of the current loop#Find the first multiple of 3 in [0, 100)for i in range(0, 100):if i % 3 == 0:breakUse the continue statement to return to the top of the loop and determine the loop condition ;If the loop condition is met , execute the next loop ;
pass statement
Sometimes it is necessary to use the concept of an empty statement , which does nothing . Since there is no {}, a special statement is required to occupy the space , otherwise it will be confusing.if x % 2 == 0:passelse:do_something
list comprehension
It's time to witness the miracle again . The powerful and concise Python syntax , the first showUse a for loop to put the resulting values in a list# Generate a sequence of squares of numbers in [0, 4)squared = [x ** 2 for x in range(4)]print squared#execution result[0, 1, 4, 9]This process can also be used with the if statement#Get all the odd numbers in the interval [0, 8 )evens = [x for x in range(0, 8) if x % 2 == 1]print evens
function
Some code that can be reused can be extracted and put into a function .Python uses def to define a function . Use return to return the result .def Add(x, y):return x + yPython uses () to call functionsprint(Add(1, 2))Understand " formal parameters " and " actual parameters ": Formal parameters are equivalent to the concept of " unknowns " in mathematics . Actual parameters are to determine specific values for unknowns .There is no concept of " overloading " in Python . For functions with the same name , the latter will override the formerdef Func():print('aaaa')def Func():print('bbbb')Func()#execution resultbbbbPython supports default parameters . Function parameters can have default valuesdef Func(debug=True):if debug:print('in debug mode')print 'done'Func()Func(False)Python unpacking (unpack) syntax , the function returns multiple valuesdef GetPoint():return 100, 200x, y = GetPoint()If I only pay attention to y and don't want to pay attention to x, I can use _ as a placeholder_, y = GetPoint()Functions are also " objects ". A function, like a number or a string , can define an " alias " to refer to it .def Func():print('aaa')func = Funcfunc()print type(func)#execution resultaaa<type 'function'>Since a function is an object , it can also be used as the parameter and return value of another function . We will discuss the details later .
file operation
Open a file using the built-in function openhandle = open(file_name, access_mode='r')file_name is the name of the file . It can be an absolute path or a relative pathhandle = open('text.txt', access_mode='r')# orhandle = open('/home/tangzhong/text.txt', access_mode='r')access_mode is the way to open the file . The options are as follows'r' : read only'w' : write only'a' : Append to write't' : Read and write as text'b' : read and write in binary modehandle is a file handle , which is an iterable object . You can directly use the for loop to read the file content line by line .for line in handle:print lineAfter the handle is used , it needs to be closed . Otherwise, it will cause a resource leak ( the number of handles that can be opened by a process is limited ).handle.close()A Complete Example : Counting Word Frequency in TextIn a text file , each line is a word . There may be repetitions . Count the number of occurrences of each word .Example file :aaabbbcccaaabbcaaaThe code is implemented as follows :handle = open('text.txt', mode='r')words = {}for word in handle:word = word[:-1] # remove the \n at the endif word not in words: # Use the in keyword to determine whether the word is the key of the dictionary.words[word] = 1else:words[word] += 1;handle.close()print words
module
When we have a large amount of code in a project , we need to put the code in multiple different .py filesThe code in other .py files can be referenced through the import keyword .The imported code file is called a " module ".The imported file , remove the .py suffix , is the module nameFor example :# add.py contentdef Add(x, y):return x + y# test.py content , directly import module nameimport addprint add.Add(1, 2)# test2.py content , only the name Add in the import add module .from add import Addprint Add(1, 2)# test3.py content , import module name , and give the module name an alias .import adda = addprint a.Add(1, 2)The order in which modules are searched is first to find the current directory , then to the Python installation directory .import sysprint sys.path #Print out the path of the module search
utility function
Earlier we came into contact with some very useful built-in functions . Here we briefly summarize
special identifier
Python uses underscores (_) as prefixes and suffixes for variables to denote special identifiers ._xxx represents a " private variable ", which cannot be imported using from module import *# add.pydef _Add(x, y):return x + y# test.pyfrom add import *_Add(1, 2)#execution resultTraceback (most recent call last):File "test.py", line 3, in <module>_Add(1, 2)NameError: name '_Add' is not defined_xxx_ ( one underscore before and after ), __xxx__ ( two underscores before and after ) are generally system-defined names . We should avoid this style when naming variables to prevent conflicts with system variables .
docstring
Writing comments is of great help to improve the readability of the program .Earlier we introduced # to represent single-line comments .For multi-line comments , we can use triple quotes ('''/""") at the beginning of the function / class . This thing is also called the documentation stringdef Add(x, y):'''define function for add two number'''return x + y
Use the doc attribute of the object to see this help document ( don't forget , functions are also objects )print(Add.__doc__)#execution resultdefine function for add two numOr use the built-in function help to achieve the same effecthelp(Add)#execution resultAdd(x, y)define function for add two numThe documentation string must be placed at the beginning of the function / class . Otherwise, it cannot be accessed using __doc__ or helpmodule documentation
Not only a function / class can have a docstring . A module can also# add.py'''define some function for add'''def Add(x, y):return x + y# test.pyimport addprint(add.__doc__)#execution resultdefine some function for add
Unix start line
For Unix -like systems such as Linux or Mac , you can add a start line to the Python code file to specify the execution mode of the program#!/usr/bin/pythonprint('haha')Save the above code as test.py. Add executable permissions to this file : chmod +x test.pyThen it can be executed by ./test.py .