2010-08-24 71 views
-3

一旦程序打印,它就會關閉。如何讓它返回到代碼的頂部,以便它循環,無限期地詢問用戶名?如何循環此程序?

代碼:

from time import sleep 

name = raw_input ("Please enter your name: ") 

print "Hello", name, "- good to see you!" 
sleep(2.00) 

僞代碼:

from time import sleep 

A 
name = raw_input ("Please enter your name: ") 

print "Hello", name, "- good to see you!" 
sleep(2.00) 
return to A 
+5

你甚至讀過關於python的一件事嗎?你怎麼知道如何在不知道什麼是循環的情況下導入模塊 – Falmarri 2010-08-24 03:20:33

+0

當然,僞代碼使用goto。 「Dijkstra不會喜歡這個」;) – delnan 2010-08-24 05:42:32

+0

這是我正在開發的程序的測試程序。我遇到了一個問題,所以我試圖在簡化的層面上獲得我想要的行爲。由於正常循環方法不起作用。 – rectangletangle 2010-08-27 00:47:10

回答

6
while True: 
    # do something 
    # do something else 
    # do more things 

對於你的具體例子:

from time import sleep 

while True: 
    name = raw_input ("Please enter your name: ") 

    print "Hello", name, "- good to see you!" 
    sleep(2.00) 

該環路的總的格式如下:

while <condition>: 
    <code> 

每個循環運行時,它會檢查是否<condition>是真值(True明明是的,但你也可以有像foo < 3或類似的更復雜的條件)。如果是,則運行<code>,然後重複。如果不是,那麼它完成循環並在程序的其餘部分繼續。

還有更多關於循環in the Python documentation的信息。

0
from time import sleep 

while True: 
    name = raw_input ("Please enter your name: ") 

    print "Hello", name, "- good to see you!" 
    sleep(2.00) 
+0

似乎我有點慢 – acqu13sce 2010-08-24 03:15:20

-3

兩種方法可以實現。 1.使用「do-while」 2.使用「while(true)if if break」

+0

Python沒有do-while – Falmarri 2010-08-24 08:21:42