python 笔记

来源:互联网 发布:价格标签打印软件 编辑:程序博客网 时间:2024/06/06 11:49

i=int(raw_input("i= "))if i==0:   print 'i=0'elif i==1:   print 'i=1'else:   print 'wrong input'

注意这里的冒号

注意这里的强制转换int(),否则raw_input输入的是字符串类型。不能比较。


i=0total=0while i<10:    i+=1    total=total+i    print 'i is:',i,'total is:', total


结果是55

注意没有++和=+

total=0for i in range(0,11):    total=total+iprint total

结果是55.

注意range的最后一个元素不算的。0+1+2+3+4+5+6+7+8+9+10


while和for中都可以使用 break和continue


函数:

def printMax(a, b): if a > b:   print a, 'is maximum\n' else:   print b, 'is maximum\n'
printMax( 3, 4)x = 5y = 7printMax(x, y)

注意def后面也有冒号


函数的默认参数:

def say(message, times = 1):    print message * timessay( 'Hello' )say( 'World' , 5)

结果显示

>>> 
Hello
WorldWorldWorldWorldWorld


文档字符串 ,它通常被简称为 docstrings 。DocStrings是一个重要的工具,由于它帮助你的程序文档更加简单易懂。

你可以使用__doc__(注意双下划线)调用printMax函数的文档字符串属性。

或者help(printMax)。记住按 q退出help

def printMax(x, y):<p>'''Prints the maximum of two numbers.</p>
 The two values must be integers.''' if x > y:   print x, 'is maximum' else:   print y, 'is maximum'
printMax( 3, 5)print printMax.__doc__

显示

>>> 
5 is maximum
Prints the maximum of two numbers.
 The two values must be integers.


模块的__name__
每个Python模块都有它的__name__,如果它是'__main__',这说明这个模块被用户单独运行,我们可以进行相应的恰当操作。

比如一个模块test.py

if __name__ == '__main__' :
    print 'This program is being run by itself'
else:
    print 'I am being imported from another module'

如果单独运行test.py,会显示

>>> 
This program is being run by itself

如果在别的程序里面import test

会显示

>>> import test
I am being imported from another module


列表

shoplist=['A','C','B','D']
print shoplist[0:4]print 'I have',len(shoplist),'items to purchase.'print 'These items are:',                                     # Notice the comma at end of the linefor item in shoplist: print item,print '\nI also have to buy E.'shoplist.append('E')print 'My shopping list is now',shoplistprint 'I will sort my list now'shoplist.sort()print 'Sorted shopping list is',shoplistprint 'The first item I will buy is',shoplist[0]olditem=shoplist[0]del shoplist[0]print 'I bought the',olditemprint 'My shopping list is now',shoplist


结果显示
>>> 

['A', 'C', 'B', 'D']
I have 4 items to purchase.
These items are: A C B D 
I also have to buy E.
My shopping list is now ['A', 'C', 'B', 'D', 'E']
I will sort my list now
Sorted shopping list is ['A', 'B', 'C', 'D', 'E']
The first item I will buy is A
I bought the A
My shopping list is now ['B', 'C', 'D', 'E']


shoplist[0:4] 返回从位置0开始,包括位置1,2,3,但是停止在位置4的一个序列切片.


元组:元组通过圆括号中用逗号分割的项目定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变


zoo=('A','B','C')print 'Number of animals in the zoo is',len(zoo)new_zoo=('D','E',zoo)print 'Number of animals in the new zoo is',len(new_zoo)print 'All animals in new zoo are',new_zooprint 'Animals brought from old zoo are',new_zoo[2]print 'Last animal brought from old zoo is',new_zoo[2][2]

结果显示

>>> 
Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are ('D', 'E', ('A', 'B', 'C'))
Animals brought from old zoo are ('A', 'B', 'C')
Last animal brought from old zoo is C


Perl程序员的注释列表之中的列表不会失去它的身份,即列表不会像Perl中那样被打散。同样元组中的元组,或列表中的元组,或元组中的列表等等都是如此。只要是Python,它们就只是使用另一个对象存储的对象


字典:

ab={ 'A' : 'a@intel.com',     'B' : 'b@intel.com',     'C' : 'c@intel.com',     'D' : 'd@intel.com' }print "A's address is %s" %ab['A']# Adding a key/value pairab['E']='e@intel.com'# Deleting a key/value pairdel ab['D']print 'There are %d contacts in the address-book' %len(ab)for name,address in ab.items(): print 'Contact %s at %s' %(name,address)if 'E' in ab:                   # OR ab.has_key('Guido') print "E's address is %s" %ab['E']

结果显示

>>> 
A's address is a@intel.com
There are 4 contacts in the address-book
Contact A at a@intel.com
Contact C at c@intel.com
Contact B at b@intel.com
Contact E at e@intel.com
E's address is e@intel.com


我们使用字典的items方法,来使用字典中的每个键/值对。这会返回一个元组的列表,其中每个元组都包含一对项目——键与对应的值。


参考,赋值:

只是如果你想要复制一个列表或者类似的序列或者其他复杂的对象(不是如整数那样的简单对象),那么你必须使用切片操作符来取得拷贝。如果你只是想要使用另一个变量名,两个名称都是参考同一个对象

shoplist=['A','B','C','D']print 'Simple Assignment'mylist=shoplist del shoplist[0]print 'shoplist is',shoplistprint 'mylist is',mylistprint 'Copy by making a full slice'mylist=shoplist[:] del mylist[0] print 'shoplist is', shoplistprint 'mylist is', mylist

显示结果一目了然:

>>> 
Simple Assignment
shoplist is ['B', 'C', 'D']
mylist is ['B', 'C', 'D']
Copy by making a full slice
shoplist is ['B', 'C', 'D']
mylist is ['C', 'D']


字符串

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 the string "war"'A=' * 'mylist=['Brazil','Russia','India','China']print A.join(mylist)


结果显示

>>> 
Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil * Russia * India * China



class C():    def __init__(self,Foo):      self.foo=Foo    def mymethod(self):          print ("test")    def mymethod2(self):          print (self.foo)mc=C(100)print (mc.foo)mc.mymethod()mc.mymethod2()

结果>>> 
100
test
100

  我们没有专门调用__init__方法,只是在创建一个类的新实例的时候,把参数包括在圆括号内跟在类名后面,从而传递给__init__方法。这是这种方法的重要之处。

如果是要del一个对象,则需要在类中定义解构器。

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.populationswaroop=Person('Swaroop')swaroop.sayHi()swaroop.howMany()kalam=Person('Abdul Kalam')kalam.sayHi()kalam.howMany()del kalamswaroop.sayHi()swaroop.howMany()


结果显示>>> 
(Initializing Swaroop)
Hi, my name is Swaroop.
I am the only person here.
(Initializing Abdul Kalam)
Hi, my name is Abdul Kalam.
We have 2 persons here.
Abdul Kalam says bye.
There are still 1 people left.
Hi, my name is Swaroop.
I am the only person here.


这里, population属于Person类,因此是一个类的变量。name变量属于对象(它使用self赋值)因此是对象的变量。



class Person:
    population=1


print Person.population


>>> 
1

这里population是属于类的,不属于类的对象。相当于static.

如果是

class Person:
    Person.population=1


print Person.population

就不行


但是在类的函数里

def __init__(self,name):   self.name=name   print '(Initializing %s)' %self.name   Person.population+=1
</pre><pre name="code" class="python">就一定要用Person.population,表示属于类的变量
如果想定义一个变量A,想让她属于类的实例对象。就要用self.A

而且。一般来说,想要定义属于类实例对象的self.A          就直接在__init__ 里面被赋值就行了。


继承:


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.salaryclass 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 linemembers=[t,s]for member in members: member.tell() # works for both Teachers and Students

结果显示


>>> 
(Initialized SchoolMember: Mrs. Shrividya)
(Initialized Teacher: Mrs. Shrividya)
(Initialized SchoolMember: Swaroop)
(Initialized Student: Swaroop)


Name:"Mrs. Shrividya" Age:"40" Salary: "30000"
Name:"Swaroop" Age:"22" Marks: "75"


读写

poem='''\Programming is funWhen the work is doneif you wanna make your work also fun: use Python!'''f=file('poem.txt','w') f.write(poem) f.close() f=file('poem.txt')# if no mode is specified, 'r'ead mode is assumed by defaultwhile True: line=f.readline() if len(line)==0:   break print line, # Notice comma to avoid automatic newline added by Pythonf.close() # close the file


结果显示

>>> 
Programming is fun
When the work is done
if you wanna make your work also fun:
 use Python!




class SchoolMember:   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),    m= SchoolMember('Lilei',22)m.__tell()print "\n"


class SchoolMember:   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),    m= SchoolMember('Lilei',22)m.tell()print "\n"


class SchoolMember:   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),    m= SchoolMember('Lilei',22)m.tell()print "\n"




class SchoolMember:   def __init__(self,name,age):    self.Hname=name    self.age=age    print '(Initialized SchoolMember: %s)' %self.Hname       def tell(self):    '''''Tell my details.'''    print 'Name:"%s" Age:"%s"' %(self.Hname,self.age),    m= SchoolMember('Lilei',22)m.tell()print "\n"class Student(SchoolMember):   def __init__(self,name,age,marks):    SchoolMember.__init__(self,name,age)    self.marks=marks    print '(Initialized Student: %s)' %self.Hname       def tell(self):    SchoolMember.tell(self)    print 'Marks: "%d"' %self.marks   s=Student('Swaroop',22,75)  s.tell() 


class SchoolMember:   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),    m= SchoolMember('Lilei',22)m.tell()print "\n"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   s=Student('Swaroop',22,75)  s.tell() 






0 0
原创粉丝点击