Python:如何使用while循环并输出正确的单词con

2024-09-30 20:23:49 发布

您现在位置:Python中文网/ 问答频道 /正文

到目前为止,我得到的是:

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!" 

问题是我明白了:

^{pr2}$

当我输入多于或少于5个单词时,它会保持该单词的计数,并且不会更改。


Tags: theinputrawleniscount单词sentence
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!"

你需要重新整理一下你的逻辑:

# 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!" 

接受输入后,应在循环内更新变量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!" 

相关问题 更多 >