Python+Django+SAE系列教程2-----Python种的函数、模块和数据结构

我们继续按照著名的《简明 Python 教程》学习,很快的我们学到了第七章。

第七章:这里面介绍了形参、实参、局部变量、Global语句等,这些都和其他语言一样如果你能看懂下面的代码就算Pass了,记住函数是用def定义的。

#!/usr/bin/python
# Filename: func_local.py

def func(x):
    print 'x is', x
    x = 2
    print 'Changed local x to', x

x = 50
func(x)
print 'x is still', x

下面我们说一下默认参数和关键参数,这个确实比其他语言牛B。

#!/usr/bin/python
# Filename: func_default.py

def say(message, times = 1):#
    print message * times

say('Hello')
say('World', 5)

以上是默认参数,需要注意的是:只有在形参表末尾的那些参数可以有默认参数值,即你不能在声明函数形参的时候,先声明有默认值的形参而后声明没有默认值的形参。
这是因为赋给形参的值是根据位置而赋值的。例如,def func(a, b=5)是有效的,但是def func(a=5, b)是 无效 的。

接下来是关键参数,这个更牛B,参数可以不按照顺序写了:

#!/usr/bin/python
# Filename: func_key.py

def func(a, b=5, c=10):
    print 'a is', a, 'and b is', b, 'and c is', c

func(3, 7)
func(25, c=24)
func(c=50, a=100)

接下来是返回值,在Python中函数无需定义返回值类型,因为Python对变量也没有类型,这就像asp或者js一样,看看下面的函数:

#!/usr/bin/python
# Filename: func_return.py

def maximum(x, y):
    if x > y:
        return x
    else:
        return y

print maximum(2, 3)

最后是DocStrings,其实就是函数的说明文档,这部分内容有别于注释,注释是给修改你程序的程序员看到,而DocStrings是给调用你写的函数的程序员看的,虽然这两种人往往都是一个人。如果你看懂了上面的几个例子,那么这一章也就可以Pass了。


第八章:这一章介绍了模块,开始看可能有点晕,要不先看看这段代码:
#!/usr/bin/python
# Filename: Hemodule.py

if __name__ == '__main__':
    MyStr="hemeng in main"
else:
    MyStr="hemeng in module"

def sayhi():
    print 'Hi,',MyStr

version = '1.0'

# End of mymodule.py

然后是调用这个模块的文件:

#!/usr/bin/python
# Filename: hemodule_demo.py

import Hemodule

#Hemodule.MyStr="New String"
Hemodule.sayhi()
print 'Version', Hemodule.version

能看懂这个也就可以Pass了,但是等会儿,这里面需要说明的有几个关键字:

首先是“字节编译的.pyc文件”,如果一个模块的py文件被另外一个调用后,那么他会自动生成一个同名的pyc文件,你看看你的文件夹是不是多了一个Hemodule.pyc的文件,这就是为了下次再调用的时候提高效率;

然后是“__name__”,每个py文件都有一个“__name__”,如果当他自己独立运行的时候这个“__name__”就是“__main__”,注意使两个下划线;

在往后就是,from..import,就是只导入部分函数和变量,同时可以少打些字

最后,是我自己做的实验,在调用模块的函数中可以改变模块内的变量,我理解的其实就是一个代码段的集合,看起来是“模块名.函数名”,跟对象似的,其实根本没有实例、类这些概念,也就是为了“字节编译的.pyc文件”可以下次再调用的时候加快速度还有就是为了代码的结构更加清楚以及复用。



第九章:这一章首先介绍了列表、元组和字典,跟其他语言也一样,列表用[],元组用(),字典用{},先说说列表,看懂这段代码就可以Pass了:

#!/usr/bin/python
# Filename: using_list.py

# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']

print 'I have', len(shoplist),'items to purchase.'

print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
    print item,

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 'Sorted shopping list is', shoplist

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

这里面其实也体现了Python的优越性,看到了吧,列表不仅有shoplist.append('rice');del shoplist[0];这些方法,还有排序的方法:shoplist.sort(),c++/js可是没有的呀。接下来是元组,看懂下面代码的也可以Pass了:

#!/usr/bin/python
# Filename: using_tuple.py

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)
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]

这里是结果:

Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant','penguin'))
Animals brought from old zoo are ('wolf', 'elephant', 'penguin')
Last animal brought from old zoo is penguin

如果你猜对了结果,那么你就可以Pass了,补充说一点其实我们用到的打印语句也是元组,记得元组前面有一个“%”,看下面:

#!/usr/bin/python
# Filename: print_tuple.py

age = 22
name = 'Swaroop'

print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python?' % name

接下来是字典,字典其实就是组“键值对”:d = {key1 : value1, key2 : value2 },不废话了,看代码:

#!/usr/bin/python
# Filename: using_dict.py
# 'ab' is short for 'a'ddress'b'ook

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)

if 'Guido' in ab: # OR ab.has_key('Guido')
    print "\nGuido's address is %s" % ab['Guido']

这里是结果:

Swaroop'saddress is swaroopch@byteofpython.info

There are 4 contacts in the address-book

Contact Swaroop at swaroopch@byteofpython.info
Contact Matsumoto at matz@ruby-lang.org
Contact Larry at larry@wall.org
Contact Guido at guido@python.org



Guido's address is guido@python.org

是不是和其他的语言一样,这里需要注意的是:我们可以使用in操作符来检验一个键/值对是否存在,或者使用dict类的has_key方法。你可以使用help(dict)来查看dict类的完整方法列表。

除了以上三个列表、元组和字典以外本章还介绍了“序列”, 列表、元组和字符串都是序列,说白了只要看到这样“shoplist[0]”,后面有“[i]”的都是序列,下面我讲讲序列的操作,这是也是Python特点的体现,还是直接看代码:

#!/usr/bin/python
# Filename: seq.py

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

# Indexing or 'Subscription' operation
print 'Item 0 is', shoplist[0]
print 'Item 1 is', shoplist[1]
print 'Item 2 is', shoplist[2]
print 'Item 3 is', shoplist[3]
print 'Item -1 is', shoplist[-1]# banana,倒数第一个
print 'Item -2 is', shoplist[-2]# carrot,倒数第二个

# Slicing on a list
print 'Item 1 to 3 is', shoplist[1:3] ['mango', 'carrot'],第一个到第三个以前
print 'Item 2 to end is', shoplist[2:]# ['carrot', 'banana']倒数第二个到最后
print 'Item 1 to -1 is', shoplist[1:-1]#第一个到倒数第一个以前
print 'Item start to end is', shoplist[:]#所有

# Slicing on a string
name = 'swaroop'
print 'characters 1 to 3 is', name[1:3]
print 'characters 2 to end is', name[2:]
print 'characters 1 to -1 is', name[1:-1]
print 'characters start to end is', name[:]

只要几个[]中间如果“:”后面有数字,那么就不包括那一个,而是“以前的数”就OK了。下面说明了对象与参考,这就像C++里面的指针,也很好理解,看看代码:

#!/usr/bin/python
# Filename: reference.py

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
结果是这样的:

Simple Assignment
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']


下面还有很多关于字符串的操作,也是Python特有“聪明”的体现:
#!/usr/bin/python
# Filename: str_methods.py

name = 'Swaroop' # This is a string object 

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"'

delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print delimiter.join(mylist)

这里,我们看到使用了许多字符串方法。startwith方法是用来测试字符串是否以给定字符串开始。in操作符用来检验一个给定字符串是否为另一个字符串的一部分。

find方法用来找出给定字符串在另一个字符串中的位置,或者返回-1以表示找不到子字符串。str类也有以一个作为分隔符的字符串join序列的项目的整洁的方法,它返回一个生成的大字符串。

说明一下join这样方法在我们构造Json对象的时候超级好用。



第十章:主要介绍了一个使用zip的例子,说明了一下开发程序的过程,我们可以忽略了,因为我们后来要做的例子,要比这个有大的多。


待续。。。







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值