python基础知识

变量:

i = 5
print i
print(id(i))#140558968312856
i = i + 1
print i
print(id(i))#140558968312832
s = '''this is a multi-line string.
this is the second line.'''
print s

5
140558968312856
6
140558968312832
this is a multi-line string.
this is the second line.

表达式:

length = 5
breadth = 2
area = length * breadth
print 'Area is',area
print 'perimeter is',2*(length + breadth)

Area is 10
perimeter is 14

if语句:

#coding=utf-8
number = 23
guess = int(raw_input('Enter an integer:'))
if guess == number:#冒号不要丢了
    print 'Congratulations, you guessed it.' 
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语句:

number = 23
running = True
while running:
    guess = int(raw_input('Enter an integer:'))
    if guess == number:
        print 'you guess is right'
        running = False
    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'

for语句:

for i in range(1,5):
    print i
else:
    print 'the for loop is over'

1
2
3
4
the for loop is over

形参:

def func(x):
    print 'x is',x
    x=2
    print 'changed local x to',x
x = 50
func(x)
print 'x is still',x
x is 50
changed local x to 2
x is still 50

在函数中,我们第一次使用x的 值 的时候,Python使用函数声明的形参的值。接下来,我们把值2赋给x。x是函数的局部变量。所以,当我们在函数内改变x的值的时候,在主块中定义的x不受影响。在最后一个print语句中,我们证明了主块中的x的值确实没有受到影响。

doc:

def printMax(x,y):
    '''Prints the maxmium of two numbers.
    the two values must be integers.'''
    x = int(x)
    y = int(y)

    if x > y:
        print x,'is maxmium'
    else:
        print y, 'is maxmium'

printMax(3,5)
print printMax.__doc__
5 is maxmium
Prints the maxmium of two numbers.
    the two values must be integers.

制造自己的模块:

# Filename:mymodule.py
def sayhi():
    print 'Hi, this is mymodule speaking.'
version = '0.1'
# Filename:mymodule.py
import mymodule
mymodule.sayhi()
print 'Version',mymodule.version
from mymodule import sayhi,version
sayhi()
print 'version',version

结果:Hi, this is mymodule speaking.
version 0.1

列表拷贝方式比较:

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
# notice that both shoplist and mylist both print the same list without
# the 'apple' confirming that they point to the same object

print 'Copy by making a full slice'
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0] # remove first item

print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that now the two lists are different

结果:

shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']

所以,大多数解释已经在程序的注释中了。你需要记住的只是如果你想要复制一个列表或者类似的序列或者其他复杂的对象(不是如整数那样的简单 对象 ),那么你必须使用切片操作符来取得拷贝。如果你只是想要使用另一个变量名,两个名称都 参考 同一个对象,那么如果你不小心的话,可能会引来各种麻烦。

类与对象的方法:

class Person:
    '''Represents a person.'''
    population = 0

    def __init__(self, name):
        '''Initializes the person's data.'''
        self.name = name
        print '(Initializing %s)' % self.name

        # When this person is created, he/she
        # adds to the population
        Person.population += 1

    def __del__(self):
        '''I am dying.'''
        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):
        '''Greeting by the person.

        Really, that's all it does.'''
        print 'Hi, my name is %s.' % self.name

    def howMany(self):
        '''Prints the current population.'''
        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()
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.
Hi, my name is Swaroop.
We have 2 persons here.
Abdul Kalam says bye.
There are still 1 people left.
Swaroop says bye.
I am the last one.

del,它在对象消逝的时候被调用。对象消逝即对象不再被使用,它所占用的内存将返回给系统作它用。在这个方法里面,我们只是简单地把Person.population减1。
当对象不再被使用时,del方法运行,但是很难保证这个方法究竟在 什么时候 运行。如果你想要指明它的运行,你就得使用del语句,就如同我们在以前的例子中使用的那样。

继承:

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

文件的使用:

poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
        use Python!
'''
f = file('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file
f = file('poem.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
    line = f.readline()
    if len(line) == 0: # Zero length indicates EOF
        break
    print line,
    # Notice comma to avoid automatic newline added by Python
f.close() # close the file

存储与取存储:

import cPickle as p
#import pickle as p

shoplistfile = 'shoplist.data'
# the name of the file where we will store the object

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

# Write to the file
f = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a file
f.close()

del shoplist # remove the shoplist

# Read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist

首先,请注意我们使用了import..as语法。这是一种便利方法,以便于我们可以使用更短的模块名称。在这个例子中,它还让我们能够通过简单地改变一行就切换到另一个模块(cPickle或者pickle)!在程序的其余部分的时候,我们简单地把这个模块称为p。
为了在文件里储存一个对象,首先以写模式打开一个file对象,然后调用储存器模块的dump函数,把对象储存到打开的文件中。这个过程称为 储存 。
接下来,我们使用pickle模块的load函数的返回来取回对象。这个过程称为 取储存 。

Raise的使用:

lass ShortInputException(Exception):
    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.'
luup:python_work gaolu$ python raising.py
Enter something -- >rqrq
No exception was raised.
luup:python_work gaolu$ python raising.py
Enter something -- >qqw
No exception was raised.
luup:python_work gaolu$ python raising.py
Enter something -- >q
ShortInputException: The input was of length 1,     was expecting at least 3

这里,我们创建了我们自己的异常类型,其实我们可以使用任何预定义的异常/错误。这个新的异常类型是ShortInputException类。它有两个域——length是给定输入的长度,atleast则是程序期望的最小长度。
在except从句中,我们提供了错误类和用来表示错误/异常对象的变量。这与函数调用中的形参和实参概念类似。在这个特别的except从句中,我们使用异常对象的length和atleast域来为用户打印一个恰当的消息。
当程序出现错误,python会自动引发异常,也可以通过raise显示地引发异常。一旦执行了raise语句,raise后面的语句将不能执行。

lambda函数:

#coding=utf-8
def make_repeater(n):
    return lambda s:s*n#返回的是一个lambda函数
twice = make_repeater(2)#返回的lambda函数的引用给twice
print twice('date')#相当于给返回的lambda函数传值
print twice(22)#同上

结果:
datedate
44

你可能感兴趣的:(python基础知识)