小皮博客 | Xiaopi's Blog

72-python基础-1

菜鸟教程确实做的挺好的。我这里只是搬运一下。

环境搭建及使用

  • 打开下载地址
  • 选择对应版本的安装包,这里使用的是3.7版本。下载并且安装。
  • 查看版本
    shengl-pro:11-python shengl$ python3 --version
    Python 3.7.0
    shengl-pro:11-python shengl$ pip3 --version
    pip 10.0.1 from /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip (python 3.7)
    

简单操作

helloworld

命令行操作

python3 # 进入交互式命令行

shengl-pro:11-python shengl$ python3
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> print("Hello World!")
Hello World!
>>> exit();
shengl-pro:11-python shengl$

编写HelloWorld程序

vim /Users/shengl/8-learn/11-python/00-startup/00-HelloWorld.py

#!/usr/bin/python3
# Author: Shengl

print("Hello, World!")

运行程序

shengl-pro:00-startup shengl$ python3 00-HelloWorld.py 
Hello, World!

基本语法

编码

  • 默认情况下以UTF-8编码,所有字符都是Unicode字符集

-- coding: utf-8 --

标识符

  • 一般规则,字母或者下划线,其他部分是字母,数字或者下划线。对大小写敏感。

保留字

  • 下述命令可以展示所有保留字
shengl-pro:00-startup shengl$ python3
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

注释

  • 单行用 #开头,多行用 ‘’’ 或者 “””

行与缩进

  • python用缩进表示代码块。所以对其和好的代码规范很重要。
  • \反斜杠用来实现多行语句。也可以用[],{},()来包括。

数字

int, bool, float, complex

字符串

  • 单引号和双引号作用一致
  • 三引号可以指定一个多行字符串
  • ‘\’是转义符号
  • “+”连接,*重复
  • index下标字符串可以0~ 开始,-1从右边开始。
  • python中的字符串不可以改变。没有字符类型,字符就是长度为一的字符串。
  • 变量[开始下标:结束下标]
#! /usr/bin/python3
# program name: 03-string.py
# comment: learn to use string
# author: ling

srcString = "Shengling"

print(srcString)                   # 输出字符串
print(srcString[0:-1])             # 第一个到倒数第二个
print(srcString[0])                # 输出字符串第一个字符
print(srcString[2:5])              # 输出从第三个开始到第五个的字符
print(srcString[2:])               # 输出从第三个开始的后的所有字符
print(srcString * 2)               # 输出字符串两次
print(srcString + '你好')           # 连接字符串

print('hello\srcString')           # 使用反斜杠(\)+n转义特殊字符
print(r'hello\srcString')          # 在字符串前面添加一个 r,表示原始字符串,不会发生转义

#输出如下

shengl-pro:00-startup shengl$ python3 03-string.py 
Shengling
Shenglin
S
eng
engling
ShenglingShengling
Shengling你好
hello\srcString
hello\srcString

空行

函数,方法或者累方法之间用空行分割,表示新的代码开始。和缩进不同的是,它并不是python语法到一部分。
在任何语言中,空行也是代码的一部分,不能多,也不要少。(可能不是程序的一部分)。

import和from … import

将整个模块导入, 格式为 import modulename.
导入某个(些)函数, 格式为 from modulename import functionName1 [, functionName2 …]
将某个模块的函数全部导入,格式为: from modulename import *

import sys

print("===========Python import mode=====")
print("命令行参数为")
for i in sys.argv:
    print(i)
print('\n python 路径为', sys.path)

执行结果

shengl-pro:00-startup shengl$ python3 04-import.py 
===========Python import mode=====
命令行参数为
04-import.py
 python 路径为 ['/Users/shengl/8-learn/11-python/00-startup', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages']

命令行参数

python -h

shengl-pro:00-startup shengl$ python3 -h
usage: /Library/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
-B     : don't write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x
...[etc.]

基本数据类型

  • 不可变: Number(数字),String(字符串),Tuple(元组);
  • 可变: List(列表),Dictionary(字典),Set(集合);

数字操作

a,b,c,d = 20,5.5,True,3+2j
print (type(a), type(b), type(c), type(d))
shengl-pro:00-startup shengl$ python3 10-number.py 
   

判定类型

  • type()不会认为子类是一种父类类型。
  • isinstance()会认为子类是一种父类类型。

列表

列表可以嵌套列表,使用广泛。数据类型也可以是任意

subList = ["sub1", 4+5j]
list = [ 'abc', 1024 , 2+3j, 'helloworld', subList ]    
print (list)            # 输出完整列表
print (list[3])         # 输出列表第一个元素
print (list[1:-1])      # 从第二个开始输出到第三个元素
print (list[2:])        # 输出从第三个元素开始的所有元素
print (subList * 2)     # 输出两次列表
print (list + subList)  # 连接列表
#执行之后的结果
shengl-pro:00-startup shengl$ python3 11-list.py 
['abc', 1024, (2+3j), 'helloworld', ['sub1', (4+5j)]]
helloworld
[1024, (2+3j), 'helloworld']
[(2+3j), 'helloworld', ['sub1', (4+5j)]]
['sub1', (4+5j), 'sub1', (4+5j)]
['abc', 1024, (2+3j), 'helloworld', ['sub1', (4+5j)], 'sub1', (4+5j)]
* 列表的元素可以被改变。用赋值操作 = * List内置了很多方法比如append(),pop() * 写在方括号中间,用逗号隔开 * 可以被索引和切片 * +进行拼接 ### Tuple(元组) TODO ### Set(集合) TODO ### Dictionary(字典) TODO ### Python的数据类型转换
# Python操作数据库MySQL ## 使用mysql-connector ### 安装 > pip3 install mysql-connector
shengl-pro:00-startup shengl$ python3
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import mysql.connector
Traceback (most recent call last):
  File "", line 1, in 
ModuleNotFoundError: No module named 'mysql'.     

 # 安装成功之后
shengl-pro:00-startup shengl$ pip3 install mysql-connector
Collecting mysql-connector
  Downloading https://files.pythonhosted.org/packages/59/e0/775bf5fb3dd4c7f9aa6877907d4a96eecca6886c603dedfea6e843e94560/mysql-connector-2.1.6.tar.gz (11.8MB)
    100% |████████████████████████████████| 11.8MB 504kB/s 
Installing collected packages: mysql-connector
  Running setup.py install for mysql-connector ... done
Successfully installed mysql-connector-2.1.6
You are using pip version 10.0.1, however version 18.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

>>> import mysql.connector
>>> 
 # 没有产生错误则安装成功。

数据库链接

  • 下载MySQL 5.7并且准备安装下载地址 ,安装MySQL不详细介绍了。
TODO 使用标准库

使用PyMySQL

安装准备

pip3 install PyMySQL

shengl-pro:00-startup shengl$ pip3 install PyMySQL
Collecting PyMySQL
  Downloading https://files.pythonhosted.org/packages/a7/7d/682c4a7da195a678047c8f1c51bb7682aaedee1dca7547883c3993ca9282/PyMySQL-0.9.2-py2.py3-none-any.whl (47kB)
    100% |████████████████████████████████| 51kB 364kB/s 
Collecting cryptography (from PyMySQL)
  Downloading https://files.pythonhosted.org/packages/98/0b/a6f293e5f10095dd8657a1b125c1ba6995c59d39cd8e20355475c8f760d0/cryptography-2.3.1-cp34-abi3-macosx_10_6_intel.whl (1.5MB)
    100% |████████████████████████████████| 1.5MB 515kB/s 
Collecting asn1crypto>=0.21.0 (from cryptography->PyMySQL)
  Downloading https://files.pythonhosted.org/packages/ea/cd/35485615f45f30a510576f1a56d1e0a7ad7bd8ab5ed7cdc600ef7cd06222/asn1crypto-0.24.0-py2.py3-none-any.whl (101kB)
    100% |████████████████████████████████| 102kB 467kB/s 
Collecting cffi!=1.11.3,>=1.7 (from cryptography->PyMySQL)
  Downloading https://files.pythonhosted.org/packages/0b/ba/32835c9965d8a0090723e1d0b47373365525c4bd08c807b5efdc9fecbc99/cffi-1.11.5-cp37-cp37m-macosx_10_9_x86_64.whl (163kB)
    100% |████████████████████████████████| 163kB 496kB/s 
Requirement already satisfied: idna>=2.1 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from cryptography->PyMySQL) (2.7)
Collecting six>=1.4.1 (from cryptography->PyMySQL)
  Downloading https://files.pythonhosted.org/packages/67/4b/141a581104b1f6397bfa78ac9d43d8ad29a7ca43ea90a2d863fe3056e86a/six-1.11.0-py2.py3-none-any.whl
Collecting pycparser (from cffi!=1.11.3,>=1.7->cryptography->PyMySQL)
  Downloading https://files.pythonhosted.org/packages/68/9e/49196946aee219aead1290e00d1e7fdeab8567783e83e1b9ab5585e6206a/pycparser-2.19.tar.gz (158kB)
    100% |████████████████████████████████| 163kB 419kB/s 
Installing collected packages: asn1crypto, pycparser, cffi, six, cryptography, PyMySQL
  Running setup.py install for pycparser ... done
Successfully installed PyMySQL-0.9.2 asn1crypto-0.24.0 cffi-1.11.5 cryptography-2.3.1 pycparser-2.19 six-1.11.0

测试数据库连接

import pymysql

 # db conn
dbconn = pymysql.connect("localhost", "root", "titps4gg", "py_test")

 # 使用cursor() 方法创建一个游标对象 cursor
cursor = dbconn.cursor()

cursor.execute("SELECT VERSION()")

 # 使用 fetchone() 方法获取单条数据
data = cursor.fetchone()
print ("Database version : %s" % data)
dbconn.close()
  • 运行程序

python3 25-mysql-pymysql-startup.py
Database version : 5.7.23


基本操作

  • 创建表
  • 插入一条多条数据
  • 查询一条或者多条数据
  • 更新删除
  • 执行事务
import pymysql

# db conn
dbconn = pymysql.connect("localhost", "test_user", "password", "py_test")

# 使用cursor() 方法创建一个游标对象 cursor
cursor = dbconn.cursor()

# DROP IFEXSIT

cursor.execute ("DROP TABLE IF EXISTS EMPLOYEE")

# 1. 使用预处理创建表
createSql = """CREATE TABLE EMPLOYEE(
               FIRST_NAME CHAR(20) NOT NULL, 
               LAST_NAME CHAR(20),
               AGE INT(4),
               SEX CHAR(1),
               INCOME FLOAT)"""
cursor.execute(createSql)

# 插入数据
insertOneSql = """INSERT INTO EMPLOYEE(FIRST_NAME,
                  LAST_NAME, AGE, SEX, INCOME)
                  VALUES ('Mac', 'Mohan', 20, 'M', 20000),('zhou', 'Yan', 20, 'M', 20000)"""

try:
     cursor.execute(insertOneSql)
     dbconn.commit()
except:
     print("Error while insert1")
     dbconn.rollback()

# once again
insertSql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
             LAST_NAME, AGE, SEX, INCOME) \
             VALUES('%s', '%s', '%d', '%c', '%d') " % \
             ('Ling', 'sheng', 20, 'M', 20000)

try:
     cursor.execute(insertSql)
     dbconn.commit()
except:
     print("Error while insert")
     dbconn.rollback()

# Search
searchSql = "SELECT * FROM EMPLOYEE \
             WHERE INCOME > '%d'" % (1500)
try:
     cursor.execute(searchSql)
     results = cursor.fetchall()
     for row in results:
         fname = row[0]
         lname = row[1]
         age = row[2]
         sex = row[3]
         income = row[4]
         print("fname=%s, lname=%s, age=%d, sex=%s, income=%d" % \
              (fname, lname, age, sex, income))
except Exception as e:
     print("Error while search: {0}".format(e))

# Update
updateSql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')

try:
     cursor.execute(updateSql)
     dbconn.commit()
except:
     print("Error while update")
     dbconn.rollback()

# Delete
deleteSql = "DELETE FROM EMPLOYEE WHERE FIRST_NAME = '%s'" % ('Mac')

try:
     cursor.execute(deleteSql)
     dbconn.commit()
except:
     print("Error while delete")
     dbconn.rollback()

dbconn.close()

执行结果

shengl-pro:00-startup shengl$ python3 26-pymysql-detail.py 
fname=Mac, lname=Mohan, age=20, sex=M, income=20000
fname=zhou, lname=Yan, age=20, sex=M, income=20000
fname=Ling, lname=sheng, age=20, sex=M, income=20000
 # 数据库中应该有2条数据。

Python发送网络请求

使用urllib

import urllib.request
import urllib.parse

url = "http://localhost:9200/_cat/master?v&pretty"
response = urllib.request.urlopen(url)
print(response.read().decode('utf-8'))

执行代码,这里是对本机的elastic search做请求

shengl-pro:00-startup shengl$ python3 30-use-urllib.py 
id                     host      ip        node
H-thNd-UT6SoHcIN8_c-_g 127.0.0.1 127.0.0.1 H-thNd-

使用requests

  • 安装requests,前面的urllib不需要安装,是python标准库
shengl-pro:00-startup shengl$ pip3 install requests
Collecting requests
  Downloading https://files.pythonhosted.org/packages/65/47/7e02164a2a3db50ed6d8a6ab1d6d60b69c4c3fdf57a284257925dfc12bda/requests-2.19.1-py2.py3-none-any.whl (91kB)
    100% |████████████████████████████████| 92kB 433kB/s 
Collecting chardet<3.1.0,>=3.0.2 (from requests)
  Downloading https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl (133kB)
    100% |████████████████████████████████| 143kB 2.4MB/s 
Collecting urllib3<1.24,>=1.21.1 (from requests)
  Downloading https://files.pythonhosted.org/packages/bd/c9/6fdd990019071a4a32a5e7cb78a1d92c53851ef4f56f62a3486e6a7d8ffb/urllib3-1.23-py2.py3-none-any.whl (133kB)
    100% |████████████████████████████████| 143kB 1.7MB/s 
Collecting certifi>=2017.4.17 (from requests)
  Downloading https://files.pythonhosted.org/packages/df/f7/04fee6ac349e915b82171f8e23cee63644d83663b34c539f7a09aed18f9e/certifi-2018.8.24-py2.py3-none-any.whl (147kB)
    100% |████████████████████████████████| 153kB 1.2MB/s 
Collecting idna<2.8,>=2.5 (from requests)
  Downloading https://files.pythonhosted.org/packages/4b/2a/0276479a4b3caeb8a8c1af2f8e4355746a97fab05a372e4a2c6a6b876165/idna-2.7-py2.py3-none-any.whl (58kB)
    100% |████████████████████████████████| 61kB 438kB/s 
Installing collected packages: chardet, urllib3, certifi, idna, requests
Successfully installed certifi-2018.8.24 chardet-3.0.4 idna-2.7 requests-2.19.1 urllib3-1.23

编写代码

import requests  
url = "http://localhost:9200/_cat/master?v&pretty"
response = requests.get(url)
print(response.text)

运行代码的返回结果

shengl-pro:00-startup shengl$ python3 31-use-requests.py 
id                     host      ip        node
H-thNd-UT6SoHcIN8_c-_g 127.0.0.1 127.0.0.1 H-thNd-

Python操作JSON

基本说明

  • json.dumps(): 对数据进行编码。
  • json.loads(): 对数据进行解码。
  • 编码转换说明
    • python格式 => JSON格式
    • dict => object
    • list,tuple => array
    • str => string
    • int,float,int- & float.. => number
    • True => true
    • False => false
    • None => null
  • 解码说明
    • object => dict
    • arry => list
    • string => str
    • number(int) => int
    • number(real) => float
    • 其他逆向

实例

import json

# 构造数据结构
subList = ["sub1", 4+5j]
listData = [ 'abc', 1024 , 2+3j, 'helloworld', subList ]
dictData = {
    'number1' : 1,
    'name' : 'ling',
    'url' : 'http://blog.xiaoyuyu.net'
}

# Python object to JSON
jsonDict = json.dumps(dictData)
print("python原始字典", repr(dictData))
print("转换为JSON对象后的字典", jsonDict)
print("")

subList = [1,2,3,4]
listData = [ 'abc', 1024 , "2+3j", 'helloworld', subList]
jsonList = json.dumps(listData)
print("python原始列表", repr(listData))
print("转换为JSON对象后的列表", jsonList)
print("")

# JSON to Python object 
pythonObject1 = json.loads(jsonDict)
print("pythonObject1['name']: ", pythonObject1['name'])
pythonObject2 = json.loads(jsonList)
print("pythonObject2[4][2]:", pythonObject2[4][2])

# 写入文件
with open('/tmp/demo-list.json', 'w') as outputFileList:
    json.dump(jsonList, outputFileList)
with open('/tmp/demo-dict.json', 'w') as outputFileDict:
    json.dump(jsonDict, outputFileDict)

# 从文件中读取
with open('/tmp/demo-list.json', 'r') as inputFileList:
    poListFile = json.loads(inputFileList)

#执行结果

shengl-pro:00-startup shengl$ python3 40-json-transfer.py 
python原始字典 {'number1': 1, 'name': 'ling', 'url': 'http://blog.xiaoyuyu.net'}
转换为JSON对象后的字典 {"number1": 1, "name": "ling", "url": "http://blog.xiaoyuyu.net"}

python原始列表 ['abc', 1024, '2+3j', 'helloworld', [1, 2, 3, 4]]
转换为JSON对象后的列表 ["abc", 1024, "2+3j", "helloworld", [1, 2, 3, 4]]

pythonObject1['name']:  ling
pythonObject2[4][2]: 3

查看文件,已经写入

vim /tmp/demo-dict.json

"{\"number1\": 1, \"name\": \"ling\", \"url\": \"http://blog.xiaoyuyu.net\"}"

Python正则表达式

TODO

版权声明

本文标题:72-python基础-1

文章作者:盛领

发布时间:2018年10月14日 - 00:41:40

原始链接:http://blog.xiaoyuyu.net/post/eae73e4e.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

如您有任何商业合作或者授权方面的协商,请给我留言:sunsetxiao@126.com

盛领 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
坚持原创技术分享,您的支持将鼓励我继续创作!