Introduction to the

  • Easy to learn
  • cross-platform
  • glue
  • Grammar interesting

Testing frameworks: Selunium (Web), RobotFarmework (translating tables into scripts), PyUnit (unit testing)

The data type

1. Integer: 0,1, -9, hexadecimal: 0x12ad

1.23E-3 = 1.23*10^(-3)

3. String: single or double quotes

4, escape characters: \n newline \t TAB character r “” indicates that characters inside quotation marks are not escaped by default.

5, Boolean: true or false, and or not

6. Null: None

Variables and Constants: Python is a dynamic language, and constants are capitalized by default, but they are not immutable.

7, character type STR

Encoding: character encoding – Unicode encoding – UTF-8 encoding

'ORD (" A ")' : converts A single character A to an integer. 'CHR (" 383 ")' : converts an integer to A corresponding characterCopy the code

Encode (‘ ASCII ‘) Byte converts to STR: ‘STR’. Encode (‘ ASCII ‘) Byte converts to STR: B ‘ABC’. Decode (‘ ASCII ‘) Chinese exceeds the range of STR and byte and cannot use decode

Length of STR: len(‘ ABC ‘)

Strings are immutable objects >>> A ='abc'
>>> b = a.replace('a'.'A')
>>>a.replace('a'.'A')
'Abc'
>>> b
'Abc'
>>> a
'abc'
Copy the code

Python

# at the beginning
#! Usr /bin/env/python3 This is a Python program
# -*- coding: UTF-8 -*- According to UTF-8 encoding
Copy the code

String formatting:

Integer 'd%' floating point 'f%' string 'S %' hex 'x%' format () :Copy the code

{1:.1f}%’. Format (‘ xiao Ming ‘, 17.125)

‘Hello, Xiao Ming, 17.1% increase in grade ‘

List the list

Class = “aa”, “bb”, “kk”]

The length of the len (class) : 3

Index class [0] : ‘aa’ class [1] : “kk”

Append element to end: class.append(‘ value’)

Append element to specified position: class.insert(2, ‘value’)

Remove the trailing element: calss.pop()

Delete specified location: class.pop(I)

Sorting: class. Sort ()

Tuples touple ()

— Tuples are readable and immutable

Num = (1, 2, 3, 4)

Length len (num) : 4

The index num (0) : 1

Note: Use the comma t = (1,) when there is only one data in the tuple.

T = (1) : 1 is confused with () in the mathematical formula, and python ends up taking mathematical numbers

The dictionary dict value} {key:

Initialize: dict = {“kk”:98,”talor”:100,”vae”:99}

Get data: dict[“kk”] or dict.get(“vae”)

If the key does not exist, an error is reported

Check whether key exists:

'kk' in dict true /false

dict.get('mm') None

Save/modify data: Dict [“kiky”] = 88 washes out the previous data

Delete data: dict.pop(“kiky”)

Dictionary < list — Dict dict keys must be immutable. Normal strings are immutable variables and can be used safely. Dict dict for Python and map for other languages

The set collection

Set is also a dictionary that contains only keys, not values.

A set can be thought of as a mathematical, non-repeating/non-sequential set

Add: se.add(4) —- Repeatedly add the same, no effect. Add: se.update(x):x can be lists, tuples, dictionaries, etc. Delete: se. Remove (4) there is no error will be deleted: se. Discard (4) there is no error will not overlap: & and sets: | do not exist at the same time value: ^

se = setSe ([1, 2, 3]) {1, 2, 3}Copy the code

Conditional judgment:

ifCondition 1: passelifCondition 2: passelifCondition 3: passelse: passCopy the code

A while else structure that executes an else block if the condition statement is false

while a==1 :
    pass

while a<5:
    a +=1
else
    printA is greater than or equal to 5.Copy the code

cycle

for x in[1, 2, 3, 4, 5] :for x inRange (5): range(5):0 -- 4, that is, 0, 1, 2, 3, 4break: Terminates the current loopcontinue: Ends the current cycle and goes directly to the next cycleCopy the code

function

  • An empty function
Def kong(): pass // placeholder for the program to runCopy the code
  • Parameter error When a function is called, the number of arguments is checked.
  • Return x,y // returns a tuple.

This parameter is mandatory

def power(x,n)
Copy the code

The default parameter n=2

Def power(x,n=2) pass power(3) def power(x,n=2) pass power(3) def power(x,n=2) pass power(3)'END')
    return L
>>> add_end()
['END']
>>> add_end()
['END'.'END']

'-------- Note: Default argument must point to immutable variable -----------'
def add_end(L=None):
    if L is None:
        L = []
    L.append('END')
    return L
Copy the code

Variable parameter

'a tuple'list'Def calc(numbers): sum = 0for n in numbers:
        sum = sum + n * n
    return sum
>>> calc([1, 2, 3])
14
'-------------- becomes variable --------- plus *'
def calc(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum
>>> calc(1, 2)
5
>>> nums = [1, 2, 3]
>>> calc(*nums)
14
Copy the code

Keyword parameter

'dictionary'Passed as a positional parameter'* *'

def person(name, age, **kw):
    print('name:', name, 'age:', age, 'other:', kw)
    
>>> extra = {'city': 'Beijing'.'job': 'Engineer'}
>>>  person('Jack', 24, **extra)
name: Jack age: 24 other: {'city': 'Beijing'.'job': 'Engineer'}
Copy the code

Name keyword arguments

Must be added between the positional argument and the named keyword argumentThe '*'Def person(name, age, *, city, job); def person(name, age, *, city, job); def person(name, age, *, city, job);print(name, age, city, job) must be called with the parameter name >>> person('Jack', 24, city='Beijing', job='Engineer')
Jack 24 Beijing Engineer
Copy the code

Parameter combination

To define functions in Python, you can use a combination of five parameters: required, default, variable, keyword, and named keyword arguments. Note, however, that the parameters must be defined in the order required, default, variable, named keyword, and keyword arguments.

  • Recursive function
def fact(n):
    if n==1:
        return 1
    return n * fact(n - 1)
Copy the code
  • Range function
for i inRange (5) : 0,1,2,3,4for i inRange (5, 9) : 5,6,7,8for i inRange (0, 10, 3) :0,3,6,9 >>>a = ['Google'.'Baidu'.'Runoob'.'Taobao'.'QQ'] > > >for i in range(len(a)):
...     print(i, a[i])
0 Google
1 Baidu
2 Runoob
3 Taobao
4 QQ
Copy the code

Advanced features

slice

Tuple/List Value >>> L[0:3]'Not including L[3]'
[L[0], L[1], L[2]]
>>> L[-2:]  'Default includes last to last, so last to last and second to last'
[L[-2],L[-1]]
>>> L[-2:-1]      'Not counting the last to last'
[L[-2]]

>>> L[:10:2]     'Take one of every two of the first 10 numbers.'
[0, 2, 4, 6, 8]
Copy the code

Iteration — Iterablefor in

  • The dictionary
By default, dict iterates over keys. If you want to iterate over value, you can use'for value ind.values()'If you want to iterate over key and value at the same time, you can use'for k, v in d.items()'. >>> d = {'a': 1, 'b': 2.'c': 3} > > >for key in d:
...     print(key)
...
a
c
b
Copy the code
  • string
>>> for ch in 'ABC':...print(ch)
...
A
B
C
Copy the code

Determine if it is iterable

>>> from collections import Iterable
>>> isinstance('abc', Iterable) # whether STR is iterableTrue > > > isinstance ([1, 2, 3], Iterable)# list is iterable
True
>>> isinstance(123, Iterable) Whether integers are iterable
False
Copy the code
  • List generator
  • The generator
  • The iterator

Python Advanced Tutorial

Regular expressionimport re

re.metch(r,str,med)  # match from the beginning of STR
re.search(r,str,med)  Match the entire STR until a match is found
re.sub()
re.findall
re.finditer
re.split(r,str,0/1)  # separate all or once
group

Copy the code

CGI programming generic gateway interface

MySQL

  • Atomicity: indivisible, all or none
  • Consistency: Transitions from one consistency state to another consistency state
  • Persistence: Once a transaction is committed, changes to the database should be permanent
  • Isolation: The execution of a transaction cannot be interfered with by other transactions
python -m pip install mysql-connector    # installation


import mysql.connertor      # import module
mydb = mysql.connector.connect(host='localhost',
user='username',passwd='password')   Create a connection

mycursor = mydb.cursor()   Create a cursor object
mycursor.excute("CRATE DATABASE run-db")  Create databaseCreat table XXX (row1 varchar(255), Row2 varchar(255)) show tables Alter table XXX add column xxx int auto_increment primary keyAlter table add columnInsert data inter into XXX (Row1,row2) VALUES (key1,key2) placeholder Insert data SQL ="inter into xxx (row1,row2) values (%s,%s)"  
val = ("row1key",row2key)
mycursor.excute(sql,val)
mydb.commit()  Update data table contentsBatch insert SQL ="INSERT INTO sites (name, url) VALUES (%s, %s)"
val = [
  ('Google'.'https://www.google.com'),
  ('Github'.'https://www.github.com'),
  ('Taobao'.'https://www.taobao.com'),
  ('stackoverflow'.'https://www.stackoverflow.com/')
]
mycursor.executemany(sql, val)
mydb.commit()    SQL > alter table contents updatedFetchall mycursor.execute("SELECT * FROM sites")
myresult = mycursor.fetchall()     # fetchAll () retrieves all records
for x in myresult:
  print(x) Query mycursor.execute("SELECT * FROM sites")
myresult = mycursor.fetchone()  Get a piece of data
print(myresult)
  
whereConditional statement SQL ="SELECT * FROM sites WHERE name ='RUNOOB'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
  print(x) wildcard % SQL ="SELECT * FROM sites WHERE url LIKE '%oo%'"Order by SQL ="SELECT * FROM sites ORDER BY name" # default ascending ASC, descending desc

limit 
mycursor.execute("SELECT * FROM sites LIMIT 3") offset Sets the starting position mycursor.execute("SELECT * FROM sites LIMIT 3 OFFSET 1")  # offset 0 is the first, 1 is the second, and so onDelete record SQL ="DELETE FROM sites WHERE name = 'stackoverflow'"Mycursor.execute (SQL) mydb.mit () Update data SQL ="UPDATE sites SET name = 'ZH' WHERE name = 'Zhihu'"Mycursor.execute (SQL) mydb.mit () Delete table SQL ="DROP TABLE IF EXISTS sites"  Mysql > alter table sites
mycursor.execute(sql)
Copy the code

PyMySql

#! /usr/bin/python3
 
import pymysql
 
Open a database connection
db = pymysql.connect("localhost"."testuser"."test123"."TESTDB" )
 
Create a cursor object cursor using the cursor() method
cursor = db.cursor()
 
Use the execute() method to execute the SQL query
cursor.execute("SELECT VERSION()")
Fetch a single piece of data using fetchone()
data = cursor.fetchone()
print ("Database version : %s " % data)
 
Use the execute() method to execute the SQL and delete the table if it exists
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
Create table with preprocessing statement
sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )"""
cursor.execute(sql)

SQL insert statement
sql = """INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
   Execute SQL statement
   cursor.execute(sql)
   Commit to database for execution
   db.commit()
except:
   Rollback if an error occurs
   db.rollback()

# SQL query statement
sql = "SELECT * FROM EMPLOYEE \ WHERE INCOME > %s" % (1000)
try:
   Execute SQL statement
   cursor.execute(sql)
   Get a list of all records
   results = cursor.fetchall()
   for row in results:
      fname = row[0]
      lname = row[1]
      age = row[2]
      sex = row[3]
      income = row[4]
       Print the result
      print ("fname=%s,lname=%s,age=%s,sex=%s,income=%s" % \
             (fname, lname, age, sex, income ))
except:
   print ("Error: unable to fetch data")
 
SQL update statement
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
try:
   Execute SQL statement
   cursor.execute(sql)
   Commit to database for execution
   db.commit()
except:
   Rollback if an error occurs
   db.rollback()
   
# SQL delete statement
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
try:
   Execute SQL statement
   cursor.execute(sql)
   # commit change
   db.commit()
except:
   Rollback if an error occurs
   db.rollback()
 
Close the database connection
db.close()
Copy the code

Python3 network programming

Python provides two levels of access to network services. :

  • Low-level network services support basic Sockets, which provide a standard BSD Sockets API that can access all methods of the Socket interface of the underlying operating system.
  • SocketServer, an advanced network service module, provides server-centric classes that simplify the development of network servers.

Socket is also called a socket. An application program sends or responds to network requests through the socket, enabling communication between hosts or processes on a computer.

Server side socket Break down
s.bind() Binding address (host, port)
s.listen() Start TCP Listening
s.accept() Passively accept TCP client connections and block waiting for them to arrive
Server side socket Break down
s.connect() Initializes the TCP server connection, usually in the format of address (host, port), if the connection fails, return socket.error
s.connect_ex() An extended version of the connect function that returns an error code instead of throwing an exception
A socket for public use Break down
s.recv() Accepts TCP data, which is returned as a string
s.send() Sends TCP data. The return value is the number of bytes to send
s.sendall() Sends TCP data in its entirety, returns None on success, and raises an exception on failure
s.recvfrom Receives UDP data, similar to recv(), but returns (data,address). Where data is the string containing the received data and address is the socket address that sends the data
s.sendto() Sends UDP data to a socket. Address is a tuple of the form (ipaddr, port) specifying the remote address. The return value is the number of bytes sent.
s.close() Close the socket
s.getpeername() Returns the remote address of the connected socket. The return value is usually a tuple (ipaddr,port)
s.getsockname() Returns the socket’s own address. Usually a tuple (ipaddr,port)
s.setsockopt(level,optname,value) Sets the value of the given socket option
s.getsockopt(level,optname[.buflen]) Returns the value of the socket option
s.settimeout(timeout) Sets the timeout period for socket operations. Timeout is a floating point number in seconds. A value of None indicates that there are no expired periods. In general, super periods should be set when sockets are first created, because they may be used for connected operations (such as connect())
s.gettimeout() Returns the value of the current timeout period, in seconds, or None if no timeout period is set.
s.fileno() Returns the file descriptor for the socket
s.setblocking(flag) If flag is 0, the socket is set to non-blocking mode, otherwise the socket is set to blocking mode (the default). In non-blocking mode, if recv() does not find any data, or send() does not send data immediately, socket.error is raised
s.makefile() Creates a file associated with the socket
The service side#! /usr/bin/python3
# file name: server.py

Import socket, sys module
import socket
import sys

Create a socket object
serversocket = socket.socket(
            socket.AF_INET, socket.SOCK_STREAM) 
The socket family can be AF_UNIX or AF_INET
Socket types can be either SOCK_STREAM or SOCK_DGRAM depending on whether they are connection-oriented or connectionless
#protocol: the default value is 0.

Get local host name
host = socket.gethostname()

port = 9999

# bind port number
serversocket.bind((host, port))

# Set the maximum number of connections, after exceeding the queue
serversocket.listen(5)

while True:
    Create a client connection
    clientsocket,addr = serversocket.accept()      

    print("Connection address: %s" % str(addr))
    
    msg='Welcome to the rookie tutorial! '+ "\r\n"
    clientsocket.send(msg.encode('utf-8')) clientsocket.close() Client#! /usr/bin/python3
# file name: client.py

Import socket, sys module
import socket
import sys

Create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

Get local host name
host = socket.gethostname() 

# set the port number
port = 9999

To connect to the service, specify the host and port
s.connect((host, port))

Receive data less than 1024 bytes
msg = s.recv(1024)

s.close()

print (msg.decode('utf-8'))
Copy the code

Python Internet module

agreement function port The module
http Web access 80 Httplib, urllib, XMLRPclib
nntp Read and post news articles 119 nntplib
ftp The file transfer 20 Ftplib, urllib
SMTP Send E-mail 25 smtplib
pop3 Accept the mail 110 poplib
IMAP4 Access to email 143 imaplib
Telnet The command line 23 telnetlib
gopher Find information 70 Gopherlib, urllib

SMTP Sending mail

#! /usr/bin/python3
import smtplib
from email.mime.text import MIMEText
from email.header import Header
 
sender = '[email protected]'
receivers = ['[email protected]']  To receive emails, you can set it to your QQ mailbox or other mailbox
 
The first parameter is the text content, the second plain parameter sets the text format, and the third UTF-8 parameter sets the encoding
message = MIMEText('Python mail sending tests... '.'plain'.'utf-8')
message['From'] = Header("Rookie Tutorial".'utf-8')     # the sender
message['To'] =  Header("Test".'utf-8')          # the receiver
 
subject = 'Python SMTP Mail Tests'
message['Subject'] = Header(subject, 'utf-8')
 
try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, message.as_string())
    print ("Email sent successfully")
except smtplib.SMTPException:
    print ("Error: Could not send mail")
  
Copy the code

If we do not have sendmail access, we can also use SMTP access of other service providers (QQ, netease, Google, etc.).

#! /usr/bin/python3
 
import smtplib
from email.mime.text import MIMEText
from email.header import Header
 
# Third-party SMTP service
mail_host="smtp.XXX.com"  # set server
mail_user="XXXX"    # username
mail_pass="XXXXXX"   # password
 
 
sender = '[email protected]'
receivers = ['[email protected]']  To receive emails, you can set it to your QQ mailbox or other mailbox
 
message = MIMEText('Python mail sending tests... '.'plain'.'utf-8')
message['From'] = Header("Rookie Tutorial".'utf-8')
message['To'] =  Header("Test".'utf-8')
 
subject = 'Python SMTP Mail Tests'
message['Subject'] = Header(subject, 'utf-8')
 
 
try:
    smtpObj = smtplib.SMTP() 
    smtpObj.connect(mail_host, 25)    # 25 is the SMTP port number
    smtpObj.login(mail_user,mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print ("Email sent successfully")
except smtplib.SMTPException:
    print ("Error: Could not send mail")
Copy the code

Python scripts

#! /usr/bin/env python3// Add this sentence to the beginning of the script

chmod +x hello.py

./hello.py
Copy the code

Print (b,end = ‘,’)