python-----基础总结
score = int(input("Input your score:") ) #得分 #必须顶行 #同一级代码缩进必须一致 #官方建议缩四个空格 if score >= 90 and score <= 100: print("A") choice = input("什么奖励想要?") if choice == "大保健": print("秦镇专属...") elif score >=80: print("B") elif score >= 70: print("B-") elif score >= 60: print("C+") elif score >= 50: print("C") elif score >= 40: print("C-") else: print("D")
name = "Alex Li;Rain Wang;Jack" print(name) print(name.strip()) #脱掉, strip girl print(name.split(";")) #分割 ,把一个字符 按空格分割成列表 print(len(name)) #长度 #name1 = 012aozhi,qinzhen, lizhi" name1 = "suhaozhi,qinzhen, lizhi" print(name1.index("h")) #索引 print(name1[0:8]) #切片 print(name1[9:16]) #切片 print("-->",name1[-6:-1]) #切片 print("-->",name1[-6:]) #切片 print("-->",name1[0::3]) #2 步长
names = ["苏浩智", "秦镇","李志","炎龙","饱满","骗子","李志"] print(names) # names[names.index("骗子")] = "徐雨轩" # # print(names) # print(names[-1]) # print(names.index("李志")) #返回 元素 的索引\下标 # print(names[3:5]) # print(names.count("李志")) #统计 # # print(type(names)) # # names.append("光头") #追加 # print(names) # #insert 插入 # # # names.insert(4,"陈涛") # names.insert(3,"洪志强") # print(names) # # print(names.pop(4)) #删除,默认删除最后一个 # names.remove("李志") # del names[1] # # # print(names) #
product_list = [['Iphone7',5800], ['Coffee',30], ['疙瘩汤',1], ['Python Book',99], ['Bike',199], ['ViVo X9',2499], ] shopping_cart = [] salary = int(input("input your salary:")) while True: index = 0 for product in product_list: print(index,product) index +=1 choice = input(">>:").strip() if choice.isdigit():#判断是否为数字 choice = int(choice) if choice >= 0 and choice < len(product_list):#商品存在 product = product_list[choice]#取到商品 if product[1] <= salary: #判断能否买得起 #买得起 shopping_cart.append(product)#加入购物车 salary -= product[1]#扣钱 print("Added product" + product[0] + "into shopping cart,\033[42;1myour current\033[0m balance" + str(salary)) else: print("买不起,穷逼!产品价格是" + str(product[1]) + "你还差" + str(product[1]-salary) + "钱") else: print("商品不存在!") elif choice == "q": print("---已购买商品列表----") for i in shopping_cart: print(i) print("你的余额为:",salary) print("----end----") break else: print("无此选项!")
menu = { '北京':{ '海淀':{ '五道口':{ 'soho':{}, '网易':{}, 'google':{} }, '中关村':{ '爱奇艺':{}, '汽车之家':{}, 'youku':{}, }, '上地':{ '百度':{}, }, }, '昌平':{ '沙河':{ '老男孩':{}, '北航':{}, }, '天通苑':{}, '回龙观':{}, }, '朝阳':{}, '东城':{}, }, '上海':{ '闵行':{ "人民广场":{ '炸鸡店':{} } }, '闸北':{ '火车战':{ '携程':{} } }, '浦东':{}, }, '山东':{}, } exit_flag = False while not exit_flag: for key in menu: print(key) choice = input(">:").strip() if len(choice) == 0 : continue if choice == 'q': exit_flag = True continue if choice in menu: #省存在,进入此省下一级 while not exit_flag: next_layer = menu[choice] for key2 in next_layer: print(key2) choice2 = input(">>:").strip() if len(choice2) == 0: continue if choice2 == 'b': break if choice2 == 'q': exit_flag = True continue if choice2 in next_layer: #再进入下一层 while not exit_flag: next_layer2 = next_layer[choice2] for key3 in next_layer2: print(key3) choice3 = input(">>>:").strip() if len(choice3) == 0: continue if choice3 == 'b': break if choice3 == 'q': exit_flag = True continue if choice3 in next_layer2: while not exit_flag: next_layer3 = next_layer2[choice3] for key4 in next_layer3: print(key4) choice4 = input(">>>>:").strip() if choice4 == 'b':break if choice4 == 'q': exit_flag = True continue
列表 增 name = [] name.append() name.insert(index, element) #元素 删 name.pop(index) , default last name.remove(element) del name[index] names.clear() #清空列表 del names 删除列表 改 name[index] = NewValue #新的值 names.extend(names2) #扩展 names = names + names2 #扩展 #names2.reverse() #反转, names2.sort() #排序 ,是按ASCII表的顺序 查 name.index(element) #返回index值 name.count(element) name[index] #返回对应的值 name #返回整个列表
break_flag = False for i in range(10): print("爷爷层",i) for j in range(10): print("=爸爸层",j) if j == 3: break_flag = True break for k in range(10): print("===>孙子层",k ) if k == 2: break_flag = True break if break_flag: break if break_flag: #if break_falg == True: print("我儿子死了,我也不活了..") break print("keep going....") break_flag = False count = 0 while break_flag == False : print("爷爷层。。。") while break_flag == False: print("爸爸层...") while break_flag == False: count +=1 if count >10: break_flag = True print("炎龙层...") print("keep going....")
menu = { '北京':{ '海淀':{ '五道口':{ 'soho':{}, '网易':{}, 'google':{} }, '中关村':{ '爱奇艺':{}, '汽车之家':{}, 'youku':{}, }, '上地':{ '百度':{}, }, }, '昌平':{ '沙河':{ '老男孩':{}, '北航':{}, }, '天通苑':{}, '回龙观':{}, }, '朝阳':{}, '东城':{}, }, '上海':{ '闵行':{ "人民广场":{ '炸鸡店':{} } }, '闸北':{ '火车战':{ '携程':{} } }, '浦东':{}, }, '山东':{}, } # # last_layer = menu #上一层 # # current_layer = menu #当前层 # # while True: # for key in current_layer: # print(key) # # choice = input(">>:").strip() # if len(choice)==0:continue # # if choice in current_layer: #进入下一层 # last_layer = current_layer #Current layer现在是当前层,进入下一层之前,存成last_layer # current_layer = current_layer[choice] #北京 # if choice == "b": # current_layer = last_layer #把上一层赋值给当前层,这样下一次循环时,循环的就是上一层 # last_layers = [ menu ] #上一层 current_layer = menu #当前层 while True: for key in current_layer: print(key) choice = input(">>:").strip() if len(choice)==0:continue if choice in current_layer: #进入下一层 last_layers.append(current_layer) #当前层添加到列表 current_layer = current_layer[choice] #北京 if choice == "b": if last_layers: current_layer = last_layers[-1] #取到上一层,赋值给current_layer last_layers.pop() if choice == 'q': break
集合: 1,去重 ,2,关系测试 交集 instersection & 两个都有 差集 difference - 在列表a里有,b里没有 并集 union | 把两个列表里的元素合并在一起,去重 对称差集 symmetric_difference
python2.x:
1 str:bytes数据
2 unicode:unicode编码后二进制数据
python3.x:
1 str:unicode
2 bytes:bytes
a = 3 b = 4 c = a if a < b else b print(c)
import sys for i in range(101): s = "\r%d%% %s" % (i,"#"*i) sys.stdout.write(s) sys.stdout.flush() import time time.sleep(0.5)
#文件操作: # 打开文件 open() # 操作文件 write() # 关闭文件 close() #f=open("test",encoding="utf8") #data=f.read() # f.close() #----------读操作---------- # python3:读字符 # python2:读字节 #data=f.read() # data=f.read(5) # 读指定个数的字符 # data2=f.read(5) #从光标位置 读指定个数的字符 # data=f.readline()#打印一行内容 # data2=f.readline() # data=f.readlines() #列表结果,打印所有行 #print(data) #print("data2",data2) # f.close() #---------练习--------- # 昨夜寒蛩不住鸣。 # 惊回千里梦,已三更。 # 起来独自绕阶行。 # 人悄悄,帘外月胧明。 # 白首为功名,旧山松竹老,阻归程。 # 欲将心事付瑶琴。 # 知音少,弦断有谁听。 # 在第四行文字中加入岳飞 # 第一种方式:(放弃) # count=0 # for line in f.readlines(): # if count==3: # line="".join([line.strip(),"岳飞"]) # print(line.strip()) # count+=1 # 第二种方式: # for line in f: # 优化内存 # if count==3: # line="".join([line.strip(),"岳飞"]) # print(line.strip()) # count+=1 #------------写操作------------ #r 只读 w:(覆盖)可写 a :追加 #w 覆盖 (有文件直接写文件,没有自己创建一个) #a #总是在光标后面添加 #r+: 默认光标开始位置,追加写 #w+ :覆盖写,想读取内容:seek调整 #a+ :光标默认在文件最后位置,一定追加写 #f=open("test3",mode="w",encoding="utf8") #f=open("test5",mode="a",encoding="utf8") #f=open("test5",mode="x",encoding="utf8") #f=open("test5",mode="rb") # f=open("test5",mode="wb+") # f.write("yyyy\nworld2") # f.flush() # f.write("iiii\nworld2") #--------flush操作----------- # f.write("hellp test5") # f.flush() # import time # time.sleep(100) #可读可写模式 r+ w+ a+ # r+ # f=open("test5",mode="r+",encoding="utf8") # print(f.read()) # f.write("where is xialv?") #w+ #f=open("test5",mode="w+",encoding="utf8") # f=open("test5",mode="r+",encoding="utf8") # # print(f.read(3)) # # #f.write("hello林海峰") # #f.seek(3,0) #将光标移到开始位置,不同于read()方法,它是按字节移动的 # #f.seek(1,-2) #将光标移到开始位置,不同于read()方法,它是按字节移动的 欠着 #print(f.read(3)) #f.seek(1,0) #f.seek(-3,2) #该模式一定按字节操作 #print("----") #print(f.read().decode("utf8")) # # print(f.read()) #print(f.tell()) # f.write(b"hello") # # print(f.read()) # f.seek(-1,2) # print(f.read()) # f.close() # a+ 总是在最后位置添加 # f=open("test5","a+") # # f.seek(0) # print(f.read()) # # f.seek(0) # # f.write("alex")
year = int(input('请输入年:')) month = int(input('请输入月:')) day = int(input('请输入天:')) sum = day days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] i = 0 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): days[1] = 29 while i < month - 1: sum = sum + days[i] i += 1 print('这一天是该年的第', sum, '天')
from urllib.request import urlopen def get(url): return urlopen(url).read() print(get('http://www.baidu.com'))
from urllib.request import urlopen def f1(url): def f2(): print(urlopen(url).read()) return f2 python=f1('http://www.python.org') python()
#内置名称空间:python内置的 查询; import builtins dir(builtins) #全局名称空间:顶头写的 globals查看全局名称空间 #局部名称空间:在函数内部定义 locals查看局部名称空间
#简单时间装饰器 import time def timer(func): def wrapper(*args, **kwargs): start = time.time() res = func(*args, **kwargs) stop = time.time() print('run time in %s' % (start - stop)) return wrapper @timer def index(): time.sleep(2) print('你妈喊你回家吃饭') index() print('-------------------------') @timer def auth(name, password): time.sleep(3) print('登陆成功:姓名:%s密码:' % name, password) auth('xaj', '234') print('-------------------------') @timer def nginx(name): time.sleep(4) print('输入合法姓名:%s' % name) nginx('xaj')
#三元表达 # def f(x,y): # return 1 if x>y else -1 # p = f(2, 3) # print(p)
#无参装饰器从下往上 # @ccc # @bbb # @aaa # def func(): # pass # func=ccc(bbb(aaa(func))) #有参装饰器从下往上 # @ccc('c') # @bbb('b') # @aaa('a') # def func(): # pass # # func=ccc('c')(bbb('b')(aaa('a')(func)))
#迭代器 #可迭代的:只要对象本身有__iter__方法,那它就是可迭代的 #为什么要用迭代器: #优点 # 1:迭代器提供了一种不依赖于索引的取值方式,这样就可以遍历那些没有索引的可迭代对象了(字典,集合,文件) # 2:迭代器与列表比较,迭代器是惰性计算的,更节省内存 #缺点: # 1:无法获取迭代器的长度,使用不如列表索引取值灵活 # 2:一次性的,只能往后取值,不能倒着取值 # 字典: d = {'s': 1, 'n': 3, 'f': 4} # i = d.__iter__() # print(i.__next__()) # print(i.__next__()) # print(i.__next__()) #----------------------------# # i = iter(d) # while True: # try: # print(next(i)) # except StopIteration: # break #----------------------------# # for k in d: # print(k) # 列表: # l = ['a','s','d','g'] # i = l.__iter__() # while True: # try: # print(next(i)) # except StopIteration: # break from collections import Iterable,Iterator s='hello' l=[1,2,3] t=(1,2,3) d={'a':1} set1={1,2,3,4} f=open('a.txt') #都是可迭代的 s.__iter__() # l.__iter__() # t.__iter__() # d.__iter__() # set1.__iter__() # f.__iter__() #可迭代对象 print(isinstance(s,Iterable)) # print(isinstance(l,Iterable)) # print(isinstance(t,Iterable)) # print(isinstance(d,Iterable)) # print(isinstance(set1,Iterable)) # print(isinstance(f,Iterable)) #查看是否是迭代器 print(isinstance(s,Iterator)) # print(isinstance(l,Iterator)) # print(isinstance(t,Iterator)) # print(isinstance(d,Iterator)) # print(isinstance(set1,Iterator)) # print(isinstance(f,Iterator))
def init(func): def wrapper(*args, **kwargs): res = func(*args, **kwargs) next(res) return res return wrapper from urllib.request import urlopen @init def get(): while True: url = yield res = urlopen(url).read() print(res) g = get() g.send('http://www.python.org')
import time t=time.time()+3600*24*3 m=int(time.mktime(time.localtime(t))) r=time.strftime("%Y-%m-%d %X %A", time.localtime(m)) print(r)
import os g=os.walk('C:\\egon') for i in g: # print(i) for j in i[-1]: file_path='%s\\%s' %(i[0],j) print(file_path)
# haha_list = [] # for i in range(100): # haha_list.append('大王巡山%s' % i) # print(haha_list) #列表生成式 # l = ['hahah%s'%i for i in range(100)] # print(l) #三元表达式 # name='alex' # name='egon' # # res='SB' if name == 'alex' else 'shuai' # print(res)
l=[1,2,3,4] s='hello' # l1=[(num,s1) for num in l if num > 2 for s1 in s] # print(l1) # l1=[] # for num in l: # for s1 in s: # t=(num,s1) # l1.append(t) # print(l1)
#列表生成式 # l=['egg%s' %i for i in range(100) if i > 50] # print(l) #列表生成式 # l=[1,2,3,4] # s='hello' # k = [(i,j)for i in l if i >2 for j in s] # print(k) # op = [] # for i in l: # if i > 2: # for j in s: # t = (i, j) # op.append(t) # print(op) #列表生成式 # l = ['hahah%s'%i for i in range(100)] # print(l)
salaries={ 'egon':3000, 'alex':100000000, 'wupeiqi':10000, 'yuanhao':2000 } f = lambda k: salaries[k] print(f('alex'))
data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35] def search(num, data): print(data) if len(data) > 1: # 二分 mid_index = int(len(data) / 2) mid_value = data[mid_index] if num > mid_value: # 19>18 # num在列表的右边 data = data[mid_index:] # data[0:]-->[18] search(num, data) elif num < mid_value: # num在列表的左边 data = data[:mid_index] search(num, data) else: print('find it') return else: if data[0] == num: print('find it') else: print('not exists') # search(9527,data) search(15, data) # search(1,data)
''' 1. 必须有一个明确的结束条件 2. 每次进入更深一层递归时,问题规模相比上次递归都应有所减少 3.递归效率不高,递归层次过多会导致栈溢出(在计算机中, 函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用, 栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的, 所以,递归调用的次数过多,会导致栈溢出) ''' def age(n): if n == 1: return 10 else: return age(n-1)+2 #age(4)+2 print(age(5))
#应用场景 #找不到共同特征和技能不用强求 #对象:学校----->归类 #共有的特征:商标为etiantian #共有的技能:招生 #独有的特征:地址不一样,老师们,课程 class School: tag='etiantian' def __init__(self,addr): self.addr=addr self.teacher_list=[] self.course_list=[] def zhaosheng(self): pass #对象:老师---->归类 #共同的技能:教课 #独有的特征:名字,性别,level,课程 class Teacher: def __init__(self,name,sex,level): self.name=name self.sex=sex self.level=level self.course_list=[] def teach(self): pass #对象:学生---->归类 #共同的特征: #共同的技能:search_score,handin #独有的特征:学号,名字,性别,课程 class Student: def __init__(self,ID,name,sex): self.id=ID self.name=name self.sex=sex self.course_list=[] def search_score(self): pass def handin(self): pass class Course: def __init__(self,name,price,period): self.name=name self.price=price self.period=period s1=Student('123123123123','cobila','female') # print(s1.id,s1.name,s1.sex) # print(s1.course_list) # s1.course_list.append('python') # s1.course_list.append('linux') # print(s1.course_list) python_obj=Course('python',15800,'7m') linux_obj=Course('linux',19800,'2m') s1.course_list.append(python_obj) s1.course_list.append(linux_obj) # print(s1.course_list) print('''student name is:%s course name is :%s course price is :%s ''' %(s1.name,s1.course_list[0].name,s1.course_list[0].price))
#coding:utf-8 #新式类的继承,在查找属性时遵循:广度优先 # class A(object): # def test(self): # print('from A') # pass # class B(A): # # def test(self): # # print('from B') # pass # class C(A): # # def test(self): # # print('from C') # pass # class D(B): # # def test(self): # # print('from D') # pass # # class E(C): # # def test(self): # # print('from E') # pass # class F(D,E): # # def test(self): # # print('from F') # pass # f1=F() # # f1.test() # # # print(F.__mro__) # print(F.mro()) #广度优先:F->D->B->E->C->A->object #python2中经典类的继承,在查找属性时遵循:深度优先 class A: # def test(self): # print('from A') pass class B(A): # def test(self): # print('from B') pass class C(A): # def test(self): # print('from C') pass class D(B): # def test(self): # print('from D') pass class E(C): # def test(self): # print('from E') pass class F(D,E): # def test(self): # print('from F') pass f1=F() f1.test() #深度优先:# F->D->B->A->E->C
#多态:同一种事物的多种形态,动物分为人类,猪类(在定义角度) class Animal: def run(self): raise AttributeError('子类必须实现这个方法') class People(Animal): def run(self): print('人正在走') class Pig(Animal): def run(self): print('pig is walking') class Dog(Animal): def run(self): print('dog is running') peo1=People() pig1=Pig() d1=Dog() peo1.run() pig1.run() d1.run() #多态性:一种调用方式,不同的执行效果(多态性) def func(obj): obj.run() func(peo1) func(pig1) func(d1) # peo1.run() # pig1.run() # 多态性依赖于: # 1.继承 # 2. ##多态性:定义统一的接口, def func(obj): #obj这个参数没有类型限制,可以传入不同类型的值 obj.run() #调用的逻辑都一样,执行的结果却不一样 func(peo1) func(pig1) func(d1)
Python staticmethod() 函数 Python 内置函数 Python 内置函数 python staticmethod 返回函数的静态方法。 该方法不强制要求传递参数,如下声明一个静态方法: class C(object): @staticmethod def f(arg1, arg2, ...): ... 以上实例声明了静态方法 f,类可以不用实例化就可以调用该方法 C.f(),当然也可以实例化后调用 C().f()。 函数语法 staticmethod(function) 参数说明: 无 实例 #!/usr/bin/python # -*- coding: UTF-8 -*- class C(object): @staticmethod def f(): print('runoob'); C.f(); # 静态方法无需实例化 cobj = C() cobj.f() # 也可以实例化后调用
#__str__定义在类内部,必须返回一个字符串类型, #什么时候会出发它的执行呢?打印由这个类产生的对象时,会触发执行 class People: def __init__(self,name,age): self.name=name self.age=age def __str__(self): return '<name:%s,age:%s>' %(self.name,self.age) p1=People('egon',18) print(p1) str(p1) #----->p1.__str__()
def test(x:int,y:int)->int: return x+y print(test.__annotations__)
#基于继承来定制自己的数据类型 class List(list): #继承list所有的属性,也可以派生出自己新的,比如append和mid def append(self, p_object): ' 派生自己的append:加上类型检查' if not isinstance(p_object,int): raise TypeError('must be int') super().append(p_object) @property def mid(self): '新增自己的属性' index=len(self)//2 return self[index] #mid取中间值 l=List([1,2,3]) print(l.mid) #基于授权来定制自己的数据类型: class Open: def __init__(self,filepath,mode,encode='utf-8'): self.f=open(filepath,mode=mode,encoding=encode) self.filepath=filepath self.mode=mode self.encoding=encode def write(self,line): print('write') self.f.write(line) def __getattr__(self, item): return getattr(self.f,item) f=Open('a.txt','w') f.write('123123123123123\n') print(f.seek) f.close() f.write('111111\n') f=open('b.txt','w') f.write('bbbbbb\n') f.close() print(f)
import random def v_code(): code = '' for i in range(5): num=random.randint(0,9) alf=chr(random.randint(65,90)) add=random.choice([num,alf]) code="".join([code,str(add)]) return code print(v_code())
# import sys # for i in range(100): # i += 1 # s="\r%d%% %s"%(i,"#"*i) # sys.stdout.write(s) # sys.stdout.flush() # import time # time.sleep(0.5)
from collections import Iterable,Iterator #判断是不是可迭代对象 class Foo: def __init__(self,start): self.start=start def __iter__(self): return self def __next__(self): return 'aSB' f=Foo(0) f.__iter__() f.__next__() print(isinstance(f,Iterable)) #是不是可迭代 f.__iter__() print(isinstance(f,Iterator)) #是不是迭代器f.__next__()
########__call__方法########: class People: def __init__(self,name): self.name=name # def __call__(self, *args, **kwargs): print('call') # p=People('egon') print(callable(People)) print(callable(p)) p() #类调用:实例化,对象引用 #加__call__对象直接可以执行 #类对象都是可被调用对象,类的实例对象是否可调用对象,取决于类是否定义了__call__方法。 #callable方法用来检测对象是否可被调用,可被调用指的是对象能否使用()括号的方法调用。 class A: # 定义类A pass callable(A) # 类A是可调用对象 #执行结果:True
#type元类是类的类。可以控制类的行为 class Mymeta(type): def __init__(self,class_name,class_bases,class_dic): # print(self) # print(class_name) # print(class_bases) # print(class_dic) for key in class_dic: if not callable(class_dic[key]):continue if not class_dic[key].__doc__: raise TypeError('没写注释,赶紧去写') # type.__init__(self,class_name,class_bases,class_dic) class Foo(metaclass=Mymeta): x=1 def run(self): 'run function' print('running') Foo=Mymeta('Foo',(object,),{'x':1,'run':run}) print(Foo.__dict__)
import struct 发送: res = struct.pack('i',33333) print(len(res)) 接受: struct.unpack('i',res)[0]
import time import pygame file=r'C:\Users\chan\Desktop\Adele - All I Ask.mp3' pygame.mixer.init() print("播放音乐1") track = pygame.mixer.music.load(file) pygame.mixer.music.play() time.sleep(10) pygame.mixer.music.stop()

浙公网安备 33010602011771号