Chinaunix首页 | 论坛 | 博客
  • 博客访问: 21017
  • 博文数量: 27
  • 博客积分: 585
  • 博客等级: 中士
  • 技术积分: 270
  • 用 户 组: 普通用户
  • 注册时间: 2012-07-20 17:11
文章分类

全部博文(27)

文章存档

2013年(1)

2012年(26)

我的朋友
最近访客

分类: Python/Ruby

2012-12-27 09:22:21

一、python中的List

 

Example 3.25. key s,  values    i tems  函数

>>> params =  {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}

>>> params.keys()   (1)

['server', 'uid', 'database', 'pwd']

 

>>> params.values() (2)

['mpilgrim', 'sa', 'master', 'secret']

 

>>> params.items()  (3)

[('server', 'mpilgrim'), ('uid', 'sa'), ('database', 'master'), ('pwd', 'secret')]

 

二、 函数解析

def info(object, spacing=10, col lapse=1): (1) (2) (3)

    """Print methods and doc strings.

   

    Takes module, class, l ist, dictionary, or string."""

    methodList = [method for method in dir(object) if callable(getattr(object, method))]

    processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)

print "\n".join(["%s %s" % (method.ljust(spacing),processFunc(str(getattr(object, method).__doc__)))

for method in methodList])

if __name__ == "__main__":                (4) (5)

    print info.__doc__

(1)  该模块有一个声明为 info 的函数。根据它的函数声明可知它有三个参数objectspacing collapse。实际上后面两个参数都是可选参数关于这点你很快就会看到。因为他们在函数中已经事先确定了函数的值,所以在赋值的时候可以不写这两个参数

(2)  info 函数有一个多行的 doc string,简要地描述了函数的功能。注意这里并没有提到返回值;单独使用这个函数只是为了这个函数产生的效果,并不是为了它的返回值。

(3)  函数内的代码是缩进形式的。

(4)  if __name__ 技巧允许这个程序在自己独立运行时做些有用的事情,同时又不妨碍作为其它程序的模块使用。在这个例子中,程序只是简单地打印出info 函数的 doc string。

(5)  if 语句使用 == 进行比较,而且不需要括号。

info 函数的设计意图是提供给工作在 Python IDE 中的开发人员使用,它可以接受任何含有函数或者方法的对象 (比如模块,含有函数,又比如list,含有方法) 作为参数,并打印出对象的所有函数和它们的 doc string。

 

三、 str函数

 

str 将数据强制转换为字符串。每种数据类型都可以强制转换为字符串。

Example 4.6.  str  介绍

>>> str(1)          (1)

'1'

>>> horsemen = ['war', 'pestilence', 'famine']

>>> horsemen

['war', 'pestilence', 'famine']

>>> horsemen.append('Powerbuilder')

>>> str(horsemen)   (2)

"['war', 'pestilence', 'famine', 'Powerbuilder']"

>>> str(odbchelper) (3)-------这个是一个模块

""

>>> str(None)       (4)

'None'

四、 if语句

 

number = 23

guess = int(raw_input('Enter an integer : '))

if guess == number:

    print 'Congratulations, you guessed it.' # New block starts here

    print "(but you do not win any prizes!)" # New block ends here

elif guess < number:

    print 'No, it is a little higher than that' # Another block

    # You can do whatever you want in a block ...

else:

    print 'No, it is a little lower than that'

    # you must have guess > number to reach here

print 'Done'

五、键盘输入:从键盘输入字符

 

guess = int(raw_input('Enter an integer : '))

阅读(248) | 评论(0) | 转发(0) |
0

上一篇:Python---字符

下一篇:python--part2

给主人留下些什么吧!~~