当前位置: 首页 > 知识库问答 >
问题:

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

商品
2023-03-14

我试图使用while循环和索引检查回文,返回True或False。我知道,使用for循环,甚至只需一行就可以简单得多:return num[:-1]==num
(num是函数中的参数)单击此处查看代码图像

如果有人能告诉我我做错了什么,我很乐意用一段时间来完成这个循环:)

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

共有2个答案

崔琦
2023-03-14
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.
华锦
2023-03-14
def palindrome(s):
    i = 0
    while i <= len(s) / 2:
        if s[i] != s[-i - 1]:
            return False
        i += 1
    return True

这应该可以了。

 类似资料:
  • 本文向大家介绍Python While循环,包括了Python While循环的使用技巧和注意事项,需要的朋友参考一下 示例 甲while环会引起将要执行的循环语句,直到循环条件为falsey。以下代码将执行循环语句总共4次。 尽管上述循环可以轻松地转换为更优雅的for循环,但是while循环对于检查是否满足某些条件很有用。以下循环将继续执行直到myObject准备就绪。 while通过使用数字(

  • 我试图做一个程序,要求客户输入他们想要购买的项目的数量。程序然后找到小计和带税的总价。我对如何添加while循环感到困惑,这样它就会根据用户放置的物品数量不断询问物品的价格,然后将所有物品添加到一起。

  • 问题内容: 通常我们这样编码: 但是也可以按照以下方式做一些事情: 我想要这样做的真正原因是因为我想使用python-progressbar的自动检测maxval。他们喜欢 问题答案: 您可以与callable一起使用。(您应该传递两个参数,一个用于可调用对象,另一个用于前哨值) 注意 当没有剩余元素并且没有放置哨兵值时,它将阻塞。另外,就像-循环,并且与普通的容器循环不同,它将从队列中删除项目。

  • 我正在尝试使用Postman来验证API。我可以毫无问题地验证单个请求,并获得所需的输出。但是,我现在想进行负载测试,并运行相同的调用5次。 我尝试使用for和while循环,但是Postman给出了一个错误。

  • Python 中,while 循环和 if 条件分支语句类似,即在条件(表达式)为真的情况下,会执行相应的代码块。不同之处在于,只要条件为真,while 就会一直重复执行那段代码块。 while 语句的语法格式如下: while 条件表达式:     代码块 这里的代码块,指的是缩进格式相同的多行代码,不过在循环结构中,它又称为 循环体。 while 语句执行的具体流程为:首先判断条件表达式的值,

  • 问题内容: 我也在学习Java和android。我们可以在while循环中执行的几乎所有事情都可以在while循环中执行。 我发现一个简单的条件,使用while循环比for循环更好 如果我必须在程序中使用counter的值,那么我认为while循环要比for循环好 使用while循环 在这种情况下,我发现while循环要比for循环好,因为如果要在for循环中实现相同的效果,则必须将counter