python学习笔记 -- 基础篇

python学习笔记 – 基础篇

资料参考视频 https://www.bilibili.com/video/BV1wD4y1o7AS?spm_id_from=333.999.0.0
HTML文档链接
https://download.csdn.net/download/YOUNGAAAAA/85005135

1.print

fp = open('D:/','a+')   #print 打印到文件     
print("123",file=fp)
fp.close()
import decimal                  #浮点数会有精度误差,需要使用这个函数消除精度误差
print (decimal.Decimal('1.1')+decimal.Decimal('1.2'))

“”“多行注释”""
+加 -减 *乘 /除 //整除 %取余 * *次方 and与 or或 not非 in在里面 not in 不在里面

a = 10 
b = 10  
c = [10,20] 
d = [10,20]
print(a is b,c is d)            #is表示id号是否相同,列表数值相同,但id也不同
print(a is not b,c is not d)

a = "helloword"
b = 'h'
print(b in a,b not in a)
a = 10
b = 20
print('大于' if a>b else '小于')      #if elif else

pass  #占位符,什么都不做

# range
a = range(10)
b = range(1,10)
c = range(1,10,2)
print(list(a),list(b),list(c))

if 1:
    pass
elif 2:
    pass
else:
    pass

while 0:
    pass
else:              #while 结束运行
    pass

for item in 'helloword':
    print(item)
for _ in range(5):
    pass
else:               #for 结束运行
    print(1)

2.列表 用于存储多个元素,相当于数组

list1 = ['helloword','ljy',666]
list2 = list(['helloword','ljy',666]) 
print(list1.index('helloword',0,-1))   #查找下标(在0和-1之间查找)
print(list1[1:3:1])
print(list1[-1:-4:-1])

0
[‘ljy’, 666]
[666, ‘ljy’, ‘helloword’]

#列表增加
print('列表增加')
list1 = [10,20,30,40]
list2 = [10,20,30,40]
list3 = [50,60]
list1.append(50)
print(list1)
list1.append(list3)
print(list1)
list2.extend(list3)    #用于拼接列表
print(list2)
list3.insert(1,10)      #任意位置添加
print(list3)

#删除列表
print('列表删除')
list1  = [10,20,30,40,50,10]
list1.remove(10)        #移除第一个元素,,输入value
print(list1)
list1.pop(-1)           #移除索引位置的元素,输入index,如果没有则默认最后一个
print(list1)        
list1[1:2] = []
print(list1)            #使用切片进行删除 
list1.clear()           #清空列表
print(list1)
del list1               #删除列表

#修改列表
print('列表修改')
list1 = []
list1[1:3] = [100,200,300]
print(list1)

#列表排序
print('列表排序')
list1.sort(reverse=True)
print(list1)
list1.sort(reverse=False)
print(list1)
list1 = sorted(list1,reverse=True)      #返回新的列表对象
print(list1)  

#列表生成式
list1 = [i for i in range(1,10)]
print(list1)

列表增加
[10, 20, 30, 40, 50]
[10, 20, 30, 40, 50, [50, 60]]
[10, 20, 30, 40, 50, 60]
[50, 10, 60]
列表删除
[20, 30, 40, 50, 10]
[20, 30, 40, 50]
[20, 40, 50]
[]
列表修改
[100, 200, 300]
列表排序
[300, 200, 100]
[100, 200, 300]
[300, 200, 100]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

3.字典 可变序列,但是是无序的。 键值对存储

#创建字典
print('创建字典')
dict1 = {'1':1,'2':2,'3':3}
dict2 = dict(q=1,w=2,e=3)
print(dict1,dict2)

#字典的操作
print('字典的操作')
print(dict1['1'],dict2.get('1',666)) #可以直接查找,也可以通过get,如果查找不到会返回none/默认值

print('1' in dict1)

dict1.clear()
print(dict1)
dict1['r'] = 3     #增加或修改
print(dict1)
del dict1

#字典视图
print('字典视图')
key = dict2.keys()
print(list(key))
value = dict2.values()
print(list(value))
item1 = dict2.items()           #转换之后是由元组组成的
print(list(item1))

for item in dict2:
    print(item,dict2[item])

#字典生成式
list1 = ['1','2','3']
list2 = [1,2,3]
dict3 = {key:value for key,value in zip(list1,list2)}
print(dict3)

*创建字典
{‘1’: 1, ‘2’: 2, ‘3’: 3} {‘q’: 1, ‘w’: 2, ‘e’: 3}
字典的操作
1 666
True
{}
{‘r’: 3}
字典视图
[‘q’, ‘w’, ‘e’]
[1, 2, 3]
[(‘q’, 1), (‘w’, 2), (‘e’, 3)]
q 1
w 2
e 3
{‘1’: 1, ‘2’: 2, ‘3’: 3}

3.元组 不可变序列,无增删改

#元组创建
t1 = (1,2,3,4)
print(t1)
t2 = tuple((1,2,3,4))
print(t2)
t3 = (10,)              #如果只有一个元素,应该加上,
print(t3)

t4 = (10,[20,30,40],50)
t4[1].append(60)        #通过像元组中的列表删改数据,可以达到修改数据的目的
print(t4)

(1, 2, 3, 4)
(1, 2, 3, 4)
(10,)
(10, [20, 30, 40, 60], 50)
30

4.集合 可变类型序列,是没有value的字典

#创建
s1 = {1,1,2,3,4}  #集合不能重复
print(s1)
s2 = set((1,2,3,4))
s3 = set([1,2])
s4 = set('python')
s5 = set({1,2,3,4})
print(s2,s3,s4,s5)

#相关操作
s1.add(5)
print(s1)
s1.update((6,7,8))      #添加多个
print(s1)

s1.remove(1)            #元素一定要存在,不然会报错
print(s1)
s1.discard(100)         #元素可以不存在,不会报错
s1.clear()

print(s2 == s3)         #内容相同就相等,与顺序无关
print(s2.issubset(s3))  #s2是否是s3的子集
print(s1.issubset(s2))  #s1是否是s2的超集
print(s1.isdisjoint(s2))#s1是否和s2有交集


#集合的数学操作
print(s2.intersection(s3),s2 & s3)  #交集
print(s2.union(s3),s2|s3)           #并集
print(s2.difference(s3),s2-s3)      #差集
print(s2.symmetric_difference(s3),s2 ^ s3)  #对称差集

#集合生成式
s7 = {i for i in range(0,10)}
print(s7)

{1, 2, 3, 4}
{1, 2, 3, 4} {1, 2} {‘y’, ‘p’, ‘t’, ‘n’, ‘h’, ‘o’} {1, 2, 3, 4}
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6, 7, 8}
{2, 3, 4, 5, 6, 7, 8}
False
False
True
True
{1, 2} {1, 2}
{1, 2, 3, 4} {1, 2, 3, 4}
{3, 4} {3, 4}
{3, 4} {3, 4}
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

5.字符串 驻留机制:字符数字下划线组成的字符串只会占用一块地址空间,字符串只有在编译的时候进行驻留,非运行时。 [-5,256]的整数数字也是驻留的。

#字符串的操作
#查找
s1 = 'hello hello'
print(s1.index('lo'))   #查找第一个出现的
print(s1.rindex('lo'))  #查找最后一个出现的
print(s1.find('w'))     #和index的区别是查找不存在的会返回-1,而index会报错
print(s1.rfind('w'))    #查找最后一个出现的

#大小写
print(s1.upper())       #传唤大小写都是产生新的字符串
print(s1.lower())       #小写
print(s1.swapcase())    #大小写互换
print(s1.capitalize())  #第一个字符大写
print(s1.title())       #每个单词首字母大写

#字符串内容对齐
print(s1.center(20,'*'))#中间对齐,第一个是长度,第二个是符号,第二个默认是空格
print(s1.ljust(20,'*')) #左对齐
print(s1.rjust(20,'*')) #右对齐
print(s1.zfill(20))     #右对齐,前面用0填充

#字符串的劈分操作
print(s1.split())       #参数sep为分割的字符,默认空格,maxsplit为最大劈分次数,返回列表
print(s1.rsplit('l',2)) #右边开始劈分

#字符串判断的方法
print(s1.isidentifier())#判断是否全是合法标识符:字母数字下划线
print('\t'.isspace())   #判断是否全是空白字符组成,回车,换行,水平制表符
print(s1.isalpha())     #判断是否全是字母
print('123'.isdecimal())#判断是否全是十进制数字
print('123'.isnumeric())#判断是否全是数字,包括罗马数字,中文数字
print('sda13'.isalnum())#判断是否全是数字字母

#字符串替换和合并
print(s1.replace('he', '12',1)) #用12替换he,第三个参数表示最多替换几次
list1 = ['1','2','3','4']
print('*'.join(list1))          #将列表或元组的元素连接成字符串,中间用前面的字符连接

#字符串的比较操作 >,<,==,!=
print('apple'>'ban',ord('a'),chr(123))  #ord:字符对应的ascii码,chr就是反过来

#字符串的切片
s2 = s1[:3]
s3 = s1[5::2]
print(s2,s3)

#格式化字符串
num = 1.12
s4 = '我%s你%2.2f' % (s2,num)
s5 = '我{0},你{1:2.2f}'.format(s2,num)
s6 = f'我{s2},你{s3}'
print(s4,s5,s6)

#字符串编解码
byte = s1.encode(encoding='UTF-8')      #还可以是由GBK的编码格式,UTF-8中文三字节,GKB两字节
str1 = byte.decode(encoding='UTF-8')
print(byte,str1)

3
9
-1
-1
HELLO HELLO
hello hello
HELLO HELLO
Hello hello
Hello Hello
hello hello

hello hello*********
*****hello hello
000000000hello hello
[‘hello’, ‘hello’]
[‘hello he’, ‘’, ‘o’]
False
True
False
True
True
True
12llo hello
1
2
3
4
False 97 {
hel el
我hel你1.12 我hel,你1.12 我hel,你 el
b’hello hello’ hello hello

6.函数 函数返回多个值时,返回的是元组

def cal(a,b = 10):      #参数可以带默认值
    print(a,b)
cal(10)

def fuc1(*arg):         #个数可变的位置参数,结果是一个元组
    print(arg)
fuc1(10,20,30)

def fuc2(**arg):        #个数可变的关键字形参,结果是一个字典
    print(arg)
fuc2(a=10,b=20,c=30)

def fuc3(*a,**b):       #如果都存在,则需要先位置参数,再关键字参数
    pass

def fuc4(a,b,c,d):
    print(a,b,c,d)
list1 = [10,20,30,40]
fuc4(*list1)            #用*将列表中的元素都作为参数传递进去
dict1 = {'a':10,'b':20,'c':30,'d':40}
fuc4(**dict1)           #用两个**将字典中的元素作为关键字参数传递

def fuc5(a,b,*,c,d):    #表示*前面用位置参数,*后面必须要关键字参数
    print(a,b,c,d)
fuc5(10,10,c = 30,d = 40)

10 10
(10, 20, 30)
{‘a’: 10, ‘b’: 20, ‘c’: 30}
10 20 30 40
10 20 30 40
10 10 30 40

7.异常处理

#异常处理机制 try
try:
    a = int(input('1'))
    b = int(input('2'))
    result = a/b
except ZeroDivisionError:
    print('it can\'t be zero')
except BaseException:           #最广泛的错误
    print('finish')
else:
    print(result)               #没有错误出现才执行
finally:
    print('end')                #无论出不出错都会执行

1.0
end
ZeroDivisionError : 除数为0 IndexError : 序列没有此索引 KeyError : 映射没有这个键 NameError : 未声明对象 SyntaxError : python语法错误 ValueError : 输入无效参数

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

--------------------
Traceback (most recent call last):
File “C:\Users\Administrator\AppData\Local\Temp\ipykernel_13828\2573376203.py”, line 4, in
print(10/0)
ZeroDivisionError: division by zero

8.类 类属性、实例方法、静态方法、类方法

继承:python可以支持多个父类,默认object。

import traceback
class Student:
    def __init__(self,name,id,id12):     #实体属性
        self.name = name
        self.id = id
        self.__id12 = id12         #如果不希望属性被外部访问,则在前面加两个下划线
    
    id1 = 123321             #直接写在类里面叫做类属性
    def idp(self):           #实例方法
        print(self.id,self.__id12)
        print(123321)
    @staticmethod           #静态方法
    def idp1():
        print(1)
    @classmethod            #类方法
    def idp2(cls):
        print(2)

stu1 = Student('ljy',123321,1)
stu1.idp()
stu1.idp1()
stu1.idp2()

stu2 = Student('lyt',123321,1)
stu2.gender = 'woman'               #动态绑定属性
def show():                         #动态绑定方法
    print('show')
stu2.show = show
stu2.show()

print(stu1._Student__id12)          #但是也是有办法可以访问到隐藏的属性

try:
    print(stu1.__id12)              
except:
    traceback.print_exc()           #如果直接访问会报错 

123321 1
123321
1
2
show
1
Traceback (most recent call last):
File “C:\Users\Administrator\AppData\Local\Temp\ipykernel_11528\3776193539.py”, line 34, in
print(stu1.__id12)
AttributeError: ‘Student’ object has no attribute ‘__id12’

class Person(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def info(self):
        print('name:%s,age:%d'%(self.name,self.age))

class Student(Person):
    def __init__(self, name, age,score):
        super().__init__(name, age)
        self.score = score
    def info(self):                 #方法重写,重新定义
        super().info()
        print(self.score)

stu1 = Student('ljy',12,100)
stu1.info()

name:ljy,age:12
100

print('Common standard library websites:'+'https://blog.csdn.net/anqixiang/article/details/112405377?utm_source=app&app_version=5.0.0&utm_source=app')
print('to be continued ...')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值