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

  1. # Filename : nice.py
  2. # encoding:utf8
  3. def printMax(x, y):
  4. u'''输出两个数字中大的一个。
  5.  
  6. 两个数字的值必须是整数'''
  7. x=int(x)
  8. y=int(y)
  9.  
  10. if x>y:
  11. print x,'is maximum'
  12. else:
  13. print y,'is maximum'
  14.  
  15. printMax(3,5)
  16. print printMax.__doc__

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

  1. # Filename : nice.py
  2. # encoding:utf8
  3. import sys
  4. for i in sys.argv:
  5. print i

或者,使用:

  1. # Filename : nice.py
  2. # encoding:utf8
  3. from sys import argv
  4. for i in argv:
  5. print i

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

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

·使用自定义的模块

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

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

  1. # Filename : nice.py
  2. # encoding:utf8
  3. shoplist=['apple','mango', 'carrot', 'banana']
  4. print 'I have', len(shoplist),'items to purchase.'
  5.  
  6. print 'These items are:',
  7. for item in shoplist:
  8. print item,
  9.  
  10. print '\nI alse have to buy rice.'
  11. shoplist.append('rice')
  12. print 'My shopping list is now', shoplist
  13.  
  14. print 'I will sort my list now'
  15. shoplist.sort()
  16. print 'Sorted shopping list is', shoplist
  17.  
  18. print 'The first item I will buy is', shoplist[0]
  19. olditem=shoplist[0]
  20. del shoplist[0]
  21. print 'I bought the', olditem
  22. print 'My shopping list is now', shoplist

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

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

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

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

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

  1. # Filename : nice.py
  2. # encoding:utf8
  3. ab={'Swaroop':'swaroopch@byteofpyton.info',
  4. 'Larry':'larry@wall.org',
  5. 'Matsumoto':'matz@ruby-lang.org',
  6. 'Spammer':'spammer@hotmail.com'
  7. }
  8. print "Swaroop's address is %s" % ab['Swaroop']
  9.  
  10. ab['Guido']='guido@python.org'
  11. del ab['Spammer']
  12. print '\nThere are %d contacts in the address-book\n' % len(ab)
  13. for name, address in ab.items():
  14. print 'Contact %s at %s' % (name, address)
  15.  
  16. if 'Guido' in ab:
  17. print "\nGuido's address is %s" % ab['Guido']

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

  1. # Filename : nice.py
  2. # encoding:utf8
  3. print 'Simple Assignment'
  4. shoplist=['apple','mango', 'carrot', 'banana']
  5. mylist=shoplist
  6.  
  7. del shoplist[0]
  8.  
  9. print 'shoplist is', shoplist
  10. print 'mylist is', mylist
  11.  
  12. print 'Copy by making a full slice'
  13. mylist=shoplist[:]
  14. del mylist[0]
  15.  
  16. print 'shoplist is', shoplist
  17. print 'mylist is', mylist

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

  1. # Filename : nice.py
  2. # encoding:utf8
  3. name ='Swaroop'
  4. if name.startswith('Swa'):
  5. print 'Yes, the string starts with "Swa"'
  6.  
  7. if 'a' in name:
  8. print 'Yes, it contains the string "a"'
  9.  
  10. if name.find('war') != -1:
  11. print 'Yes, it contains the string "war"'
  12.  
  13. delimiter='_*_'
  14. mylist=['Brazil','Russia','India','China']
  15. print delimiter.join(mylist)

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

  1. # Filename : nice.py
  2. # encoding:utf8
  3. class Person:
  4. def sayHi(self):
  5. print 'Hello, how are you?'
  6.  
  7. p=Person()
  8. p.sayHi()

·__init__方法:其实就是constructor

  1. # Filename : nice.py
  2. # encoding:utf8
  3. class Person:
  4. def __init__(self,name):
  5. self.name=name
  6. def sayHi(self):
  7. print 'Hello, my name is', self.name
  8.  
  9. p=Person("Chris")
  10. p.sayHi()

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

  1. # Filename : nice.py
  2. # encoding:utf8
  3. class Person:
  4. '''Represents a person.'''
  5. population = 0
  6.  
  7. def __init__(self,name):
  8. '''Initializes the preson's data.'''
  9. self.name = name
  10. print '(Initializing %s)'%self.name
  11.  
  12. #When this person is created, he/she
  13. #adds to the population
  14. Person.population += 1
  15.  
  16. def __del__(self):
  17. '''I am dying.'''
  18. print '%s says bye.'%self.name
  19. Person.population -= 1
  20.  
  21. if Person.population == 0:
  22. print 'I am the last one.'
  23. else:
  24. print 'There are still %d people left.'%Person.population
  25.  
  26. def sayHi(self):
  27. '''Greeting by the person.
  28.  
  29. Really, that's all it does.'''
  30. print 'Hi, my name is %s.'%self.name
  31.  
  32. def howMany(self):
  33. '''Prints the current population.'''
  34. if Person.population == 1:
  35. print 'I am the only person here.'
  36. else:
  37. print 'We have %d persons here.'%Person.population
  38.  
  39. swaroop=Person('Swaroop')
  40. swaroop.sayHi()
  41. swaroop.howMany()
  42.  
  43. kalam=Person('Abdul Kalam')
  44. kalam.sayHi()
  45. kalam.howMany()
  46.  
  47. swaroop.sayHi()
  48. swaroop.howMany()

·类继承的一个例子:

  1. # Filename : nice.py
  2. # encoding:utf8
  3. class SchoolMember:
  4. '''Represents any school member.'''
  5. def __init__(self, name, age):
  6. self.name=name
  7. self.age=age
  8. print '(Initialized SchoolMember: %s)'%self.name
  9.  
  10. def tell(self):
  11. '''Tell my details.'''
  12. print 'Name:"%s" Age:"%s"'%(self.name,self.age),
  13.  
  14. class Teacher(SchoolMember):
  15. '''Represents a teacher.'''
  16. def __init__(self,name,age, salary):
  17. SchoolMember.__init__(self,name,age)
  18. self.salary=salary
  19. print '(Initialized Teacher: %s)'%self.name
  20.  
  21. def tell(self):
  22. SchoolMember.tell(self)
  23. print 'Salary: "%d"'%self.salary
  24.  
  25. class Student(SchoolMember):
  26. '''Represents a student.'''
  27. def __init__(self,name, age, marks):
  28. SchoolMember.__init__(self,name, age)
  29. self.marks=marks
  30. print '(Initialized Student: %s)'%self.name
  31.  
  32. def tell(self):
  33. SchoolMember.tell(self)
  34. print 'Marks: "%d"'%self.marks
  35. t=Teacher('Mrs. Shrividya', 40, 30000)
  36. s=Student('Swaroop', 22, 75)
  37.  
  38. print #输出一个空白行
  39.  
  40. members=[t,s]
  41. for member in members:
  42. member.tell()

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

  1. # Filename : nice.py
  2. # encoding:utf8
  3. poem='''\
  4. Programming is fun
  5. When the work is done
  6. if you wanna make your work also fun
  7. use Python!
  8. '''
  9.  
  10. f=file('poem.txt','w') #打开文件,写入形式
  11. f.write(poem)
  12. f.close()
  13.  
  14. f=file('poem.txt')
  15. #如果没有指定模式,默认使用read模式
  16. while True:
  17. line=f.readline()
  18. if len(line)==0:#长度为0的行,意味着文件结束(EOF)
  19. break
  20. print line,
  21. f.close()

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

  1. # Filename : nice.py
  2. # encoding:utf8
  3. import sys
  4.  
  5. try:
  6. s=raw_input('Enter something --> ')
  7. except EOFError:
  8. print '\nWhy did you do an EOF on me?'
  9. sys.exit()
  10. except:
  11. print '\nSome error/exception occurred.'
  12.  
  13. print 'Done'

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

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

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

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

使用lambda

  1. # Filename : nice.py
  2. # encoding:utf8
  3. def make_repeater(n):
  4. return lambda s:s*n
  5.  
  6. twice=make_repeater(2)
  7.  
  8. print twice('word')
  9. print twice(5)

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

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

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

  1. i=[]
  2. i.append('item')
  3. print `i`
  4. 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. C中有关引用和指针的异同

    参考于https://blog.csdn.net/wtzdedaima/article/details/78377201 C语言也学了蛮久的,其实一直都没有用到过或者碰到过引用的例子.前端时间再全面复 ...

  2. python学习(23)requests库爬取猫眼电影排行信息

    本文介绍如何结合前面讲解的基本知识,采用requests,正则表达式,cookies结合起来,做一次实战,抓取猫眼电影排名信息. 用requests写一个基本的爬虫 排行信息大致如下图 网址链接为ht ...

  3. .Net并行编程系列之三:创建带时间限制(Timeout)的异步任务并取得异步任务的结果

    尝试创建基于MVVM三层架构的异步任务: 场景:View层触发ViewModel层的动作请求,ViewModel层异步的从Model层查询数据,当数据返回或者请求超时时正确更新ViewModel层数据 ...

  4. string 中的一些优化事项

    1.1 fmt  vs  "+" (无转义) import ( "testing" "fmt" ) var ( str = "he ...

  5. python2(中文编码问题):UnicodeDecodeError: 'ascii' codec can't decode byte 0x?? in position 1

    python在安装时,默认的编码是ascii,当程序中出现非ascii编码时,python的处理常常会报这样的错UnicodeDecodeError: 'ascii' codec can't deco ...

  6. CF&&CC百套计划2 CodeChef December Challenge 2017 Total Diamonds

    https://www.codechef.com/DEC17/problems/VK18 #include<cstdio> #include<iostream> #includ ...

  7. vscode nodejs智能提示功能

    1.依赖一些第三方的插件,先安装typings这个包,如果使用的是淘宝镜像,输入cnpm.cmd执行: cnpm i typings -g //cnpm install typings -global ...

  8. [转载]8 种提升 ASP.NET Web API 性能的方法

    http://www.oschina.net/translate/8-ways-improve-asp-net-web-api-performance 英文原文:8 ways to improve A ...

  9. 希尔密码(Hill Cipher)的实现

    原理应该不用多讲了,自己百度就可以. C++实现: #include <iostream> #include <string> #include <memory.h> ...

  10. 解析html和采集网页的神兵利器

    HtmlAgilityPack是一个基于.Net的.第三方免费开源的微型类库,主要用于在服务器端解析html文档(在B/S结构的程序中客户端可以用Javascript解析html).截止到本文发表时, ...