程序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語句。