2012-07-24 84 views
1

如果這是一個荒謬的問題,我很抱歉,但我只是學習python,我無法弄清楚這一點。 :)蟒蛇雖然循環故障

我的程序應該打印用戶輸入的任何狀態的資本。有時它會連續工作十次,其他時間連續工作三次,然後它會在您鍵入狀態後停止。如果我重新啓動它並輸入停止的狀態,它將工作得很好....隨機次數然後它會再次停止。我究竟做錯了什麼?我的代碼也很糟糕?我不知道使用什麼類型的代碼,所以我只是在我可以開展工作的任何地方扔掉。

x = str(raw_input('Please enter a sate: ')) 
    while x == 'Alabama': 
     print 'Montgomery is the capital of', x 
     x = str(raw_input('Please enter a state: ')) 
    while x == 'Alaska': 
     print 'Juneau is the capital of', x 
     x = str(raw_input('Please enter a state: '))     
    while x == 'Arizona': 
     print 'Phoenix is the capital of', x 
     x = str(raw_input('Please enter a state: ')) 
    while x == 'Arkansas': 
     print 'Little Rock is the capital of', x 
     x = str(raw_input('Please enter a state: '))' 
+1

有人試圖幫助你的代碼格式化。你應該讓他們自己做,或者自己做,以便代碼實際上是可讀的。 – crashmstr 2012-07-24 17:33:11

回答

5
  1. 你的意思是一個大while循環內使用多個if語句,而不是多個while循環。在這段代碼中,一旦你經歷了一個while循環,你就再也回不到它了。只要您按字母順序給出州名,此代碼將只能工作

  2. 不要這樣做!還有一個很多更好的方法來使用python dictionaries

    capitals = {"Alabama": "Montgomery", "Alaska": "Juneau", "Arizona": "Phoenix", "Arkansas": "Little Rock"} 
    while True: 
        x = str(raw_input('Please enter a state: ')) 
        if x in capitals: 
         print capitals[x], "is the capital of", x 
    

否則,到頭來你會爲50對幾乎相同的線,如果你想覆蓋所有50個州。

+0

非常感謝你!我們還沒有覆蓋字典,我應該等到那時試圖做到這一點大聲笑 – user1549425 2012-07-24 17:42:46

+0

你非常歡迎。如果回答您的問題,請不要忘記[接受](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 – 2012-07-24 17:48:26

1

我不認爲你瞭解while循環。基本上,

while condition: 
    dostuff() 

做的東西,而條件爲真。只要條件不成立,你就繼續前進。我認爲你在尋找什麼是一樣的東西:

x=True 
while x 
    x=raw_input('please enter a state'): 
    if x == 'Alabama': 
     ... 
    elif x == 'Alaska': 
     ... 

這將永遠循環下去,直到用戶點擊剛剛進入(bool('')在Python False

然而,一個更好的辦法做到這一點會可以使用字典:

state_capitals={'Alabama':'Montgomery', 'Alaska':'Juneau'} 
x=True 
while x 
    x=raw_input('please enter a state'): 
    print '{0} is the capital of {1}'.format(state_capitals[x],x) 

用這種方式,將引發一個KeyError當不良資產被賦予(你能趕上使用try塊,如果你想)。

+0

謝謝你的回答!你們真棒! – user1549425 2012-07-24 17:44:06

0

在所有誠實方面,這是更糟的可怕。但是,你很可能是初學者,因此會發生這樣的事情。

對於這個任務,你應該使用dict包含國家=>資本映射和讀國名一次

capitals = {'Alabama': 'Montgomery', 
      'Alaska': 'Juneau', 
      ...} 
state = raw_input('Please enter a state: ') 
if(state in capitals): 
    print '{0} is the capital of {1}'.format(capitals[state], state) 
else: 
    print 'Sorry, but I do not recognize {0}'.format(state) 

如果你想使用一個while循環,使用戶可以輸入多個如果用戶不輸入任何內容,則可以將整個代碼包裝在while True:區塊中,並在raw_input之後緊接着使用if not state: break來中斷循環。

+0

謝謝你回答我的問題,我完全是一個初學者大聲笑 – user1549425 2012-07-24 17:45:52