Python简明教程,此资源位于http://woodpecker.org.cn/abyteofpython_cn/chinese/ s=u'中文字符' #u表示unicode,使用u之后能正常显示中文 s='''多行文本 这是第二哈''' #'''表示多行注释。也可以用""" 布尔型:True,False docString:文档字符串。eg:

# Filename : nice.py
# encoding:utf8
def printMax(x, y):
u'''输出两个数字中大的一个。 两个数字的值必须是整数'''
x=int(x)
y=int(y) if x>y:
print x,'is maximum'
else:
print y,'is maximum' printMax(3,5)
print printMax.__doc__

会把中文注释都输出 python使用模块: ·sys模块:

# Filename : nice.py
# encoding:utf8
import sys
for i in sys.argv:
print i

或者,使用:

# Filename : nice.py
# encoding:utf8
from sys import argv
for i in argv:
print i

在vim中执行w之后, 执行!python % 123 sdfds 那么将输出123 sdfds(分两行输出) ·使用__main__模块:

# Filename : nice.py
# encoding:utf8
if __name__=='__main__':
print 'This program is being run by itself'
else:
print 'I am being imported from another module'

·使用自定义的模块

# Filename : nice.py
# encoding:utf8
import mymodule mymodule.sayhi()
print 'Version', mymodule.version
# Filename:mymodule.py
# encoding:utf8
def sayhi():
print 'Hi, this is my module.'
version = '0.1'

数据结构部分: 使用列表list:

# Filename : nice.py
# encoding:utf8
shoplist=['apple','mango', 'carrot', 'banana']
print 'I have', len(shoplist),'items to purchase.' print 'These items are:',
for item in shoplist:
print item, print '\nI alse have to buy rice.'
shoplist.append('rice')
print 'My shopping list is now', shoplist print 'I will sort my list now'
shoplist.sort()
print 'Sorted shopping list is', shoplist print 'The first item I will buy is', shoplist[0]
olditem=shoplist[0]
del shoplist[0]
print 'I bought the', olditem
print 'My shopping list is now', shoplist

·元组的使用:类似于数组,但是可以嵌套用

# Filename : nice.py
# encoding:utf8
zoo=('wolf','elephant','penguin')
print 'Number of animals in the zoo is', len(zoo) new_zoo=('monkey','dolphin',zoo)
print 'Number of animals in the new zoo is', len(new_zoo)
print 'All animals in new zoo are', new_zoo
print 'Animals brought from old zoo are', new_zoo[2]
print 'Last animal brought from old zoo is', new_zoo[2][2]

·使用元组输出(print语句中的参数输出哈哈)

# Filename : nice.py
# encoding:utf8
age=22
name='Swaroop' print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python' % name

·使用字典(好吧,我表示写过几个不太成功的http post请求的脚本之后,知道什么是字典了。。。)

# Filename : nice.py
# encoding:utf8
ab={'Swaroop':'swaroopch@byteofpyton.info',
'Larry':'larry@wall.org',
'Matsumoto':'matz@ruby-lang.org',
'Spammer':'spammer@hotmail.com'
}
print "Swaroop's address is %s" % ab['Swaroop'] ab['Guido']='guido@python.org'
del ab['Spammer']
print '\nThere are %d contacts in the address-book\n' % len(ab)
for name, address in ab.items():
print 'Contact %s at %s' % (name, address) if 'Guido' in ab:
print "\nGuido's address is %s" % ab['Guido']

·所谓的“索引与切片”,我认为只是玩弄下标的小把戏(包括数组,列表和字符串) ·对象与参考

# Filename : nice.py
# encoding:utf8
print 'Simple Assignment'
shoplist=['apple','mango', 'carrot', 'banana']
mylist=shoplist del shoplist[0] print 'shoplist is', shoplist
print 'mylist is', mylist print 'Copy by making a full slice'
mylist=shoplist[:]
del mylist[0] print 'shoplist is', shoplist
print 'mylist is', mylist

直接用=赋值,那么两个对象指向同一个存在。(两者是同一事物) 如果使用[:](这应该叫做切片了吧),那么两者为不通的对象 ·几个扩展的字符串方法:

# Filename : nice.py
# encoding:utf8
name ='Swaroop'
if name.startswith('Swa'):
print 'Yes, the string starts with "Swa"' if 'a' in name:
print 'Yes, it contains the string "a"' if name.find('war') != -1:
print 'Yes, it contains the string "war"' delimiter='_*_'
mylist=['Brazil','Russia','India','China']
print delimiter.join(mylist)

【面向对象】 谈python的面向对象了。python就是这么强大。 self关键字: 类的方法区别于普通函数之处:第一个参数一定是self(也可以换为别的关键字但是不建议)。 这个self作用是,当类的一个实例对象调用类的方法的时候,self指的是这个对象本身。 {我认为在类的方法的参数列表中写self没有必要,使用约定俗成的this其实更好} ·类的创建:

# Filename : nice.py
# encoding:utf8
class Person:
def sayHi(self):
print 'Hello, how are you?' p=Person()
p.sayHi()

·__init__方法:其实就是constructor

# Filename : nice.py
# encoding:utf8
class Person:
def __init__(self,name):
self.name=name
def sayHi(self):
print 'Hello, my name is', self.name p=Person("Chris")
p.sayHi()

·__del__方法:类似于destructor (不过下面这个例子的运行结果让人很晕,明明没有调用__del__,但结果表明它偷偷的执行了)

# Filename : nice.py
# encoding:utf8
class Person:
'''Represents a person.'''
population = 0 def __init__(self,name):
'''Initializes the preson's data.'''
self.name = name
print '(Initializing %s)'%self.name #When this person is created, he/she
#adds to the population
Person.population += 1 def __del__(self):
'''I am dying.'''
print '%s says bye.'%self.name
Person.population -= 1 if Person.population == 0:
print 'I am the last one.'
else:
print 'There are still %d people left.'%Person.population def sayHi(self):
'''Greeting by the person. Really, that's all it does.'''
print 'Hi, my name is %s.'%self.name def howMany(self):
'''Prints the current population.'''
if Person.population == 1:
print 'I am the only person here.'
else:
print 'We have %d persons here.'%Person.population swaroop=Person('Swaroop')
swaroop.sayHi()
swaroop.howMany() kalam=Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany() swaroop.sayHi()
swaroop.howMany()

·类继承的一个例子:

# Filename : nice.py
# encoding:utf8
class SchoolMember:
'''Represents any school member.'''
def __init__(self, name, age):
self.name=name
self.age=age
print '(Initialized SchoolMember: %s)'%self.name def tell(self):
'''Tell my details.'''
print 'Name:"%s" Age:"%s"'%(self.name,self.age), class Teacher(SchoolMember):
'''Represents a teacher.'''
def __init__(self,name,age, salary):
SchoolMember.__init__(self,name,age)
self.salary=salary
print '(Initialized Teacher: %s)'%self.name def tell(self):
SchoolMember.tell(self)
print 'Salary: "%d"'%self.salary class Student(SchoolMember):
'''Represents a student.'''
def __init__(self,name, age, marks):
SchoolMember.__init__(self,name, age)
self.marks=marks
print '(Initialized Student: %s)'%self.name def tell(self):
SchoolMember.tell(self)
print 'Marks: "%d"'%self.marks
t=Teacher('Mrs. Shrividya', 40, 30000)
s=Student('Swaroop', 22, 75) print #输出一个空白行 members=[t,s]
for member in members:
member.tell()

【Python中的逗号】 在循环输出一行字符串的时候使用逗号结尾,可以避免多输出空的换行 ·python的文件操作: f=file('file_name',mode) f.write(str) f.close() f.readline() 一个例子:

# Filename : nice.py
# encoding:utf8
poem='''\
Programming is fun
When the work is done
if you wanna make your work also fun
use Python!
''' f=file('poem.txt','w') #打开文件,写入形式
f.write(poem)
f.close() f=file('poem.txt')
#如果没有指定模式,默认使用read模式
while True:
line=f.readline()
if len(line)==0:#长度为0的行,意味着文件结束(EOF)
break
print line,
f.close()

·异常处理 一个EOFError的例子:

# Filename : nice.py
# encoding:utf8
import sys try:
s=raw_input('Enter something --> ')
except EOFError:
print '\nWhy did you do an EOF on me?'
sys.exit()
except:
print '\nSome error/exception occurred.' print 'Done'

·列表综合 一个简洁的列表:

# Filename : nice.py
# encoding:utf8 listone=[2,3,4]
listtwo=[2*i for i in listone if i>2]
print listtwo

函数接受不定个数参数的时候,使用* eg:

# Filename : nice.py
# encoding:utf8
def powersum(power, *args):
'''Return the sum of each argument raised to specified power.'''
total=0
for i in args:
total += pow(i, power)
return total
print powersum(2,3,4)
print powersum(2,10)

使用lambda

# Filename : nice.py
# encoding:utf8
def make_repeater(n):
return lambda s:s*n twice=make_repeater(2) print twice('word')
print twice(5)

exec:用来执行存储在字符串中的python表达式 eg:

# Filename : nice.py
# encoding:utf8
eval('print "Hello world"')

repr函数:用来取得对象的规范字符串表示。效果和反引号相同 eg

i=[]
i.append('item')
print `i`
print repr(i)

有一道题目这样描述: “创建一个类来表示一个人的信息。使用字典储存每个人的对象,把他们的名字作为键。 使用cPickle模块永久地把这些对象储存在你的硬盘上。使用字典内建的方法添加、 删除和修改人员信息。 一旦你完成了这个程序,你就可以说是一个Python程序员了。” 在网上找过了,基本上功能好实现(例如http://iris.is-programmer.com/2011/5/16/addressbook.26781.html) 但我想知道保存到硬盘的data文件中的内容(用pickle存储的),在user选择modify的时候,是否能够修改?and what about delete? I' m confuse about it, and many code version doesn't deal with the data file well. Once I re-run the python file, the stored data is empty, because 他们不从data文件中read数据! About GUI in Python: There are several tools we can use. They are: PyQt: works well in Linux. Not free in windows PyGTK: works well in Linux. wxPython:windows下可以用。免费。 TkInter:据说IDLE就是这个开发的 TkInter是标准Python发行版的一部分。在Linux和Windows下都可以用

【笔记】Python简明教程的更多相关文章

  1. 《Python简明教程》总结

    Python经典教程<Python简明教程> 目录: 为什么Python 安装Python 体验Python Python数据类型 运算符与表达式 控制流 函数 模块 数据结构 解决问题 ...

  2. python中global的用法——再读python简明教程

    今天看了知乎@萧井陌的编程入门指南,想重温一下 <python简明教程>,对global的用法一直不太熟练,在此熟练一下,并实践一下python中list.tuple.set作为参数的区别 ...

  3. python简明教程

    Python简明教程 MachinePlay关注 0.7072018.09.26 01:49:43字数 2,805阅读 9,287 Python一小时快速入门 1.Python简介   pylogo. ...

  4. Python 简明教程 --- 3,Python 基础概念

    微信公众号:码农充电站pro 个人主页:https://codeshellme.github.io 控制复杂性是计算机编程的本质. -- Brian Kernighan 了解了如何编写第一个Pytho ...

  5. Python 简明教程 --- 2,第一个Python 程序

    微信公众号:码农充电站pro 个人主页:https://codeshellme.github.io 如果你发现特殊情况太多,那你肯定是用错方法了. -- Carig Zerouni 当你在自己的电脑上 ...

  6. Python 简明教程 --- 1,搭建Python 环境

    微信公众号:码农充电站pro 个人主页:https://codeshellme.github.io 人生苦短,我用Python. -- 龟叔T恤 Python 是一门解释型语言,所以要想运行Pytho ...

  7. Python 简明教程 --- 18,Python 面向对象

    微信公众号:码农充电站pro 个人主页:https://codeshellme.github.io 代码能借用就借用. -- Tom Duff 目录 编程可分为面向过程编程和面向对象编程,它们是两种不 ...

  8. Python 简明教程 --- 13,Python 集合

    微信公众号:码农充电站pro 个人主页:https://codeshellme.github.io 如果代码和注释不一致,那很可能两者都错了. -- Norm Schryer 目录 前几节我们已经介绍 ...

  9. Python 简明教程 --- 14,Python 数据结构进阶

    微信公众号:码农充电站pro 个人主页:https://codeshellme.github.io 如果你发现特殊情况太多,那很可能是用错算法了. -- Carig Zerouni 目录 前几节我们介 ...

随机推荐

  1. Gym 101933

    Gym 101933 B. Baby Bites水题直接模拟即可 #include <cstdio> #include <cstring> #include <queue ...

  2. bzoj 3224

    3224: Tyvj 1728 普通平衡树 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 16656  Solved: 7255[Submit][St ...

  3. winscp以命令行方式同步服务器数据到PC机磁盘上

    目前服务器上每日会产生备份文件,需要使用winscp工具把备份同步到本地PC机硬盘上.平时都是图形界面用鼠标点击方式来同步的,效率低下,因此编写了winscp自动同步脚本,并加入到计划任务中定时自动运 ...

  4. Python【zip-map-filter】三个内置函数

    print("============内置函数:zip===========")l2 = ['a','b','c','e','f','g']l3 = [1,2,3]L4=['A', ...

  5. JAVA 线程池基本总结

    合理利用线程池能够带来三个好处. 第一:降低资源消耗.通过重复利用已创建的线程降低线程创建和销毁造成的消耗. 第二:提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立即执行. 第三:提高线程 ...

  6. Dubbo学习笔记1:使用Zookeeper搭建服务治理中心

    Zookeeper是Apache Hadoop的子项目,是一个树形的目录服务,支持变更推送,适合作为Dubbo服务的注册中心,工业强度较高,推荐生成环境使用. , 下面结合上图介绍Zookeeper在 ...

  7. http请求头和响应头详细解释

    想对http请求头和响应头有更细致的了解,请看如下 Requests部分 Header 解释 示例 Accept 指定客户端能够接收的内容类型 Accept: text/plain, text/htm ...

  8. 说说JavaScript中的事件模型

    1.javascript中为元素添加事件处理程序的方法有以下几种方式,可以为javascript元素添加事件处理程序 (1) 直接将事件处理代码写在html中(2) 定义一个函数,赋值给html元素的 ...

  9. JQuery的选择器对控件ID含有特殊字符的解决方法-涨姿势了!

    1.jquery类库在我们实际项目中用的很多,大家经常需要根据控件的id,获取对应的html元素. 但是:当id含有特殊字符的时候,是不能选中的. 2. 自己简单的测试了下,jquery的id选择器只 ...

  10. 微服务深入浅出(11)-- SpringBoot整合Docker

    添加Dockerfile 在目录src/main/resources目录下店家Dockerfile文件: From java MAINTAINER "Eric"<eric.l ...