终于完整的从头到尾看了一本书,《A Byte of python》。正如结尾所说这只是开始的结束。还需继续前行,技术的道路永无止境!
注:如果含有中文字符,在python文件开头加上注释:
# -*- coding: utf-8 -*-
1.文本显示格式:
print"hello world!"
mark='多行文本显示,段落'
print '{0:-^60}'.format(mark)
c='''This is a multi-line string. This is the first line.
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."
'''
print c
mark='转义字符,r的使用,多行显单行'
print '{0:-^60}'.format(mark)
d= 'What\'s your name?'
e="What's your name?"
m=r"this is the first line\nthis\tis the second line"
m0="this is the first line\nthis\tis the second line"
n="this is the first line.\
this is also the first line."
print d+'\n'+ e +'\n'+ m+'\n'+m0+'\n'+n
mark='format使用'
print '{0:-^60}'.format(mark)
name='daisy'
age=25
gender='女生'
introduction=('{0:-^12}是一个{1}岁的{2}'.format(name,age,gender))
question=' Do you know where is the {0} years old {1} from?'.format(age,gender)
print introduction +question
2.循环和控制流
mark='while use,remeber this while has else\
excute break will not excute else'
print '{0:-^60}'.format(mark)
number=23
running=True
while running:
guess=int(input("enter a integer:"))
if guess==number:
print 'congratulation,you guessed it!'
break
elif guess<number:
print 'no,it is a little higher'
else :
print 'no,it is a little lower'
else:
print 'the while loop is over'
print 'done'
mark="for use,range function generate a sequence,\
default size is 1.else is optional"
print '{0:-^60}'.format(mark)
for i in range(1,6,2):
print i
else:
print 'the for loop is over'
3.数据结构
#list
programmingLangs=['c','c++','c#','java','python','shell']
print("I have learned the programming languages as below:",programmingLangs)
programmingLangs.append("ruby")
del programmingLangs[5]
programmingLangs.sort()
count=len(programmingLangs)
print("the count of this set is",count)
print("i known those programming languages well:",programmingLangs)
for lang in programmingLangs:
print(lang)
#tuple
zoo=() #null
zoo=("elephant",) # contain one value
zoo=('1','2','3')
new_zoo=('77','88',zoo)
length=len(zoo)
length2=len(new_zoo)
print("the length of zoo is {0},the length of new_zoo is {1}".format(length,length2))
print("newzoo have value {0}".format(new_zoo[2][2]))
print(zoo)
zoo=(('1','2','3'),)
print(len(zoo))
#dict
dic={'1':'100分','2':'90分','3':'85分'}
print("The number one got {0}".format(dic['1']))
del dic['2']
dic['4']='67分'
if (dic.has_key('4')):
dic['5']='60分'
else:
dic['4']='67分'
for rank,score in dic.items():
print('number {0} got {1}'.format(rank,score))
# sequence facet
list=['a','b','c','d','e']
str='china'
#forward print
for i in range(len(list)):
print(" item {0} is {1}".format(i,list[i]))
print(list)
#backward print
for i in range(len(list)):
print("last item {0} is {1}".format(i,list[-1-i]))
print(list[::-1])
print(str[:])
print(str[:4:2])
print(str[2:])
print(str[1:-1])
#set
# see the difrence between copy and assignment
set1=set(["haerbin","hebei","bejing","shanghai"])
setc=set1.copy()
setc.add("henan")
setc.add("hubei")
# sub set
print(setc.issuperset(set1))
setc.remove("hebei")
print(set1 & setc)
print(set1 | setc)
#reference
setalias=set1
set1.remove("bejing")
delimiter='_*_*_'
print(delimiter.join(setalias))
4.函数调用
def SayHello():
print "daisy please be come down!"
SayHello()
#全局变量
x=60
def func():
#函数内部使用外部定义的变量,必须使用global标记为全局语句
global x
x=20
print ('x changed value is',x)
func()
print ("value of x is",x)
#默认参数
def say(message,times=1):
print (message*times)
say("hello")
say("hello",5)
#复杂参数
def total(initial=5,*numbers,**keywords):
count=initial
for number in numbers:
count+=number
for key in keywords:
count+=keywords[key]
return count
print("total is:",total(2,34,35,36,a=6,c=7,d=5))
#打印注释
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__)
5.类定义
from Module import *
class Person:
guess='false'
def __init__(self,name):
self.name=name
def SayHi(self):
print("hello {0},how are you ?".format(self.name))
def Guess():
Person.guess='true'
Guess()
#静态方法
Guess=staticmethod(Guess)
@staticmethod
def GetMax(x,y):
GetMax(x,y)
#对象消失的时候配调用
def __del__(self):
print('I am dead')
p=Person("daisy")
p.SayHi() # 调用对象方法
Person.Guess() # 调用类方法
Person.GetMax(34,67)
print(p.name) #调用对象变量
print(Person.guess) #调用类变量
del p
6.类继承
class SchoolMember:
def __init__(self,name,age):
self.name=name
self.age=age
def tell(self):
print("Name :{0},Age:{1}".format(self.name,self.age))
class Teacher(SchoolMember):
def __init__(self,name,age,salary):
SchoolMember.__init__(self,name,age)
self.salary=salary
def tell(self):
SchoolMember.tell(self)
print("salary:{0:d}".format(self.salary))
class Student(SchoolMember):
def __init__(self,name,age,marks):
SchoolMember.__init__(self,name,age)
self.marks=marks
def tell(self):
SchoolMember.tell(self)
print("marks:{0:d}".format(self.marks))
t=Teacher("daisy",25,3000)
s=Student("ageala",26,100)
t.tell()
s.tell()
7.输入输出
# input and output
def reverse(text):
return text[::-1]
def is_palindrome(text):
text=text.lower()
text=text.replace(' ','')
return text == reverse(text)
str=input('enter text:')
if(is_palindrome(str)):
print("{0} is palindrome".format(str))
else:
print("{0} is not palindrome".format(str))
#file
poem1='''\
白日依山尽,黄河入海流。
欲穷千里目,更上一层楼。'''
poem2='''
举头望明月,低头思故乡。
床前明月光,疑是地上霜。'''
f=open("poem.text",'w')
f.write(poem1)
f.close()
f=open("poem.text",'a')
f.write(poem2)
f.close()
f=open("poem.text")
while True:
line=f.readline()
if(len(line)==0):
break
print(line)
f.close()
#pickle (store any object)
import pickle
objectFileName="shop.data"
shoplist=(('apple','banana','mango','watermelon'),('carrot','cucombber'))
f=open(objectFileName,'wb')
pickle.dump(shoplist,f)
f.close()
#after code,it will be automate closed
with open(objectFileName,'rb') as f:
storedlist=pickle.load(f)
print(storedlist[0][3])
8.标准类库简介
# python standard library
import sys,warnings
info=sys.version_info
if(info[0]<3):
warnings.warn("need python 3",RuntimeWarning)
import os,platform,logging
if platform.platform().startswith('Windows'):
loggingfile=os.path.join(os.getenv('HOMEDRIVE'),'test.log')
print(loggingfile)
else:
loggingfile=os.path.join(os.getenv('HOME'),'test.log')
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s:%(levelname)s:%(message)s',
filename=loggingfile,
filemode='w'
)
logging.debug('start of the program')
logging.info('doing something')
logging.warning('dying now')
import json
import urllib,urllib.parse,urllib.request,urllib.response
yhoo_app_id='jl22psvV34HELWhdfUJbfDQzlJ2B57KFS_qs4I8D0Wz5U5_yCI1Awv8.lBSfPhwr'
searchbase='http://search.yahooapis.com/WebSearchService/V1/webSearch'
class YahooSearchError(Exception):
pass
def Search(query,results=20,start=1,**kwargs):
kwargs.update({
'appid':yhoo_app_id,
'query':query,
'results':results,
'output':json,
})
url=searchbase+'?'+urllib.parse.urlencode(kwargs)
result=json.load(urllib.request.urlopen(url))
if 'ERROR' in result:
YahooSearchError(result['ERROR'])
return result['ResultSet']
query=input("what you want to search?")
for result in Search(query)['Result']:
print("title: {0},url :{1}".format(result['Title'],result['Url']))
但是没有调用成功,因为用的是python2.7,下次试一下python3.0
9.其他内容
# return more than one value by tuple
def get_score():
return ("shiyaru",100)
name,score=get_score()
print("{0} got {1}".format(name,score))
# lambda
points = [ { 'x' : 2, 'y' : 3 }, { 'x' : 4, 'y' : 1 } ]
points.sort(lambda a, b : -cmp(a['x'], b['x']))
print(points)
def make_repeater (n):
return lambda s: (s*n)
twice = make_repeater( 5 )
print twice( 'word' )
print twice( 5 )
#list filter
list1=[2,3,4,5,6,7,8,1,23]
list2=[2*i for i in list1 if i%2 != 0]
print(list2)
# tuple and dictionary reference
def totalScore(*score):
total=0
for s in score:
total += s
return total
def total(**studentScore):
total=0
for k,v in studentScore.items():
total += v
return total
print('total score is :{0}'.format(totalScore(55,66,88,78,89,58,100)))
print('total score is :{0}'.format(totalScore(*[55,66,88,89,58,100])))
print('total score is :{0}'.format(total(shi=45,ya=88,ru=98)))
print('total score is :{0}'.format(total(**{'1':100,'2':90,'3':85})))
#exec and eval
exec("""list1=[2,3,4,5,6,7,8,1,23]
list2=[2*i for i in list1 if i%2 != 0]
print(list2)""")
eval('8*54')
#assert
a=[1,2]
assert len(a) >= 1
#repr
points = [ { 'x' : 2, 'y' : 3 }, { 'x' : 4, 'y' : 1 } ]
printstr=repr(points)
print(printstr)
print(eval(printstr))
10.实现实例
import pickle
class PersonInfo:
def __init__(self,email,telnum):
self.email=email
self.telnum=telnum
dic={"shi":PersonInfo("1464077148@qq.com","15827320659"),
"he":PersonInfo("5674077148@qq.com","15827356759"),
"xiong":PersonInfo("1464789148@qq.com","15844520659")}
firendsfile="firends.data"
def syncfirends(dic):
with open(firendsfile,"wb") as f:
pickle.dump(dic,f)
def getfriends():
with open(firendsfile,"rb") as f:
dic=pickle.load(f)
for name,info in dic.items():
print("my firend {0} detail infomation is email:{1} tel:{2} ".format(name,info.email,info.telnum))
def addfriends(name,pernsoninfo):
with open(firendsfile,"rb") as f:
dic=pickle.load(f)
if(dic.has_key(name)==False):
dic[name]=pernsoninfo
syncfirends(dic)
print("I have {0} friends now ".format(len(dic)))
def deletefriend(name):
with open(firendsfile,"rb") as f:
dic=pickle.load(f)
del dic[name]
syncfirends(dic)
print("I have {0} friends now ".format(len(dic)))