看不懂简明python教程_简明python教程读书记录

@author : istory85

第九章 数据结构

1.字符串的方法

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 war'

delimiter = '_*_'

mylist = ['Brazil', 'Russia', 'Japan', 'China']

print delimiter.join(mylist)

第十章 编写一个python脚本

1. 备份脚本 版本4.0

import os

import time

source = ['/root/a.txt', '/root/b.txt']

target_dir = '/root/backup/'

today = target_dir + time.strftime('%Y%m%d')

now = time.strftime('%H%M%S')

comment = raw_input('Enter a comment --> ')

if len(comment)== 0:

target = today + os.sep + now + '.zip'

else:

target = today + os.sep + now + '_' + \

comment.replace(' ', '_') + '.zip'

if not os.path.exists(today):

os.mkdir(today)

print 'Successfully created directory', today

zip_command = "zip -qr '%s' %s" %(target, ' '.join(source))

if os.system(zip_command) == 0:

print 'Successful backup to', target

else:

print 'Backup Failed'

第十一章 面向对象的编程

1.定义一个简单的人 类

class Person:

def __init__(self, name):

self.name = name

def sayHi(self):

print 'Hello, my name is', self.name

p = Person('Swaroop')

p.sayHi()

2.测试一个类

class Person:

population = 0

def __init__(self, name):

self.name = name

print '(Initializing %s)' % self.name

Person.population += 1

def __del__(self):

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):

print 'Hi, my name is %s.' % self.name

def howMany(self):

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()

kalam.__del__()

kalam.howMany()

swaroop.__del__()

swaroop.howMany()

3.继承 ,由学校成员类继承出老师类和学生类

class SchoolMember:

def __init__(self, name, age):

self.name = name

self.age = age

print '(Initialized SchoolMemeber: %s)' % self.name

def tell(self):

print 'Name:"%s" Age:"%s"' % (self.name, self.age)

class Teacher(SchoolMember):

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):

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, 3000)

s = Student('Swaroop', 22, 75)

print #prints a blank line

members = [t, s]

for member in members:

member.tell()

第十二章 文件的输入,输出

1.一首简单小诗歌的打印

poem = '''\

Programing is fun

when the work is done

if you wanna makeyour work also fun:

use Python!

'''

f = file('poem.txt', 'w')

f.write(poem)

f.close()

f = file('poem.txt')

while True:

line = f.readline()

if len(line) == 0:

break

print line,

f.close()

2.储存器

import cPickle as p

shoplistfile = 'shoplist.data' #name

shoplist = ['apple', 'mango', 'carrot'] #thing

f = file(shoplistfile, 'w') #read

p.dump(shoplist, f) #store

f.close() #close

del shoplist #del thin

f = file(shoplistfile) #read

storedlist = p.load(f) #load and read

print storedlist #show

第十三章 异常

1.处理异常

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'

2.如何引发异常

class ShortInputException(Exception):

'''A user-defined exception class.'''

def __init__(self, length, atleast):

Exception.__init__(self)

self.length = length

self.atleast = atleast

try:

s = raw_input('Enter something --> ')

if len(s) < 3:

raise ShortInputException(len(s), 3)

except EOFError:

print '\nWhy did you do an EOF on me?'

except ShortInputException, x:

print 'ShortInputException: The input was of length %d, \

was expecting at least %d' % (x.length, x.atleast)

else:

print 'No exception was raised'

3.运行过程中手动中止,ctr-c,会发生键盘中断异常

import time

try:

f = file('poem.txt')

while True:

line = f.readline()

if len(line) == 0:

break

time.sleep(2)

print line,

finally:

f.close()

print 'Cleaning up...closed the file'

第十四章 python标准库

1.sys模块 -- 命令行参数

import sys

def readfile(filename):

'''Print a file to the standard output.'''

f = file(filename)

while True:

line = f.readline()

if len(line) == 0:

break

print line,

f.close()

if len(sys.argv) < 2:

print 'No action specified.'

sys.exit()

if sys.argv[1].startswith('--'):

option = sys.argv[1][2:]

if option == 'version':

print 'Version 1.2'

elif option == 'help':

print '''\

This program prints files to the standard output.

Any number of files can be specified.

Options include:

--version : Prints the version number

--help : Display this help'''

else:

print 'Unkown option.'

sys.exit()

else:

for filename in sys.argv[1:]:

readfile(filename)

2.os 模块

os.name --指示当前使用平台 对windows, 返回'nt',对于linux等,返回'posix'.

os.getcwd()得到当前工作目录 os.getenv()/putenv() 读取和设置环境变量

os.listdir()返回指定目录下的所有文件和目录名 os.remove()

os.system()运行shell脚本 os.sep取代了当前系统的路径分隔符

os.linesep给出当前平台的行终止符 os.path.split()返回一个路径的目录名和文件名

os.path.isfile()/isdir()判断给出的路径是一个文件还是一个目录

os.path.existe()检验给出的路径是否真实的存在

第十五章 更多python的内容

1.特殊的方法

__init__ __del__ __str__ __lt__

__getitem__ __len__

2.单语句块 / 列表综合

listone = [2, 3, 4,100]

listtwo = [2*i for i in listone if i > 2]

print listtwo

3.在函数中接受元组和列表,*前缀存储为一个元组,**前缀则存储为一个字典的键值对

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)

4.lambda 形式 lambda参数:表达式

def make_repeater(n):

return lambda s: s*n

twice = make_repeater(2)

print twice('word')

print twice(5)

5.exec和eval语句 exec来执行储存在字符串和文件中的python语句。

eval来计算存储在字符串中的有效python表达式

exec 'print "Hello World"'

print eval ('2*3')

6.assert语句 用来声明某个条件是真的

mylist = ['item']

assert len(mylist) >= 1

mylist.pop()

assert len(mylist) >= 1

7.repr函数,用来取得对象的规范字符串表示

i = []

i.append('item')

print `i`

print repr(i)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值