关闭

python的循环,pass和DocString

标签: python
237人阅读 评论(0) 收藏 举报
分类:
先来说说最简单的while循环和for循环:

while循环和C的相似性更高:

while 1>0:
    guess=int(input('enter a number: '))
    if guess==23:
        print 'guess right!'
        break
    elif guess>23:
        print 'higher'
    else :
        print 'lower'
print 'the loop1 is over'

注意for的写法:
for i in range(1,10,3): # equal to C: for(int i=1;i<10;i+=2)
    print i
else: # else statement can follow loop
    print 'the loop2 is over'
它们的输出:

>>> 
enter a number: 2
lower
enter a number: 44
higher
enter a number: 23
guess right!
the loop1 is over
1
4
7
the loop2 is over
>>> 

pass在python函数中代表不返回值,或者说是返回None,类似于C的return ;

def maxnum(a,b):
    if a>b:  return a
    else : pass  #return none statement 
print maxnum(23,45)
print maxnum(45,23)

>>> 
None
45
>>> 

接下来聊聊DocString:

其全称是documentation strings。它放在函数的第一行,能输出提示信息,帮助函数更容易理解,使用函数的__doc__(双下划线)来输出信息。

def midfind(a,lx,rx,goal):
    ''' this is a half find for ourneed number, 
    the return is goal number's place.'''

    low=lx
    high=rx
    while low<=high:
        mid=(low+high)>>1
        if a[mid]>goal:
            high=mid-1
        elif a[mid]<goal:
            low=mid+1
        else: return mid
    return -1
a=[3,5,7,10,23,45]
print midfind(a,0,5,5)+1
print (midfind.__doc__) #midfind.__doc__ is the document strings,
                        #note: multi-line for __  

>>> 
2
 this is a half find for ourneed number, 
    the return is goal number's place.
>>> 


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:225875次
    • 积分:7669
    • 等级:
    • 排名:第2750名
    • 原创:562篇
    • 转载:12篇
    • 译文:0篇
    • 评论:30条
    我的链接
    最新评论