Python基础教程:从入门到实战的快速指南
本教程专为有编程经验的开发者设计,通过对比Java、C/C++等语言,快速展示Python在脚本编写、网络测试及文件处理上的简洁优势。内容涵盖环境配置、字符串与列表操作、条件循环、函数定义、文件I/O、异常处理及模块包管理等核心概念,帮助读者在短时间内掌握Python编程要点并投入实际开发。
为什么选择Python
设想一个常见任务:检测局域网内主机的连通性,IP范围设定为192.168.0.101至192.168.0.200。
常规思路是采用Shell脚本:Linux环境下使用bash,Windows环境下使用批处理。例如在Windows中执行ping命令并解析控制台输出,通过查找“Reply from...”或“time out...”等关键字来判断连通状态。
若使用Java实现,代码结构如下:
String 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= 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();
}
虽然该Java代码能正常运行,但部署过程较为繁琐,涉及以下额外步骤:
- 首先必须定义一个类文件。
- 其次需要编写标准的main方法入口。
- 接着需将源代码编译为字节码文件。
- 最后,由于字节码无法直接执行,还需编写额外的bat或bash脚本以启动程序。
使用C/C++同样能完成此任务,但C/C++并非跨平台语言。在简单示例中差异不明显,但在复杂场景(如将连通状态写入网络数据库)中,因Linux和Windows网络接口实现差异,需编写两套函数版本。相比之下,Java无需处理此类平台差异问题。
使用Python实现相同功能的代码如下:
import subprocess
cmd="cmd.exe" begin=101 end=200 while begin<end:
p=subprocess.Popen(cmd,shell=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 "execution result: %s"%p.stdout.read()
与Java相比,Python代码更为简洁,开发效率更高。无需定义main函数,保存后即可直接运行。同时,Python也具备跨平台特性,与Java一样无需担心底层接口差异。
资深C/Java开发者可能认为使用C/Java编写此类程序速度更快,这取决于个人习惯。但实际经验表明,同时掌握Java和Python后,使用Python处理此类脚本的速度通常快于Java。例如,操作本地文件时Python仅需一行代码,而Java需使用多个流包装类。每种语言都有其适用场景,Python在处理简短程序及操作系统交互任务时最为省时省力。
Python适用场景
Python非常适合处理足够简单的任务,如Shell脚本替代。若用户偏好使用Python设计大型商业网站或复杂游戏,完全可以根据需求自由发挥。
Hello world示例
安装Python后(本机测试版本为2.5.4),打开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,这是一个显著优势。
国际化支持
尝试以不同方式问候世界。新建编辑器并输入以下代码:
print "欢迎来到奥运中国!"
raw_input("Press enter key to close this window!");
保存代码时,Python会提示是否更改文件字符集,界面如下:
# -*- coding: cp936 -*-
print "欢迎来到奥运中国!"
raw_input("Press enter key to close this window! ");
将字符集更改为更熟悉的格式:
# -*- coding: GBK -*-
print "欢迎来到奥运中国!" # 使用中文的例子
raw_input("Press enter key to close this window");
程序运行结果与之前一致,显示良好。
简易计算器功能
使用微软自带计算器进行复杂计数较为繁琐。打开Python解释器,可直接进行计算:
a=100.0
b=201.1
c=2343
print (a+b+c)/c
字符串、ASCII与UNICODE处理
可按以下方式打印预定义格式的字符串:
print """ Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to """
字符串如何访问?参考以下示例:
word="abcdefg" a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: "+b # index 1 and 2 elements of word.
c=word[:2]
print "c is: "+c # index 0 and 1 elements of word.
d=word[0:]
print "d is: "+d # All elements of word.
e=word[:2]+word[2:]
print "e is: "+e # All elements of word.
f=word[-1]
print "f is: "+f # The last elements of word.
g=word[-4:-2]
print "g is: "+g # index 3 and 4 elements of word.
h=word[-2:]
print "h is: "+h # The last two elements.
i=word[:-2]
print "i is: "+i # Everything except the last two characters
l=len(word)
print "Length of word is: "+ 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 "I'm sorry we should use unicode char!Characters number of your Chinese \ name in unicode is:"+str(l);
使用List列表
类似于Java中的List,这是一种便捷易用的数据类型:
word=['a','b','c','d','e','f','g']
a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: " print b # index1 and 2 elements of word.
c=word[:2]
print "c is: " print c # index0 and 1 elements of word.
d=word[0:]
print "d is: " print d # All elements of word.
e=word[:2]+word[2:]
print "e is: " print e # All elements of word.
f=word[-1]
print "f is: " print f # The last elements of word.
g=word[-4:-2]
print "g is: " print g # index3 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[图片上传中...(image-b4ced-1616074265420-0)] " word.append('h')
print word
条件和循环语句
# Multi-way decision
x=int(raw_input("Please enter an integer:")) if x<0:
x=0 print"Negative changed to zero" elif x==0:
print "Zero" else:
print "More" # Loops List
a= ['cat', 'window', 'defenestrate'] for x ina:
print x, len(x)
如何定义函数
# Define and invoke function.
def sum(a,b):
return a+b
func = sum
r = func(5,6)
print r
# Defines function with default argument
def add(a,b=2):
return a+b
r=add(1)
print r
r=add(1,5)
print r
此外,介绍一个便捷实用的函数:
# The range() function
a =range(5,10)
print a
a = range(-2,-7)
print a
a = range(-7,-2)
print a
a = range(-2,-11,-3) # The 3rd parameter stands for step
print a
文件I/O操作
spath="D:/download/baa.txt" f=open(spath,"w") # Opens file for writing.Creates this file doesn't exist. f.write("First line 1.\n")
f.writelines("First line 2.")
f.close()
f=open(spath,"r") # Opens file forreading for line in f:
print line
f.close()
异常处理机制
s=raw_input("Input your age:") if s =="":
raise 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 exception
print "You are %d" % i," years old" finally: # Clean up action
print "Goodbye!"
类和继承机制
class Base:
def __init__(self):
self.data =[]
def add(self, x):
self.data.append(x)
def addtwice(self, x):
self.add(x)
self.add(x)
# Child extends Base class Child(Base):
def plus(self,a,b):
return a+b
oChild =Child()
oChild.add("str1")
print oChild.data
print oChild.plus(2,3)
包管理机制
每个.py文件称为一个module(模块),模块之间可相互导入。参考以下示例:
# a.py
def add_func(a,b):
return a+b
# b.py
from a import add_func # Also can be : import a
print "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可定义在包(Package)内。Python定义包的方式略有特殊:假设存在parent文件夹,其包含child子文件夹,child中包含module a.py。如何让Python识别此文件层次结构?只需在每个目录中放置一个名为_init_.py的文件,内容可为空。目录结构如下所示:
parent
--__init_.py
--child
-- __init_.py
--a.py
b.py
Python如何定位我们定义的module?标准包sys中的path属性记录了Python的包路径,可打印查看:
import sys
print sys.path
通常可将module包路径添加到环境变量PYTHONPATH中,该变量会自动加入sys.path属性。另一种便捷方法是在代码中直接指定module路径至sys.path:
import sys
sys.path.append('D:\\download')
from parent.child.a import add_func
print sys.path
print "Import add_func from module a" print"Result of 1 plus 2 is: " print add_func(1,2)
总结
本教程内容简明易懂。许多Python特性以隐含方式呈现,如无需显式声明数据类型、关键字说明及字符串函数解释等。熟练程序员应熟悉这些概念,以便在花费一小时阅读本教程后,通过已有知识迁移快速熟悉Python,并立即开始编程实践。
本文到此结束,希望能为读者提供帮助,欢迎继续关注本站更多内容!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









