简明python教程笔记
自然字符串
如果你想要指示某些不需要如转义符那样的特别处理的字符串,那么你需要指定一个自然字符串。自然字符串通过给字符串加上前缀r或R来指定。
r"Newlines are indicated by \n"
在文件头加上linux下运行python的主程序模块和文件名
#!/usr/bin/python
#Filename:test.py
打印DocString(文档字符串)是个好习惯
#!/usr/bin/python
#Filename:test.py def printMax(x, y):
'''Prints the maximum of two numbers. The two values must be integers.'''
x = int(x) # convert to integers, if possible
y = int(y)
if x > y:
print x, 'is maximum'
else:
print y, 'is maximum' printMax(3, 5)
print printMax.__doc__
Result
主模块入口Sample
#!/usr/bin/python
# Filename: using_name.py
if __name__ == '__main__':
print 'This program is being run by itself'
else:
print 'I am being imported from another module'
构建自己的模块
mymodule
#!/usr/bin/python
# Filename: mymodule.py
def sayhi():
print 'Hi, this is mymodule speaking.'
version = '0.1'
# End of mymodule.py
import的主module
#!/usr/bin/python
# Filename: mymodule_demo.py
import mymodule
mymodule.sayhi()
print 'Version', mymodule.version
数据结构
列表,即Javascript中的数组,可以对它进行增删改查的操作
#!/usr/bin/python
# Filename: using_list.py # This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana'] print 'I have', len(shoplist),'items to purchase.' #length print 'These items are:', # Notice the comma at end of the line
for item in shoplist: #for-in circle
print item, print '\nI also have to buy rice.'
shoplist.append('rice') #append element
print 'My shopping list is now', shoplist print 'I will sort my list now'
shoplist.sort() #sort elements
print 'Sorted shopping list is', shoplist print 'The first item I will buy is', shoplist[0] #get element by index
olditem = shoplist[0]
del shoplist[0] #delete element
print 'I bought the', olditem
print 'My shopping list is now', shoplist
Result
元组,和列表类似,但是不能修改,即为不能修改的列表,用()包裹。
元组可以直接输出,定义中可以直接包含其他元组
类似于C++中的多维数组
#!/usr/bin/python
# Filename: using_tuple.py 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]
Result
元组一般用于打印
#!/usr/bin/python
# Filename: print_tuple.py age = 22
name = 'Swaroop'
print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python?' % name
字典,类似于Javascript里的Object,key/value键值对,Hash表
#!/usr/bin/python
#Filename:test.py #ab is short for 'a'ddress 'b'ook ab={
'Swaroop' : 'swaroopch@byteofpython.info',
'Larry' : 'larry@wall.org',
'Matsumoto' : 'matz@ruby-lang.org',
'Spammer' : 'spammer@hotmail.com'
} print "Swaroop's address is %s" % ab['Swaroop'] #Adding a key/value pair
ab['Guido'] = 'guido@python.org' #Deleting a key/value pair
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: #OR ab.has_key(Guido)
print "\nGuido's address is %s" %ab['Guido']
Result
列表、元组和字符串都是序列,但是序列是什么,它们为什么如此特别呢?序列的两个主要特点是索引操作符和切片操作符。索引操作符让我们可以从序列中抓取一个特定项目。切片操作符让我们能够获取序列的一个切片,即一部分序列。
#!/usr/bin/python
# Filename: seq.py shoplist = ['apple', 'mango', 'carrot', 'banana'] # Indexing or 'Subscription' operation
print 'Item 0 is', shoplist[0] #Item 0 is apple
print 'Item 1 is', shoplist[1] #Item 1 is mango
print 'Item 2 is', shoplist[2] #Item 2 is carrot
print 'Item 3 is', shoplist[3] #Item 3 is banana
print 'Item -1 is', shoplist[-1] #Item -1 is banana
print 'Item -2 is', shoplist[-2] #Item -2 is carrot # Slicing on a list
print 'Item 1 to 3 is', shoplist[1:3] #Item 1 to 3 is ['mango', 'carrot']
print 'Item 2 to end is', shoplist[2:] #Item 2 to end is ['carrot', 'banana']
print 'Item 1 to -1 is', shoplist[1:-1] #Item 1 to -1 is ['mango', 'carrot']
print 'Item start to end is', shoplist[:] #Item start to end is ['apple', 'mango', 'carrot', 'banana'] # Slicing on a string
name = 'swaroop'
print 'characters 1 to 3 is', name[1:3] #characters 1 to 3 is wa
print 'characters 2 to end is', name[2:] #characters 2 to end is aroop
print 'characters 1 to -1 is', name[1:-1] #characters 1 to -1 is waroo
print 'characters start to end is', name[:] #characters start to end is swaroop
Result
引用,类似于C++的指针,如果我们把一个列表赋值给一个新变量,实际是新变量指向列表的内存地址,如果我们把一个序列复制给一个新变量,这只是Copy操作。
#!/usr/bin/python
# Filename: reference.py print 'Simple Assignment'
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the same object!
del shoplist[0]
print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that both shoplist and mylist both print the same list without
# the 'apple' confirming that they point to the same object
print 'Copy by making a full slice' mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0] # remove first item
print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that now the two lists are different
Result
常用的字符串方法
#!/usr/bin/python
# Filename: str_methods.py name = 'Swaroop' # This is a string object
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脚本
设计思路
1. 需要备份的文件和目录由一个列表指定。
2. 备份应该保存在主备份目录中。
3. 文件备份成一个zip文件。
4. zip存档的名称是当前的日期和时间。
5. 我们使用标准的zip命令,它通常默认地随Linux/Unix发行版提供。Windows用户可以使用Info-Zip程序。注意你可以使用任何地存档命令,只要它有命令行界面就可以了,那样的话我们可以从我们的脚本中传递参数给它。
Code
#!/usr/bin/python
# Filename: backup_ver1.py import os
import time # 1. The files and directories to be backed up are specified in a list.
source = ['/home/swaroop/byte', '/home/swaroop/bin']
# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that # 2. The backup must be stored in a main backup directory
target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using # 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' # 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) # Run the backup
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'
面向对象
类与对象的方法
举个简单的例子就能看懂,书上的缩进写的一团糟,看起来有点类,手打一遍,发现Python真的很优雅!
#!/usr/bin/python
#Filename:test.py class Person:
'''Represents a person.'''
population = 0 def __init__(self,name):
'''Initializes the person'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 strill %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()
Result
继承
#!/usr/bin/python
#Filename:test.py 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 #prints a blank line members = [t,s]
for member in members:
member.tell() #works for both Teachers and Students
Result
输入输出
文件
你可以通过创建一个file类的对象来打开一个文件,分别使用file类的read、readline或write方法来恰当地读写文件。对文件的读写能力依赖于你在打开文件时指定的模式。最后当你完成对文件的操作的时候,你调用close方法来告诉Python我们完成了对文件的使用。
#!/usr/bin/python
#Filename:test.py poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
''' f = file('poem.txt','w') #open for 'w'rting
f.write(poem) #write text to file
f.close() #close the file f = file('poem.txt')
#if no mode is specified,'r'ead mode is assumed by default
while True:
line = f.readline()
if len(line) == 0:#Zero length indicates EOF
break
print line,
#Notice comma to avoid automatic newline added by Python f.close() #close the file
储存与取储存 dump()&load()
Python提供一个标准的模块,称为pickle。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为 持久地 储存对象。
还有另一个模块称为cPickle,它的功能和pickle模块完全相同,只不过它是用C语言编写的,因此要快得多(比pickle快1000倍)。你可以使用它们中的任一个,而我们在这里将使用cPickle模块。记住,我们把这两个模块都简称为pickle模块。
#!/usr/bin/python
#Filename:test.py import cPickle as p
#import pickle as p shoplistfile = 'shoplist.data'
# the name of the file where we will store the object shoplist = ['apple', 'mango', 'carrot'] # Write to the file
f = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a file
f.close() del shoplist # remove the shoplist # Read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist
异常
try...except的用法
#!/usr/bin/python
#Filename:test.py import sys try:
s = raw_input('Enter something --> ')
except EOFError:
print '\nWhy did you do an EOF on me?'
sys.exit() # exit the program
except:
print '\nSome error/exception occurred.'
# here, we are not exiting the program print 'Done'
http://pythonguidecn.readthedocs.org/zh/latest/
http://old.sebug.net/paper/books/LearnPythonTheHardWay/
简明python教程笔记的更多相关文章
- 《简明python教程》笔记一
读<简明Python教程>笔记: 本书的官方网站是www.byteofpython.info 安装就不说了,网上很多,这里就记录下我在安装时的问题,首先到python官网下载,选好安装路 ...
- 学习笔记《简明python教程》
学习笔记<简明python教程> 体会:言简意赅,很适合新手入门 2018年3月14日21:45:59 1.global 语句 在不使用 global 语句的情况下,不可能为一个定义于函数 ...
- 简明Python教程 ~ 随书笔记
本文是阅读<简明Python教程>所做的随书笔记,主要是记录一些自己不熟悉的用法,或者所看到的比较有意思的内容,本书英文版A Byte of Python, 中文译版 简明Python教程 ...
- 笔记|《简明Python教程》:编程小白的第一本python入门书
<简明Python教程>这本书是初级的Python入门教材,初级内容基本覆盖,对高级内容没有做深入纠结.适合刚接触Python的新手,行文比较简洁轻松,读起来也比较顺畅. 下面是我根据各个 ...
- 《简明Python教程》学习笔记
<简明Python教程>是网上比较好的一个Python入门级教程,尽管版本比较老旧,但是其中的基本讲解还是很有实力的. Ch2–安装Python:下载安装完成后,在系统的环境变量里,在Pa ...
- 简明Python教程自学笔记——命令行通讯录
[前言]学习Python已经有一段时间了,相关的书籍资料也下载了不少,但是没有一本完整的看完,也没有编出一个完整的程序.今天下午比较清闲就把<简明Python教程>看了一遍,然后根据书里面 ...
- python读书笔记-《简明python教程》上
1月15日 <简明python教程>上 基本结构: 基础概念+控制流+函数+模块+数据结构+面向对象+I/O+异常+标准库+其他 1.概念 1-0 退出python linux: ...
- (原+转)简明 Python 教程:总结
简明 Python 教程 说明:本文只是对<简明Python教程>的一个总结.请搜索该书查看真正的教程. 第3章 最初的步骤 1. Python是大小写敏感的. 2. 在#符号右面的内容 ...
- 【转】简明 Python 教程
原文网址:http://woodpecker.org.cn/abyteofpython_cn/chinese/ 简明 Python 教程Swaroop, C. H. 著沈洁元 译www.byteof ...
随机推荐
- grunt入门讲解2:如何使用 Gruntfile 配置任务
Grunt的task配置都是在 Gruntfile 中的grunt.initConfig方法中指定的.此配置主要包括以任务名称命名的属性,和其他任意数据.一旦这些代表任意数据的属性与任务所需要的属性相 ...
- T4模板_入门
T4模板作为VS自带的一套代码生成器,功能有多强大我也不知道,最近查找了一些资料学习一下,做个笔记 更详细的资料参见: MSDN: http://msdn.microsoft.com/zh-cn/li ...
- java、maven环境搭建
1.选择[新建系统变量]--弹出"新建系统变量"对话框,在"变量名"文本框输入"JAVA_HOME",在"变量值"文本框 ...
- python3.6执行AES加密及解密方法
python版本:3.6.2 首先安装pycryptodome cmd执行命令:pip install pycryptodome 特别简单,代码如下: #!/usr/bin/python # -*- ...
- vSphere Client 连接ESXi 或者是vCenter 时虚拟机提示VMRC异常的解决办法
1. 自己的vSphere 连接vCenter 向管理虚拟机 结果发现总是有异常. 提示如图示 VMRC控制台的连接已经断开 2. 花了比较长的时间也没搞定. 后来百度发现 关闭一个进程 然后重新登录 ...
- C# 窗体文件下的 MainForm.cs,MainForm.Designer.cs,MainForm.resx,是什么,干什么
Form.cs和Form.Designer.cs其实是一个类,Visual Studio为了让我们方便管理,用partial关键字把窗体类给拆开了, Form.Designer.cs存放的是窗体的布局 ...
- SQL中MAX()和MIN()函数的使用(比较字符串的大小)
在SQL数据库中,最大/最小值函数—MAX()/MIN()是经常要用到的,下面就将为您分别介绍MAX()函数和MIN()函数的使用,供您参考,希望对您学习SQL数据库能有些帮助. 当需要了解一列中的最 ...
- Logrotate还有谁记得它??
我发现很多人的服务器上都运行着一些诸如每天切分Nginx日志之类的CRON脚本,大家似乎遗忘了Logrotate,争相发明自己的轮子,这真是让人沮丧啊!就好比明明身边躺着现成的性感美女,大家却忙着自娱 ...
- Spring学习13-中IOC(工厂模式)和AOP(代理模式)的详细解释
我们是在使用Spring框架的过程中,其实就是为了使用IOC,依赖注入,和AOP,面向切面编程,这两个是Spring的灵魂. 主要用到的设计模式有工厂模式和代理模式. IOC是工厂模式参考:设计模式- ...
- 第214天:Angular 基础概念
一.Angular 简介 1. 什么是 AngularJS - 一款非常优秀的前端高级 JS 框架 - 最早由 Misko Hevery 等人创建 - 2009 年被 Google 公式收购,用于其多 ...