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 的文件.该文件内容可以为空.这个层次结构如下所示:
--__init_.py
--child
-- __init_.py
--a.py
b.py
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 学习笔记---基础篇的更多相关文章
- Python学习笔记基础篇——总览
Python初识与简介[开篇] Python学习笔记——基础篇[第一周]——变量与赋值.用户交互.条件判断.循环控制.数据类型.文本操作 Python学习笔记——基础篇[第二周]——解释器.字符串.列 ...
- Python学习笔记——基础篇【第一周】——变量与赋值、用户交互、条件判断、循环控制、数据类型、文本操作
目录 Python第一周笔记 1.学习Python目的 2.Python简史介绍 3.Python3特性 4.Hello World程序 5.变量与赋值 6.用户交互 7.条件判断与缩进 8.循环控制 ...
- Python学习笔记——基础篇【第七周】———类的静态方法 类方法及属性
新式类和经典类的区别 python2.7 新式类——广度优先 经典类——深度优先 python3.0 新式类——广度优先 经典类——广度优先 广度优先才是正常的思维,所以python 3.0中已经修复 ...
- Python学习笔记——基础篇【第四周】——迭代器&生成器、装饰器、递归、算法、正则表达式
目录 1.迭代器&生成器 2.装饰器 a.基本装饰器 b.多参数装饰器 3.递归 4.算法基础:二分查找.二维数组转换 5.正则表达式 6.常用模块学习 #作业:计算器开发 a.实现加减成熟及 ...
- Python学习笔记——基础篇【第六周】——面向对象
Python之路,Day6 - 面向对象学习 本节内容: 面向对象编程介绍 为什么要用面向对象进行开发? 面向对象的特性:封装.继承.多态 类.方法. 同时可参考链接: http:// ...
- Python学习笔记基础篇-(1)Python周边
一.系统命令 1.Ctrl+D 退出Python IDLE input方法中输入EOF字符,键入Ctrl+D 2.命令行选项: -d 提供调试输出 -O 生成优化的字节码(.pyo文件) -S 不 ...
- Python学习笔记——基础篇2【第三周】——计数器、有序字典、元组、单(双)向队列、深浅拷贝、函数、装饰器
目录 1.Python计数器Counter 2.Python有序字典OrderredDict 3.Python默认字典default 4.python可命名元组namedtuple 5.Python双 ...
- Python学习笔记——基础篇【第五周】——正在表达式(re.match与re.search的区别)
目录 1.正在表达式 2.正则表达式常用5种操作 3.正则表达式实例 4.re.match与re.search的区别 5.json 和 pickle 1.正则表达式 语法: import re # ...
- Python学习笔记——基础篇【第七周】———进程、线程、协程篇(socket基础)
http://www.cnblogs.com/wupeiqi/articles/5040823.htmlhttp://i.cnblogs.com/EditPosts.aspx?postid=55437 ...
随机推荐
- 静态属性@property
property 作用其实把类里面的逻辑给隐藏起来(封装逻辑,让用户调用的时候感知不到你的逻辑) property实例1:class Room: def __init__(self): pass @p ...
- java中定义的四种类加载器
1,Bootstrap ClassLoader 启动类加载器2,ExtClassLoader 扩展类加载器3,AppClassLoader 系统类加载器4,ClassLoader 类加 ...
- Excel和Word 简易工具类,JEasyPoi 2.1.7 版本发布
JEasyPOI 简介 EasyPOI 功能如同名字easy,追求的就是简易,让一个没接触过poi的人员,可以傻瓜化的快速实现Excel导入导出.Word模板导出,可以仅仅5行代码就可以完成Excel ...
- mingw 设置python 设置git环境变量
1.python路径设置: 安装python 比如目录:C:\Python27 假如mingw安装C盘根目录下的话,进入下面目录:C:\MinGW\msys\1.0\etc 找到 fstab 文件修改 ...
- ElasticSearch centos7 安装
参考: https://blog.csdn.net/u014180504/article/details/78733827 https://blog.csdn.net/youzhouliu/artic ...
- Tomcat虚拟目录设置
ssh $host "rm -fr /var/www/$tomcat_name/webapps/*" 远程分发war包部署tomcat项目时,需要先清除项目目录. -------- ...
- Spring事务管理——回滚(rollback-for)控制
探讨Spring事务控制中,异常触发事务回滚原理.文章进行了6种情况下的Spring事务是否回滚. 以下代码都是基于Spring与Mybatis整合,使用Spring声明式事务配置事务方法. 1.不捕 ...
- 217/219. Contains Duplicate /Contains Duplicate II
原文题目: 217. Contains Duplicate 219. Contains Duplicate II 读题: 217只要找出是否有重复值, 219找出重复值,且要判断两者索引之差是否小于k ...
- ArcGIS案例学习笔记4_2_水文分析批处理地理建模
ArcGIS案例学习笔记4_2_水文分析批处理地理建模 联系方式:谢老师,135_4855_4328,xiexiaokui#139.com 概述 计划时间:第4天下午 目的:自动化,批量化,批处理,提 ...
- ArcGIS案例学习笔记-CAD数据自动拓扑检查
ArcGIS案例学习笔记-CAD数据自动拓扑检查 联系方式:谢老师,135-4855-4328,xiexiaokui#qq.com 功能:针对CAD数据,自动进行拓扑检查 优点:类别:地理建模项目实例 ...