版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、欧阳文创编欧阳文创编欧阳文创编欧阳文创编Python 入门教程 超详细 1 小时学Python时间:2021.03.12时间:2021.03.12创作:欧阳文为什么使用 Python假设我们有这么一项任务:简单测试局域网中的电脑ip192.168.0.101192.168.0.200.思路:用shell编程.(Linux通常是而Windows是批处理脚本).例如,在Windows上用pingip 的命令依次测试各个机器并得到控制台输出.由于ping通时候控制台文本通常是Reply from . 而不通的时候本是timeout . ,所以,在结果中进行字符串查找,即可知道该机器是否连通.实现:J
2、ava代码如下:Stringcmd=cmd.exeping;Stringipprefix=192.168.10.;Stringcmd=cmd.exeping;Stringipprefix=192.168.10.;intbegin=101;intend=200;Processp=null;for(inti=begin;iend;i+)p=Runtime.getRuntime().exec(cmd+i);StringStringline=null;BufferedReaderreader=newBufferedReader(newInputStreamReader(p.getInputStream
3、();while(line=reader.readLine()!=nuBufferedReaderreader=newBufferedReader(newInputStreamReader(p.getInputStream();while(line=reader.readLine()!=null)/Handlingline,maylogsit.reader.close();p.destroy();这段代码运行得很好,问题是为了运行这段代码,你还需要做一些额外的工作.这些额外的工作包括:编写一个类文件main将之编译成字节代码bash当然,用 C/C+同样能完成这项工作.但C/C+不是跨C/C+
4、a的信息记录到网络数据库.由于Linux和Windows的网络口实现方式不同,你不得不写两个函数的版本.用Java就有这样的顾虑.同样的工作用Python实现如下: import subprocesscmd=cmd.exe begin=101 end=200while beginend:l=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE)p.stdin.write(ping 192.168.1.+str(begin)+ n)p.stdin.close()p.wait()print executio
5、nresult: %s%p.stdout.read()对比Java,Python的实现更为简洁,你编写的时间更快.你不需要写main函数,并且这个程序保存之后可以直接运行.另外,和Java一样,Python是跨平台的.有经验的C/Java程序员可能会争论说用C/Java写会比Python写得快.这个观点见仁见智.我的想法是当你同时掌握Java和Python之后,你会发现用Pythonw );a.pyF5,你就可以看到程序的Javaw );a.pyF5,你就可以看到程序的Python 应用场合足够简单的任务,例如一些 shell 编程.如果你喜欢用 Python 设计大型商业网站或者设计复杂的游
6、戏,悉听尊便.快速入门Hello worldPython2.5.4)DLE(Python GUI)Python句能够立即运行.我们写下一句著名的程序语句:printprintHello,world!并按回车.你就能看到这句被K&R引入到程序世界名言.在解释器中选择File-New Window或快捷键 Ctrl+N ,打开一个新的编辑器.写下如下语句:printHello,world!printHello,world!raw_input(Pressenterkeytoclosethiswindo改变文件的字符集结果如下?改变文件的字符集结果如下?21?coding?cpprint2021欢迎来
7、到奥运中国32021raw_input2021Pressenterkeytoclosethiswindow2021?将该字符集改为我们更熟悉的形式?21?coding?GBK?print2021欢迎来到奥运中国32021?21?使用中文的例子raw_input2021Pressenterkeytoclosethiswindow2021?程序一样运行良好ow2021?PythonPython找到你a.pya.py.Python能够直接运行,对比 Java,这是一个优势.国际化支持?我们换一种方式来问候世界新建一个编辑器并写如?下代码?print2021print2021欢迎来到奥运中国32021
8、raw_input2021Pressenterkeytoclosethiswind?方便易用的计算器?n?a=100.0b=201.1c=2343printa=100.0b=201.1c=2343print(a+b+c)/c字符串,ASCII和UNICODE可以如下打印出预义输出格式的字符串:printUsage:thingyOPTIONS-hDisplayprintUsage:thingyOPTIONS-hDisplaythisusagemessage-HhostnameHostnametoconnectto字符串是怎么访问的?请看这个例子:word=abcdefga=word2printa
9、is:+ab=word1:3print bis: +b # index 1 and 2 element s ofword.c=word:2print cis: +c # index 0 and 1 element s ofword.d=word0:print dis: +d # All elementsofe=word:2+word2:print eis: +e # All elementsoff=word-1print fis: +f # The lastelementsof d.g=word-4:-2print gis: +g # index 3 and 4 element s ofwor
10、d.h=word-2:print his: +h # The lasttwo elements. i=word:-2print iis: +i # Everything exceptthe t two charactersl=len(word)printprintLengthofwordis:+str(l)请注ASCIIUNICODEprintInputyourChinesename:s=raw_input(Pressentertobecontinued );printYournameis:+s;l=len(s)printLengthofyourChinesenameinasccodesis:
11、+str(l);a=unicode(s,GBK)l=len(a)printImsorryweshoulduse unicodechar!Characters numberofyourChinesenameinunicodeis:+str(l);List类似JavaList,这是一种方便易用的数据类型:word=a,b,c,d,e,f,ga=word2printais:+aword=a,b,c,d,e,f,ga=word2printais:+ab=word1:3printbis:printb#index1and2elementsofword.c=word:2c=word:2printcis:pr
12、intc#index0and1elementsofword.d=word0:printdis:printdprintcis:printc#index0and1elementsofword.d=word0:printdis:printd#Allelementsofword.e=word:2+word2:printeis:printe#Allelementsofword.f=word-1printfis:printf#Thelastelementsofword.g=word-4:-2printgis:printg#index3and4elementsofword.h=word-2:printhis
13、:printh#Thelasttwoelements.i=word:-2printiis:printi#EverythingexceptthelasttwocharactersprintprintAddsnewelement l=len(word)l=len(word)printprintLengthofwordis:+str(l)word.append(h)printword.append(h)printword条件和循环语句#Multi-waydecisionx=int(raw_input(Pleaseenteraninteger:)ifx0:x=0printNegative#Multi-
14、waydecisionx=int(raw_input(Pleaseenteraninteger:)ifx0:x=0printNegativechangedtozeroelifx=0:printZeroelse:printMore#LoopsLista=cat,window,defenestrateforxina:printx,len(x)如何定义函数#Defineandinvokefunction.defsum(a,b):returna+bfunc=sumr=func(5,6)printrdefsum(a,b):returna+bfunc=sumr=func(5,6)printr#Define
15、sfunctionwithdefaultargumentdefadd(a,b=2):returna+br=add(1)printrr=add(1,5)print r并且,介绍一个方便好用的函数:#Therange()functiona=range(5,10)printaa=range(-2,-7)printaa=range(-7,-2)printaa=range(-2,-11,-3)#The3rdparameterstan欧阳文创编欧阳文创编欧阳文创编欧阳文创编dsdsfor stepprintaI/Ospath=D:/download/baa.txtf=open(spath,w)#Opens
16、fileforwriting.Createsthisfilespath=D:/download/baa.txtf=open(spath,w)#Opensfileforwriting.Createsthisfiledoesntexist.f.write(Firstline1.n)f.writelines(Firstline2.)f.close()f=open(spath,r)#Opensfileforreadingforlineinf:printlinef.close()异常处理s=raw_input(Inputyourage:)ifss=raw_input(Inputyourage:)ifs=
17、:raiseException(Inputmustnobeempty.)try:i=int(s)except ValueError:欧阳文创编欧阳文创编欧阳文创编欧阳文创编printprintCouldnotconvertdatatoaninteger.except:printUnknownexception!else:#Itisnteger.except:printUnknownexception!else:#ItisusefulforcodethatmustbeexecutedifthetryclausedoesnotraiseanexceptionprintYouare%d%i,year
18、soldfinally:#CleanupactionprintGoodbye!类和继承classBase:definitclassBase:definit(self):self.data=defadd(self,x):self.data.append(x)def addtwice(self, x):self.add(x) self.add(x)# Child extends Baseclass Child(Base):欧阳文创编欧阳文创编欧阳文创编欧阳文创编defdefplus(self,a,b):returna+boChild=Child()oChild.add(str1)returna+b
19、oChild=Child()oChild.add(str1)printoChild.dataprintoChild.plus(2,3)包机制#a.pydefadd_func(a,b):returna+b#b.py#a.pydefadd_func(a,b):returna+b#b.pyfromaimportadd_func #Alsocan be:importaprintImportadd_funcfrommoduleaprintResultof1plus 2is:printadd_func(1,2)#Ifusingimporta,thenhereshouldbea.add_funcmodule.Python假设我们有一个parent文件夹,该文件夹有一个child子件夹.child中有一个module a.py . 如何让Python知道个文件层次结构?很简单,每个目录都放一个名为_init_.py 的文件.该文件内容可以为空.这个层次结构如下所示: parent-init_.py-child-init_.py-a.pyb.pyPythonmodulesys,pathPython打印出来:import sysprint sys.pathmodulePYTHONPATHpath
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 08水利大类2027广西专升本水利大类全真模拟-第三套(冲刺拔高·难)(含详解与质量评价)
- 2027届安徽省宿州市十三校高考临考冲刺数学试卷含解析
- 2026年溢洪道闸门操作工(技师)职业技能等级认定强化训练试题
- 贵州省铜仁市铜仁伟才学校2027届高三第五次模拟考试数学试卷含解析
- 2026年地铁防爆安检员(中级)职业技能等级认定强化训练试题
- 高中劳动技术教学设计:金秋果韵·瓜中之王哈密瓜全产业链体验与品牌构建
- 小学六年级英语 Module 6 Unit 2 The name of the spaceship is Shenzhou V 教学设计
- 八年级地理“中国的疆域与人口”复习课教学设计
- 高中英语高三一轮复习War and Peace单元整体教学设计
- 初中道德与法治九年级专题七筑牢保护防线护航健康成长教学设计
- (2026年)医院感染暴发应急处置与报告
- 2026年教育原理模拟试卷(含答案)
- 2026湖塘镇公开招聘城市管理网格员25人考试备考试题及答案解析
- 2026年首创环保集团淮南区域公司公开招聘工作人员18名笔试参考题库及答案解析
- 儿童化妆课课件
- SEMI F104-24 中文版(超纯水和液态化学品输送系统组件颗粒贡献测试方法 2024 年重大修订)
- 2026年广东省春季高考(学考)语文真题(含解析)
- DB11-T 1774-2026 建筑新能源应用设计规范
- 中国中西医结合治疗指南2025版
- 2026年安徽医科大学护理专升本真题及答案
- 幼儿园培训体系建设方案
评论
0/150
提交评论