2012-02-23 60 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')