An introduction to Python

Table of contents

Introduction and Features of Python

Python supports multiple programming styles

explain run

Cross-platform

Scalable and strong

Embeddable

rich library

Python version selection

Building a Python development environment

Get to know the Python interpreter

quick start

Variables and assignments

dynamic type

Variable Naming Rules

Know "Numbers"

Know "string"

Know "Boolean type"

input Output

note

operator

Scope and Lifecycle

Python keywords

list/tuple/dictionary

understand "quote"

Code Blocks and Indentation

if statement

while loop

 for loop

break和continue

pass statement

list comprehension

function

file operation

module

utility function

special identifier

docstring

module documentation

Unix start line 


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 C
Python 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 perfectly
Python 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.14
Python3: The latest version is Python3.6.2
Although 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 executed
Press 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 initialization
Use = for initialization and assignment operations
>>> counter = 0
>>> miles = 1000.0
>>> name = 'Bob'
>>> kilometers = 1.609 * miles
Operations like ++/-- are not supported in Python and can only be written as
>>> n += 1

dynamic type

The same variable can be assigned different types of values
>>> a = 100
>>> print a
100
>>> a = 'hehe'
>>> print a
hehe

Variable 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 a
My 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 is
Use 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 * b
Traceback (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))
4
Format string , you can use % to replace the format .
>>> a = 100
>>> pystr = "a = %d"
>>> result = pystr % a
>>> print(result)
a = 100
It can be simplified as follows
>>>print("a = %d" % a)
a = 100

Know " Boolean type "

>>> a = True
>>> print a
True
>>> 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 0

input 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)
aaa
The 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) + 1
101

note

Python uses # as a single-line comment . The content behind # is the content of the comment
a = 1.0 # define a
print(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 file

operator

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 // b
0
Note 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 ** b
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000
Python also supports standard comparison operators . > < >= <= == != The result of the expression of these operators is a Boolean value
>>> 2 < 4
True
>>> 2 == 4
False
>>> 2 > 4
False
>>> 2 != 4
True
Python also supports logical operators . and or not
>>> 2 < 4 and 2 == 4
False
>>> 2 > 4 or 2 < 4
True
>>> not 6.2 <= 6
True
In 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'
hahaha
You can use == != between strings to determine whether the contents of the strings are the same
>>> 'haha' != 'hehe'
True
The 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 variables
if, else, elif, while, for, try/except ( we'll talk about that later ) don't change the scope of variables
for 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 = 1
        print(x)
print(x) #Out of the def function statement block , the x variable can no longer be accessed
The 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 scope
a = 100
def Func():
  x = 0
  print(globals())
  print(locals())
print 'In Gloabl'
print(globals())
print(locals())
print('In Func')
Func()
#execution result
In 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] = 100
Traceback (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)
25094648
Reassigning 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_something1
elif expression2:
        do_something2
else:
        do_something3
Python 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 loop
while expression:
        do_something
# Loop to execute print three times
counter = 0
while counter < 3:
        print 'loop %d' % counter
        counter += 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 string
a = 'hehe'
for c in a:
        print c
#execution result
h
e
h
e
#Loop through each element in the list
a = [1, 2, 3, 4]
for item in a:
print item
#execution result
1z
2
3
4
#Loop through all key-values ​​in the dictionary
a = {'ip':'192.168.1.1', 'port':80}
for key in a:
print key, a[key]
#execution result
ip 127.0.0.1
port 80
The built-in function range can generate a list of numbers , which is convenient for for loop traversal
# for loop executes three prints
for i in range(0, 3):
        print 'loop %d' % i
#execution result
loop 0
loop 1
loop 2
The 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

breakcontinue

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:
        break
Use 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:
        pass
else:
        do_something

list comprehension

It's time to witness the miracle again . The powerful and concise Python syntax , the first show
Use 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 + y
Python uses () to call functions
print(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 former
def Func():
        print('aaaa')
def Func():
        print('bbbb')
Func()
#execution result
bbbb
Python supports default parameters . Function parameters can have default values
def Func(debug=True):
        if debug:
                print('in debug mode')
        print 'done'
Func()
Func(False)
Python unpacking (unpack) syntax , the function returns multiple values
def GetPoint():
        return 100, 200
x, 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 = Func
func()
print type(func)
#execution result
aaa
<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 open
handle = open(file_name, access_mode='r')
file_name is the name of the file . It can be an absolute path or a relative path
handle = open('text.txt', access_mode='r')
# or
handle = 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 mode
handle 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 line
After 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 Text
In a text file , each line is a word . There may be repetitions . Count the number of occurrences of each word .
Example file :
aaa
bbb
ccc
aaa
bb
c
aaa
The code is implemented as follows :
handle = open('text.txt', mode='r')
words = {}
for word in handle:
        word = word[:-1] # remove the \n at the end
        if word not in words: # Use the in keyword to determine whether the word is the key of the dictionary.
                words[word] = 1
        else:
                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 files
The 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 name
For example :
# add.py content
def Add(x, y):
        return x + y
# test.py content , directly import module name
import add
print add.Add(1, 2)
# test2.py content , only the name Add in the import add module .
from add import Add
print Add(1, 2)
# test3.py content , import module name , and give the module name an alias .
import add
a = add
print 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 sys
print 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.py
def _Add(x, y):
        return x + y
# test.py
from add import *
_Add(1, 2)
#execution result
Traceback (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 string
def 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 result
define function for add two num
Or use the built-in function help to achieve the same effect
help(Add)
#execution result
Add(x, y)
define function for add two num
The documentation string must be placed at the beginning of the function / class . Otherwise, it cannot be accessed using __doc__ or help

module 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.py
import add
print(add.__doc__)
#execution result
define 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/python
print('haha')
Save the above code as test.py. Add executable permissions to this file : chmod +x test.py
Then it can be executed by ./test.py .

Guess you like

Origin blog.csdn.net/weixin_62700590/article/details/132081658