Python:如何使用while循环并输出正确的字数

时间:2012-02-23 05:37:20

标签: python while-loop python-2.7 word-count

这是我到目前为止所做的:

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个单词时,它会保持该单词的数量并且不会改变。

5 个答案:

答案 0 :(得分: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 :(得分: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!" 

答案 2 :(得分: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!" 

答案 3 :(得分:0)

我认为您的代码段缺少部分。无论如何,您应该在wordCount之后评估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!" 

答案 4 :(得分:0)

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

xlen('hello')