0

これは私がこれまでに持っているものです:

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 語より多い場合も少ない場合も、その単語数が保持され、変更されません。

4

5 に答える 5

3

Python には他の言語のようなループがないためdo-while、このイディオムは関数の重複を防ぎraw_input、ループが少なくとも 1 回実行されるようにします。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!"
于 2012-02-23T05:52:32.413 に答える
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!" 
于 2012-02-23T05:47:33.263 に答える
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!" 
于 2012-02-23T05:47:52.897 に答える
0

あなたのコード スニペットにはパーツが欠けていると思います。とにかく、新しい値で更新されるようにwordCountafterを評価する必要があります。raw_input

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!" 
于 2012-02-23T05:51:28.327 に答える