s=0for i in range(1,101):
s+=ielse:print(s)defmain(n):'''打印菱形图形'''
for i inrange(n):print(('*'*i).center(n*3))for i in range(n,0,-1):print(('*'*i).center(n*3))
main(6)#计算理财产品收益
deflicai(base,rate,days):
result=base
times= 365//daysfor i inrange(times):
result= result+result*rate/365*days #假设本金与利息一起滚动
returnresultprint(licai(100000,0.0543,90))#多次调用同一函数而产生的bug
def demo(newiten,old_list=[]):'''如果增加一个判断返回值初始化为默认值时,就不会产生bug
如:if old_list is None: old_list=[]'''old_list.append(newiten)returnold_listprint(demo('5',['1','2','3']))print(demo('aaa',['a','b']))#在多次调用函数并不为默认值参数传递值时,默认值参数只#在第一次调用时进行解释,这样会导致bug
print(demo('a'))print(demo('g'))#计算圆的面积
from math importpi as PIdefCircleArea(r):ifisinstance(r,(int,float)):return PI * r**2
else:print('Error')print(CircleArea(3))#使用lambda表达式,注意其变量的作用域
r=[]for x in range(10):
r.append(lambda n=x:n**2)#不能直接引用x值,lambda表达式中使用局部变量
print(r[5]())#类对象的定义
classA:def __init__(self,value1=0,value2=0):
self._value1=value1
self.__value2 =value2defshow(self):print(self._value1)print(self.__value2)
a=A()print(a._value1)print(a._A__value2)#数据成员定义
classDemo(object):
total=0def __new__(cls, *args, **kwargs):#该方法在__init__()之前被调用
if cls.total >= 3:raise Exception("最多只能创建3个对象")else:print('实例化',Demo.total)return object.__new__(cls)def __init__(self):
Demo.total= Demo.total + 1t1=Demo()#方法
classRoot:__total =0def __init__(self,v):
self.___value=v
Root.__total +=1
defshow(self):print('Self:',self.___value)print('Root:',Root.__total)
@classmethoddefclassShowTotal(cls):'''类方法,只能访问类成员'''
print(cls.__total)
@staticmethoddefstaticShowTotal():'''静态方法,也是只能访问类成员'''
print(Root.__total)
r= Root(3)
Root.classShowTotal()
Root.staticShowTotal()
r.show()#属性
classTest1:def __init__(self,value):
self.__value =value
@property#修饰器属性,只读,无法修改和删除
defvalue(self):return self.__value
classTest2:def __init__(self,value):
self.__value =valuedef __getValue(self):return self.__value
def __setValue(self,v):
self.__value =v
value= property(__getValue,__setValue)#设置属性可读可写操作#继承
classPerson:def __init__(self):print('this is a parent class')defsetName(self,name):if notisinstance(name,str):print('name must be string.')
self.__name = ''
returnself.__name =nameprint(self.__name)#派生类
classTeacher(Person):def __init__(self):
super(Teacher,self).__init__()#也可以直接用Persion.__init__()
defsetDepartment(self,department):#if type(department) != str:
if notisinstance(department,str):print('department must be string.')
self.__department = 'Computer'
returnself.__department =departmentif __name__ == '__main__':
zhangsan=Teacher()
zhangsan.setName('Lisi')'''探讨继承中的问题,到底基类是否要继承object呢'''
classA:deffoo(self):print('called A.foo()')classB(A):pass
classC(A):deffoo(self):print('called C.foo()')classD(B,C):passd=D()
d.foo()#A类继承object,或不继承object结果会是什么呢?(答案:called C.foo())
'''分析:如果A类是经典类(不继承object),当调用D的实例的foo()方法时,Python
会按照深度优先的方法搜索foo(),路径B-A-C,执行A中的foo();如果A是新式类(继承object),
则会按照广度优先的方法去搜索foo(),路径B-C-A,执行C中的foo();
通过以上分析:其实新式类更符合逻辑;通常对应Python3.x中的新式类已经兼容了经典类,即无论A是否
继承object类,D中都会执行C中的foo()方法,但是在Python2.7-3.0中仍然存在上述的差异,所以我们推荐使用新
式类,要继承object类'''
#类的继承机制
classA(object):def __init__(self):
self.__private()
self.public()def __private(self):#基类的私有成员方法
print('__private Method of A1')defpublic(self):print('public Method of A2')classB(A):#没有构造函数,在创建实例时,直接走基类构造函数,对于重写
#非私有成员方法后,此时在基类调用的方法为派生类中的
#如果有构造函数,实例化时则直接是走派生类中的构造函数
def __private(self):print('Method of B1')defpublic(self):print("public Method of B2")
b=B()
b.public()#字符串#1.短字符串驻留机制,共享同一个副本值
a='1234'b='1234'
print(id(a) ==id(b),b)#2.格式化模板类
from string importTemplate
t= Template('My name is ${name},and is ${age} years old')
d={'name':'dong','age':34}print(t.substitute(d))#3.字符串常用方法find(),rfind(),index(),rindex(),count()
'''find():查找字符串首次出现的位置
rfind():查找字符串最后出现的位置
index():查找字符串首次出现的位置'''s= 'apple,peach,banana,peach,pear'
print(s.find('pp'))print(s.index('pp'))#4.split(),rsplit(),partition(),rpartition()
'''split(),rsplit()返回的是列表,如果有多个连线空白字符在未指定分隔符情况下,默认作为一个
partition(),rpartition()返回的是元组'''li= s.split(',')print(li)print(s.partition(',,'))#分隔成3部分,如果原字符串中不包含分隔符,则返回原字符串及两个空字符串
ss='2014-10-20'
print(list(map(int,ss.split('-'))))#map对数据进行类型转换#5.join()将列表中的多个字符串连接起来,并插入指定字符
lst = ['say','hello','miao','bai']print("-".join(lst))#使用split()与join()方法可以巧妙删除字符串中多余的空字符,并保留一个#6.lower(),upper(),capitalize(),title(),swapcase()
'''lower():返回小写字符串;upp():返回大写字符串:capitalize():返回字符串首字符大写;
title():每个单词首字母大写;swapcase():大小写互换;
注意:这几个方法都是返回新字符串,对原字符串不做任何修改'''
#7.replace() 替换,也是返回新字符串
print('dfjgdifezadewwsaza'.replace('zad','ZAD'))#8.maketrans(),translate()方法生成字符映射表和按映射表转换字符串并替换成字符,该方法可用来对字符串进行加密#demo:创建映射表,将字符"abcdef123"一一对应转换成'uvwxyz@#$'
table =''.maketrans('abcdef123','uvwxyz@#$')
s='Python is a greate programming language,I like it!'
print(s.translate(table))#按照映射表进行转换,使用方法可以实现恺撒加密算法#9.对不可变对象字符串进行修改,需使用io.StringIO或array模块#10.strip(),rstrip(),lstrip()分别用来删除两端、右端或左端连续的空字符串或指定字符串
'''这三个方法是对原字符串进行修改的'''
print('aaasdffffsfafaaaa'.rstrip('a'))print('aaasdffaffsfafaaaa'.rstrip('af'))#注意:字符串中的af有不再两侧的,所以不删除#11.eval()对字符串转换成Python表达式求值
print(eval('2+3'))print(eval('[2,3,4,5]'))#注意:这里不能使用list(x)进行转换#12.in、sartswith、endswith方法可用判断是否存在或以指定字符串开始或结束#demo:startswith、endswith可以接受一个元组,如判断文件扩展名:
importos
[print(filename) for filename in os.listdir(r'F:\\') if filename.endswith(('.txt','.jpg','.gif'))]#13.center()、ljust()、rjust()、zfill()返回指定宽度的新字符串,原字符串居中、左对齐、右对齐、左侧以字符0填充
print('hello world'.center(20,'-'))print('uoi'.zfill(20))#13.切片--读取字符串元素,不支持修改字符串
conent = 'Hello World!'
print(conent[:7])#案例精选#1.编写函数实现字符串加密和解密,循环使用指定密钥,采用简单的异或算法
defcrypt(source,key):from itertools importcycle
result=''temp=cycle(key)for ch insource:
result= result + chr(ord(ch)^ord(next(temp)))returnresult
source='ShangDong insitite of business and technology'key='Dong Fuguo'
print('Before source:'+source)
encryt=crypt(source,key)print('After encryt:'+encryt)
decryt=crypt(encryt,key)print('After decryt:'+decryt)