Python -- while的作用(未

发布时间:2019-06-24 15:53:34编辑:auto阅读(1410)

    1,判断条件(例如保证输入)


    1. import math 
    2. #Get base 
    3. inputOK = False 
    4. while not inputOK: 
    5.     base = input('Enter base: '
    6.     if type(base) == type(1.0): inputOK = True 
    7.     elseprint('Error. Base must be floating point number.'
    8. #Get Height 
    9. inputOK = False 
    10. while not inputOK: 
    11.     height = input('Enter height: '
    12.     if type(height) == type(1.0): inputOK = True 
    13.     elseprint('Error. Height must be floating point number.'
    14. hyp = math.sqrt(base*base + height*height) 
    15. print 'Base: '+str(base)+',height: '+str(height)+', hyp: '+ str(hyp) 

    注意inputOK,很好读的代码吧?是MIT计算机科学及编程导论上的作业。抽时间去网易公开课去看看。

    2,达到条件才输出


    1. def calcE(): 
    2.     x = y = 1 
    3.     sum = 0 
    4.     while (sum < 4000000): 
    5.         sum += (x + y) 
    6.         x, y = x + 2 * y, 2 * x + 3 * y 
    7.     return sum  

    这个没什么好说的、很清晰。

     

关键字