如何使用while循环python检查回文

时间:2015-11-11 20:14:24

标签: python indexing while-loop palindrome

我正在尝试使用while循环和索引来检查回文,返回True或False。我知道使用for循环甚至只需一行就可以做得更简单:     return num [:: - 1] == num
(num是函数内的参数) click for image of code here

如果有人能说明我在这里做错了什么会很棒,我想用一个循环完成这个:)

顺便说一句,回文是一个单词或短语,可以通过相反的方式读取,例如:水平,赛车,旋转器等

2 个答案:

答案 0 :(得分:1)

def palindrome(s):
    i = 0
    while i <= len(s) / 2:
        if s[i] != s[-i - 1]:
            return False
        i += 1
    return True

这应该这样做。

答案 1 :(得分:0)

str = input("Enter a string: ") #taking a string from user & storing into variable.
li = list(str) #converting the string into list & storing into variable.
ln = len(li) #storing the length of the list into a variable.
revStr = "" #defining an empty variable (which will be updated & will be final result to check palindrome).
i = ln - 1 #value of i will be used in loop.

while i >= 0: #here logic is to start from right to left from the list named "li". That means going from last to first index of the list till the index value is "0" of the "li" list.
    revStr = revStr + li[i] #concatenating & updating the "revStr" defined variable.
    i = i - 1 #decreasing the value of i to reach from the last index to first index.
str = str.lower() #converting value into lowercase string.
revStr = revStr.lower() #converting the final output into lowercase string to avoid case sensitive issue.

if str == revStr: #the two string is same or not?
    print(str, ", is PALINDROME!") #if same.
else:
    print(str, ", isn't PALINDROME!") #if not same.