theArcticOcean

博观而约取,厚积而薄发

python的循环,pass和DocString
先来说说最简单的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.
>>> 


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/theArcticOcean/article/details/49943557
文章标签: python
个人分类: python
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

python的循环,pass和DocString

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭