简明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 ...
随机推荐
- 团队作业4 Alpha冲刺《嗨!你的快递》
仓库地址:https://git.coding.net/day_light/ourexpressmaster1.git 张新宇 1第一天日期:2018/6/13 1.1今日任务 进行核心功能数据匹 ...
- iOS开发面试题(中级)
//想面试的童鞋们来看看自己会多少, 老鸟可以无视直接绕过...1. Object-c的类可以多重继承么?可以实现多个接口么?Category是什么?重写一个类的方式用继承好还是分类好?为什么?与Ex ...
- Android之自定义View学习(一)
Android之自定义View学习(一) Canvas常用方法: 图片来源 /** * Created by SiberiaDante on 2017/6/3. */ public class Bas ...
- 深入浅析JavaScript的API设计原则(转载)
一.接口的流畅性 好的接口是流畅易懂的,他主要体现如下几个方面: 1.简单 操作某个元素的css属性,下面是原生的方法: ? 1 document.querySelectorAll('#id').st ...
- 利用css制作带边框的小三角
标签(空格分隔):css 在项目中会使用到的小实例,目前知道的有两种方法来实现 设置元素的宽和高,利用rotate实现,比较简单的一种 div{ width: 10px; height: 10px; ...
- python 安装pymssql
error: command 'gcc' failed with exit status 1 ---------------------------------------- Command &quo ...
- JDBC的基础接口及其用法
JDBC基础 所谓JDBC即是:Java DataBase Connectivity,java与数据库的连接.是一些用来执行SQL语句的Java API. 我们进行JDBC的编程,主要常用的几个概念: ...
- HUAS 2017暑假第六周比赛-题解
A.Parenthesis 括号匹配的问题有一种经典的做法. 将左括号看成1,右括号看成-1,做一遍前缀和sum. 括号序列是合法的当且仅当\(sum[n]=Min(sum[1],sum[2].... ...
- QPainter 基础绘图
调用QPainter的接口来绘制一些基本的图形 头文件: #include <QMainWindow> #include <QPainter> namespace Ui { c ...
- 回车”(carriage return)和”换行”(line feed)的区别和来历-(附:ASCII表)
这两天研究小票打印机编程手册,遇到这样一个问题: LF,即Line Feed,中文意思“换行”:CR,即Carriage Return,中文意思“回车”.但是我们通常把这两个混为一谈.既然设置 ...