一、python基础知识
1、变量
复制代码
1
2message="hello python"
变量始终记录变量的最新值。
变量名包含字母、数字、下划线,不能以数字开头。
2、字符串
复制代码
1
2"this is a string."
2.1 修改字符串大小写:⬇
复制代码
1
2
3
4
5
6
7
8str="this is a string" str.title() #单词首字母大写; str.upper() #所有字母大写; str.lower() #所有字母小写
2.2 合并字符串:⬇
== 使用 + 号 ==
2.3 添加空白:⬇
复制代码
1
2
3t n
2.4 删除空白:⬇
复制代码
1
2
3
4
5
6
7str.strip() #删除首尾空白 str.lstrip() #删除左空白 str.rstrip() #删除右空白
3、数字
两乘号表示乘方
将非字符串型转换为字符串: str()
4、列表
复制代码
1
2person=['jay','jj','bruceli']
4.1 访问列表元素:⬇
复制代码
1
2
3print( person[0] ) #索引为-1时访问最后一个元素
4.2 修改:⬇
复制代码
1
2
3person[0]=‘liangbo’ #索引为-1时访问最后一个元素
4.3 添加:⬇
复制代码
1
2
3
4
5person.append('sherlock') #列表末尾添加元素 person.insert(0,'holmes') #在索引处添加元素
4.4 删除:⬇
复制代码
1
2
3
4
5
6
7del person[0] #删除索引位置的元素 ss=person.pop(0) #被弹出的元素不在列表中 person.remove('jay') #删除特定元素
4.5 对列表排序:⬇
复制代码
1
2
3
4
5
6
7
8
9person.sort(reverse=True) #对列表永久排序:并按照与字母相反的顺序 person.sorted() #临时排序 person.reverse() #倒着打印列表 len( person ) #确定列表长度
4.6 遍历列表:⬇
复制代码
1
2
3
4
5cats=['ll','ss','xx'] #最好使用单复数形式遍历 for cat in cats: print(cat)
expected an indented block(期待一个缩进模块)
复制代码
1
2
3range(4, 19 , 2 ) #产生从4开始,18结束的数字 , 步长
4.7 数字列表:⬇
复制代码
1
2
3
4
5
6
7
8digits=[1,2,3,4,5,6] min(digits) #数字列表中的最小值 max(digits) #数字列表中的最大值 sum(digits) #数字列表 求和
复制代码
1
2
3v=[value**2 for value in range(1,5)] #列表解析:创建了一个1到4的平方构成的数字列表
4.8 切片:⬇
复制代码
1
2
3
4
5
6
7
8
9
10
11lists=['jay','jack','wanjiu','yuqian'] print( list[0:2] ) #从 下标0 到 下标2 切片 print( list[ :2] ) #从 下标0 到 下标2 切片 print( list[ -2 : ] ) #从 下标-2 到 最后 切片
4.9 复制列表:⬇
复制代码
1
2
3
4
5
6list=["hh","lili","wa","liu"] nu=list[:] print(list) print(nu) #如果只是简单的令 nu=list 会出现列表都指向同一个
5、元组
5.1 修改元组:⬇
复制代码
1
2
3
4
5
6
7
8dims=(123,233) for dim in dims: print(dim) dims=(44,77) for dim in dims: print(dim) #变量发生改变,并不是元组变了,而是将新的原祖赋值给变量#
6、if语句
6.1 :简单例子 ⬇
复制代码
1
2
3
4
5
6
7
8
9cars=['audi','bmw','benz'] for car in cars: if car=='bmw': #两个等号是发问:变量car的值是bmw吗?# #检查是否相等时 区分大小写# print(car.upper()) else: print(car.title())
6.2 :and,or,in ,not in,布尔表达式⬇
复制代码
1
2
3
4
5
6
7ss=36 ll=45 if (ss<77) and (ll>66): print('yes') else: print('no')
复制代码
1
2
3
4
5
6lists=['ll','sss','wali'] if 'll' in lists: print('yes') else: print('no')
复制代码
1
2
3game=True candi=False
6.3 :确定列表是否为空 ⬇
复制代码
1
2
3
4
5
6
7reqs=[] if reqs: #if 列表名:若列表存在元素,返回True# print("目前为空") else: print("haha")
7、字典:(类似C结构体)
7.1 :一个简单的字典 ⬇
复制代码
1
2
3
4
5alien={'color':'red','points':6} print(alien['color']) #C: alien.color print(alien['points'])
7.2 :添加,删除键值对 ⬇
复制代码
1
2
3
4
5##添加 alien={'color':'green'} alien['x']=25 print(alien)
复制代码
1
2
3##删除 del alien['color']
7.3 :类似对象组成的对象 ⬇
复制代码
1
2
3
4
5favoriteLan={ 'ss':'c', 'wy':'python' }
7.4 :遍历字典 ⬇
复制代码
1
2
3
4
5
6
7
8
9favoriteLan={ 'ss':'c', 'wy':'python' } for key,value in favoriteLan.items(): ## items()是一个方法,将键值对返回到 key,value两个变量中 print("nkey:"+key) print("nvalue:"+value)
复制代码
1
2
3
4
5
6
7favoriteLan={ 'ss':'c', 'wy':'python' } for name in favoriteLan.keys(): ## keys()是一个方法,返回键。
复制代码
1
2
3
4
5
6
7
8
9favoriteLan={ 'ss':'c', 'lov':'hello', 'wy':'python' } for name in sorted(favoriteLan.keys()): ## 按顺序返回键。 print(name)
复制代码
1
2
3
4
5
6
7
8
9
10
11favoriteLan={ 'ss':'c', 'lov':'hello', 'wy':'python', 'q':'hello' } for name in set(favoriteLan.values()): ## values()返回值 ## set()是集合,剔除重复的值。 print(name)
7.5 :嵌套 ⬇
复制代码
1
2
3
4
5
6alien_0={'color':'red','points':50} alien_1={'color':'green','points':10} aliens=[alien_0,alien_1] for alien in aliens: print(alien)
8、用户输入和while循环:
8.1 :输入 ⬇
复制代码
1
2
3name=input('please inputn') print(name)
复制代码
1
2
3
4
5
6hei=input('heightn') hei=int(hei) ## int() 将字符串转为数值型 if hei>18: print('hh')
8.2 :while ⬇
复制代码
1
2
3
4
5num=1 while num<=4: print(num) num+=1
复制代码
1
2
3
4
5
6## 利用while删除重复的元素 pets=['cat','pig','cat'] while 'cat' in pets: pets.remove('cat') print(pets)
8.3 :使用用户输入填充字典 ⬇
复制代码
1
2
3
4
5
6
7
8
9
10
11
12reps = {} active = True while active: name = input('what is your name?n') mountain = input('which mountain would you like to climb someday?') reps[name] = mountain repeat = input('yes/no') if repeat == 'yes': active = True else: active = Falseprint(reps)
9、函数:
9.1 :定义函数 ⬇
复制代码
1
2
3
4
5def get_user(): '''定义''' print('hello') get_user()
9.2 :关键字实参 ⬇
复制代码
1
2
3
4
5
6def get_user(uname,uage): '''定义''' print(uname) print(uage) get_user(uage=15,uname='aa')
9.3 :默认实参 ⬇
复制代码
1
2
3
4def get_user(uname='ll'): print(uname) get_user()
9.4 :返回值 ⬇
复制代码
1
2
3
4
5
6def pname(firstname,lastname,midname=''): pu=firstname+''+midname+''+lastname return pu newn=pname('wa','shiyi') print(newn)
9.5 :返回字典 ⬇
复制代码
1
2
3
4
5
6
7
8
9def get_person(firstn,lastn): newp={ 'firn':firstn, 'lan':lastn } return newp pp=get_person('wa','yy') print(pp)
9.6 :传递列表 ⬇
复制代码
1
2
3
4
5
6
7def getU(names): for name in names: msg="hello,"+name.title()+"!" print(msg) lista=['wa','li','sak'] getU(lista)
复制代码
1
2
3
4#禁止函数修改列表 #将列表副本传递 function_name(list_name[:])
9.7 :传递任意数量的实参 ⬇
复制代码
1
2
3
4
5
6def mak_pizza(*toppings): ## *toppings代表所有的参数,将参数封装到元组中 print(toppings) mak_pizza('pepperoni') mak_pizza('mush','green','cheese')
复制代码
1
2
3
4
5
6
7
8## 结合位置实参和任意数量实参 def mak_pizza(size,*toppings): print('size'+str(size)+'配料是:') for topping in toppings: print(topping) mak_pizza(16,'pepperoni') mak_pizza(21,'mush','green','cheese')
复制代码
1
2
3
4
5
6
7
8
9
10
11## 传递任意数量关键字实参 def per_info(first,last,**otherinfo): per={} per['first_name']=first per['last_name']=last for key,value in otherinfo.items(): per[key]=value return per uu=per_info('wy','lxs',movie='maohelaoshu',mountain='ximalaya') print(uu)
9.8 :将函数存储在模块中 ⬇
复制代码
1
2
3
4import makepizza ## 引入makepizza.py整个模块 makepizza.make_pizza(16,'pep','green')
复制代码
1
2
3
4from makepizza import make_pizza ## 引入makepizza.py模块中的函数 make_pizza(18,'pep','red')
复制代码
1
2
3
4import makepizza as mp ## 用as 给模块/函数 起别名 mp.make_pizza(21,'pepsss','yellow')
复制代码
1
2
3
4
5
6## 这是定义的makepizza.py def make_pizza(size,*toppings): print(str(size)+'需要的原料:') for topping in toppings: print(topping)
10、类:
10.1 :创建、使用类 ⬇
复制代码
1
2
3
4
5
6
7
8
9
10
11
12## 这是类的创建 class Dog(): '''小狗类''' def __init__(self,name,age): ## 注意这里下划线 每一侧各有 两个! self.name=name self.age=age def sit(self): print(self.name+"小狗已经蹲下") def roll_over(self): print(self.name+"小狗翻滚")
复制代码
1
2
3
4## 用类创建实例 dog1=Dog('doggy',7) print(dog1.name)
10.2 :使用实例 ⬇
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15## 修改属性的值 ##方法一:直接修改 class Car(): def __init__(self, make,model,year): self.make=make self.model=model self.year=year self.odometer=0 def read_odometer(self): print(self.make+' '+self.model+' '+str(self.odometer)) new_car=Car('audi','a4',2016) new_car.odometer=12 new_car.read_odometer()
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21## 修改属性的值 ##方法二:使用方法修改 class Car(object): """docstring for Car""" def __init__(self, make,model,year): self.make=make self.model=model self.year=year self.odometer=0 def read_odometer(self): print(self.make+' '+self.model+' '+str(self.odometer)) def update_odometer(self,newdata): if newdata > self.odometer: self.odometer=newdata else: print("you don't update data!n ") car1=Car('audi','a4',2017) car1.update_odometer(18) car1.read_odometer()
10.3 :继承 ⬇
复制代码
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
27class Car(object): ##父类 def __init__(self, make,model,year): self.make=make self.model=model self.year=year self.odometer=0 def read_odometer(self): print(self.make+' '+self.model+' '+str(self.odometer)) def update_odometer(self,newdata): if newdata > self.odometer: self.odometer=newdata else: print("you don't update data!n ") class Elcar(Car): ##子类 def __init__(self,make,model,year): super().__init__(make,model,year) #使得子类与父类相关联 self.elc=70 def descibe_battery(self): print(self.make+' '+self.model+' '+"has a"+str(self.elc)+"-kwh battery") my_car=Elcar('tesla','model3',2016) my_car.descibe_battery() ##如果需要重写 父类 方法,则只需要在子类中创建一个与父类方法同名的方法。
10.4 :导入 ⬇
复制代码
1
2
3
4from car import Car my_car1=Car('tesla','model',2017) my_car1.read_odometer()
11、文件和异常:
11.1 :读取整个文件 ⬇
复制代码
1
2
3
4with open('pi_digits.txt') as file_object: cont=file_object.read() print(cont)
复制代码
1
2
3
4
5
6with open('D:yYStudycodepythonCodeotherfileoth.txt') as file_object: ##绝对路径: 是反斜杠 cont=file_object.read() print(cont)
复制代码
1
2
3
4
5with open(''otherfileoth.txt'') as file_object: ##相对路径 cont=file_object.read() print(cont)
11.2 :逐行读取 ⬇
复制代码
1
2
3
4
5
6filename='otherfileoth.txt' with open(filename) as file_object: for line in file_object: print(line.rstrip()) ##取消每行末尾的换行符,取消空白
复制代码
1
2
3
4
5filename='otherfileoth.txt' with open(filename) as file_object: lines=file_object.readlines() ##创建一个包含文件内容的列表
11.3:写入文件 ⬇
复制代码
1
2
3
4
5
6
7filename='pi_digits.txt' with open(filename,'w') as file_object: file_object.write('i love python!') #如果写入多行,要在末尾加入换行符 #模式'w' 使得覆盖掉原文本内容 #模式 'a' 会在原文本后面写入(附加模式)
11.4:异常 ⬇
复制代码
1
2
3
4
5
6
7try: print(5/0) except ZeroDivisionError: print("you can't divide by zero!") #利用 try except进行错误处理 #pass :什么都不做
11.5:存储数据 ⬇
复制代码
1
2
3
4
5
6
7#存储 import json numb=[1,2,3,4,5] filename='numbe.json' with open(filename,'w') as file_name: json.dump(numb,file_name)
复制代码
1
2
3
4
5
6
7#读入到内存中 import json filename='numbe.json' with open(filename) as file_name: nn=json.load(file_name) print(nn)
12、测试:
12.1 :测试函数 ⬇
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14import unittest #引入测试单元 def get_f_name(fi,la): quan=fi+' '+la return quan.title() class NameTestCase(unittest.TestCase): #定义一个测试类,必须继承于unittest.TestCase """测试name_function.py""" def test_first_last_name(self): #其中的一个单元测试,用于测试get_f_name()的一部分 f_name=get_f_name('ja','jo') self.assertEqual(f_name,'Ja Jo') unittest.main()
最后
以上就是害怕鸡最近收集整理的关于python学习笔记一、python基础知识的全部内容,更多相关python学习笔记一、python基础知识内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复