python學習之while語句

while語句在一個條件爲真的情況下,while語句允許你重複執行一塊語句。直接看例子:

#!/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'

 

當輸入23時,程序執行done,結束,否則一直在循環(當然輸入非整數時語法錯誤,程序會跳出的)。

運行結果:

$ python while.py
Enter an integer : 50
No, it is a little lower than that.
Enter an integer : 22
No, it is a little higher than that.
Enter an integer : 23
Congratulations, you guessed it.
The while loop is over.
Done

//這裏要說明的是python語言對空格要求的很嚴格,必須是對應的,否則語法是不正確的。例如上面例子中

……

if guess == number:
        print 'Congratulations, you guessed it.'
        running = False # this causes the while loop to stop
    elif guess < number:
……

編寫成

if guess == number:
        print 'Congratulations, you guessed it.'
         running = False # this causes the while loop to stop
    elif guess < number:
運行結果:

File "while.py", line 12
    running = False # this causes the while loop to stop
    ^
SyntaxError: invalid syntax

 

這一點不像其他語言那麼靈活的。

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