Python
导入pymysql import pymysql.cursors 连接数据库 import pymysql.cursors def connect(): return pymysql.connect(host='localhost', port=3306, user='root', password='386mysql.', database='test', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) 插入数据 def insert(): …
CSV (Comma Separated Values),逗号分隔值,有时也称为字符分隔值,因为分隔字符也可以不是逗号。
引入python csv import csv 使用csv reader读取 contacts.csv
10,jim,18614023231 11,tom,18614023232 12,mike,18614023233 with open(contacts.csv,newline='') as csvfile: reader=csv.reader(csvfile,delimiter=',') for row in reader: …
安装 pip install requests 导入 import requests 发送get请求 r = requests.get('http://www.baidu.com') r.status_code #200 r.text r.encoding r.cookies r.headers r.headers['content-type'] 发送post请求(自定义头部) headers = { 'Authorization': 'bearer …
触发异常 创建 division.py 文件
result = 2 / 0 print(result) 程序报错:
Traceback (most recent call last): File "division.py", line 1, in <module> result = 2 / 0 ZeroDivisionError: division by zero 捕获异常 try: result = 2 / 0 print(result) except ZeroDivisionError: print('除数不能为0') # output: 除数不 …
准备工作 1、文件结构
python_work(目录) -- hello.txt -- read_all.py -- read_by_line.py -- write_file.py -- append_file.py 2、创建hello.txt,内容如下:
hello world hello tomorrow hello time hello myself 读取整个文件 创建read_all.py,内容如下:
with open('hello.txt') as file_reader: content = file_reader.read() print(content) 逐 …
创建类 创建 animal.py 文件,定义动物类。
class Animal: """初始化方法""" def __init__(self, name, age): self.name = name self.age = age """方法eat""" def eat(self): print(self.name.title() + ' ' + 'is eating.') """方法run""" def …
定义函数 # 定义函数 def hello(): print('hello world!') # 调用函数 hello() # Prints out: hello world! 参数传递 1、设置参数
def hello(name): print('hello %s' % name) temp = hello('jack') # Prints out: hello jack print(temp) # Prints out: None def sum(a, b): return a + b sum(1, 2) # Prints out: 3 2、 …
创建元组 # 定义空元组 t1 = () print(t1) # Prints out: () print(type(t1)) # Prints out: <class 'tuple'> # 定义一元组 t2 = (2,) print(t2) # Prints out: (2,) print(type(t2)) # Prints out: <class 'tuple'> # 定义三元组 t3 = (30, 10, 55) print(t3) # Prints out: (30, 10, 55) print(type(t3)) # …
创建字典 1、使用{}字面量
person = { 'id': 1, 'name': 'peng', 'age': 20, 'address': 'Beijing' } print(person) # Prints out: {'id': 1, 'name': 'peng', 'age': 20, 'address': 'Beijing'} 2、使用内置函数dict
person = dict(id=1, …
集合特性 集合(set)是一个无序的不重复元素序列。
确定性。 互异性。 无序性。 创建集合 1、使用大括号 {} 创建
colors = { 'red', 'green', 'blue' } print(colors) # Prints out: {'green', 'red', 'blue'} numbers = { 1, 2, 3, 3, 4 } print(numbers) # Prints out: {1, 2, 3, 4} 2、使用 set() 函数创建
colors = …