checkin 发表于 2020-11-10 22:08:09

小白救助

import operator
a = list(input("请输入一个正整数:"))
b = a[::-1]
if operator.eq(a,b):
    print("是一个回文数")
else:
    print("不是回文数")



import operator
a = list(input("请输入一个正整数:"))
b = a.reverse()
if operator.eq(a,b):
    print("是一个回文数")
else:
    print("不是回文数")

如上面两个判断回文数的代买,唯一的区别就是一个是切片的方式创建倒序的列表,后一个用的是reverse函数。可为什么前面一个能够实现功能第二个就永远输出不是回文数呢??
新手学习{:10_266:}{:10_266:}跪请大手子解答一下!!!

Twilight6 发表于 2020-11-10 22:15:19

本帖最后由 Twilight6 于 2020-11-10 22:21 编辑


列表的绝大多数方法是没有返回值的,所以第二个 a.reverse() 没有返回值 则默认返回 None

所以b = None 则 if 条件永远不会成立,你需要重新复制一份,对复制后的进行 reverse()

参考代码:
import operator
a = list(input("请输入一个正整数:"))
b = a[:]
b.reverse()
if operator.eq(a,b):
    print("是一个回文数")
else:
    print("不是回文数")

页: [1]
查看完整版本: 小白救助