Python 学习笔记---基础篇

1. 简单测试局域网中的电脑是否连通.这些电脑的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()

2. 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)

3. Python --- 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 # 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

4. Python的条件循环语句:

# 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)

5. Python 的函数定义:

# 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

#Defines multi argument return
def sub():
     a=1
     b=2
     return a,b

m,n=sub()
print("m=",m,"n=",n)
m=sub()[0]
n=sub()[1]
print("m=",m,"n=",n)

# The range() function
a =range(5,10)
print a

6. Python 文件基本处理:

#txt文件
spath="D:/download/aaa.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()

#word 文件
w = win32com.client.Dispatch('Word.Application')
# 后台运行,不显示,不警告
w.Visible = 0
w.DisplayAlerts = 0

# 打开新的文件
filenamein=""
filenameout=""
doc = w.Documents.Open(FileName=filenamein)
# 打印
doc.PrintOut()

# 关闭
# doc.Close()
w.Documents.Close(wc.wdDoNotSaveChanges)
w.Quit()

7. Python 异常处理:

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!"

8. Python 类和继承:

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)

9. Python 包机制

每一个.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"

module可以定义在包里面.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面试经典:

https://github.com/taizilongxu/interview_python

https://github.com/imhuay/Algorithm_Interview_Notes-Chinese

总结

你会发现这个教程相当的简单.许多Python特性在代码中以隐含方式提出,这些特性包括:Python不需要显式声明数据类型,关键字说明,字符串函数的解释等等.需要长期锻炼.Python学习了Java的长处,提供了大量极方便易用的标准库供程序员"拿来主义".(这也是Python成功的原因).

  

  

  

 

上一篇:Python学习笔记——基础篇【第六周】——hashlib模块


下一篇:ubuntu16.04安装mrpt