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 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 >>>
def maxnum(a,b): if a>b: return a else : pass #return none statement print maxnum(23,45) print maxnum(45,23) >>> None 45 >>>
其全称是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. >>>