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

由于 Pythondo-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!"
于 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

我认为您的代码片段缺少部分。无论如何,您应该评估wordCountafterraw_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 回答
0
def xlen(string_data):
    try:
        count = 0
        while 1:
            string_data[count]
            count = count + 1
    except(IndexError):
        print count

xlen('hello')
于 2016-10-10T13:58:01.487 回答