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