2012-02-23 58 views
0

這是我到目前爲止有:的Python:如何使用while循環和輸出正確的字數

while len(words) != 5: 
     words = raw_input("Enter a 5 worded sentence: ").split() 
     print "Try again. The word count is:", wordCount 
if len(words) == 5: 
     print "Good! The word count is 5!" 

問題是,我得到這個:

Enter a 5 worded sentence: d d d d 
Try again. The word count is: 4 
Enter a 5 worded sentence: d d d d d d 
Try again. The word count is: 4 
Enter a 5 worded sentence: d d d d d 
Try again. The word count is: 4 
Good! The word count is 5! 

當我進入更或少於5個字,它保持該字數並不會改變。

+0

你在哪裏初始化變量'wordCount'? – 2012-02-23 05:39:57

+0

我把它放在while循環之前。 wordCount = len(文字) – user1227404 2012-02-23 05:41:47

+0

請確保您發佈生成您的輸出的實際代碼。現在,你的代碼會失敗,因爲在測試長度之前未定義「單詞」。 – 2012-02-23 05:59:56

回答

1

你只需要重新整理你的一些邏輯:

# prompt before entering loop 
words = raw_input("Enter a 5 worded sentence: ").split() 
while len(words) != 5: 
     print "Try again. The word count is:", len(words) 
     words = raw_input("Enter a 5 worded sentence: ").split() 

# no need to test len again 
print "Good! The word count is 5!" 
0

變量應的wordCount循環內進行更新,你接受輸入後。只有這樣它纔會反映出新的價值。這樣的事情: -

while len(words) != 5: 
    words = raw_input("Enter a 5 worded sentence: ").split() 
    wordCount = len(words) 
    print "Try again. The word count is:", wordCount 
if len(words) == 5: 
    print "Good! The word count is 5!" 
0

我認爲你的代碼段缺少部分。無論如何,您應該在raw_input之後評估wordCount,以便使用新值更新它。

wordCount = 0 
while wordCount != 5: 
    words = raw_input("Enter a 5 worded sentence: ").split() 
    wordCount = len(words) 
    print "Try again. The word count is:", wordCount 

print "Good! The word count is 5!" 
+0

謝謝!我忘了那個wordCount = 0. – user1227404 2012-02-23 05:57:33

+0

那麼你可以接受答案,如果它是你想要的。 – 2012-02-23 06:04:36

3

因爲Python沒有do-while循環像其他一些語言中,這個成語防止raw_input功能的重複,並確保循環至少執行一次。獲取新輸入後,請務必更新word_count

while 1: 
    words = raw_input("Enter a 5 worded sentence: ").split() 
    word_count = len(words) 
    if word_count == 5: break 
    print "Try again. The word count is:", word_count 
print "Good! The word count is 5!" 
+1

我們可不可以教新手寫'醜陋'這樣的醜陋的東西嗎? – 2012-02-23 06:48:42

+0

這是一個常見的成語。 – 2012-02-23 07:03:34

+0

這並不正確。這嚴重違反了Zen IMHO。 – 2012-02-23 07:05:07

0
def xlen(string_data): 
    try: 
     count = 0 
     while 1: 
      string_data[count] 
      count = count + 1 
    except(IndexError): 
     print count 

xlen('hello')