#Exception#
""" try: (可能发生错误的代码) except: (如果出现异常,执行的代码) """ # 捕获指定异常 try: print(name) except NameError as e: print("出现了变量未定义异常") print(e) # 捕获多个异常 try: print(1 / 0) except (NameError, ZeroDivisionError) as e: # 用元组储存可能出现的异常 print(e) # 捕获所有异常 try: print(name) except Exception as e: # == except: print(e) else: # 没异常执行 print("很高兴, 没有出现异常") finally: # 无论如何都会执行的代码,如关闭文件等 print("结束力") # 异常具有传递性,会基于函数的调用一层一层向上传
#Json#
# JSON 是一个特定格式的字符串, 是各个编程语言的中转站, 可以实现语言的互通 # JSON 在python中是字典,或是列表(里面嵌套的是字典) # 导入JSON 模块 import json # 准备符合json 格式的python 数据 data = [{"name": "理塘丁真", "age": 23}, {"name": "芝士雪豹", "age": 0}] # 通过json.dumps(data) 方法把python 数据转化为json 数据, 但中文的话还得增加一个参数 json_str = json.dumps(data, ensure_ascii=False) print(type(json_str)) print(json_str) print("--------------") # 通过json.loads(data) 方法把json 数据转化为python 数据 s = '[{"name": "理塘丁真", "age": 23}, {"name": "芝士雪豹", "age": 0}]' python_str = json.loads(s) print(type(python_str)) print(python_str)
#Pychart.Bar#
from pyecharts.charts import Bar from pyecharts.options import LabelOpts bar = Bar() bar.add_xaxis(["中国", "美国", "英国"]) bar.add_yaxis("GDP", [30, 20, 10], label_opts=LabelOpts( position="right" )) # 将标签移至右侧 # 反转坐标轴 bar.reversal_axis() bar.render()
#Pychart.Line#
from pyecharts.charts import Line from pyecharts.options import TitleOpts, LegendOpts, ToolboxOpts, VisualMapOpts # 创建折线图对象 line = Line() # 对x和y轴进行增加数据 line.add_xaxis(["中国", "美国", "英国"]) line.add_yaxis("GDP", [30, 20, 10]) # 设置全局配置项, 更多的配置可以在pyecharts.org里面找 line.set_global_opts( title_opts=TitleOpts(title="GDP展示", pos_left="center", pos_bottom="1%"), # pos可以控制距离某个方向有多远(注意逗号) legend_opts=LegendOpts(is_show=True), # 表示是(否)展示图例 toolbox_opts=ToolboxOpts(is_show=True), # 表示是(否)展示工具箱 visualmap_opts=VisualMapOpts(is_show=True), # 表示是(否)展示视觉特效 ) # 使用render方法将代码生成为图像 line.render() # 运行之后会生成一个html文件, 可以在浏览器里打开
#Pychart.Map#
from pyecharts.charts import Map from pyecharts.options import VisualMapOpts # 准备地图对象 map = Map() # 准备数据 data = [ ("北京市", 99), ("上海市", 9), ("江西省", 99999), ("云南省", 599), ("广东省", 499) ] # 导入数据 map.add("测试地图", data, "china") # 设置全局属性 map.set_global_opts( visualmap_opts=VisualMapOpts( is_show=True, is_piecewise=True, pieces=[ {"min": 1, "max": 9, "label": "1-9人", "color": "#CCFFF"}, {"min": 10, "max": 99, "label": "10-99人", "color": "#FFFF99"}, {"min": 100, "max": 499, "label": "100-499人", "color": "#FF9966"}, {"min": 500, "max": 999, "label": "500-999人", "color": "#FF6666"}, {"min": 1000, "max": 9999, "label": "1000-9999人", "color": "#CC3333"}, {"min": 10000, "label": "10000以上", "color": "#990033"} ] ) ) map.render()
----------------------------------------------------Stage 2----------------------------------------------------
#Class#
import random
# # ----------------------------------------基础----------------------------------------
# # 设计一个类(类比为设计一张登记表)
# class Student:
# name = None # 成员变量
# gender = None
# nationality = None
# Native_place = None
# age = None
#
# # def 方法名(self, 形参1, ...): 想访问成员变量就必须用self
# def say_hi(self): # 成员方法
# print(f"大家好, 我是{self.name}")
#
#
# # 创建对象(打印一张表)
# stu_1 = Student()
# stu_2 = Student()
#
# # 对象属性进行赋值
# stu_1.name = "丁真珍珠"
# stu_1.gender = "man"
# stu_1.nationality = "China"
# stu_1.Native_place = "西藏"
# stu_1.age = 23
#
# stu_1.say_hi()
#
# # 获取对象中储存的信息
# print(stu_1.name)
#
#
# class Clock:
# id = None
# price = None
#
# def ring(self):
# import winsound
# winsound.Beep(50, 1000,)
#
#
# clock1 = Clock()
# clock1.ring()
# # ----------------------------------------魔术方法----------------------------------------
# # 构造方法 __init__ : 创建对象时自动执行, 并将参数自动传递给__init__方法使用
#
# class Info1:
# name = None
# age = None
# tel = None
#
# def __init__(self, name, age, tel):
# self.name = name
# self.age = age
# self.tel = tel
# print("创建了一个类对象")
#
# # 字符串方法 __str__
# # 当类对象需要被转换成字符串时, 往往会输出内存地址, 通过str方法可控制转换字符串行为
# # 在使用str()函数或者print时候被调用, 并自己决定输出什么内容
# def __str__(self):
# return f"Student类对象, name:{self.name}, age:{self.age}"
#
# # 小于大于符号比较 __lt__
# def __lt__(self, other):
# return self.age < other.age
#
# # 小于等于大于等于符号比较 __le__
# def __le__(self, other):
# return self.age <= other.age
#
# # ==符号比较 __eq__
# def __eq__(self, other):
# return self.age == other.age
#
#
# stu1 = Info1("尼古丁真", 23, 13879694754)
# stu2 = Info1("芝士雪豹", 5, 0)
# stu3 = Info1("理塘丁真", 23, 13879694754)
#
# print(stu1)
# print(stu1 < stu2)
# print(stu1 > stu2)
# print(stu1 <= stu3)
# print(stu1 == stu3)
#
#
# # ----------------------------------------封装----------------------------------------
# # 定义私有变量和私有方法: 在名称前面加上 __ 双下划线, 他们在创建的对象中不能被调用, 仅能在类中的其他成成员使用
# class Iphone:
# __iphone14 = None
#
# def __call(self):
# print("calling")
#
# # ----------------------------------------继承----------------------------------------
# # class 类名(父类名):
# # 类内容体
# # 对于多继承的同名属性, 越靠左优先级越高
# class Champion2021:
# gun_1 = "Vandal"
#
# def di4u(self):
# print("this could be the day i die for u")
#
#
# class Champion2022:
# gun_2 = "Phantom"
#
# def fire_again(self):
# print("Fire again")
#
#
# class Champion2023:
# gun_3 = "Vandal"
#
# def ticking_away(self):
# print("oh~")
#
#
# class Champion(Champion2021, Champion2022, Champion2023):
# pass # pass 关键字可以用来填充类
#
#
# vlr = Champion()
# vlr.di4u()
# vlr.fire_again()
# vlr.ticking_away()
# print(vlr.gun_3)
#
#
# class Fu_Rong_Wang:
# cigarette = "Old"
#
# def smoke(self):
# print("我芙蓉王源最爱")
#
# def shit(self):
# print("shit")
#
#
# class Rick5(Fu_Rong_Wang):
# cigarette = "Brand new" # 复写父类成员
#
# print(Fu_Rong_Wang.cigarette)
# print("super().cigarette") # 子类直接调用父类成员变量
#
# def smoke(self): # 复写父类方法
# Fu_Rong_Wang.smoke(self)
# Fu_Rong_Wang.shit(self)
# super().smoke() # 子类直接调用父类方法, 但只能在子类方法内调用, 且用super调用时不需要self
# print("我尼古丁真最爱")
#
#
# rk = Rick5()
# print(rk.cigarette)
# rk.smoke()
# ----------------------------------------变量类型注解----------------------------------------
# 为自己定义的函数(方法)中的变量给定类型, 方便Pycharm识别
# 方法 : 变量名: 类型 (= 值)
# tuple 的详细注解需要把每个元素都标注出来
# 基础数据类型注解
var_1: int = 24
var_2: str = "Kobe"
var_3: bool = True
# 类对象类型注解
class Student:
pass
stu: Student = Student()
# 基础容器类型注解
my_list: list = [1, 2, 3]
my_tuple: tuple = (1, 2, 3)
my_set: set = {1, 2, 3}
my_dict: dict = {"key": 1}
my_str: str = "man"
# 容器类型详细注解
myList: list[int] = [1, 2, 3]
myTuple: tuple[int, str, bool] = (1, "what", True)
mySet: set[int] = {1, 2, 3}
myDict: dict[str, int] = {"key": 1}
# 注释注解
var_4 = random.randint(8, 24) # type: int
def fun():
return 10
var_5 = fun() # type: int
# ----------------------------------------函数和方法类型注解----------------------------------------
def fun(x: int, y: str, z: bool) -> int: # 对形参和返回值进行注解
pass
# ----------------------------------------Union联合类型注解----------------------------------------
from typing import Union
mylist: list[Union[str, int]] = [1, 2, "man"]
mydict: dict[str, Union[str, int]] = {"Kobe": 24, "man": 8}
def func(data: Union[int, str]) -> Union[int, str]:
pass
# ----------------------------------------多态----------------------------------------
class Animal: # 顶层设计
def speak(self): # 抽象方法
pass
class Dog(Animal):
def speak(self):
print("woof woof")
class Cat(Animal):
def speak(self):
print("meow meow")
def make_noise(animal: Animal):
animal.speak()
dog = Dog()
cat = Cat()
make_noise(dog)
make_noise(cat)
#MySQL#
# -------------------------------------基础-------------------------------------
# -- 查看数据库
# show databases; # sql不区分大小写 -- 注释 /* 注释 */
#
# -- 使用数据库
# use sys;
#
# -- 创建数据库
# create database test charset utf8;
#
# -- 删除数据库
# drop database test;
#
# -- 查看当前使用的数据库
# select database();
# -------------------------------------DDL 表管理-------------------------------------
# use world;
#
# -- 查看表
# show tables;
#
# -- 创建表
# create table student(
# id int,
# name varchar(10), -- 限制长度
# age int
# );
# -- 列的类型有: int, float, varchar(字符), date(日期), timestamp(时间戳类型)
#
# 删除表
# drop table student;
# -------------------------------------DML-------------------------------------
# -- 向表中插入数据 insert into 表[(列1, 列2, ... , 列N)] values(值1, 值2, ... , 值N) [(值1, 值2, ... , 值N), ...]
# insert into student (id) values(1), (2), (3);
# insert into student (id, name, age) values(3, 'Paul', 29), (4, '乔治', 29);
#
# -- 数据删除 delete from 表 [where 条件判断] 如 id = 5, id < 3, id != 2 ...
# delete from student where id <=4
#
# -- 数据更新 update 表 set 列=值 [where 条件判断] 若不加条件判断,则会更新整张表的值
# update student set name='shit' where id = 1;
# -------------------------------------DQL-基础查询-分组聚合-排序分页-------------------------------------
# -- 数据查询 select 字段列表|* from 表 [where 条件判断] 含义: 从(from)表中, 选择(select)某些列进行展示
# select name from student;
# select * from student where age = 29;
#
# -- 分组聚合 select 字段|聚合函数 from 表 [where 条件] group by 列 可用来按性别, 年龄分组统计
# -- 聚合函数有: sum(列) 求和, avg(列)求平均值, min(列)求最小值, max(列)求最大值, count(列|*)求数量
# select gender, sum(age), avg(age), min(age), max(age), count(*) from student group by gender;
#
# -- 排序 select 字段|聚合函数 from 表 [where 条件] group by 列 oder by 列 [asc|desc](升|降序, 且asc是默认的)
# select * from student where age >= 18 order by age asc;
#
# -- 分页 + limit n[, m] 进行数量限制或者分页显示, 若加m则表示从第n+1条开始向后展示m条
# select * from student limit 6, 4;
#
# -- 注意: 顺序按照 select from where group by order by limit
# # -------------------------------------PYTHON操纵MySQL-------------------------------------
# from pymysql import Connection
#
# conn = Connection(
# host='localhost',
# port=3306,
# user='root',
# password='123456',
# autocommit=True # 设置自动提交就无需手动确认了
# )
# # # 打印数据库软件信息
# # print(conn.get_server_info())
# # ----------------------------------------------执行非查询性质的sql语句----------------------------------------------
# cursor = conn.cursor() # 获取游标对象
# conn.select_db("test") # 选择数据库
# cursor.execute("create table test_pymysql(id int, info varchar(255));") # 使用游标对象, 执行sql语句, 创建表(分号可写可不写)
# # ----------------------------------------------执行查询性质的sql语句----------------------------------------------
# cursor = conn.cursor() # 获取游标对象
# conn.select_db("world") # 选择数据库
# cursor.execute("select * from student")
#
# results: tuple = cursor.fetchall() # 获取查询结果
# for r in results:
# print(r)
# # ----------------------------------------------执行数据插入的sql语句----------------------------------------------
# cursor = conn.cursor() # 获取游标对象
# conn.select_db("world") # 选择数据库
# cursor.execute("insert into student values(001, '冈本', 18, '男')")
# conn.commit() # 确认插入操作, 也可在创建对象时设定自动提交
#
# # 关闭到数据库的链接
# conn.close()
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/2302_79764677/article/details/140266254