本笔记用作个人学习和查漏补缺使用,欢迎借鉴学习,提出建议,转载需标注出处www.jjyaoao.space

Day01

各种表示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 可以输出数字
print(520);
print(98.5);
print("hello world");
print('hello world');

# 含有运算符的表达式
print(3+1);

#将数据输出文件中 注意点2.使用file = fp
fp = open('D:/text.txt','a+'); #a+如果文件不存在就创建,存在就在文件后面继续追加
print('helloworld' , file = fp);
fp.close();

#不进行换行输出(输出内容在一行当中)

print('hello','world','Python');

#转义字符
#python中\t 占4字节,c++中占8字节
print('hello\nworld'); # \ + 首字母 n --》 newline 的首字符表示换行
print('hello\tworld');
print('helloooo\tworld');
print('hello\rworld'); #world将hello进行覆盖
print('hello\bworld'); # \b退格


print('https:\\\\www.baidu.com');
print("老师说:\'大家好\'");

#源字符,不希望字符串中的转义字符起作用,就使用源字符,就是在字符串之前加上r,或R

print(r'hello\nworld');

#注意事项 最后一个字符不能是反斜杠
#print(r'hello\nworld\');
print(r'hello\nworld\\');

print(chr(0b100111001011000));
print(ord('乘'));

注释

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
name = '玛丽亚'
print(name);
print("标识",id(name));
print("类型",type(name));
print("值",name);

print("十进制",118);
print("二进制",0b1010111);
print("八进制",0o176);
print("十六进制",0x1EAF);

#十六进制 hexadecimal
#八进制 octal
#二进制 binary
#十进制 decimal

#浮点数
a = 3.1415926;
print(a,type(a));
n1 = 1.1;
n2 = 2.2;
print(n1+n2);

from decimal import Decimal
print(Decimal('1.1') + Decimal("2.2"));

f1 = True;
f2 = False;
print(f1 + 1); # 2
print(f2 + 1); # 1

str1 = '人生苦短 我用python';
str2 = "人生苦短,我用python";
str3 = '''人生苦短
我用python ''';
str4 = """人生苦
短我用python"""

print(str1,type(str1));
print(str2,type(str2));
print(str3,type(str3));
print(str4,type(str4));

name = "张三";
age = 20;
#print('我叫' + name + '今年,' + age + "岁");#会报错,不支持直接连接两个不同字符类型
print('我叫' + name + '今年,' + str(age) + "岁");

a = 10;
b = 198.8;
c = False;
print(type(a),type(b),type(c));
print(str(a),str(b),str(c));
print(type(str(a)),type(str(b)),type(str(c)));

'''
多行注释
啊啊

'''

强转

1
2
3
4
5
6
7
8
9
10
#input输入函数
# present = input("大圣想要什么礼物呢?");
# print(present,type(present));

a = input('请输入一个加数:');
b = input("another");
print(type(a),type(b));

print(a+b);
print(int(a)+int(b));

运算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
print(1+1); #加法运算
print(1-1);
print(2*4);
print(1/2); # /除法运算
print(11//2); # //整除运算
print(11 % 2); # %取余运算
print(2**3); #表示的是2的3次方
print(-9//-4) # 2
print(9 // -4) # -3
print(-9 // 4) # -3

print(9 % -4) # -3 公式 余数= 被除数-除数*商 9 - (-4)*(-3) = -3
print(-9 % 4) # 3

a = b = c = 20;
print(a,id(a));
print(b,id(b));
print(c,id(c));
print('------支持参数赋值-------');
a = 20;
a += 30;
print(a);
a -= 10;
print(a);
a*=2;
print(a);
print(type(a));
a /= 3;
print(a);
print(type(a));
a //= 2;
print(a);
a %= 3;
print(a);
print(type(a));

print("--------解包赋值----------");
a,b,c = 20,30,40;
print(a,b,c);
'''一一对应'''

a,b = 10, 20;
print('交换之前:',a,b);
a,b = b,a;
print('交换之后',a,b);

位运算,优先级

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
a,b = 10, 20;
print('a>b吗?',a > b);
print('a<b吗?',a < b);
'''= ==

==比较的是值还是标识呢?比较的是值
比较对象标识的使用 is (算是地址吧)

java里==比较的是地址
equal()比较的是字符串内的内容
'''
lst1=[11,22,33,44];
lst2=[11,22,33,44];
print(lst1==lst2);
print(lst1 is lst2);
print(lst1 is not lst2);

print(id(lst1));
print(id(lst2));

a,b = 1,2;
print(a == 1 and b == 2); # true
print(a == 1 or b == 2); #true

f = True;
f2 = False;
print(not f);
print(not f2);

s = "helloworld";
print('w' in s);
print('k' in s);

'''
算术:** 乘除取余 +-
位 >> << & |
比较 >= <= > < == !=
布尔 and or
比较 =
算数优先级从上到下执行,算数开始-》比较
有括号先算括号的
'''

对象的布尔值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
'''
Python一切皆对象,每个对象都有一个布尔值
'''
print(bool(False));
print(bool(0));
print(bool(0.0));
print(bool(None));
print(bool(''));
print(bool(""));
print(bool([])); #空列表
print(bool(list())); #空列表
print(bool( () )); #空元组
print(bool(tuple()));#空元组
print(bool({})); #空字典
print(bool(dict())); #空字典
print(bool(set())); #空集合

"""以上皆是false,其余都是true"""

分支结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# money = 1000; #余额
# s = int(input('请输入取款金额'));
# #判断余额是否充足
# if money >= s :
# money = money - s;
# print('取款成功,余额为',money);
# else:
# print('余额不足');

# score = int(input('请输入一个成绩'));
# if 90<=score<=100:
# print('A');
# elif 80 <= score <= 89:
# print('B');
# elif 70 <= score <= 79:
# print('C');
# elif 60 <= score <= 69:
# print('D');
# elif 0 <= score <= 59:
# print('EEEE');
# else:
# print('不及格啊');

# answer = input('你是会员吗?Y/N');
# money = float(input('请输入您的购物金额'));
#
# if answer == 'y':# 不区分大小写,好耶,离谱
# if money >= 200:
# print('八折,付款金额为:',money*0.8);
# elif money >= 100:
# print('九折,付款金额为:',money*0.9);
# else:
# if money>=200:
# print('打9.5折',money*0.95);
# else:
# print('不打折',money);

# print('使用条件表达式进行比较')
# num_a = int(input("请输入第一个整数"));
# num_b = int(input("请输入第二个整数"));
# print(str(num_a) + '大于等于' + str(num_b) if num_a>=num_b else str(num_a) + "小于" + str(num_b));

# answer = input('您是会员吗?y/n');
# if answer == 'y':
# pass
# else:
# pass #pass 自动跳过本句,用来搭建框架吧

age = int(input('请输入您的年龄'));

if age: #每一个都是布尔值
print(age);
else:
print('年龄为:',age);

range函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#range()的三种创建方式
'''第一种创建方式'''
r = range(10);
print(r); #range(0,10)
print(list(r)); #用于查看range对象中的整数序列 -->list是列表的意思

r = range(1,10); #左闭右开
print(list(r));

r = range(1,10,2);#起始值,结束值,步长
print(list(r)) #[1,3,5,7,9]
print(10 in r);
print(9 in r);

print(10 not in r);
print(9 not in r);

While

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
a = 1;
sum = 0;
while a < 10:
print(a);
sum += a;
a+=1;
print('和为',sum);

a = 1;
sum = 0;
while a <= 100:
sum+=a;
a+=1;
print(sum)

a = 0;
while a < 3:
pwd = input('请输入密码');
if pwd == '8888':
print('密码正确');
break;
else:
print('密码不正确');
a+=1;
else:
print('对不起,三次密码均属入错误');

for-in

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
'''for 自定义的变量 in 可迭代对象'''

for item in 'python':
print(item);

#range()产生一个整数序列
for i in range(10):
print(i);
#不需要自定义变量,可将自定义变量写为’_‘
for _ in range(5):
print('人生苦短我用python');

sum = 0;
for item in range(1,101):
if item % 2 == 0:
sum += item;
print('1-100之间偶数和为',sum);

for item in range(100,1000):
ge = item%10 #个位
shi = item // 10 % 10; #十位
bai = item // 100; #百位

if ge**3 + shi**3 + bai**3 == item:
print(item);

break

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# for item in range(3):
# pwd = input('请输入密码:');
# if pwd == '8888':
# print('密码正确');
# break;
# else:
# print('密码不正确');

# for item in range(1,51):
# if item % 5 == 0:
# print(item);
#
# for item in range(1,51):
# if item% 5 != 0:
# continue;
# print(item);

for item in range(3):
pwd = input('请输入密码:');
if pwd == '8888':
print('密码正确');
break;
else:
print('密码不正确');
else:
print('对不起,三次密码均输入错误');

嵌套循环

1
2
3
4
5
6
7
8
9
for i in range(1,4):
for j in range(1,5):
print('*',end = '\t');
print() #换行 print() = print(end = '\n');

for i in range(1,10):
for j in range(1,i+1):
print(i,'*',j,'=',i*j,end='\t'); #end=应该是连续输出的意思吧
print();

为何需要列表

1
2
3
4
5
6
7
#变量可以储存一个元素,列表则是一个大容器,可以存储n多个元素,程序可以方便对这些数据进行整体操作
#列表相当于其他语言中的数组

lst = ['hello','world',98];
print(id(lst)); #列表对象的id
print(type(lst)); #列表对象的类型
print(lst); #列表对象的值

keyword_demo

1
2
3
import keyword
print(keyword.kwlist)
'''调出所有关键字'''

Day02

BUG

BUG各种各样

1
2
3
4
5
6
7
8
9
'''
age = input ('请输入你的age'); #input读入全是str类型,下面if要用需要进行强转
if age >= 18 #没有打分号
print('chengnianren');
= 赋值 ==判断

索引越界
方法使用不够熟练 append是list的方法,并且每次只能加一个元素
'''

BUG解决

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
'''
try: #try except (else没报错就执行) (finally报不报错 都执行)
a = int(input('输入第一个整数'));
b = int(input('请输入第二个整数'));
result = a / b;

except ZeroDivisionError: #零的报错
print('对不起,除数不允许为0');
except ValueError: #各种报错
print('只能输入数字串');
else:
print('结果为:', result);
finally:
print('无论是否异常都会执行');
print('程序结束');
'''

'''traceback'''
import traceback
try:
print('------------');
print(1/0);
except:
traceback.print_exc();

Object

特殊属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#print(dir(object));
class A:
pass
class B:
pass
class C(A,B):
def __init__(self,name,age):
self.name = name;
self.age = age;
class D(A):
pass;
x = C('Jack',20);
print(x.__dict__); #实例对象的属性字典
print(C.__dict__);

print(x.__class__); #输出了对象所属的类
print(C.__bases__); #C类的符类类型的元素
print(C.__base__); #类的基类(c的括号最前面的那个,这里是A会输出a,改成b也会输出b)
print(C.__mro__) #类的层次结构
print(A.__subclasses__()) #子类的列表

特殊方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
a = 20;
b = 100;
c = a+b;
d = a.__add__(b);

print(c);
print(d);

class Student:
def __init__(self,name):
self.name = name;
def __add__(self, other):
return self.name+other.name;
def __len__(self):
return len(self.name)
stu1 = Student('张三');
stu2 = Student('李四');

s = stu1 + stu2 #实现了两个对象的加法运算(再student类中编写了__add__()特殊方法
print(s);
s = stu1.__add__(stu2);#效果一样
print(s);

print('-----------');
lst = [11,22,33,44];
print(len(lst)) #len是内容函数len
print(lst.__len__());
print(len(stu1)); #输出需要写一个len方法

元组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
'''可变序列  列表[],字典{}'''

'''不可变序列 字符串''/"",元组()'''

#创建
t = ('Python','world',98);
print(t);
print(type(t));

t1 = tuple(('python','world',98));
print(t1);

t2 = 'python','world',98
print(t2);
print(type(t2));

t3 = ('python');#不加,默认为 str
print(t3);
print(type(t3));

t4 = ('python',);#不加,默认为 str
print(t4);
print(type(t4));

x1 = []; #空列表
x2 = (); #空元组
x3 = {}; #空字典

#元组为何设计成不可变序列
'''
多任务环节下,同时操作对象时不需要加锁
因此,在程序中尽量使用不可变序列

注意事项:
元组中储存的时对象的引用 ***
a)如果元组中对象本身不可变对象,则不能再引用其他对象
b)如果元组中的对象时可变对象,则可变对象的引用不可以改变,但数据可以改变
'''

遍历

1
2
3
4
5
6
t = ('python','world',98);
print(t[0]);
print(t[1]);
print(t[2]);
for item in t:
print(item);

函数的创建和调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# def calc(a,b):
# c = a+b;
# return c;
#
# result = calc(10,20);
# print(result);

def fun(num):
odd = [];
even = [];
for i in num:
if i % 2:
odd.append(i);
else:
even.append(i);
return odd,even;

lst = [10,29,34,23,44,53,55];
print(fun(lst));
'''
返回值默认是元组
'''
def fun(a,b=10): #b成为默认值参数
print(a,b);

fun(100);
fun(20,30);
print('hello');
print('world');

print('hello',end='\t'); #为何能从自动换行,加了end就变成了持续执行
print('world'); #点进print的源码就可以看见,end默认为换行\n

def fun (*args): #可变的位置参数 由*代表随便你传多少 *类似定义了一个列表类型形参
print(args);

fun(10); fun(10,30); fun(30,405,50);

def fun1(**args): #定义了一个字典类型的形参
print(args);

fun1(a=10);
fun1(a=20,b=30,c=40);
'''
def fun2(*args,*a):
def fun2(**args,**args):
这两代码都会报错,个数可变的位置参数和关键字参数都只能是一个
'''
def fun2(*args1,**args2):
pass
'''
def fun3(**args1,*args2):
pass
在一个函数定义过程中,要求个数可变位置形参放在首个,关键字形参放在后面一个
'''

def fun(a,b,c):
print('a=',a);
print('b=',b);
print('c=',c);

fun(10,20,30);
lst = [11,22,33];
fun(*lst); #不加*的话,默认只穿入了一个参数,会报错

fun(a=100,c=300,b=200);#关键字实参 得到的任然是顺序1,2,3
dic = {'a':111,'b':222,'c':333};
fun(**dic); #两个*就是调用时将value作为关键字实参传入,若改为一个*,则传入keya,b,c

def fun4(a,b,*,c,d): #从这个*之后只能采用关键字实参传递
print('a=',a);
print('b=',b);
print('c=',c);
print('d=',d);

列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#创建列表
lst = ['hello','world',98];
print(lst[0],lst[-3]);
print(lst.index('hello'));
# print(lst.index('hello',1,4))#3

lst2 = list(['hello','world',98]);
'''列表的特点
1 列表元素按顺序有序排序
2 索引映射唯一一个元素
负数索引-n开始往-(n-1),-(n-2)走 0+正数索引从0开始往1,2走(均是列表第一个元素开始走)
3 任意数据类型混存
4 动态分配回收
'''

lst = [10,20,30,40,50,60,70,80];
print('原列表',id(lst));
lst2 = lst[1:6:1];
print('切的片段',id(lst2));
print(lst[1:6]);#默认步长为一
print(lst[1:6:2]);
print(lst[1::2]);
print(lst[::-1]); #每一次走-1步 每次+(-1)

lst = [10,20,'python','hello'];
print(10 in lst);
print(100 not in lst);
for item in lst:
print(item);

#列表添加
lst = [10,20,30];
lst.append(100);

lst2 = ['hello','world'];
lst.extend(lst2);
print(lst);

#在1这个位置添加对象90,并且把原本在1这位置的往后放
lst.insert(1,90);
print(lst);

#任意位置添加N多个元素
lst3 = [True,False,'hello'];
lst[1:] = lst3;
print(lst);#切断添加操作

#列表的删除
lst = [10,20,30,40,50,60,30];
lst.remove(30);
print(lst);#仅移除第一个30

#pop()根据索引移除元素
lst.pop(1);
print(lst);

lst.pop();#不指定,则删除最后一个,栈(stack),后进先出

lst[1:3] = []; #删除原内容
print(lst);

lst.clear(); #删除列表所有元素
print(lst);

del lst; #删除列表对象

#列表修改

lst = [10,20,30,40];
lst[2] = 100;
print(lst);
lst[1:3] = [300,400,500,600];
print(lst);

生成式

1
2
3
4
5
lst= [i*i for i in range(1,10)];
print(lst);

lst2=[i*2 for i in range(1,6)];
print(lst2);

排序操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
lst = [20,40,10,98,54];
print('排序前的列表',lst,id(lst));

lst.sort();
print('排序之后的列表',lst,id(lst));

lst.sort(reverse=False);
print(lst);


lst.sort(reverse=True);
print(lst);

new_list = sorted(lst);
print(lst);
print(new_list);

变量的作用域

1
2
3
4
5
6
7
8
9
10
'''
局部变量 仅在函数内部有效,局部变量使用global声明,这个变量就会变成全局变量
全局变量,函数体外的变量,可以用于函数内外

'''
def fun3():
global age;
age = 20;
print(age);
#age变成全局变量

字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#创建字典
scores = {'张三':100,'李四':98,'王五':45};
print(scores);
print(type(scores));

student = dict(name = 'jack',age = 20);
print(student);

d = {};
print(d);

#元素的获取
print(scores['张三']);#未找到报错

print(scores.get('张三'));#未找到输出none

print(scores.get('嘛七',99));#未找到返回99

#增删改

del scores['张三']#删除指定的key-value对
#scores.clear() 清空字典的元素
print(scores);
scores['陈六'] = 98;#新增
print(scores);
scores['陈六'] = 100;#修改
print(scores);

#获取列表视图
scores = {'张三':100,'李四':98,'王五':45};
keys = scores.keys();
print(keys);
print(type(keys));
print(list(keys));#将所有key组成的视图转换为列表

#获取所有的value
values = scores.values();
print(values);
print(type(values));
print(list(values));

#key + value 为 item
#获取所有的key-value对
item = scores.items();
print(item);
print(type(item));

d = {'name':123,'name':456};
print(d); #出现覆盖,key不允许重复

d = {'name':122,"nikename":'张三'};
print(d); #value允许重复

生成式

1
2
3
4
items=['Fruit','books','others'];
prices = [96,78,85];
d = {item.upper():price for item,price in zip(items,prices)}; #zip为打包
print (d);

字符串

各种操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
'''
index() 查找字串第一次出现的位置,不存在则抛异常
rindex()最后一次出现的位置,找不到抛异常
推荐使用find
find() 找第一次,找不到返回-1
rfind() 找最后一次,找不到返回-1


upper() 把字符串中所有的字符都转成大写字母
lower() 把字符串中所有字符都转成小写字母
swapcase() 所有大写转小,小写转大
capitalize() 把第一个字符转换成大写,把其余字符转化为小写
title() 把每一个单词第一个字符转换成大写,剩余字符转换为小写

center() 字符串居中对齐
ljust() 字符串左对齐
rjust() 右对齐//默认空格
zfill() 右对齐之后左边用0填充

split() 从左边开始分割
rsplit() 从右边开始分割

s = 'hello world python';
lst = s.split();
print(lst) #['hello', 'world', 'python']

s = 'hello|world|python';
lst = s.split(sep='|');
print(lst) #['hello', 'world', 'python']

lst = s.split(sep='|',maxsplit=1);
print(lst) #['hello', 'world|python']

判断字符串
isidentifier() 判断是否合法
isspace() 判断是否全部为空白字符(回车,换行,水平制表符)
isalpha() 判断指定字符串是否全部由字母组成
isdecimal() 判断指定字符串是否全部由十进制的数字组成
isnumeric() 判断指定的字符串是否全部由数字组成
isalnum() 判断指定字符串是否全部由字母和数字组成

字符串其他操作
替换 replace() 3参数,第一个是被替换的字串,第二个指定替换字串的字符串,
该方法返回替换后得到的字符串,而调用第三个参数可以只当
最大的替换次数
合并 join () 将列表或者元组中的字符串合并成一个字符串

s = 'hello,python';
print(s.replace('python','java')); # hello,java
s1 = 'hello,python,python,python';
print(s1.replace('python','java',2)); #hello,java,java,python
lst = ['hello','java','python'];
print("|".join(lst)); #hello|java|python
print(''.join(lst)); #hellojavapython
print('*'.join('python')); #p*y*t*h*o*n
'''

比较操作和切片操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
print('apple' > 'app');  #true
print('apple' > 'banana') #false 等于97>98 False ASCII
print(ord('a'),ord('b'));
print(ord('陈'));

print(chr(97),chr(98));
print(chr(38472)); #陈
'''
ord和chr是互相相反可以切换的值
is 是比较的id ==比较的内容 比较内容通常从第一位开始依次比较
'''
'''
由于字符串是不可变类型
不具备增删改操作
切片操作将产生新的对象
具体切片和之前学过的一样(::)
'''

编码和解码

1
2
3
4
5
6
7
8
9
10
11
s = "天涯共此时";
#编码
print(s.encode(encoding='GBK')); #一个中文两字节
print(s.encode(encoding='UTF-8')); #一个中文三字节

#解码
byte = s.encode(encoding='GBK');
print(byte.decode(encoding = 'GBK'));


#print(byte.decode(encoding = 'UTF-8')); 解不了,编码和解码的格式一定要相同

驻留机制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
a = 'python';
b = 'python';
c = '''python''';
print(id(a));
print(id(b));
print(id(c));#和java一样
#符合标识符的字符串(没奇奇怪怪的特殊符号例如%,就id相等,不然就不是标准的字符串
'''
#驻留的几种情况
#字符串的长度为0/1时
#符合标识符的字符串
#字符串只在编译时进行驻留,而非运行时
#[-5,256]之间的整数数字
pycharm却对驻留进行了优化,对abc%或者-6这些,也是强制执行是他们相同
join()的效率比+高,+要先计算出总长度,再创建一个新的
'''
a = 'abc';
b = 'ab' + 'c';#这是在编译时,就已经被强大的pycharm算好了
c = ''.join(['ab','c']); #运行时的结果,要开辟新的空间来储存abc
print(a is b) #true
print(a is c) #false

格式化字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
name = '张三';
age = 20;
print('我叫%s,今年%d岁' % (name,age));

print("我叫{0},今年{1}岁".format(name,age));

print('%10d' % 99); #10表示的是宽度
print("%.3f" % 3.1415926) #保留三位小数
print("%10.3f" % 3.1415926);
print('hellohello'); #10位,做对比
print('{0:.3}'.format(3.1415926)) #.3表示一共是3位
print('{0:.3f}'.format(3.1415926)) #.3f表示一共是3位小数
print('{:10.3f}'.format(3.1415926)) # 同时设置宽度和精度,一共是10位,三位是小数
#0可以省略,注意细节不是,而是.

类,对象,方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Student:  #Student为类的名称,每个单词的首字母大写,其余小写
# 在类之外定义的称为函数,在类之内定义的称为方法
native_pace = 'sichuan';
def __init__(self,name,age):
self.name = name;
self.age = age;
def eat(self): #实例方法至少包含一个self
print('我是学生我在吃饭');
@staticmethod
def method():
print('我使用了staticmethod进行修饰,我是静态方法');
@classmethod #类方法至少有一个cls
def cm(cls):
print('我是类方法,我使用了classmethod');

def drink():
print('我在类外,我是函数');

#Python中一切皆对象
# print(id(Student));
# print(type(Student));
# print(Student);

stu1 = Student('张三',20); #有了实例对象,就可以调用类中的内容
print(stu1);
print(stu1.age);
print(stu1.name);
Student.eat(stu1); #31行和32行功能相同 类名.方法名(类的对象)
stu1.eat(); #对象名.方法名()

Student.cm(); #类方法的使用
Student.method(); #静态方法的使用

stu2 = Student('李四',30);
print('-----------------为stu2动态绑定性别属性----------');
stu1.gender = '女';

print(stu1.age,stu1.name,stu1.gender);
#可以绑定本来不存在于类的属性给对象

def show():
print('定义在类之外的,称为函数');
stu1.show = show;
stu1.show();
#stu1具有了show函数(绑定),方法show是stu1的方法

递归函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def fac(n):
if n==1:
return 1;
else:
return n*fac(n-1);

def fac1(n):#斐波那契数列
if n==1:
return 1;
elif n==2:
return 1;
else:
return fac1(n-2)+fac1(n-1)
print(fac(6));
print(fac1(6));

集合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
s = {2,3,4,5,5,6,7,7};
print(s);#集合中的元素不允许重复,和数学中的很像

s1 = set(range(6));
print(s1,type(s1));#等等各种各样

s = {10,20,30,504,60};
#集合元素的判断操作
print(10 in s);
print(100 in s);
#集合元素的新增操作
s.add(80);#集合是随意的,位置随意 add 一次添加一个
print(s);
s.update([100,99,8]);#一次至少添加一个
s.update((78,64,56));
print(s);
#删除

#remove(); 若想要删除的不存在,则会报错
#discard(); 不会报异常
#pop(); 由于集合里顺序是随机放置的,所以是随机删除,但是按顺序从最左边开始删
#clear(); 全没了 set()

s = {10,20,30,40};
s2 = {30,40,10,20};
print(id(s),id(s2));
print(s == s2); #true 在python里,==为判断数值相同,再次提醒
s1 = {10,20,30,40,50,60};
s2 = {10,20,30,40};
s3 = {10,20,90};
#判断是否是子集
print(s2.issubset(s1)); #s2是s1的子集吗? true
print(s3.issubset(s1));

#判断是否是超集
print(s1.issuperset(s2)); #true
print(s1.issuperset(s3)); #false

#等等各种,看英文灵活判断就是了

生成式

1
2
3
4
5
6
7
#列表生成式
lst = [ i*i for i in range(6)];
print(lst);

#集合生成式
s = {i*i for i in range(10)};
print(s);

数学操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#交集
s1 = {10,20,30,40};
s2 = {20,30,40,50,60};
print(s1.intersection(s2));#结果相同,与下面那个&
print(s1 & s2);
#并集
print(s1.union(s2));
print(s1 | s2);
print(s1);
print(s2);

#差集
print(s1.difference(s2)); #s1减去与s2共有的
print(s1 - s2);

print(s1); print(s2);
#对称差集
print(s1.symmetric_difference(s2));
print(s1^s2);#共有的为0,不是共有为1.等于s1和s2中不是s1与s2相交的那一部分

面向对象

多态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Animal(object):
def eat(self):
print('动物会吃');
class Dog(Animal):
def eat(self):
print('狗吃骨头');
class Cat(Animal):
def eat(self):
print('猫吃鱼');

class Person:
def eat(self):
print('人吃五谷杂粮');

#定义一个函数
def fun(obj):
obj.eat();

#开始调用函数
fun(Cat());
fun(Dog());
fun(Animal());
print('-----------------')
fun(Person());
'''静态多态必要条件
继承,重写,父类引用指向子类对象
动态多态崇尚鸭子模型(python)
当一只鸟走起来像鸭子,游泳像鸭子,收起来也想鸭子,那么鸟就可以称为鸭子
不关心对象什么类型,只关心他的行为
'''

封装,继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Student:  #属性前加两个下划线,代表私有
def __init__(self,name,age): #直接定义的叫类构造方法,至少会包含self,用于绑定调用此方法的实例对象
self.name = name;
self.__age = age;
def show(self):
print(self.name,self.__age);

stu = Student('张三',20);
stu.show();
print(stu.name);
#print(dir(stu)) 可以查看age的全名
print(stu._Student__age);


class Person(object): #Person继承object类
def __init__(self,name,age):
self.name = name;
self.age = age;
def info(self):
print(self.name,self.age);
class Student(Person):
def __init__(self,name,age,stu_no):
super().__init__(name,age);
self.stu_no = stu_no;
def info(self): #左边像cd一样的指的位置是override
print(self.stu_no);
def __str__(self):
return '我的名字是{0},今年{1}岁'.format(self.name,self.age);

class Teacher(Person):
def __init__(self,name,age,teachofyear):
super().__init__(name,age);
self.teachofyear = teachofyear;
def info(self): #这也是重写噢
super().info();
print('教龄',self.teachofyear);
#python,c++支持多继承, java不支持

stu = Student('张三',20,'yes');
print(dir(stu));
print(stu); #默认调用__str__()这样的方法
print(type(stu));

Day03

OS

相关操作

1
2
3
4
5
6
7
8
#os与操作系统相关,可以调用操作系统

import os;
os.system('notepad.exe');
os.system('calc.exe');

#直接调用启动文件
os.startfile('E:\QQ+刚安装电脑时的东西\Bin\QQ.exe')

相关函数

1
2
3
4
5
6
7
8
9
10
11
import os;
print(os.getcwd()); #返回当前工作目录

lst = os.listdir('../Day03'); #返回指定路径下的文件和路径信息
print(lst);

# os.mkdir('newdir2'); #创建目录
# os.makedirs('A/B/C'); #创建多级目录
# os.rmdir('newdir2'); #删除目录
# os.removedirs('A/B/C'); #删除多级目录
# os.chdir(path) #设置path为当前工作目录

path相关函数

path相关函数

With语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#该类实现特殊方法enter和exit,被称为遵守上下文管理器协议,
#该类对象的实例对象,称为上下文管理器
class MyContentMgr(object):
def __enter__(self):
print('enter方法被调用');
return self;

def __exit__(self, exc_type, exc_val, exc_tb):
print('exitbeidiao');

def show(self):
print('show方法被调用执行了');

with MyContentMgr() as file:
file.show(); #无论是否报异常,都会自动关闭资源

with open('logo.png','rb') as src_file:
with open('copy2logo.png',"wb") as target_file:
target_file.write(src_file.read());#自动打开和关闭
'''与常用的文件打开方式对应着看'''

创建对象

1
2
3
4
5
6
7
8
9
10
11
#object
class Person(object):
def __init__(self,name,age):
print('__init__被调用,self的id值为:{0}'.format(id(self))); #9264
self.name = name;
self.age = age;
def __new__(cls, *args, **kwargs):
print('__new__被调用,cls的id值为:{0}'.format(id(cls))); #1520
obj = super().__new__(cls);
print('duixiang的id值为:{0}'.format(id(obj))); #9264
return obj

包的使用

1
2
3
4
5
6
7
8
9
10
11
12
#在这里导入pageage1包

import pageage1.moduleA as ma #as为起别名,是pageage1.moduleA的别名
import pageage1.module_B
print(ma.a);

import calc;
import pageage1;
'''import只能导入包名和模块名'''
from pageage1 import module_B;
from pageage1.moduleA import a;
'''使用from import可以导入包,函数名,变量,模块名'''

文件

常见文件打开方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
file = open('b.txt','w');
file.write('Python');
file.close();

file = open('b.txt','a'); #append 追加模式
file.write('Python');
file.close();

src_file = open('logo.png','rb'); #二进制模式:b
target_file = open('copylogo.png','wb'); #打开
target_file.write(src_file.read()); #写入过程
target_file.close();
'''与With对应着看'''
#+ 以读写方式打开,不能单独使用,需要与其他模式一起使用,例:a+

文件对象常用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
'''
read([size]) 从文件中读size个字节或字符返回,省略size则读取所有内容
readline() 从文本文件读取一行
readlines() 每一行都作为独立的字符串对象,并将这些对象放入***列表***
write(str) 将str内容写入文件
writelines(s_list) s_list写入文本文件,不添加换行符
seek(offset,[whence])
文件指针位置offset(相对于whence)
为正往结束方向移动,为负往开始方向移动
whence不通知表示不同含义
0:从文件头开始 1:从当前位置开始 2:从文件尾开始
tell() 返回文件指针当前位置
flush()不关闭文件,将缓冲区内容读入文件
close()关闭文件,将缓冲区内容写入文件,释放相关对象资源
'''
file = open('a.txt','r');
#print(file.read(2));

文件的读写操作

1
2
3
4
5
6
7
8
9
'''
file = open(filename [,mode,encoding])
文件对象 创建文件对象的函数(open) filename:要创建或打开的文件名称 mode:打开模式,默认为只读
encoding:默认文本文件编码格式GBK(不是python文件,python文件为UTF-8
'''

file = open('a.txt','r'); #a需要是GBK
print(file.readlines());
file.close();

浅拷贝深拷贝

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
'''
浅拷贝:python一般都是浅拷贝,拷贝时,对象包含的子对象内容不拷贝 也就是说拷贝后的对象和源对象会同时引用一个子对象
深拷贝 使用copy的deepcopy,所有的对象都不相同
'''
class CPU:
pass;
class Disk:
pass
class Computer:
def __init__(self,cpu,disk):
self.cpu = cpu;
self.disk = disk;

cpu1 = CPU();
cpu2 = cpu1; #赋值操作,不是copy
print(cpu1,id(cpu1));
print(cpu2,id(cpu2));

print('----------浅拷贝------');
disk = Disk();
computer = Computer(cpu1,disk);

import copy;
computer2 = copy.copy(computer);
print(computer,computer.cpu,computer.disk); #computerid不同,cpu和disk id相同
print(computer2,computer2.cpu,computer2.disk);

computer3 = copy.deepcopy(computer);
print(computer,computer.cpu,computer.disk);
print(computer3,computer3.cpu,computer3.disk);#每一个对象都不同

模块

导入

导入calc2,设置为主程序

1
2
import calc2;
print(calc2.add(100,200));

导入calc模块使用

1
2
3
import calc;
print(calc.add(10,20));
print(calc.div(10,4));

常见内容模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import sys;
import urllib.request;
import time;
import os;
import calendar;
import urllib; #pachong
import json; #pachong
import re;
import math;
import decimal;
import logging;
print(sys.getsizeof(24));
print(sys.getsizeof(False));


print(urllib.request.urlopen('http://www.baidu.com').read());
'''

'''

第三方模块的安装

1
2
3
4
5
6
7
8
9
10
11
12
'''pip install 模块名
使用 :import 模块名'''

import schedule;
import time;
def job():
print('hahah');

schedule.every(3).seconds.do(job);
while True:
schedule.run_pendind();
time.sleep(1);