Python学习笔记(简易版2022.8.25)

**
(这篇博客是在有一些Java基础上,跟着B站上唐宇迪的5h速成python的学习过程记录;整体来说,这个5个小时讲述了一些语法的基础,很多内容并不是很深,适合初学语法的人看看;笔记记在代码块里,方便直接写,用的是pycharm)

1. 简单的操作——字符串

"""
简单运算符号:
    %——取余
    **——次方
    abs——绝对值
    round——取整:round(15.3)
    max——最大值:max(1,2,5,6)
    min——最小值
    1.3e-5——科学记数法
    
类型查看:(python中给变量赋值不需要先定义数值的数据类型;比如:a=3即可将数字3赋值给变量a)
    type(变量)——查看变量的类型
    
字符串操作:
    字符串的拼接:
        tang='hello'+'python'
        print(tang)
        
        tang6=tang
        print(tang6)
        
        print(len(tang6))#计算字符串中的字符个数
        
    字符串的切分:见下面         
"""


tang=1.5
print(type(tang))

tang2=int(tang)
print(type(tang2))
print(tang2)

tang3=float(tang2)
print(tang3)

tang_str='123'
print(type(tang_str))

tang4=int(tang_str)
print(tang4)

tang_str1='桂英'
print(type(tang_str1))

#tang5=int(tang_str1)——报错:ValueError: invalid literal for int() with base 10: '桂英'
#print(tang5)

print(3>54)#输出bool类型的结果

#字符串拼接方法:
tang='hello'+'python'
print(tang)

tang6=tang*3
print(tang6)

print(len(tang6))#计算字符串中的字符个数


#字符串的切分:
tang='1 2 3 4 5'
print(tang.split())


tang='1,2,3,4,5'
tang7=tang.split(',')
print(tang.split(','))#用逗号切分


#字符串的合并:
tang8=''
tang8.join(tang7)
print(tang8.join(tang7))


#字符串的替换:
tang="hello"+'world'
tang2=tang.replace('world','python')
print(tang2)


#字符串转换为大写:
print(tang2.upper())


#字符串转换为小写:
print(tang2.lower())


#字符串去除空格:
tang2='          nihso     '
print(tang2.strip())


#字符串去除左边空格:
tang2='          nihso   123       '
print(tang2.lstrip())


#字符串去除右边空格:
tang2='          nihso   123       '
print(tang2.rstrip())


#字符串值的传递:
tang2='nihso   123     {} {} {}  '.format('tang','yu','di')
print(tang2)


#字符串值的传递:
tang2='nihso   123     {2} {1} {0}  '.format('tang','yu','di')
print(tang2)


#字符串值的传递—按照参数传递:
tang2='nihso   123     {tang} {yu} {di}  '.format(tang=1,yu=2,di=3)
print(tang2)


#字符串值的传递—以%形式:
tang2='nihso:'
a=45
b=4.5
print('%s %f %d'%(tang2,b,a))

2.列表操作

'''
list结构——列表结构

    tang=[]

    通过[]来创建一个list结构
    里面放任何类型的东西都可以,没有类型的限制,也没有长度的限制
    
    也可以通过:
        tang=list([1,2,3])——来创建一个list结构
        
'''


tang=[]
print(type(tang))

tang=[1,2,3,4]
print(tang)

tang=['1','2',3,4]
print(tang)

tang=list([1,2,3])
print(tang)#结果:[1, 2, 3]
print(len(tang))#——计算list中的数据数

a=[123,456]
b=['nihao','hahah']
print(a+b)#结果:[123, 456, 'nihao', 'hahah']
print(a*3)#[123, 456, 123, 456, 123, 456]
print(a[0])#123
print(a[1])#456
print(a[-1])#456
print(b[-1])#hahah
print(a[0:])#[123, 456]——从第一个数一直到最后的所有值
print(a[1:])#[456]——从第二个数一直到最后的所有值
a[0]=789
print(a)#[789, 456]
a[:]=['tang','zhang','123']
print(a)#['tang', 'zhang', '123']

a=[1,2,3,4,5,6,7]
print(a[4:7])#[5, 6, 7]——这个索引是左闭右开,第七位不算

del a[0]
print(a)#[2, 3, 4, 5, 6, 7]

del a[0]
print(a)#[3, 4, 5, 6, 7]

del a[3:]
print(a)#[3, 4, 5]——从第四个数开始全部删除

print(4 in a)#True——判断4是否在a这个列表里面
print(6 in a)#False
print(6 not in a)#True

tang='tang yu di'
print('tang' in tang)#True

a=[1,2,[3,4,2]]
print(a[2])#[3, 4]
print(a[2][1])#4——结构比较复杂的时候,先找第一层,再找第二层
print(a.count(2))#1——计数操作:统计列表里面的2的数量

a=['af','fa','qpp']
print(a.index('af'))#0——找索引
#print(a.index('afdf'))#ValueError: 'afdf' is not in list——没有就找不到索引

b=[]
b.append(123)
#b.append(123,456)#TypeError: append() takes exactly one argument (2 given)——每次只能添加一个值
print(b)

b.append('tang ')
print(b)#[123, 'tang ']

b.append([1,2,3])
print(b)#[123, 'tang ', [1, 2, 3]]

b.insert(2,'python')
print(b)#在第3个位置插入字符python,原来的第三个值后移——[123, 'tang ', 'python', [1, 2, 3]]

b.remove([1,2,3])
print(b)#[123, 'tang ', 'python']——移除其中的[1,2,3]

c=[1,2,3,1,2,5]
c.remove(1)
print(c)#[2, 3, 1, 2, 5]——当里面有很多的1的时候,默认将第一个1删除

print(c.pop(2))#1——弹出位于第3个的值:1,并且将它返回出来,原来的列表里面就没有了
print(c)##[2, 3, 2, 5]

c.sort()
print(c)#[2, 2, 3, 5]——排序之后,原始的数据改变

d=[5,4,123,8,54,85]
e=sorted(d)
print(d)#[5, 4, 123, 8, 54, 85]——排序之后,原始的数据没有变化
print(e)#[4, 5, 8, 54, 85, 123]——排序数据

e.reverse()
print(e)#[123, 85, 54, 8, 5, 4]——将原始数据直接倒过来排序

3. 字典操作

'''
字典操作:
    tang={}——创建字典
    tang=dict()——创建字典
    
字典的结构操作:
    key-value

结论:字典里面的值是通过对应的键来调的,不需要索引号,也就是不需要索引值,顺序不重要
'''

tang={}
print(type(tang))

tang1=dict()
print(type(tang1))

print(tang)#{}

tang['first']=123
print(tang)#{'first': 123}

tang['second']=456
print(tang)#{'first': 123, 'second': 456}

tang[123]=789
print(tang)#{'first': 123, 'second': 456, 123: 789}

print(tang['second'])#456——通过键来找到值

tang[123]=963
print(tang)#{'first': 123, 'second': 456, 123: 963}

a={'c':456,'b':898,'a':963}
print(a)#{'c': 456, 'b': 898, 'a': 963}

a={}
a[123]=456
a['qiu']=[1,2,23]
print(a)#{123: 456, 'qiu': [1, 2, 23]}——也就是说,字典里面的值也是任何类型都可以的

tang={}
tang1={1:456,2:789}
tang2={'1':456,'3':963}
tang['456']=tang1
tang['789']=tang2
print(tang)#{'456': {1: 456, 2: 789}, '789': {'1': 456, '3': 963}}——字典里面嵌套字典

tang=dict([('tang',1),('yu',2)])#——通过这种形式来创建一个字典
print(tang)#{'tang': 1, 'yu': 2}

tang['tang']+=1
print(tang)#{'tang': 2, 'yu': 2}

print(tang.get('tang'))#2——拿出tang这个键对应的值
print(tang['tang'])#2——拿出tang这个键对应的值

print(tang.get('tang3','meiyou'))#meiyou——对于原来的字典中没有的数,可以自己定义再访问,虽然觉得没什么卵用
print(tang)#{'tang': 2, 'yu': 2}——原名的字典并没有改变

print(tang.pop('tang'))#2--弹出tang对应的值,并且返回这个弹出的值
print(tang)#{'yu': 2}——弹出后,原来的值被删除掉了

del tang['yu']
print(tang)#--直删除


'''复杂的操作:字典的更新:'''

tang={'tang':123,'yu':456}
tang2={'tang':45888,'di':963}
tang.update(tang2)
print(tang)#{'tang': 45888, 'yu': 456, 'di': 963}——将原来的tang对应的值修改,并且将不存在的di键值加入进来

print('tang' in tang)#True——对应的值是否在字典里面

print(tang.keys())#dict_keys(['tang', 'yu', 'di'])——打印所有的键值
print(tang.values())#dict_values([45888, 456, 963])
print(tang.items())#dict_items([('tang', 45888), ('yu', 456), ('di', 963)])

4.集合操作

'''
集合操作:集合会保留唯一的元素,也就是将重复的元素去除掉
    tang=set()
集合常用与将list中的重复的数清除掉,保留干净的list值
'''

tang=[123,123,456,798,798]
tang=set(tang)
print(tang)#{456, 123, 798}
tang=list(tang)
print(tang)#[456, 123, 798]——将重复的数据清除掉之后,任然恢复为list数据类型

tang=set()
print(type(tang))#<class 'set'>

tang=set([1,1,1,2,2,2,3,3,3])
print(tang)#{1, 2, 3}

tang={1,2,2,3,3,3,3,74,5,6}
print(tang)#{1, 2, 3, 5, 6, 74}


'''
集合的操作
'''

a={1,2,3,4}
b={2,3,4,5}
print(a.union(b))#{1, 2, 3, 4, 5}——求并集
print(a|b)#{1, 2, 3, 4, 5}——求并集

print(a.intersection(b))#{2, 3, 4}——求交集
print(a&b)#{2, 3, 4}

print(a.difference(b))#{1}——a与b的不同之处
print(b.difference(a))#{5}
print(a-b)#{1}

a={1,2,3,4,5}
b={2,3,4}
print(b.issubset(a))#True——判断b是a的子集
print(b<=a)#True
print(a<=a)#True——自己是自己的子集

c={78,98}
a.update(c)
print(a)#{1, 2, 3, 4, 5, 98, 78}

a.remove(1)
print(a)#{2, 3, 4, 5, 98, 78}

a.pop()
print(a)#{3, 4, 5, 98, 78}——这里的弹出就没有索引来指定了。因为集合里面的数据是没有顺序的,所以只能是从第一个数往出弹

5.赋值机制

'''
赋值机制:
'''

tang=1000
yudi=tang
print(id(tang))#1842098213232
print(id(yudi))#1842098213232

print(yudi is tang)#True

tang=1000000000
yudi=1000000000
print(id(tang))#2472866161008
print(id(yudi))#2472866161008——为了节省内存空间,对于两个不一样的变量的值相同时,内存地址将指向同一地址

6.判断结构

'''
 判断结构
'''

tang=100
if tang>200:
    print('ok')
elif tang<1000:
    print(123)
else:
    print(465)

tang=[1,2,3,465]
if 1 in tang:
    print('ok')
elif 2 in tang:#结果只输出了OK,说明只要判断的语句执行了,下面的语句就不再执行
    print('hhh')

7.循环结构

'''
循环结构
continue
break
'''

tang=0
while tang<10:
    print(tang)
    tang+=1


tang=set([1,2,3])
while tang:
    tangs=tang.pop()
    print(tangs)#1  2   3——这里是将原来的集合里面的数都弹出来,直到原来的集合变成一个空集合,不再执行


tang=set(['tang','yu','di'])
for name in tang:
    print(name)


for i in range(10):
    print(i)


tang=[123,4,456,7898,5,412,3,45,61,310,354,5]
for i in range(len(tang)):
    print(tang[i])


'''
break 和 continue
'''

for k in tang:
    if k%2==0:
        print('这个数是:{}{}'.format(k,'偶数'))
    else:
        continue#本次循环不再执行,继续下一次的循环
    print('这个数是:%s,%d'%('偶数',k))


for k in tang:
    if k%3==0:
        print('这个数是:{},,,{}'.format(k,'3的倍数'))
    else:
        break#整体的循环过程停止,不再继续
    print('这个数是:%s,%d'%('3的倍数',k))

8.函数

'''
函数
'''

a=10
b=30
def print_value():
    print('a=',a)
print_value()


def abb(a,b):
    print(a + b)
    return a+b
    #print(a+b)     #有了return之后,print语句就不再执行

abb(3,5)#8
print(abb(3,5))#8 8


def abbc(a=89,b=5):
    print(a + b)
    return a+b
abbc()
abbc(5)
abbc(5,56)


def number(a,*args):#当所需要的参数数量不确定的时候,可以先将用*args代替
    b=0
    for i in args:
        a+=i
        b+=a
    return a,b
(a,b)=number(1,5,5,5,6)
print(a,b)


def abcd(**kwargs):
    for arg,value in kwargs.items():
        print(arg,value)
abcd(x=2,y=6)#    x 2     y 6

9.模块与包

'''
模块与包
'''

import test09
print(test09)#<module 'test09' from 'G:\\python学习\\2022.8.24\\test09.py'>
print(test09.tang_v)

test09.tang_v =156
print(test09.tang_v)

ttt=[56,45,65]
print(test09.tang(ttt))


import test09 as t9
print(t9)#<module 'test09' from 'G:\\python学习\\2022.8.24\\test09.py'>
print(t9.tang_v)

from test09 import tang_v,tang#以这种方式导入的话,引用相应的参数以及函数时,不再需要以文件名.的方式来调用,直接用就行
print(tang_v)
li=[56,45,78,89]
print(tang(li))


from test09 import *        #直接将所有的属性和方法导入进来,不需要依次填写
print(tang_v)
li=[56,45,78,89]
print(tang(li))


import os   #os:操作系统
# os.remove('test.py')#删除包test.py

print(os.path.abspath('.'))#G:\python学习\2022.8.24————调用系统路径
#test09.py

tang_v=10
def tang(list1):
    tang_sum=0
    for i in range(len(list1)):
        tang_sum+=list1[i]
    return tang_sum
list2=[1,2,3,4,5]
# print(tang(list2))

10.异常处理

'''
异常处理部分

    try:
    
    except :
    
'''

import math
# for i in range(10):
#     input_number=input('请输入:')
#     if input_number=='q':
#         break
#     result=math.log(float(input_number))
#     print(result)


# for i in range(10):
#     try:
#         input_number=input('请输入:')
#         if input_number=='q':
#             break
#         result=math.log(float(input_number))
#         print(result)
#     except ValueError:
#         print('输入有误')


# for i in range(10):
#     try:
#         input_number=input('请输入:')
#         if input_number=='q':
#             break
#         result=1/math.log(float(input_number))
#         print(result)
#     except ValueError:
#         print('输入有误')
#     except ZeroDivisionError:
#         print('0不能做分母')
#     except Exception:#不能确定所有的错误类型的时候,先将你知道的几种类型写出来,之后用Exception总写
#         print('异常了啦')


'''
自己定义一个异常,利用继承
'''
# class TangError(ValueError):
#     pass
# cur=['1',5,89,656,46,3]
# while True:
#     cur_test=input('输入:')#这里有一个搞不懂的点,为什么用int类型的数据去匹配就不行,用字符串类型的去匹配就不报错
#     #cur_test = int(input('输入:'))  #明白了,这里的input默认为字符串类型,需要转换一下,才能按照整数类去识别
#     if cur_test not in cur:
#         raise TangError('Invalid input:%s'%cur_test)#raise抛出一个异常(为保证程序执行的安全性,需要将异常抛出来);try except相当于捕捉异常


'''
finally关键字
'''

try:
    1/0
except:
    print('0000')
finally:
    print('不论这个报错是否执行,我都能保证finally里面的语句执行')

11.文件操作

'''
操作文件
'''

'''
读取文件:从open到close
'''
txt=open('test11')#注意:找文件的时候,一定要将文件名字用''括起来
print(txt)#<_io.TextIOWrapper name='test11' mode='r' encoding='cp936'>

#txt=open('./test11')#./表示当前文件夹下         打印出现乱码的问题:澶╂皵鐪熷ソ

txt=open('./test11',encoding='utf-8')#解决乱码问题,解码的方式定为utf-8就好了

#txt=open('./data/test11')#./data/表示当前文件夹中的data文件夹下


# txt_read=txt.read()
# print(txt_read)


lines=txt.readlines()#这里注意:read和Readlines两个函数是冲突的,read读完了之后,Readlines的指针直接对应到了文件的最后,也就是说,读不出数据,因此在读这一句的时候,要将前面的read函数注释掉
print(type(lines))#<class 'list'>
print(lines)#['hello\n', '天气真好\n', '天气真好']

for i in lines:#读取每一行
    print('当前行:',i)
    pass

txt.close()#关闭当前的文件,完成一次读取任务


'''
创建文件
'''
txt=open('test11.1','w')#w代表写入,w模式下会将原来的文件覆盖
txt.write('123')
txt.write('\n-*-*')
txt.write('456')
txt.close()

txt=open('test11.1','a')#a代表append,a模式下不会将原来的文件覆盖
txt.write('\n123')
txt.write('\n-*-*')
txt.write('456')
txt.close()

# txt=open('test11.1','w')
# for i in range(10):
#     txt.write(str(i)+'\n')
# txt.close()#如果没有将文件关闭,下面的读取就不能进行,虽然已经写入了,但是无法读取
# txt2=open('test11.1',encoding='utf-8')
# print(txt2.read())


'''
写文件最好按照以下的历程:避免出现错误
        try:
        except Exception:
        finally:
'''

txt=open('test11.1','w')
try:
    for i in range(100):
        10/(i-5)
        txt.write(str(i)+'\n')
except Exception:
    print('error:',i)
finally:
    txt.close()
    

'''
写文件的简便方法:with方法
    自动带了关闭文件
'''

with open('test11.1','w') as f:
    f.write('jin tian tian  qi xia yu ')

12.类的操作

'''
类的操作
类:面向对象
'''

class people:
    ' 帮助信息:  ****'
    #实例属性,所有的实例都会共享
    number=100
    #构造方法:实例化的时候,先调用它
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def display(self):
        print('number=',people.number)
    def display_name(self):
        print(self.name)

print(people.__doc__)# 帮助信息:  ****

p1=people('zhangwieming ',23)
print(p1.number,p1.name,p1.age)
#p1.display()#NameError: name 'number' is not defined
p1.display()

p1.name='zhang'
print(p1.name)

# del p1.name
# print(p1.name)#AttributeError: 'people' object has no attribute 'name'

print(hasattr(p1,'name'))#True——hasattr判断p1是否有这个属性
print(hasattr(p1,'sex'))#False

print(getattr(p1,'name'))#zhang

setattr(p1,'name','yuditang')#修改属性

print(getattr(p1,'name'))#yuditang

# delattr(p1,'name')#删除属性
# getattr(p1,'name')#AttributeError: 'people' object has no attribute 'name'

'''
相关的内置属性
'''
print(people.__doc__)# 帮助信息:  ****
print(people.__name__)# people——类名
print(people.__module__)# __main__——类所在的模块的定义
print(people.__bases__)# (<class 'object'>,)——类的父类的构成元素
print(people.__dict__)# {'__module__': '__main__', '__doc__': ' 帮助信息:  ****', 'number': 100, '__init__': <function people.__init__ at 0x000001C7DFC8BD90>, 'display': <function people.display at 0x000001C7DFC8BE18>, 'display_name': <function people.display_name at 0x000001C7DFC8BEA0>, '__dict__': <attribute '__dict__' of 'people' objects>, '__weakref__': <attribute '__weakref__' of 'people' objects>}


class Parent:
    number=100
    def __init__(self):
        print('调用父类构造方法')
    def parentM(self):
        print('调用父类的方法')
    def setAttr(self,A):
        Parent.parentattr=A
    def getAttr(self):
        print('父类属性:',Parent.parentattr)
    def newM(self):
        print('父类的定义了')

class child(Parent):
    def __init__(self):
        print('调用子类的构造函数')
    def childM(self):
        print('调用子类的方法')
    def newM(self):
        print('子类改掉了')

c=child()
c.childM()
c.parentM()
c.setAttr(100)
c.getAttr()
c.newM()

13.时间操作

'''
时间的导入
'''

import time
print(time.time())#1661434267.9003227——从1970.1.1到现在一共经历了多久时间
print(time.localtime(time.time()))#time.struct_time(tm_year=2022, tm_mon=8, tm_mday=25, tm_hour=21, tm_min=31, tm_sec=7, tm_wday=3, tm_yday=237, tm_isdst=0)——当前时间
print(time.asctime(time.localtime(time.time())))#Thu Aug 25 21:33:40 2022

print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))#2022-08-25 21:35:34

import calendar
print(calendar.month(2022,10))

print(help(calendar.month))

**

初步学习的笔记,有错误联系我订正,搭配唐宇迪的视频看着更香(https://www.bilibili.com/video/BV1sW41157KE?p=24&spm_id_from=pageDriver&vd_source=ac549f1b6278878aa4a20ac111bbf57f)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值