Python的世界

可爱的Python——足够简单问题的解决之道


假设我们有这么一项任务:简单测试局域网中的电脑是否连通.这些电脑的ip范围从192.168.0.101到192.168.0.200.
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()

1、搭建开发环境

linux:    

1、安装开发环境

sudoapt-getinstallopenjdk-6-jdk
sudoapt-getinstalleclipse
python一般Linux自带

在eclipase中,InstallNewSoftware 
这是地址:Location:http://pydev.org/updates(PyDev的更新地址)

选择PyDev下的PyDevforEclipse,其他的不选
安装之后重启eclipse

2、 配置PyDev插件
 
PyDev->Interpreter-Python,New一个Python解释器,填上解释器名字和路径,路径选相应的python.exe。
 File->New->Project,选PyDev下的PyDevProject,Grammer和Interpreter选相应的版本,Finish。
 
windows:

1、下载工具jthon(http://wiki.python.org/jython/DownloadInstructions),下载后双击执行该jar包.   第一步时选择所有,包括所有源. 

2、在DOS命令窗口执行批处理。 
cmd进入命令行状态。到安装目录c:/jthon2.5.5/执行jython.bat。 

3、在eclipse中安装jthon插件 
在help->softupdate->add sites 输入:windowhttp://pydev.sourceforge.net/updates/ 下载完后。选中这些下载选项。后点直接安装

4、配置jython. 
在window-->属性->pydev->interpreter-jython->new->浏览你安装jthon的目录(c://jython2.5.5.)指向jython.jar.点击应用。然后点击ok. 


2、Hello Python

print "Hello Python"
Python就是如此神奇

3、国际化的语言支持

# -*- coding: GBK -*- 
print "欢迎来的Python的世界!" # 使用中文
raw_input("Press enter key to close this window");
可以这样设置语言的支持

4、方便易用的计算器

a=100.0
b=201.1
c=2343
print (a+b+c)/c
python就是计算器?

5 、字符串

打印出预定义输出格式的字符串:
print """
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
Python怎么访问字符串呢?
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);



6 、列表 

word=['a','b','c','d','e','f','g']
a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: "
print b # index 1 and 2 elements of word.
c=word[:2]
print "c is: "
print c # index 0 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 # 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 word

Python有着简易方便的数据类型

7、条件和循环语句

# 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 in a:
print x, len(x)

Python是艺术家!

8、函数

# 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

Python竟然拥有如此完美的身材

9、文件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 for reading

for line in f:
print line

f.close()

处理文件是不是很简单?

10、异常处理
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!"

Python这样来解决异常

11、类和继承
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)

Pyhon最可爱的面向对象语言

12、包机制

每一个.py文件称为一个module,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"

带有文件层级结构的导包
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)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值