Python---A Byte of Python

#coding=utf-8 
#Be aware '#coding=utf-8' must inputin 1st line for CN language 
#https://docs.python.org/2/index.html   #python说明文档 
#基本概念 
print('Hello World')   #(#)于添加备注 
print('What\'s your name?') 
#\表示转意符,也可以表示字符串在下一行继续 
#以下两行结果是一样的 
print("This is the first sentence.\ 
    This is the second sentence.") 
print("This is the first sentence. This is the second sentence") 
#变量和字面意义上的常量 
#在python中,不需要定义数据类型;只需赋值 
i=5                           #Assign i 
print (i) 
i=i+1                         #Var change 
print (i)                      #Show 
s='''This is a multi-line string. 
This is the second line.'''             #Assign s 
print (s) 
#逻辑行->;与物理行->\ 
i=5;print (i)                        #一个物理行,多个逻辑行 
s='This is a string.\ 
This continues the string.'         #多个物理行,一个逻辑行 
print (s) 
#Chapter5 运算符和表达式 
#http://www.runoob.com/python/python-operators.html 
#Python算术运算符 
#+ 加 两个对象相加3 + 5得到8.'a' + 'b'得到'ab' 
print (3+5) 
print ('a'+'b') 
# - 减 得到负数或是一个数减去另一个数 
print (-5.2) 
print (50-24) 
# * 乘 两个数相乘或是返回一个被重复若干次的字符串 
print (2*3) 
print ('la'*3) 
# ** 幂 返回x的y次幂 
print (3**4) 
# / 除 x除以y 4/3得到1(整数的除法得到整数结果) 
print (4/3) 
print (4.0/3.0)          #浮点数 
# // 取整除 返回商的整数部分 
print (4//3) 
print (9.0//2.0) 
# % 取模返回除法的余数8 
print (8%3) 
print (-25.5%2.25) 
#Python比较运算符 
# == 等于比较对象是否相等 
x=2;y=2 
print (x==y)          #TRUE 
x='str';y='stR' 
print (x==y)          #FALSE 
y='str' 
print (x==y)          #TRUE 
# != 不等于比较两个对象是否不相等 
x=2;y=3 
print (x!=y)         #TRUE 
#<> 不等于比较两个对象是否不相等(类似!=) 
# > 大于返回x是否大于y 
# 如果两个操作数都是数字,它们首先被转换为一个共同的类型。否则,它总是返回False。 
print (5>3) 
print (5>'str') 
# < 小于返回x是否小于y。 
# 所有比较运算符返回1表示真,返回0表示假;这分别与特殊的变量True和False等价。 
print (5<3) 
print (5>3) 
print (3<5<7) 
# >= 大于等于返回x是否大于等于y 
print (4>=3) 
# <= 大于等于返回x是否小于等于y 
print (4<=3) 
#Python逻辑运算符 
# and 布尔“与” 
# or  布尔“或” 
# not 布尔“非” 
# 短路计算:x=False;y=True;x and y;Python不会计算y,因为它知道这个表达式的值肯定是False 
x=True;y=True 
print (x and y)                   #True 
print (x or y)                    #True 
print (not (x and y))            #False 
print (not (x or y))             #False 
x=True;y=False 
print (x and y)                  #False 
print (x or y)                   #True 
print (not (x and y))           #True 
print (not (x or y))            #False 
x=False;y=True 
print (x and y)                 #False 
print( x or y )                 #True 
print (not (x and y))          #True 
print (not (x or y))           #False 
x=False;y=False 
print (x and y  )              #False 
print (x or y )                #False 
print (not (x and y))         #True 
print (not (x or y))          #True 
#Python赋值运算符 
# = 简单的赋值 
x=10;y=20 
print (x) 
print (y) 
# += 加法赋值 y+=x -> y=y+x 
y+=x 
print (y) 
# -= 减法赋值 y-=x -> y=y-x 
y-=x 
print (y) 
# *= 减法赋值 y*=x -> y=y*x 
y*=x 
print (y) 
# /= 除法赋值 y/=x -> y=y/x 
y/=x 
print (y) 
# /%= 取模赋值 y%=x -> y=y%x 
y%=x 
print (y) 
# **= 幂赋值 y**=x -> y=y**x 
y=2 
y**=x 
print (y) 
# //= 取整并问题赋值 y//=x -> y=y//x 
y//=x 
print (y) 
#Python位运算符 
#按位运算符是把数字看作二进制来进行计算 
a=60                                #60=0011 1100 
b=13                                #30=0000 1101 
#& 按位与运算符:参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0 
print (a&b)                          #12=0000 1100 
# | 按位或运算符:只要对应的二个二进位有一个为1时,结果位就为1 
print (a|b)                          #61=0011 1101 
# ^ 按位异或运算符:当两对应的二进位相异时,结果为1 
print (a^b)                          #49=0011 0001 
# ~ 按位取反运算符:对数据的每个二进制位取反,即把1变为0,把0变为1 
print (~a)                           #-61=1100 0011 
# << 左移动运算符:运算数的各二进位全部左移若干位,由"<<"右边的数指定移动的位数,高位丢弃,低位补0 
print (a<<2)                         #240=1111 0000 
# >> 右移动运算符:把">>"左边的运算数的各二进位全部右移若干位,">>"右边的数指定移动的位数 
print (a>>2)                        #15=0000 1111 
#Python成员运算符 
#Python还支持成员运算符,包括字符串,列表或元组 
# in 如果在指定的序列中找到值返回True,否则返回False 
# not in 如果在指定的序列中没有找到值返回True,否则返回False 
a=2;b=20 
list=[1,2,3,4,5] 
print (a in list)                 #True 
print (b in list)                 #False 
print (a not in list)             #False 
print (b not in list)             #True 
#Python身份运算符 
#身份运算符用于比较两个对象的存储单元 
# is 是判断两个标识符是不是引用自一个对象 
# is not是判断两个标识符是不是引用自不同对象 
# ==比较操作符:用来比较两个对象是否相等,value做为判断因素 
# is同一性运算符:比较判断两个对象是否相同,id做为判断因素 
x=y=[4,5,6]                 #Assign 
z=[4,5,6]                   #Assign 
print (x==y)                        #True 
print (x==z)                        #True 
print (x is y)                      #True 
print (x is z)                      #False 
print (id(x))                       #x ID 
print (id(z))                       #z ID 
print (x is not y)                     #False 
print (x is not z)                     #True 
#/Chapter6 控制流 if for while 
#if语句 
#if语句用来检验一个条件,如果条件为真运行语句if块,否则处理else块(可选) 
#if语句结尾处含一个:,语句块需要正确缩进 
#简单猜数字 
number=23           #需猜测的数字 
guess=int(input('Enter an integer:')) 
if guess==number:                   #相等 
    print ('You guessed it') 
elif guess<number:                  #小于 
    print ('It is a higher than that') 
else:                               #大于 
    print ('It is a little lower than that') 
print ('Done') 
#while语句 
# 只要一个条件为真的情况下,while语句重复执行一块语句 
# while语句有一个可选的else从句 
number=23           #需猜测的数字 
running=True        #Assign 
while running: 
    guess=int(input('Enter an integer:')) 
    if guess==number:                   #相等 
        print ('You guessed it') 
        running=False                   #Exit Loop 
    elif guess<number:                  #小于 
        print ('It is a higher than that') 
    else:                               #大于 
        print ('It is a little lower than that') 
else: 
    print ('The while loop is over') 
print ('Done') 
#for循环 
# for..in是另外一个循环语句,它在一序列的对象上递归/逐一使用队列中的每个项目 
#range返回一个序列的数,向上延伸到第二个参数(不包含第二个参数),第三个参数为步长 
for i in range(1,13,2): 
    print (i) 
else: 
    print ('The for loop is over') 
# break语句 
# break语句用来终止循环语句的,哪怕循环条件没有称为False或序列还没有被完全递归,也停止执行循环语句 
#如果你从for或while循环中终止,任何对应的循环else块将不执行 
while True: 
    s=input('Enter something:') 
    if s=='quit':             #出口=输入quit 
        break                 #退出while 
    print ('Length of the string is',len(s))    #输入字符长度 
print ('Done') 
# continue语句 
#continue语句用来跳过当前循环块中的剩余语句,然后继续进行下一轮循环 
while True: 
    s=input('Enter something:') 
    l=len(s) 
    if s=='quit':           #出口 
       break                #退出while 
    if l==4: 
       print ('Input is of sufficient length') 
       continue             #返回至while 
    print ('Input is out of sufficient length') 
print ('Done') 
#Chapter7 函数 
#函数通过def关键字定义,函数名称+()+: 
def sayHello():                   #定义函数 
    print ('Hellow World!')       #函数代码 
sayHello()                         #call function 
def printMax(a,b): 
    if a>b: 
        print (a,'is maximum') 
    else: 
        print (b,'is maximum') 
printMax(3,4)             #directly give literal values 
x=5 
y=7 
printMax(x,y)            #give variables as arguments 
#使用局部变量 
def func_local(x):                #此处x是参数 
    print ('x is',x)         #显示输入参数 
    x=2                     #重新赋值x 
    print ('Changed local x to',x)        #显示新x 
x=50                        #初始化参数 
func_local(x)                     #call function 
print ('x is still',x)      #输出x,这里x!=2因为x是局部变量 
#使用全局变量global 
#可以声明多个全局变量global x,y,z 
def func_global(): 
    global x                #声明全局变量x 
    print ('x is',x)         #显示输入参数 
    x=2                     #重新赋值x 
    print ('Changed local x to',x) 
x=50                        #初始化参数 
func_global()               #call function 
print ('Value of x is',x)     #输出x,这里x=2因为x是全局变量 
#默认参数值argument 
#参数根据位置 
def func_default(message,times=1):       #times=1是默认参数 
    print (message*times)             #函数代码 
func_default('Hello')           #funciton with default 
func_default('World',5)         #funciton with input arrgument 
#关键参数 
#参数根据关键字(name)决定 
def func_key(a,b=5,c=10):       #=后面是默认值 
    print ('a is',a,' And b is',b,' And c is',c) 
func_key(3,7) 
func_key(25,c=24) 
func_key(c=50,a=100) 
# return语句 
# return语句用来从一个函数返回值或跳出函数 
def func_return(x,y): 
    if x>y: 
        return x        #返回x 
    else: 
        return y        #返回y 
print (func_return(2,3))    #test the funciton 
#something import 
#没有返回值的return语句等价于return None 
#None是Python中表示没有任何东西的特殊类型例,一个变量的值为None,可以表示它没有值 
def someFunction(): 
    pass            #pass语句在Python中表示一个空的语句块 
#DocStrings文档字符串 
# DocStrings是一个重要的工具,由于它帮助你的程序文档更加简单易懂,你应该尽量使用它。 
# 你甚至可以在程序运行的时候,从函数恢复文档字符串 
def func_doc(x,y): 
    #文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾 
    #第二行是空行,从第三行开始是详细的描述 
    '''Prints the maximum of two numbers. 
 
    The two values must be integers.''' 
    x=int(x)    #covert to integers, if possibel 
    y=int(y) 
    if x>y: 
        print (x,'is maximum') 
    else: 
        print (y,'is maximum') 
func_doc(3,5) 
print (func_doc.__doc__)          #注意双_ 
#Chapter8 模块 
#使用sys模块 
import sys          #引入sys模块;sys包含了与Python解释器和它的环境有关的函数 
print ('The command line arguments are:') 
for i in sys.argv: 
    print (i) 
print ('\n\nThe PYTHONPATH is',sys.path,'\n') 
# from..import语句 
from sys import argv 
temp=argv[0] 
for i in temp: 
    print (i) 
#模块的__name__ 
# import using_name     #注意此处不用.py后缀 
#制造你自己的模块 
import mymodule        #引用mymodule 
mymodule.sayhi()        #执行sayhi 
print ('Version',mymodule.version)    #打印version 
# 也可以用from...import来执行 
from mymodule import sayhi,version 
sayhi() 
print ('Version',version) 
# dir()函数 
import sys 
# print dir(sys)       #get list of attributes for sys module 
print (dir())         #返回当前模块的属性列表 
a=5                    #创建一个新的变量 
print (dir())         #a会被显示出来 
del a                 #remove a name 
print (dir())         #a移除 
#Chapter8 数据结构 
#Python中有三种内建的数据结构——列表、元组和字典 
#列表list 
#mylist.append('an item')           #在列表尾添加一个项目 
shoplist=['apple','mango','carrot','banana']   #定义list 
print ('I have',len(shoplist),'items to purchase.') 
print ('These items are:',)        # Notice the comma at end of the line 
print ('These items are:',)        # Notice the comma at end of the line 
for item in shoplist: 
    print (item,)     #在print语句的结尾使用了逗号来消除的换行符 
print ('\nI also have to buy rice.')     #\n是换行符 
shoplist.append('rice')    #在list尾增加rice 
print ('My shopping list is now',shoplist) 
print ('I will sort my list now') 
shoplist.sort()                    #list排序a-z 
print (shoplist[1:3])             #部分List 
print ('Sorted shopping list is',shoplist) 
print ('The first item I will buy is',shoplist[0]) 
olditem=shoplist[0]                #将1st赋值给olditem 
del shoplist[0]                   #把1st从shoplist中移除 
print ('I bought the',olditem) 
print ('My shopping list is now',shoplist) 
#使用元组tuple 
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 bought from old zoo are',new_zoo[2]) 
print ('Last animals brought from old zoo is', new_zoo[2][2]) 
#元组最常用是在打印语句中 
age=22 
name='swaroop' 
print ('%s is %d years old'%(name,age))    #%s->字符串;%d->整数 
print ('%s is %s years old'%(name,age))    #也可以都转成%s字符串 
#字典 d={key1:value1,key2:value2,...} 
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']) 
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():         #将ab.items()的值循环并赋值 
    print ('Contact %s at %s' %(name,address)) 
if 'Guido' in ab:       #也可以写成 
# if ab.has_key('Guido') 
    print ("\nGuido's address is %s" %ab['Guido']) 
#序列Sequence 
shoplist=['apple','mango','carrot','banana']   #定义Seq 
# Indexing or 'Subscription' operation 
print ('Item 0 is',shoplist[0]) 
print ('Item 2 is',shoplist[2]) 
print ('Item -1 is',shoplist[-1]) 
print ('Item -2 is',shoplist[-2]) 
# Slicing on a list,seq[I,J] not including J 
print ('Item 1 to 3 is', shoplist[1:3]) 
print ('Item 2 to end is', shoplist[2:])        #从2至最后 
print ('Item 1 to -1 is', shoplist[1:-1]) 
print ('Item start to end is', shoplist[:])     #All Sequence 
# Slicing on a string 
name = 'swaroop' 
print ('characters 1 to 3 is', name[1:3]) 
print ('characters 2 to end is', name[2:])     #从2至最后 
print ('characters 1 to -1 is', name[1:-1]) 
print ('characters start to end is', name[:])     #All Sequence 
# 引用 
print ('Simple Assignment') 
shoplist = ['apple', 'mango', 'carrot', 'banana'] 
mylist_1 = shoplist # mylist is just another name pointing to the same object! 
mylist_2 = shoplist[:] # make a copy by doing a full slice 
print (id(shoplist)) 
print (id(mylist_1)) 
print (id(mylist_2)) 
del shoplist[0]               #Delete 1st elelment 
print ('shoplist is', shoplist) 
print ('mylist_1 is', mylist_1) 
print ('mylist_2 is', mylist_2) 
#notice that now the two lists are different 
#字符串 
name = 'Swaroop' # This is a string object 
if name.startswith('Swa'):              #method:startswith开始.... 
    print ('Yes, the string starts with "Swa"') 
if 'aro' in name:                       #function in在...中间 
    print ('Yes, it contains the string "aro"') 
if name.find('war') != -1:              #method:find查找    -1表示未找到 
    print ('Yes, it contains the string "war"') 
delimiter = '_*_' 
mylist = ['Brazil', 'Russia', 'India', 'China'] 
print (delimiter.join(mylist))            #method:join合并 
#第10章编写一个Python脚本 
#创建一个备份程序 
import os                   #引入os 
# import sys 
import time                 #引入time 
import zipfile              #引入zipfile 
from os.path import join 
source='C:\\Users\\zhengt\\Desktop\\ExcelStudyNote'        #需要备份地址 
#在windows下需用转义符\来转义\,所以\\或者r'C:\Documents' 
# source=['C:\\Users\\zhengt\\Desktop\\Rtest','C:\\Users\\zhengt\\Desktop\\Other']  #多个地址用,分隔 
# target_dir='C:\\Users\\zhengt\\Desktop\\Study\\'      #v1.存储地址 
#用时间定义zip名字,time.strftime()函数获取时间 
# target=target_dir+time.strftime('%Y%m%d%H%M%S')+'.zip'        #v1.备份文件名 
target_dir='C:\\Users\\zhengt\\Desktop\\'      #v2.存储地址 
today=target_dir+time.strftime('%Y%m%d')        #v2.以当天日期作为备份目录 
now=time.strftime('%H%M%S')                     #v2.以当前日期作为备份文件名 
if not os.path.exists(today):           #os.path.exists(path)判断地址是否存在 
    os.mkdir(today)                      #make directory 
    print ('Successfully created directory',today) 
target=today+os.sep+now+'.zip'          #os.sep是地址份隔符,windows下=\\ 
# zip_command="zip -qr %s%s" %(target,source)   #Fail under Windows 
#Use zipfile under windows 
# help(zipfile)         #测试zipfile是否可用 
def zip_folder(source,target): 
    zip=zipfile.ZipFile(target,'w',zipfile.ZIP_DEFLATED)    #调用zipfile 
    for dirpath,dirnames,filenames in os.walk(source):   #循环source 
    #os.walk() yields a 3-tuple (dirpath, dirnames, filenames) 
    #dirpath is a string, the path to the directory 
    #dirnames is a list of the names of the subdirectories in dirpath 
    #filenames is a list of the names of the non-directory files in dirpath 
        # print dirpath,dirnames,filenames 
        for filename in filenames:              #循环文件 
            # print "compressing",join(dirpath,filename).encode("gbk") 
            zip.write(join(dirpath,filename))     #文件写入zip 
            #如果空文件夹也需写入,增加以下命令行 
        # if len(files)==0: 
        #     print 'empty dir' 
        #     continue 
            # zif=zipfile.ZipInfo((dirpath+'/').encode("gbk"+"/")) 
            # zip.writestr(zif,"") 
    zip.close()    #关闭zip文件 
    print ("Finish compressing") 
zip_folder(source,target)       #运行zip_folder命令 
#第11章面向对象的编程 
#必须有一个额外的第一个参数-->self 
# 假如你有一个类称为MyClass和这个类的一个实例MyObject。当你调用这个对象的方法MyObject.method(arg1, arg2)的时候, 
# 这会由Python自动转为MyClass.method(MyObject, arg1,arg2)——这就是self的原理了。 
class Person:       #创建一个新的类 
    def sayHi(self):  #self is must 
        print ('Hello, How are you?') 
p=Person()      #赋值p=Person类 
p.sayHi()       #运行类的方法.sayHi 
#也可以写成 
Person().sayHi() 
#__init__方法 
class Person:                       #创建一个新的类 
    def __init__(self,name_in):     #初始化,self必须;name_in表示输入参数 
        self.name=name_in           #定义self.name名称=输入参数 
    def sayHi(self):                #定义Person.sayHi 
        print ('Hello,my name is',self.name)      #定义sayHi 
p=Person('Swaroop')              #传递参数 
p.sayHi() 
#也可以写成 
# Person('Swaroop').sayHi() 
# 类与对象的方法 
# 类的变量由一个类的所有对象共享使用 
# 对象的变量有相同的名称,但是互不相关的 
#Class And Object Variables 
class Robot: 
    '''Represents a robt,with a name.''' 
    #A class variable, counting the number of robots 
    population=0 
    #Initialize the Robot 
    def __init__(self,name_in):                           #初始化 
        '''Initialized the data''' 
        self.name=name_in 
        print('(Initializing {0})'.format(self.name))   #打印 
        #When Robot is created, adds to population 
        Robot.population += 1 
    #__del__ mehtod is run when object is no longer in use 
    #No guarantee when method will be run 
    def __del__(self):                                  #删除 
        '''I am dying.''' 
        print('{0} is being destoryed!'.format(self.name)) 
        Robot.population-=1 
        if Robot.population==0: 
            print ('{0} was the last one.'.format(self.name)) 
        else: 
            print ('There are still {0:d} robots working.'.format(Robot.population)) 
 
    def sayHi(self): 
        '''Greeting by the robot.''' 
        print('Greetings, my masters call me {0}'.format(self.name)) 
    def howMany(): 
        '''Prints the current population.''' 
        print('We have {0:d} robots.'.format(Robot.population)) 
    howMany=staticmethod(howMany) 
droid1=Robot('R2-D2') 
droid1.sayHi() 
Robot.howMany() 
droid2=Robot('C-3P0') 
droid2.sayHi() 
Robot.howMany() 
print("Robots have finished their work.So let's destory them.") 
del droid1 
del droid2 
#继承 
class SchoolMember: 
    '''Represents any school member.''' 
    def __init__(self,name,age): 
        self.name=name                   #name读入 
        self.age=age                     #age读入 
        print('(Initialized SchoolMember:{0}'.format(self.name)) 
 
    def tell(self): 
        '''Tell my details.''' 
        print('Name:"{0}" Age:"{1}"'.format(self.name,self.age)) 
 
class Teacher(SchoolMember): 
    '''Represents a teacher.''' 
    def __init__(self,name,age,salary): 
        SchoolMember.__init__(self,name,age) 
        self.salary=salary                #salary读入 
        print('(Initialized Teacher:{0})'.format(self.name)) 
 
    def tell(self): 
        SchoolMember.tell(self) 
        print('Salary:"{0:d}"'.format(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:{0})'.format(self.name)) 
 
    def tell(self): 
        SchoolMember.tell(self) 
        print('Marks:"{0:d}"'.format(self.marks)) 
 
t=Teacher('Mrs.Shrividya',40,30000) 
s=Student('Swaroop',25,75) 
 
print()      #print a blank line 
 
members=[t,s] 
for member in members: 
    member.tell() 
# 输入/输出 
def reverse(text): 
    return text[::-1]        #返回一个倒序文本 
 
def is_palindrome(text): 
    rev_txt=reverse(text) 
    return text==rev_txt    #返判是否是回文 
 
something=input('Enter text: ') 
#如用input()需输入字符需带'';数字不需 
punctuation=(' ','.','?','!',':',';','-','(',')','[',']','\'','\"',',')       #需要移除的符号 
for p in punctuation: 
    # print(p) 
    something=something.replace(p,"")    #移除 
flag=is_palindrome(something) 
if (flag):      #TRUE 
    print("Yes,it is a palindrome") 
else:          #FALSE 
    print("No,it is not a palindrome") 
#文件 
from __future__ import print_function    #引入future 
poem='''\ 
Programming is fun 
When the work is done 
if you wanna make your work aslo fun: 
    use Python! 
''' 
#if 'poem.txt' doesn't exists,will create 
f=open('poem.txt','w')  #open for 'w'riting 
f.write(poem)            #write text to file 
f.close()                #close the file 
 
f=open('poem.txt')      #if no mode is specified, 'r'ead mode by default 
while True: 
    line=f.readline() 
    if len(line)==0:    #Zero length indicates EOF 
        break 
    print(line,end='') 
f.close()             #close the file 
#Pickle and Unpickling 
import pickle 
import pickle as P                #也可以将pickle用import作为变量读入 
shoplistfile='shoplist.data'     #the name of file where we will store the object 
shoplist=['apple','mango','carrot']    #the list 
f=open(shoplistfile,'wb')                #Write to file w=write,b=binary 
pickle.dump(shoplist,f)                  #dump the object to file 
f.close() 
del shoplist                            #destroy the shoplist variable 
f=open(shoplistfile,'rb')               #Read back from storage,r=read 
storedlist=pickle.load(f)               #load the object from file 
print(storedlist)                       #输出 
#异常 
#try...except...else            #try处理正常语句,发生错误时except调用,没有错误else调用 
#如查try的语句含有多句,碰到error会转到except 
try: 
    print ('Before Error') 
    text=input('Enter something -->') 
    print ('Got Error')           #没有发生错误会执行Print语句 
except EOFError:                #没有内建输入,Ctrl+d 
    print ('\nWhy did you do an EOF on me?') 
except KeyboardInterrupt:       #用户中断执行, 
    print ('You cancelled the operation.') 
else: 
    print ('You entered {0}'.format(text))    #没有异常值时,else调用 
print ('Done')                                  #这句在try外面 
 
#引发异常 
class ShortInputException(Exception):         #异常值类 
    '''A user-defined exception class.''' 
    def __init__(self,length,atleast):        #initial长度和最少长度 
        Exception.__init__(self) 
        self.length=length                    #定义长度 
        self.atleast=atleast                  #定义最小长度 
 
try: 
    s=input('Enter something -->')         #输入值 
    if len(s)<3: 
        raise ShortInputException(len(s),3)    # 
    #Other work can continue as usual here 
except EOFError: 
    print('\nWhy did you do an EOF on me?') 
except ShortInputException as x: 
    print('ShortInputException: The input was length %d,\ 
        was expecting at least %d'%(x.length,x.atleast)) 
else: 
    print('No exception was raised.') 
 
import time                   #引用time 
try: 
    f=file('poem.txt') 
    while True:               #Our usual file-reading idiom 
        line=f.readline()      #读入行 
        if len(line)==0:       #最后行 
            break 
        time.sleep(2)          #暂停2秒 
        print (line,)           #打印 
 
finally:                      #finally总是被执行,就算有Error 
    f.close()                  #关闭文件 
    print ('Cleaning up...closed the file') 
#以下语句也可以达到相同目的 
with open('poem.txt') as f: 
    for line in f: 
        print (line,) 
 
#Python标准库 
#http://python.usyiyi.cn/python_278/library/logging.html 
import os, platform, logging          #引入模块 
# os.name             #显示平台 
# os.getcwd()         #得到当前工作目录 
# os.getenv()和os.putevn()   #读取和设置环境变量 
# os.listdir()         #返回指定目录下的所有文件和目录 
# os.remove()          #删除一个文件 
# os.system()          #用来运行shell命令 
# os.linesep           #字符串给出当前平台使用的行终止符 
# os.path.split()      #函数返回一个路径的目录名和文件名 
# os.path.isfile()和os.path.isdir()  #函数分别检验给出的路径是一个文件还是目录 
# os.path.exists()      #检验给出的路径是否真的存在 
if platform.platform().startswith('Windows'):            #Windows平台 
    logging_file= os.path.join(os.getenv('HOMEDRIVE'), os.getenv('HOMEPATH'), 'test.log') 
else: 
    logging_file= os.path.join(os.getenv('HOME'),'test.log')    #其他平台 
print("Logging to", logging_file) 
 
logging.basicConfig( 
    level=logging.DEBUG, 
    format='%(asctime)s | %(levelno)s | %(message)s | %(processName)s', 
    filename=logging_file, 
    filemode='w', 
) 
logging.debug("Start of the program")       #输出Debug 
logging.info("Doing something")             #输出Info 
logging.warning("Dying now")                 #输出Warning 
 
# 特殊的方法 
# __init__(self,...) 这个方法在新建对象恰好要被返回使用之前被调用 
# __del__(self) 恰好在对象要被删除之前调用 
# __str__(self) 在我们对对象使用print语句或是使用str()的时候调用 
# __lt__(self,other) 当使用小于运算符(<)的时候调用。类似地,对于所有的运算符(+,>等等)都有特殊的方法 
# __getitem__(self,key) 使用x[key]索引操作符的时候调用 
# __len__(self) 对序列对象使用内建的len()函数的时候调用 
 
# 单语句块 
flag=True 
if flag:print ('Yes') 
#列表综合 
listone=[2,3,4]             #定义数据 
print (type(listone))         #显示listone类别 
listtwo=[2*i for i in listone if i>2]        #根据listone产生新的listtwo 
print (listtwo) 
 
#在函数中接收元组和列表 
#当要使函数接收元组或字典形式的参数的时候,有一种特殊的方法, 
# 它分别使用*表示元组;**表示字典的键/值 
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))                 #对3*2+4*2 
print (powersum(2,10) )                 #10*2 
 
#lambda形式 
#lambda语句被用来创建新的函数对象,并且在运行时返回它们 
def make_repeater(n): 
    return lambda s:s*n 
twice=make_repeater(2) 
 
print (twice('Word')) 
print (twice(5)) 
 
# exec和eval语句 
# exec语句用来执行储存在字符串或文件中的Python语句 
#eval语句用来计算存储在字符串中的有效Python表达 
exec 'print "Hello World"'      #执行 
print (eval('2*3') )                #计算 
 
#assert语句 
#assert语句用来声明某个条件是真的,用来检验至少有一个为真 
mylist=['item'] 
assert len(mylist)>=1 
mylist.pop()               #列表移除对象 
assert len(mylist)>=1      #结果会返回一个Error 
 
#repr函数 
#repr函数用来取得对象的规范字符串表示 
i=[]                 #定义变量为list 
i.append('2*3')     #增加对象 
#观看以下两个结果不同 
print (eval(repr(i[0])))             #规范字符 
print (eval(i[0])  )                #字符计算


转载于:https://my.oschina.net/tedzheng/blog/671230

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值