


下载本文档
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、实例教程:1小时学会Python1序言面向读者本文适合有经验的程序员尽快进入Python2.x 世界.特别地,如果你掌握Java和Javascript,不用1小时你就可以用Python快速流畅地写有用的 Python程序.Python3.x 用户请参考:由于Django 不支持python3,所以为了你的开展潜力,建议你学习python2.x 为什么使用Pytho n假设我们有这么一项任务:简单测试局域网中的电脑是否连通 .这些电脑的ipX围从到192.168.0.200.思路:用shell编程.Linux 通常是bash而Windows 是批处理脚本.例如,在Windows 上用ping i
2、p的命令依次测试各个机器并得到控制台输出.由于ping通的时候控制台文本通常是"Reply from ."而不通的时候文本是"time out .", 所以,在结果中进行字符串查找,即可知道该机器是否连通. 实现:Java代码如下:Str ing cmd="cmd.exe ping "String ipprefix="192.168.10."int begin=101;int end=200;Process p= null ;for (int i=begin;i<end;i+)p= Run time.getR
3、u ntime().exec(cmd+i);String line =null ;BufferedReaderreader=newBufferedReader( newIn putStreamReader(p.getl nputStream();while (line = reader .readLine() != null )/Ha ndli ng line , may logs it.reader .close();p.destroy();这段代码运行得很好,问题是为了运行这段代码,你还需要做一些额外的工作.这些额外的工作包括?编写一个类文件?编写一个main方法? 将之编译成字节代码?由
4、于字节代码不能直接运行,你需要再写个小小的bat或者bash脚本来运行.当然,用C/C+同样能完成这项工作.但C/C+不是跨平台语言.在这个足够简单的例子中也许看不 岀C/C+和Java实现的区别,但在一些更为复杂的场景,比方要将连通与否的信息记录到网络数据库.由于Linux和Windows的网络接口实现方式不同,你不得不写两个函数的版本.用Java就没有这样的顾虑. 同样的工作用Python实现如下:比照Java,Python 的实现更为简洁,你编写的时间更快.你不需要写main函数,并且这个程序保存之后 可以直接运行.另外,和Java 样,Python 也是跨平台的.有经验的C/Java
5、程序员可能会争论说用C/Java写会比Python写得快.这个观点见仁见智.我的想法是当你同时掌握Java和Python之后,你会发现用Python写这类程序的速度会比 Java快上许多.例如操作本地文件时你仅需要一行代码而不需要Java的许多流包装类.各种语言有其天然的适合的应用X围.用Python处理一些简短程序类似与操作系统的交互编程工作最省时省力.Pytho n应用场合足够简单的任务,例如一些shell编程.如果你喜欢用Python设计大型商业或者设计复杂的游戏,悉听尊便.2快速入门2.1 Hello world安装完Python之后(我本机的版本是2.5.4),翻开IDLE(Pyth
6、on GUI),该程序是Python语言解释器,你写的语句能够立即运行.我们写下一句著名的程序语句:pri nt "Hello,world!"并按回车.你就能看到这句被K&R引入到程序世界的名言.在解释器中选择"File"-"NewWindow" 或快捷键Ctrl+N ,翻开一个新的编辑器.写下如下语句:pri nt "Hello,world!"raw_input("Press enter key to close this windowL ");保存为a.py文件.按F5,你就可以看到
7、程序的运行结果了.这是Python的第二种运行方式. 找到你保存的a.py文件,双击.也可以看到程序结果.Python的程序能够直接运行,比照Java,这是一个优势.2.2国际化支持我们换一种方式来问候世界.新建一个编辑器并写如下代码print "欢送来到奥运中国!"raw_input("Press enter key to close this window-");在你保存代码的时候,Python会提示你是否改变文件的字符集,结果如下:# -*- codi ng: cp936 -*- print "欢送来到奥运中国!"raw_in
8、put("Press en ter key to close this wi ndow);将该字符集改为我们更熟悉的形式:# -*- cod ing: GBK -*-print "欢送来到奥运中国!" #使用中文的例子raw_input("Press enter key to close this window");程序一样运行良好.2.3方便易用的计算器用微软附带的计算器来计数实在太麻烦了.翻开Python解释器,直接进行计算a=100.02.4 字符串,ASCII 和 UNICODE可以如下打印岀预定义输岀格式的字符串print "
9、;"“Usage: thingy OPTIONS-hDisplay this usage message-H host nameHost name to conn ect tomill字符串是怎么访问的?请看这个例子word="abcdefg"a=word2pri nt "a is: "+ab=word1:3pri nt "b is: "+b # in dex 1 and 2 eleme nts of word.c=word:2pri nt "c is: "+c # in dex 0 and 1 elem
10、e nts of word.d=word0:pri nt "d is: "+d # All eleme nts of word.e=word:2+word2:print "e is: "+e # All elements of word.f=word-1pri nt "f is: "+f # The last eleme nts of word.g=word-4:-2pri nt "g is: "+g # in dex 3 and 4 eleme nts of word.h=word-2:pr int "
11、h is: "+h # The last two eleme nts.i=word:-2print "i is: "+i # Everything except the last two charactersl=le n( word)pri nt "Le ngth of word is: "+ str(l)请注意ASCII和UNICODE字符串的区别pri nt "In put your Chin ese n ame:"s=raw_ in put("Press en ter to be contin ued);pr
12、int "Your name is :"+s;l=le n(s)print "Le ngth of your Chin ese n ame in asc codes is:"+str(l);a=u nicode(s,"GBK")l=le n(a)pri nt "I'm sorry we should use uni code char!Characters n umber of your Chin ese n ame in uni code is:"+str(l);2.5 使用 List类似Java里的Li
13、st,这是一种方便易用的数据类型word='a','b','c','d','e','f','g'a=word2pri nt "a is: "+ab=word1:3pri nt "b is:"pr int b # in dex 1 and 2 eleme nts of word.c=word:2pri nt "c is:"pr int c # in dex 0 and 1 eleme nts of word.d=word0:p
14、ri nt "d is:"pri nt d # All eleme nts of word.e=word:2+word2:pri nt "e is:"pri nt e # All eleme nts of word.f=word-1pri nt "f is:"pri nt f # The last eleme nts of word.g=word-4:-2pri nt "g is:"pr int g # in dex 3 and 4 eleme nts of word.h=word-2:pri nt "h
15、 is:"pri nt h # The last two eleme nts.i=word:-2pri nt "i is:"print i # Everything except the last two charactersl=le n( word)pri nt "Le ngth of word is: "+ str(l)pri nt "Adds new eleme nt2.6条件和循环语句# Multi-way decisi on x= int (raw input("Please enter an integer:&q
16、uot;) if x<0:x=0pri nt "Negative cha nged to zero" elif x=0:pri nt "Zero" else :pri nt "More"# Loops Lista = 'cat', 'w in dow', 'defe nestrate'for x in a:pr int x, le n(x)2.7如何定义函数# Define and in voke fun cti on.def sum(a,b):return a+b func =
17、sum r = fun c(5,6) pri nt r# Defines fun cti on with default argume nt def add(a,b=2):return a+br=add(1)pri nt rr=add(1,5)pri nt r并且,介绍一个方便好用的函数:# The ran ge() fun cti ona =ran ge(5,10)pri nt aa = ran ge(-2,-7)pri nt aa = ran ge(_7,_2)pri nt aa = range(-2,-11,-3) # The 3rd parameter standsfor steppr
18、i nt a2.8 文件I/Ospath="D:/dow nload/baa.txt"f=ope n( spath,"w") # Opens filefor writi ng.Createsthis file does n't exist.f.write("First line 1.n")f.writelines("First line 2.") f.close()f=ope n( spath,"r") # Opens filefor read ing for line in f:pri
19、 nt line f.close()2.9异常处理s=raw_ in put("I nput your age:")if s ="":raise Excepti on( T nput must no be empty.") try :i= int (s)except ValueError:pri nt "Could not con vert data to an in teger."except:pri nt "Unknown excepti on!"else : # It is useful for c
20、ode that must be executedif the try clause does not raise anexcepti onpri nt "You are %d" % i," years old"fin ally : # Clea n up acti onpri nt "Goodbye!"2.10类和继承2.11 包机制每一个.py文件称为一个module,module之间可以互相导入.请参看以下例子# b.pyfrom a import add_func # Also can be : import a print
21、"Import add func from module a"print "Result of 1 plus 2 is:"print add_func(1,2)# If using "import a" , then here should be "a.add_func"module可以定义在包里面.Python定义包的方式稍微有点乖僻,假设我们有一个parent文件夹,该文 件夹有一个child子文件夹.child中有一个module a.py . 如何让Python知道这个文件层次结构 ?很简 单,每个目录都放一个名为_init_.py的文件.该文件内容可以为空.这个层次结构如下所示:pare nt-_i nit_.py-child可以将之打印岀来通常我们可以将module的包路径放到环境变量PYTHONPATH 中,该环境变量会自动添加到sys.path 属性.另一种方便的方法是编程中直接指定我们的module路径到sys.path 中:import syssys.path.appe
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 哲学视野下的世界
- 春季营销战略解析
- 老旧供水管网更新改造工程可行性研究结论及建议
- 电化学储能电站项目概况
- 2025年自动化贴补强机项目申请报告模板
- 2025合同保密协议书范本标准版
- 生物●天津卷丨2023年天津市普通高中学业水平选择性考试生物试卷及答案
- 剧情模拟测试题及答案大全
- 2025年刀具预调仪项目提案报告模板
- 理赔员招聘考试题及答案
- 2024年中国近代史纲要期末复习题库
- 地方低空经济平台建设指南白皮书
- GB/T 14600-2025电子气体一氧化二氮
- 网络管理员考试实操训练试题及答案
- 婚庆合作入股协议书
- 2025年药剂师资格考试模拟试题及答案
- 2025年陕西省西安市西咸新区中考二模语文试题(原卷版+解析版)
- 财务人员销售技巧培训课件
- GB/T 45545-2025厨房家具配合尺寸
- 燃脂塑形内衣套装行业深度调研及发展战略咨询报告
- 四川甘孜州能源发展集团有限公司招聘真题2024
评论
0/150
提交评论