单行注释
#
多行注释
‘’’
‘’’
“”"
“”"
name = 'xr'
Number (数字)
int 整形
float 浮点型
complcx 复数
String (字符串)
Boolean (布尔)
True
False
List (列表)
Set (集合)
Tuple (元祖)
numTuple = (1,2,3)
Dictionary(字典)
f"{name}"
age = 20
print(type(age)) #
age = 2.0
print(type(age)) #
bool = False
print(type(bool)) #
userList = ['xr', 'zs']
print(type(userList)) #
numTuple = (1, 2, 3)
print(type(numTuple)) #
users = {'name': 'xr'}
print(type(users)) #
a = 2.0
b= int(a)
print(b,type(b)) # 2
a = True
b= int(a)
print(b,type(b)) # 1
a = '123'
b= int(a)
print(b,type(b)) # 123
# 错误
a = '123a'
b= int(a)
print(b,type(b)) # ValueError: invalid literal for int() with base 10: '123a'
a = '1.23'
b= int(a)
print(b,type(b)) # ValueError: invalid literal for int() with base 10: '1.23'
a = 10
b= float(a)
print(b,type(b)) # 10.0
a = '10'
b= float(a)
print(b,type(b)) # 10.0
a = True
b= float(a)
print(b,type(b)) # 1.0
a = 1
b= str(a)
print(b,type(b)) # 1
a = 1.3
b= str(a)
print(b,type(b)) # 1.3
a = True
b= str(a)
print(b,type(b)) # True
# a = 0
# a = 0.0
# a = ''
# a = []
# a = ()
a = {}
b= bool(a)
print(b,type(b)) # False
age = 12
if age > 18:
print('大于18')
elif age < 10:
print('小于10')
else:
print('大于18小于10之间')
range()
for num in range(6):
print(num)
0
1
2
3
4
5
for num in range(2, 6):
print(num)
2
3
4
5
for num in range(2, 6, 3):
print(num)
2
5
userList = ['小明', '小红']
for user in userList:
print(user)
for user in range(len(userList)):
print(user)
小明
小红
0
1
a = 'abcde'
# 5
print(len(a))
# 1
print(a.find('b'))
# 1
print(a.count('c'))
a=' abc '
# abc
print(a.strip())
a='1,2,3'
# ['1', '2', '3']
print(a.split(','))
a='abc'
# ABC
print(a.upper())
a='ABC'
# abc
print(a.lower())
str = 'abcd'
value = str.replace('b','e')
print(value) # aecd
print(str) # abcd
查找某元素的下标 index(查找的元素)
list = ['a','b','c']
print(list.index('b')) # 1
print(list.index('d')) # 如果元素不存在会报错 'd' is not in list
修改列表的下标值
list = ['a','b','c']
list[1] = 2
print(list) # ['a', 2, 'c']
插入元素 insert(下标,值)
list = ['a','b','c']
list.insert(3,'d')
print(list) # ['a', 'b', 'c', 'd']
追加元素到尾部 append(值)
list = ['a','b','c']
list.append('d')
print(list) # ['a', 'b', 'c', 'd']
追加多个元素 extend([多个值,…])
list = ['a','b','c']
list.extend(['d','e'])
print(list) # ['a', 'b', 'c', 'd', 'e']
删除元素
# del list[下标]
list = ['a','b','c']
del list[1]
print(list) # ['a', 'c']
# pop(下标)
list = ['a','b','c']
ele = list.pop(1)
print(list,ele) # ['a', 'c'] b
# remove(删除的值)
list = ['a','b','c']
list.remove('b')
print(list) # ['a', 'c']
# 清空列表 clear()
list = ['a','b','c']
list.clear()
print(list) # []
统计某元素出现的次数
list = ['a','b','c','a']
count = list.count('a')
print(count) # 2
统计列表总元素个数
list = ['a','b','c']
length = len(list)
print(length) # 3
list = ['a','b','c']
print('a' in list) # True
print('d' in list) # False
print('d' not in list) # True
while
list = ['a','b','c']
index = 0
while index < len(list):
print(list[index])
index += 1
for in
list = ['a','b','c']
for i in list:
print(i)
元祖中的数据不能被修改,但是如果嵌套列表则列表里可以修改
如果元祖中只有一个值,那么结尾要加逗号否则是 int 类型
a= (4)
b=(5,)
c=()
#
print(type(a),type(b),type(c))
index()
count()
len()
while
for in
序列是指:内容连续,有序,可使用下标索引的一类数据容器
列表、元组、字符串均可视为序列
语法:序列[起始下标(包含,可以写空):结束下标(不包含,可以写空):步长]
切片并不会影响序列,而是创建一个新的数据
a = 'abcdef'
# a
print(a[0])
# ab
print(a[0:2])
# ab
print(a[:2])
# bcdef
print(a[1:])
# ac
print(a[0:4:2])
集合:是无序的,不是序列,不支持元素的重复
set = {'a','b'}
空 {} 是 字典
空集合需要这样定义
set = set()
添加元素 add(添加的元素)
set = {'a','b','c'}
set.add('d')
print(set) # {'c', 'a', 'd', 'b'}
移除元素 remove(移除的元素)
set = {'a','b','c'}
set.remove('b')
print(set) # {'a', 'c'}
从集合随机取出元素(既删除)
set = {'a', 'b', 'c'}
res = set.pop()
print(res, set) # c {'a', 'b'}
清空集合
set = {'a', 'b', 'c'}
set.clear()
print(set) # set()
取出两个集合的差集
语法:集合 1.difference(集合 2)
取出集合 1 和集合 2 的差集(集合 1 有而集合 2 没有的元素),得到一个新的集合,集合 1 集合 2 不变
set1 = {1,2,3}
set2 = {1,4,5}
res = set1.difference(set2)
print(res) # {2, 3}
消除两个集合的差集
语法:集合 1.difference_update(集合 2)
对比集合 1 和集合 2 的,在集合 1 内,删除和集合 2 相同的元素。集合 1 被修改了,集合 2 不变
set1 = {1,2,3}
set2 = {1,4,5}
set1.difference_update(set2)
print(set1,set2) # {2, 3} {1, 4, 5}
两个集合合并
set1 = {1,2,3}
set2 = {1,4,5}
set3 = set1.union(set2)
print(set3) # {1, 2, 3, 4, 5}
统计集合元素数量
set = {1,2,3}
print(len(set)) # 3
for in
获取字典的个数
user = {'name': 'xr', 'age': 20}
print(len(user)) # 2
获取 value
user = {"name":"xr","age": 15}
# xr
print(user['name'])
# 15
print(user.get('age'))
# None
print(user.get('sex'))
# KeyError: 'sex'
print(user['sex'])
新增和修改,有则修改,无则新增
user = { "age": 15}
user['name'] = 'xr'
print(user) # {'age': 15, 'name': 'xr'}
删除
user = {'name': 'xr', 'age': 20}
res = user.pop('name')
print(res) # xr
print(user) # {'age': 20}
user = {'name': 'xr', 'age': 20}
# del user["age"]
# {'name': 'xr'}
del user
# 会把字典 user 包括变量整个删除
# NameError: name 'user' is not defined. Did you mean: 'super'?
print(user)
user = {'name': 'xr', 'age': 20}
# 清空
user.clear()
# {}
print(user)
user = {'name': 'xr', 'age': 20}
for key in user.keys():
# name
# age
print(key)
for value in user.values():
# xr
# 20
print(value)
for key,value in user.items():
# name xr
# age 20
print(key,value)
for item in user.items():
# ('name', 'xr')
# ('age', 20)
print(item)
def f():
print('1')
f()
函数返回值
def sum(a,b):
return a+b
res = sum(2,3)
result = sum(b=3,a=5)
print(res,result)
多个返回值
def f():
return 1, 2
x, y = f()
print(x, y) # 1 2
def user(name, age=18):
print(f"{name}--{age}")
# 位置参数
user('xr', 20) # xr--20
# 关键字参数
user(age=10, name='zs') # zs--10
# 缺省参数(默认值)
user('ls') # ls--18
# 不定长参数
def info(*args):
print(args) # 合并为元组类型
info() # ()
info('xr') # ('xr',)
def user_info(**kwargs):
print(kwargs)
# 传递 key=value
user_info(name='xr',age=20) # {'name': 'xr', 'age': 20}
def test(fun):
res = fun(1, 2)
print(res)
def fun(x, y):
return x+y
test(fun) # 3
函数体只能写一行
lambda x,y: x+y
def test(fun):
res = fun(1, 3)
print(res)
test(lambda x, y: x+y) # 4
def add(x,y):
"""
add 计算两数和
:param x:
:param y:
:return: 结果
"""
result = x + y
print(f'x+y: {result}' )
return result
add(1,2)
num = 100
print(num) # 100
def init():
num = 20 # 此时局部 num 和 全局 num 不是一个变量
print(num) # 20
init()
print(num) # 100
global 关键字把局部变量设为全局变量
num = 100
print(num) # 100
def init():
global num # 设置内部变量为全局变量
num = 20
print(num) # 20
init()
print(num) # 20
read(num) num 读取文件的长度,没写则读取所有内容
# f = open('test.txt','r',encoding='utf-8')
# print(f.read())
# readlines 读取文件的全部行放进列表中,每个值是一行内容
# print(f.readlines())
# readline() 读取文件一行
# f.readline()
# 循环读取文件
# for line in f:
# print(line)
# 文件关闭
# f.close()
# with open 不需要手动关闭
# with open('test.txt') as f:
# for line in f:
# print(line)
f = open('test.txt','a',encoding='utf-8')
f.write('\n内容')
f.close()
try:
可能出现错误的代码
except:
出现异常执行的代码
try:
f = open('tests.txt', 'r')
except:
print('File not found')
try:
f = open('not.txt', 'r')
except FileNotFoundError as e:
print(f"{e}")
try:
f = open('not.txt', 'r')
except (FileNotFoundError,NameError):
print()
try:
f = open('not.txt', 'r')
except Exception as e:
print(e)
else:
print('没有出现异常执行的代码')
finally:
print('无论成功还是失败都会执行的代码')
语法:[from 模块名] import [模块|类|变量|函数|*] [ as 别名]
import time
print('11')
time.sleep(2)
print('22')
import time as times
print('11')
times.sleep(2)
print('22')
from 模块名 import 功能名
from time import sleep
print('11')
sleep(2)
print('22')
from time import sleep as sleeps
print('11')
sleeps(2)
print('22')
# 导入 time 所有功能
from time import *
print('11')
sleep(2)
print('22')
新建 custom_module.py 文件
def add(num1, num2):
print(num1 + num2)
# __main__ 模块引入的时候不会调用下面,只有单独运行此文件才会执行
if __name__ == '__main__':
add(2, 3)
index.py
import custom_module
custom_module.add(1,2)
只有 __all__中有的函数才能在 from custom_module import *
引入方式中使用
__all__ = ['subtract']
def add(num1, num2):
print(num1 + num2)
def subtract(num1, num2):
print(num1 - num2)
from custom_module import *
subtract(1,2)
add(1,2) # "add" is not defined
必须有 init.py 可以为空文件
custom_package/init.py
__all__ = ['module']
custom_package/module.py
def add(num1, num2):
print(num1 + num2)
index.py
import custom_package.module
custom_package.module.add(1,3)
from custom_package.module import add
add(2,4)
all
from custom_package import *
module.add(2,4)
下载
pip install 包名
使用镜像加速
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple 包名
import json
把 python 数据转化 json 数据
json.dumps(user)
把 json 数据转化 python 数据
json.loads(user)
class Student:
name = None
# 此时方法中 self 必填
def say_hi(self):
print(f"{self.name}")
stu = Student()
stu.name = 'xr'
stu.say_hi()
class Student:
# 此处变量可以省略
name = None
def __init__(self, name):
self.name = name
print('__init__')
# 实例化时构造方法就会执行
stu = Student('xr')
只能在类内中使用
class Student:
__name = None
def __say_hi(self):
print("__say_hi")
stu = Student()
stu.__say_hi() # 'Student' object has no attribute '__say_hi'
单继承
class Person:
def print_info(self):
print('person')
class Student(Person):
def print(self):
print('student')
stu = Student()
stu.print()
多继承
class Person:
def print_info(self):
print('person')
class Teacher:
def print_info(self):
print('Teacher')
class Student(Teacher, Person):
# pass 解决不写内容报错
pass
stu = Student()
stu.print_info() # Teacher
子类中调用父类中的方法
class Person:
def print_info(self):
print('person')
class Student(Person):
def print(self):
# 方式1
Person.print_info(self)
# 方式2 此时不需要传 self
super().print_info()
stu = Student()
stu.print()
变量类型注解
# 类对象注解
class Student:
pass
stu: Student = Student()
# 基础容器类型注解
list: list = [1, 2]
tuple: tuple = (1, '2')
dict: dict = {"name": "xr"}
# 容器类型详细注解
list: list[int] = [1, 2]
tuple: tuple[int,str] = (1, '2')
dict: dict[str,str] = {"name": "xr"}
# 在注释中进行类型注解
num = 10 # type: int
函数和方法类型注解
# 形参就行类型注解
def add(x: int, y: int):
x+y
# 函数返回值就行注解
def add(x: int, y: int) -> int:
return x+y
混合类型注解
Union
from typing import Union
list: list[Union[str, int]] = [1, 'a']
dict: dict[str, Union[str, int]] = {
"name": "xr",
"age": 18
}
此时 num1 在 inner 中不能修改
def outer(num1):
def inner(num2):
print(f"{num1} = {num2}")
return inner
fn = outer(1)
fn(2) # 1 = 2
使用 nonlocal 修饰符
def outer(num1):
def inner(num2):
nonlocal num1
num1 += num2
print(f"{num1}")
return inner
fn = outer(1)
fn(2) # 3
写法1
import time
定义一个 sleep 函数,不改变函数情况下增加功能
def sleep():
print('睡眠中...')
time.sleep(1)
def outer(cb):
def inner():
print('新增逻辑1')
cb()
print('新增逻辑2')
return inner
fn = outer(sleep)
fn()
使用语法糖
import time
def outer(cb):
def inner():
print('新增逻辑1')
cb()
print('新增逻辑2')
return inner
@outer
def sleep():
print('睡眠中...')
time.sleep(1)
sleep()
单例模式
app.py
class Utils:
pass
utils = Utils()
index.py
from app import Utils
u1 = Utils
u2 = Utils
print(id(u1)) #1381794304896
print(id(u2)) # 1381794304896
工厂模式
class Person:
pass
class Student(Person):
pass
class PersonFactory:
def get_person(self,type):
if type == 's':
return Student
p = PersonFactory()
s = p('s')