python入门基础代码#查找index函数的帮助help(str.index)#for循环和break语句frommathimportsqrtforiinrange(2,101):flag=1k=int(sqrt(i))forjinrange(2,k1):ifi%j==0:flag=0breakif(flag):printi#continue语句,满足条件跳出continue后面的语句sumA=0i=1whilei=5:sumA=ii=1ifi==3:continueprint'i=%d,sum=%d'%(i,sumA)#循环中的else语句k=5foriinrange(1,10):ifk==3:breakelse:printi#自定义函数/素材1-100间素数frommathimportsqrtdefisprime(x):ifx==1:returnFalsek=int(sqrt(x))forjinrange(2,k1):ifx%j==0:returnFalsereturnTrueforiinrange(2,101):ifisprime(i):printideff(x,y=True):#默认参数要放在参数列表的最后'xandybothcorrectwordsornot'ify:printx,'andybothcorrect'printx,'isOk'f(68)f(68,False)#传递函数defaddme2me(x):return(xx)defself(f,y):printf(y)self(addme2me,2.2)#lambda函数my_add=lambdax,y:xymy_add(5,6)#数据获取与表示f=open(r'E:\360Downloads\firstpro.txt','w')#新建一个文件f.write('hello,world')#f为对象,write写入文件f.close()f=open(r'E:\360Downloads\firstpro.txt','r')#r代表读出p1=f.read(5)#5代表读出的字节数p2=f.read()printp1,p2f.closef1=open(r'E:\360Downloads\companies.txt')cname=f1.readlines()foriinrange(0,len(cname)):cname[i]=str(i1)''cname[i]f1.closef2=open(r'E:\360Downloads\scompanies.txt','w')f2.writelines(cname)f2.close()#网络数据获取importurllibr=urllib.urlopen(')html=r.read#序列#标准类型运算符'apple''banana'[1,2,3]!=[4,5,6]#值比较atuple=('ba',126.4)btuple=atuplebtupleisnotatuple#对象身份比较('86.40''122.64')and('apple''banana')#布尔运算#序列类型运算符week=['mondy','tuesday','wednesday','thursday','firday','satuday','sunday']printweek[1],week[-2],'\n',week[1:4],'\n',week[:6],'\n',week[::-1]#序列值的序号是从0开始到N-1或者从-1到N'apple'*3'ba'in('ba','theboeingcompany')#序列类型转换工厂函数list('hello,world')#将字符串转成列表tuple('hello,world')#将字符串转成元组#字符串s1='''hello'a'''b''world!'''s1#三引号可以保持里面字符串的原貌s2=r'd:\python\a.py's2ccode=['axp','ba','cat','csco','cvx']cprice=['86.40','122.64','99.44','23.78','115.91']foriinrange(5):print'%d%8s:%8s'%(i,ccode[i],cprice[i])#%8s指的占8个字符print'iget%d%%!'%32#两个%%会留下一个astr='whatdoyouthinkofthissaying'nopain,nogain'?'tempstr=astr.split('\'')[1]#\'为转义字符iftempstr.istitle():print'itistitleformat'else:print'itisnottitleformat'printtempstr.title()astr='\101\t\x41\n'#\八进制数000代表的字符\t代表横向制表符printastr#列表jscores=[9,9,8.5,10,7,8,8,9,8,10]ascore=9jscores.sort()jscores.pop()#去掉最高分jscores.pop(0)#去掉最低分jscores.append(ascore)#合并avescore=sum(jscores)/len(jscores)printavescoreweek=['monday','tuesday','wednesday','thursday','firday']weekend=['saturday','sunday']week.extend(weekend)#extend合并函数fori,jinenumerate(week):#enumerate函数产生从0开始的序列printi1,jnumlist=[3,11,5,8,16,1]numlist.sort(reverse=True)#按逆序排列numlistfruitlist=['apple','banana','pear','lemon','avocado']fruitlist.sort(key=len)fruitlist#按字符长度排序#列表解析[x**2forxinrange(10)][x**2forxinrange(10)ifx**250][(x1,y1)forxinrange(2)foryinrange(2)]#元组atruple=(1,2,3)atrupleatruple[1:]len(atruple)btruple=(['monday',1],2,3)btruple[0][1]2014,#创建元组2014alist=['axp','ba','cat']atruple=('axp','ba','cat')alist[1]='alibaba'atruple[1]='alibaba'#元组是不可变的,列表是可变的alist=[3,5,2,4]alist.sort()#改变原来列表alistalist=[3,5,2,4]sorted(alist)#sorted只是新生成一个列表的副本,原来的列表并没有改变alist#但元组就只能使用sorted,不能用sort,因为不能改变元组atruple=(3,5,2,4)atruple.sort#会报错deffunc(args1,args2='world'):#元组作为函数形式的参数printargs1,args2func('hello',)func(args2='apple',args1='hello')deffunc(args1,*args):printargs1printargsfunc('hello,','wangdachui','liuyuan','linlin')#返回值类型为元组的函数enumerate()、coerce()#字典ainfo={'wangdachui':3000,'niuyun':2000,'linlin':3000}#直接创建字典info=[('wangdachui',3000),('niuyun',2000),('linlin',3000)]binfo=dict(info)#利用dict函数创建字典cinfo=dict([['wangdachui',3000],['niuyun',2000],['linlin',3000]])dinfo=dict(wangdachui=3000,niuyun=2000,linlin=3000)adict={}.fromkeys(('wangdachui','niuyun','linlin'),3000)#fromkeys函数将所有的keys初始值设置为3000adictplist=[('axp','americanexpress','86.40'),('ba','theboeingcompany','122.64'),('cat','caterpillarinc.','99.44')]alist[]blist[]foriinrange(2):astr=plist[i][0]bstr=plist[i][2]alist.append(astr)blist.append(bstr)adict=dict(zip(alist,blist))#zip函数#字典的使用#字典的基本操作ainfo={'wangdachui':3000,'niuyun':2000,'linglin':4500,'tianqi':8000}ainfo['niuyun']#键值查找ainfo['niuyun']=9999#更新ainfoainfo['funyun']=1000#查找'mayun'inainfo#成员判断delainfo#删除字典ainfo={'wangdachui':3000,'niuyun':2000,'linglin':4500,'tianqi':8000}forkeyinainfo.keys():print'name=%s,salary=%s'%(key,ainfo[key])'niuyun'ssalaryis%(niuyun)s.'%ainfo#%(key)格式说明符%字典对象名ainfo={'wangdachui':3000,'niuyun':2000,'linglin':4500,'tianqi':8000}ainfo.keys()ainfo.values()ainfo={'wangdachui':3000,'niuyun':2000,'linglin':4500,'tianqi':8000}binfo={'wangdachui':3000,'niuyun':9999,'linglin':4500,'wangzi':8000}ainfo.update(binfo)#update函数快速更改ainfoastock={'axp':86.4,'ba':122.64}bstock=astockastock={}#此时只会讲astock清空,不会将bstock清空,需要用clear函数才会将关联的都删除bstockastock.clear()bstock#字典作为函数的形式参数deffunc(args1,*argst,**argsd):#一个*是可变长位置参数,**可变长关键字参数printargs1printargstprintargsdfunc('hello','wangdachui','niuyun','linglin',a1=1,a2=2,a3=3)#集合names=['wangdachui','niuyun','wangzi','wangdachui','lingling','niuyun']namesset=set(names)#set删除重复对象,因为集合的元素都不重复namessetaset=set('hello')asetfset=frozenset('hello')fset#集合比较aset=set('sunrise')bset=set('sunset')'u'inasetaset=