Python简明教程学习笔记
# 第3章 最初的步骤
print("What's your name?") #Python是大小写敏感的Python是大小写敏感的 确保在每一行的开始字符前没有空格或者制表符
help(str)
quit()
copyright()
credits()
license()
help('print')
# 第4章 基本概念
"This is the first sentence.\
This is the second sentence."
# 行末的单独一个反斜杠表示字符串在下一行继续,而不是开始一个新的行
# 标识符的命名
开头字母或_
标识符区分大小写
标识符其他部分可以由字母/下划线/数字组成
# 例4.1 使用变量和字面意义上的常量
i=5
print(i)
i=i+1
print(i)
s = '''This is a multi-line string.
This is the second line.'''
print(s)
# 逻辑行与物理行 ps:在每个物理行只写一句逻辑行,避免使用分号
i=5;
print(i);
i=5;print(i);
i=5;print(i)
# 用单引号括起来换行要加"\",用三引号则可不加
s = 'This is a string. \
This continues the string.'
print(s)
# 第5章 运算符与表达式
2 + 3
'a'+'b'
8//3 #取整除,返回商的整数部分
5%3 #取模
2<<2 #得8,左移,低位补零,二进制
11>>1 #得5,右移,高位丢弃(丢弃最右边一位),二进制
& 按位与 数的按位与 5 & 3得到1。
| 按位或 数的按位或 5 | 3得到7。
^ 按位异或 数的按位异或 5 ^ 3得到6
~ 按位翻转 x的按位翻转是-(x+1) ~5得到6。
3<5<7
# 第6章 控制流
# if-elif-else
number=23
guess=int(input('Enter an integer : '))
if guess==number:
print("Congratulations, you guessed it.")
print("(but you do not win any prizes!)")
elif guess<number:
print("No, it is a little higher than that")
else:
print("No, it is a little lower than that")
print("done")
# while-else
number=23
running=True #这里running要设为True或者1才有效
while running:
guess=int(input("Enter an integer : "))
if guess==number:
print("Congratulations, you guessed it.")
running=False #改成break有同样的效果
elif guess<number:
print("No, it is a little higher than that")
else:
print("No, it is a little lower than that")
else:
print("The while loop is over.")
print("Done")
# for..in
for i in range(1,5,2): #注意这里以冒号结尾,[1,5),步长为2
print(i)
else:
print("over")
# break
while True:
s=input('Enter something : ')
if s == 'quit':
break
print('Length of the string is',len(s))
print('done')
# continue
while True:
s=input('Enter something : ')
if s=='quit':
break
if len(s)<3:
continue #忽略块中的剩余的语句
print('Input is of sufficient length')
# 第7章 函数
# 定义函数
def sayhello():
print('hello')
sayhello()
# 使用函数形参
def printMax(a,b):
if a>b:
print(a,'is maximum')
else:
print(b,'is maximum')
printMax(3,4)
x=5
y=7
printMax(x,y)
# 使用局部变量 x的值在函数里改变了,但实际x的值在全局里没有改变
def func(x):
print('x is',x)
x=2
print('Changed local x to',x)
x=50
func(x)
print('x is still',x)
# 使用Global语句 此时全局变量x会改变
def func():
global x
print('x is',x)
x=2
print('Changed local x to',x)
x=50
func()
print('Value of x is',x)
# 使用默认参数值
def say(message,times=1):
print(message*times)
say('Hello')
say('World ',5)
#重要只有在形参表末尾的那些参数可以有默认参数值,即你不能在声明函数形参的时候,先声明有默认值的形参而后声明没有默认值的形参。
#这是因为赋给形参的值是根据位置而赋值的。例如,def func(a, b=5)是有效的,但是def func(a=5, b)是 无效 的。
# 使用关键参数
def func(a,b=5,c=10):
print('a is',a,'b is',b,'c is',c)
func(3,7)
func(25,c=24)
func(c=50,a=100)
# return语句
def maximum(x,y):
if x>y:
return x
else:
return y
print(maximum(2,3))
def someFunction():
pass
print(someFunction()) #return None
# 使用DocStrings-文档字符串
def printMax(x,y):
'''Prints the maximum of two numbers.
The two values must be integers.'''
x=int(x)
y=int(y)
if x>y:
print(x,'is maximum')
else:
print(y,'is maximum')
printMax(3,5)
print(printMax.__doc__)
# 文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述。
help(printMax) #原理就是抓取函数的__doc__属性
# 第8章 模块
import sys
print ('The command line arguments are:')
for i in sys.argv:
print (i)
print ('\n\nThe PYTHONPATH is', sys.path, '\n')
# 使用模块的__name__
if __name__ == '__main__':
print('This program is being run by itself')
else:
print('I am being imported from another module')
def sayhi():
print('Hi, this is mymodule speaking.')
version = '0.1'
import mymodule
mymodule.sayhi()
print('Version', mymodule.version)
from mymodule import sayhi, version
sayhi()
print('Version', version)
# dir()函数 列出模块定义的标识符。标识符有函数、类和变量
import mymodule
dir(mymodule)
a=5
dir()
del a
dir()
# 第9章 数据结构
# 使用列表
shoplist=['apple','mango','carrot','banana']
print('I have',len(shoplist),'item to purchase')
print('These items are:',end=' ')
for item in shoplist:
print(item,end=' ')
print('\nI also have to buy rice.')
shoplist.append('rice')
print('My shopping list is now',shoplist)
print('I will sort my list now')
shoplist.sort()
print('The first item I will buy is',shoplist[0])
olditem=shoplist[0]
del shoplist[0]
print('I bought the',olditem)
print('My shopping list is now',shoplist)
# 使用元组 元组和字符串一样是 不可变的 即你不能修改元组
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)) #还是3,这里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])
singleton = (2 , )
# 元组与打印语句
age=22
name='Swaroop'
print('%s is %d years old' %(name,age)) #%s表示字符串,%d表示整数
# print的这个用法使得编写输出变得极其简单,它避免了许多字符串操作。它也避免了我们一直以来使用的逗号。
print('Why is %s playing with that python?' %name)
# 字典
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))
# 序列
shoplist=['apple','mango','carrot','banana']
# Slicing on a list
print('Item 0 is',shoplist[0])
print('Item -1 is',shoplist[-1]) #右数第一个
shoplist[1:3] #['mango', 'carrot'] 不包括最右边的对象,即[1,3)
print('Item 2 to end is', shoplist[2:])
print('Item start to end is', shoplist[:])
# Slicing on a string
name='swaroop'
print('characters 1 to 3 is',name[1:3])
# 对象和参考
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)
# 小结:如果是要获得一份拷贝,则使用mylist=shoplist[:],如果是想使用另一个变量名参考同一个对象,则使用mylist=shoplist
# 更多字符串的内容
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: #这里存在是1,不存在是-1
print('Yes, it contains the string "war"')
delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))
# 第10章 解决问题——编写一个Python脚本(略)
# 第11章 面向对象的编程
# 类
class Person:
pass
p=Person()
print(p) #计算机内存地址
# 使用对象的方法
class Person:
def sayHi(self):
print('Hello')
p=Person()
p.sayHi()
Person().sayHi()
# __init__方法 在类的一个对象被建立时,马上运行。这个方法可以用来对你的对象做一些你希望的初始化
class Person:
def __init__(self,name):
self.name=name
def sayHi(self):
print("Hello,my name is",self.name)
p=Person('Swaroop')
p.sayHi()
#类的变量 由一个类的所有对象(实例)共享使用。只有一个类变量的拷贝,所以当某个对象对类的变量做了改动的时候,这个改动会反映到所有其他的实例上。
#对象的变量 由类的每个对象/实例拥有。因此每个对象有自己对这个域的一份拷贝,即它们不是共享的,在同一个类的不同实例中,虽然对象的变量有相同的名称,但是是互不相关的。
class Person:
population=0 #类的变量
def __init__(self,name):
self.name=name #对象的变量
print('Initializing %s' %self.name)
Person.population+=1 #Person.population=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()
# 继承
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
# 第12章 输入/输出
# 使用文件
poem='''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f=open('poem.txt','w') # open for 'w'riting
f.write(poem)
f.close()
f=open('poem.txt') # if no mode is specified, 'r'ead mode is assumed by default
while True:
line=f.readline()
if len(line)==0:
break
print(line,end=' ')
f.close()
# 储存器
import pickle as p
shoplistfile='shoplist.data'
shoplist=['apple','mango','carrot']
f=open(shoplistfile,'wb')
p.dump(shoplist,f) #将对象shoplist保存到f中去
f.close()
# 在python3以上版本中,如果要用存储器,那么读写文件都要用‘rb’和'wb'模式。
del shoplist #remove the shoplist
#Read back from the storage
f=open(shoplistfile, "rb")
storedlist=p.load(f)
print(storedlist)
# 第13章 异常
# 处理异常
import sys
try:
s=Input('Enter something --> ')
except NameError:
print('Why did you do an EOF on me' )
sys.exit()
except:
print('Some error/exception occurred')
print('Done')
# 第15章 更多Python的内容
# 使用列表综合
listone=[2,3,4]
listtwo=[2*i for i in listone if i > 2]
print(listtwo)
# 在函数中接收元组和列表
def powersum(power,*args): #args是用来存储多余的参数
total=0
for i in args:
total+=pow(i,power) #i的power次方
return total
powersum(2,3,4) #3的平方加4的平方
powersum(2,10)
# lambda形式 用来创建新的函数对象,并且在运行时返回它们
def make_repeater(n):
return lambda s:s*n
twice=make_repeater(2)
print(twice('word'))
print(twice(5))
# assert语句 用来声明某个条件是真的
mylist=['item']
assert len(mylist)>=1
mylist.pop(-1) #移除最右一个对象
assert len(mylist)>=1
# repr函数 用来取得对象的规范字符串表示
i=[]
i.append('item')
i
repr(i)