python 教程

来源:互联网 发布:测绘工程就业前景知乎 编辑:程序博客网 时间:2024/04/19 23:04

http://sebug.net/paper/python/


定义标准注释


#!/usr/bin/python
def func(x):
        '''Func just print some number.
        
        x is a number assigned by you'''
        print 'x is', x
        print 'y is', y

print func.__doc__
#help(func)

在python中,用三个'号包含起来一个注释。 这个是个标准的文档注释。

可以用   func.__doc__ 来显示

或者用 help(func) 来显示


list 结构

#!/usr/bin/python
shoplist = ['apple', 'mango', 'carrot', 'banana']
houselist = ['shose', shoplist]

print 'I have', len(shoplist), 'items to purchase.'
print shoplist
print shoplist[0]
print '%s is 3 %s' %(shoplist[0], shoplist[1])

print houselist
print houselist[1]

tuple 结构

#!/usr/bin/python
zoo = ('wolf', 'elephant', 'penguin')
print 'Number of animals in the zoo is', len(zoo)

new_zoo = ('monkey', 'dolphin', zoo)
print 'Number of aninals in new zoo is', len(new_zoo)
print 'All animals in the 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]

看不出tuple和 llist的区别。。。


使用字典

#!/usr/bin/python

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']
print "This is the name card", ab

ab['Guido'] = 'guido@python.org'
print "This is the name card", ab

del ab['Spammer']


使用模块

在python中,模块是用文件的名字来命名的。 这点有时候要注意,起名字的时候不要用标准的库的名字。

库的默认搜索路径由sys.path来指定。

可以用,   来添加系统的搜索路径

import sys
sys.path.append(xxx)

下面是个简单的例子。

mymodule.py 文件

#!/usr/bin/python

def sayhi():
        print "Hi, this is mymodule speaking." \
                        "ok"

version = '0.1'

--------------------------

mymodule_demo.py 文件
#!/usr/bin/python

import mymodule

mymodule.sayhi()
print 'Version', mymodule.version

execfile("mymodule.py")




原创粉丝点击