收藏 分销(赏)

实例教程1小时学会Python.pdf

上传人:曲**** 文档编号:226591 上传时间:2023-03-09 格式:PDF 页数:10 大小:387.02KB 下载积分:15 金币
下载 相关 举报
实例教程1小时学会Python.pdf_第1页
第1页 / 共10页
实例教程1小时学会Python.pdf_第2页
第2页 / 共10页


点击查看更多>>
资源描述
实例教程:1小时学会Python1序言面向读者本文适合有经验的程序员尽快进入Python2.x世界,特别地,如果你掌握Java和Javascript/、用1小 时你就可以用Python快速流畅地写有用的Python程序.Python3.x IIJ 户 请 参,:http:/ 频任务:简单测试局域网中的电脑是否连通.这些电脑的ip范围从192.168.0.101 到 192.168.0.200.思路:川shell编程.(Linux通常足bash ifu Windows是批处理脚本),例如/i Windows L用ping ip 的命令依次测试各个机耀并得到控制价输出.由于ping通的时候控制台文本通常是Reply from”而 不通的时候文本是time out,所以,在结果中进行字符串些找,即可知道该机器是否连通.实现:Java代码如下:String cmd=,cmd.exe pingString ipprefix=192.168.10.n;int begin=101;int end=200;Process p=null;for(int i=begin;iend;i+)p=Runtime.getRuntime().exec(cmd+i);String line=null;BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream();while(line=reader.readLine()!=null)/Handling line,may logs it.reader.close();p.destroy();)这段代码运行得很好,问题是为运行这段代码,你还需快做 此额外的L作.这此额外的作包括:编写一个类文件 编写一个main方法 将之编译成字节代码 由字节代码不能行接运仃.,你需要再写个小小的bat或朽bash脚本来运行.当然,川C/C+同样能完成这项工作.但C/C+不是踏平台语三在这个足够简单的例子中也许看不 出C/C+和Java实现的区别,但他此史为复杂的场景,比如要将连通与者的信息i已录到网络数据库,由 十Linux和Windows的网络接【1实现方式不同,你不得不写两个函数的版本J目Java就没有这样的顾虑.同样的I作用Python实现如下:import subprocesscmd=cmd.exebegin=101end=200while beginend:p=subprocess.Popen(cmd/shell=True,stdout=subprocess.PIPE/stdin=subprocess.PIPEz stderr=subprocess.PIPE)p.stdin.write(ping 192.168.1,+str(begin)+n)p.stdin.close()p.wait()print execution result:%s%p.stdout.read()对比Java,Python的灰现更为简洁,你编写的时间更快,你不需要写main函数,并II这个程序保存之后 可以立接运行.另外,和Java IT,Python也是跨平台的.仃经胎的C/Java程序员nJ能会争论说用C/Java写会比Python写得快.这个观点见仁见智.我的想法 是当你同时掌握Java和Python之后,你会发现用Python写这类程序的速度会比Java快上许多.例如操 作本地文件时你仅需要行代码而不需要Java的许多流包装类.各种语汇有M:天然的适合的应用范围.用 Python处理 比简短程序类似与操作系统的交/编程丁作外省时省力.Python应用场合足够简单的任务,例如 些shell编程.如果你应欢用Python设计大型商业网站或者设刊复杂的游戏,悉听尊便.2快速入门2.1 Hello world安装完Python之后(我木机的版本是2.5.4)JJJ|IDLE(Python GUI),该程序是Python语言解释 器,你写的语句能够立即运行.我们写下句著名的程序语句:print Hello,world!并接回车.你就能看到这句被K&R引入到程序世界的名言.在解释器中选择File-New Window或快捷键Ctrl+N,打开一个新的编辑器,写下如下语句:print Hello,world!raw_input(Press enter key to close this window);保存为a.py文件.按F5,你就可以看到程庠的运行结果了.这是Python的第.种运行方式.找到你保存的a.py文件,双击.也可以看到程序结果.Python的程序能够自接运行,对比Java,这是 个优势.2.2 国际化支持我们换种方式来问候世界.新建个编辑器并写如下代码:print 欢迎来到奥运中国!”raw_input(Press enter key to close this window);在你保存代码的时候,Python会提小你是办改变文件的字符集,结果如下:#coding:cp936print”欢迎来到奥运中国!”raw_input(Press enter key to close this window);将该字符集改为我们更熟悉的形式:#coding:GBKprint欢迎来到奥运中国!”#使用中文的例子raw_input(Press enter key to close this window);程庠样运行良好.2.3 方便易用的计算器用微软附带的il算器来计数实在太麻烦了,打开Python解一器,在接进行计算:a=100.0b=201.1c=2343print(a+b+c)/c2.4 字符串,ASCII 和 UNICODE可以如F打印出预定义输出格式的字符H;:printnUsage:thingy OPTIONS-h Display this usage message-H hostname Hostname to connect ton ii n字符串足怎么访问的?请看这个例r:word=abcdefga=word2 print a is:+a b=wordl:3 print b is:+b#index 1 and 2 elements of word.c=word:2print c is:+c#index 0 and 1 elements of word.d=word0:print d is:+d#All elements of word.e=word:2+word2:print e is:+e#All elements of word.f=word-l print f is:+f#The last elements of word.g=word-4:-2print g is:+g#index 3 and 4 elements of word.h=word-2:print h is:+h#The last two elements.i=word:-2print i is:+i#Everything except the last two characters l=len(word)print Length of word is:4-str(l)请注意ASCII和UNICODE字符申的区别:print Input your Chinese name:s=raw_input(Press enter to be continued);print Your name is:+s;l=len(s)print Length of your Chinese name in asc codes is:+str(l);a=unicode(s,GBK)l=len(a)print Im sorry we should use unicode charlCharacters number of your Chinese name in unicode is:+str(l);2.5 使用 List类似Java里的List,这是 种方便易用的数据类型:word=a7b7c,;d7e/,f,g a=word2 print a is:+a b=wordl:3 print b is:print b#index 1 and 2 elements of word.c=word:2print c is:print c#index 0 and 1 elements of word.d=word0:print d is:print d#All elements of word.e=word:2+word2:print e is:print e#All elements of word.f=word-l print f is:print f#The last elements of word.g=word-4:-2 print g is:print g#index 3 and 4 elements of word.h=word-2:print h is:print h#The last two elements.i=word:-2 print i is:print i#Everything except the last two characters l=len(word)print Length of word is:+str(l)print Adds new element word.append(h)print word2.6 条件和循环语句#Multi-way decision x=int(raw_input(Please enter an integer:)if x0:x=0print Negative changed to zeroelif x=0:print Zeroelse:print More#Loops Lista=cat,window,defenestrate for x in a:print x,len(x)2.7 如何定义函数#Define and invoke function.def sum(a,b):return a+bfunc=sumr=func(5,6)print r#Defines function with default argumentdef add(a/b=2):return a+br=add(l)print rr=add(l,5)print r井介绍 个方位好用的函数:#The range()functiona=range(5z10)print aa=range(-2,-7)print aa=rangeC-72)print aa=range(-2z-ll,-3)#The 3rd parameter stands for step print a2.8 文件I/Ospath=D:/download/baa.txtf=open(spath,w)#Opens file for writing.Creates this file doesnt exist.f.write(First line l.n)f.writelines(First line 2.)f.close()f=open(spath,r)#Opens file for readingfor line in f:print linef.close()2.9 异常处理s=raw_input(Input your age:)if sraise Exception(Input must no be empty.)try:i=int(s)except ValueError:print Could not convert data to an integer.except:print Unknown exception!else:#It is useful for code that must be executed if the try clause does not raise an exceptionprint You are%d%i,years oldfinally:#Clean up action print Goodbye!2.10 类和继承class Base:def init_(self):self.data=def add(self,x):self.data.append(x)def addtwice(selfz x):self.add(x)self.add(x)#Child extends Baseclass Child(Base):def plus(selfza,b):return a+boChild=Child()oChild.add(strl)print oChild.dataprint oChild.plus(2,3)2.11包机制每个.py文件称为 个module,module之间可以互相导入.请参看以下例子:#a.pydef add_func(a,b):return a+b#b.pyfrom a import add_func#Also can be:import aprint Import add_func from module aprint Result of 1 plus 2 is:print add_func(l,2)#If using import a”,then here should be a.add_funcmodule可以定义在包里面.Python定义包的方式稍微有点古怪,假设我们行 个parent文件夹,该文 件央行个child文件夹.child中价个module a.py.加何止Python知道这个文件层次结构?很简 单,每个“,丧都放个名为,用t_.py的文件,该文件内容可以为空.这个层次结构如下所小:parent-_init_.py-child-_init_.py-a.pyb.py那么Python如何找到我们定义的mod那e?在标准包sys I1,path属性记录了 Python的包路径.你 可以将之打印出来:import sysprint sys.path通常我们可以将module的包路径放到环境变景PYTHON PATH中,该环境变量会自动添加到 sys.path属性.另 种方便的方法是编租斗宜接指定我们的module路径到sys.path I1:import syssys.path.append(D:download)from parent.child.a import add_func print sys.pathprint Import add_func from module aprint Result of 1 plus 2 is:print add_func(l,2),I
展开阅读全文

开通  VIP会员、SVIP会员  优惠大
下载10份以上建议开通VIP会员
下载20份以上建议开通SVIP会员


开通VIP      成为共赢上传

当前位置:首页 > 通信科技 > 开发语言

移动网页_全站_页脚广告1

关于我们      便捷服务       自信AI       AI导航        抽奖活动

©2010-2026 宁波自信网络信息技术有限公司  版权所有

客服电话:0574-28810668  投诉电话:18658249818

gongan.png浙公网安备33021202000488号   

icp.png浙ICP备2021020529号-1  |  浙B2-20240490  

关注我们 :微信公众号    抖音    微博    LOFTER 

客服