Python 为什么我没有得到以下代码的输出?

Python 为什么我没有得到以下代码的输出?,python,string,python-3.x,Python,String,Python 3.x,我没有得到jupyter笔记本中以下代码的输出。 这段代码基本上检查单词的长度是否均匀,并将其打印出来。 我发现在“new”(列表)中添加每个单词后,while循环甚至不起作用 我知道还有其他方法可以用更简单的方式实现这一点,但我希望它能起作用 st = 'Print every word in this sentence that has an even number of letters' new=[] i=0 for words in st.split(): new.append(

我没有得到jupyter笔记本中以下代码的输出。 这段代码基本上检查单词的长度是否均匀,并将其打印出来。 我发现在“new”(列表)中添加每个单词后,while循环甚至不起作用

我知道还有其他方法可以用更简单的方式实现这一点,但我希望它能起作用

st = 'Print every word in this sentence that has an even number of letters'
new=[]
i=0
for words in st.split():
    new.append(words)
l=len(st)
while i<=l:
    if len(new[i])%2==0:
        print(new[i])
        i=i+1
st='打印这个句子中每个字母数为偶数的单词'
新=[]
i=0
对于st.split()中的单词:
新增.追加(字)
l=len(st)

我不知道如何修复你的代码,因为它有太多的错误。刚刚写出了最接近的可能的解决方案

st = 'Print every word in this sentence that has an even number of letters'
words = st.split()

for w in words:
    if len(w)%2==0:
        print(w)

有几个问题。例如,
l=len(st)
应该是
l=len(new)
i问题是
i=i+1
发生在
if
语句内部。这意味着我永远不会超过0,因为第一个单词的长度是奇数。要解决此问题,请将i=i+1放在
if
语句之外

while i<=l:
    if len(new[i])%2==0:
        print(new[i])
    i=i+1

当i时,您会收到一个无限循环,因为第一个条件不满足,并且i不会增加。

您的代码有问题:
st='打印这个句子中每个字母数为偶数的单词'
new=[]#您可以在此处创建单词列表,而不是循环
i=0
对于st.split()中的单词:
新增.追加(字)
l=len(st)#len(新)

你能解释为什么吗(i@AshishRaju当然。你的句子中有13个单词,因为
i
是从0开始的,你只需要增加到12,因为如果你计算0,0到12实际上是13项。@AshishRaju所以
i=i+1
行的位置正确,但你只需要删除一个制表符(或四个空格)从前面开始,因此它与if语句内联
while i<=l:
    if len(new[i])%2==0:
        print(new[i])
    i=i+1
st = 'Print every word in this sentence that has an even number of letters'
new=[] # You can create the list of words here instead of a loop
i=0
for words in st.split():
    new.append(words)
l=len(st)    # len(new)
while i<=l:  # i < l (since indexing of i starts from 0 to n-1 length
    if len(new[i])%2==0:
        print(new[i])
        i=i+1 # this needs to be outside loop, since it will only increment if even word is found
st = 'Print every word in this sentence that has an even number of letters'
new = s st.split()
i = 0
l = len(new)
while i < l:
    if len(new[i])%2 == 0:
        print (new[i])
    #else:
    #    pass
    i = i+1 
st = "Print every word in this sentence that has an even number of letters"
new=[]
i=0
for words in st.split():
    new.append(words)
l=len(words)
while i<l:
    if len(new[i])%2==0:
        print(new[i])
    i=i+1
st="Print every word in this sentence that has an even number of letters"
[word for word in st.split() if len(word)%2==0]