简体   繁体   English

为什么我的 Function 内部的 While 循环一直返回真值?

[英]Why Does My While Loop Inside Function Keep Returning True?

I am trying to learn while loops.我正在尝试学习 while 循环。

To practice, I created a simple while loop with an If statement inside a function to check and see if a word is a palindrome.为了练习,我在 function 中创建了一个带有 If 语句的简单 while 循环,以检查单词是否为回文。 For some reason, even if the word is not a palindrome, it keeps returning True.出于某种原因,即使这个词不是回文,它也会一直返回 True。

I expected the output of the print function on the last line to be False:我预计最后一行打印 function 的 output 为 False:

from collections import deque

word = "tacrocat"

def check_palindrome(word):
    d = deque(word)
    while len(d) > 1:
        if d.pop() == d.popleft():
            return True
    return False

print(check_palindrome(word))

NOTE: When I change the if statement evaluation to ",=", change the return statement inside the if statement to False, and change the return statement in the while loop to True.注意:当我将 if 语句评估更改为“,=”时,将 if 语句中的 return 语句更改为 False,并将 while 循环中的 return 语句更改为 True。 it seems to accurately detect palindromes - but I have no idea why.它似乎可以准确地检测回文 - 但我不知道为什么。

Once it finds a return True it will come out of the function.一旦找到return True ,它就会从 function 中出来。

In the first iteration it will compare t with t and exit the function.在第一次迭代中,它将tt进行比较并退出 function。

In your case it comes out at first letter.在你的情况下,它出现在第一个字母。

rather you can do as stated by @Goodies in comment相反,您可以按照@Goodies 在评论中所述进行操作

from collections import deque

word = "tacrocat"

def check_palindrome(word):
    d = deque(word)
    while len(d) > 1:
        if d.pop() != d.popleft():
            return False
    return True
print(check_palindrome(word))

This is happening because it is returning True if any one of the characters on either side of centre are equal.发生这种情况是因为如果中心两侧的任何一个字符相等,它就会返回True This is probably confusing but basically it checks if any of the letters are mirrored not all of them because the return True exits early.这可能令人困惑,但基本上它会检查是否有任何字母被镜像,而不是全部,因为return True提前退出。
This means that, actually, your function does not always return True , for example a word like "word" would return false.这意味着,实际上,您的 function 并不总是返回True ,例如像“word”这样的词会返回 false。
To fix this, rather than return True when one match is found and otherwise return False , you could return False if any do not match and else return True like so (see comment above by @Goodies):要解决此问题,而不是在找到一个匹配项时返回True否则返回False ,您可以在任何匹配时返回False ,否则返回True就像这样(请参阅@Goodies 上面的评论):

from collections import deque

word = "tacrocat"

def check_palindrome(word):
    d = deque(word)
    while len(d) > 1:
        if d.pop() != d.popleft():
            return False
    return True

print(check_palindrome(word))

which (correctly) outputs:哪个(正确)输出:

False

If the program is written like this:如果程序是这样写的:

from collections import deque

word = "tacrocat"

def check_palindrome(word):
    d = deque(word)
    while len(d) > 1:
        if d.pop() == d.popleft():
            return True
    return False

print(check_palindrome(word))

At iteration-1:在第 1 次迭代中:

Since both the first character('t') and last character('t') in the deque are equal it will enter the if condition and return True.由于双端队列中的第一个字符('')和最后一个字符('t')相等,它将进入 if 条件并返回 True。 When a return statement is executed in a function, then the control comes out of the function. In other words, as soon as return True statement is executed, the control comes back to print statement without executing remaining iterations of while loop and since we returned True, so True will be printed as output.当在 function 中执行 return 语句时,控制从 function 中退出。换句话说,一旦执行 return True 语句,控制将返回 print 语句,而不执行 while 循环的剩余迭代,因为我们返回True,所以 True 将打印为 output。

Let's analyze second program:我们来分析第二个程序:

from collections import deque

word = "tacrocat"

def check_palindrome(word):
    d = deque(word)
    while len(d) > 1:
        if d.pop() != d.popleft():
            return False
    return True

print(check_palindrome(word))

At iteration-1:在第 1 次迭代中:

Current deque: [t,a,c,r,o,c,a,t]

We are popping both first element and last element and checking whether they are not equal in if condition.我们同时弹出第一个元素和最后一个元素,并检查它们在 if 条件下是否不相等。 Since 't' and 't' are equal, if condition will not execute and while loop will continue.由于 't' 和 't' 相等,if 条件将不会执行并且 while 循环将继续。

At iteration-2:在迭代 2:

Current deque: [a,c,r,o,c,a]

Since 'a' and 'a' are equal, if condition will not execute and while loop will continue.由于 'a' 和 'a' 相等,if 条件将不会执行并且 while 循环将继续。 Both first and last elements are popped (pop and popleft)第一个和最后一个元素都弹出(pop 和 popleft)

At iteration-3:在第 3 次迭代中:

Current deque: [c,r,o,c]

Since 'c' and 'c' are equal, if condition will not execute and while loop will continue.由于 'c' 和 'c' 相等,if 条件将不会执行并且 while 循环将继续。 Both first and last elements are popped (pop and popleft)第一个和最后一个元素都弹出(pop 和 popleft)

At iteration-4:在第 4 次迭代中:

Current deque: [r,o]

Since 'r' and 'o' are not equal, if condition will execute and return False statement is executed.由于 'r' 和 'o' 不相等,if 条件将执行并执行 return False 语句。 So, the function check_palindrome will terminate with return value as False and so we get output as False.因此,function check_palindrome 将以返回值为 False 终止,因此我们得到 output 为 False。

The second program is correct because to check if a word is palindrome or not, we need to check all letters whether they are satisfying the condition or not.第二个程序是正确的,因为要检查一个单词是否是回文,我们需要检查所有字母是否满足条件。 Just checking only the first and last character of a word and if they are equal, then it doesn't mean the remaining letters are same.只检查单词的第一个和最后一个字符,如果它们相等,则并不意味着其余字母相同。 We need to check them too.我们也需要检查它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM