while-控制流

程序while.py

-----------------------------------------------------------------------------------------------

#!/usr/bin/python
# Filename: while.py

number = 23
running = True

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

    if guess == number:
        print 'Congratulations, you guessed it.'
        running = False # this causes the while loop to stop
    elif guess < number:
        print 'No, it is a little higher than that'
    else:
        print 'No, it is a little lower than that'
else:
    print 'The while loop is over.'
    # Do anything else you want to do here

print 'Done'

---------------------------------------------------------------------------------------------

while語句沒有什麼特別的地方。只要注意:

當while循環條件變爲False的時候,else塊才被執行。這甚至也可能是在條件第一次被檢驗的時候。如果while循環有一個else從句,它將始終被執行,除非遇到break語句。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章