打开JUPTER NOTEBOOK,新建一个PYTHON文档。
n = input("Please input string: ") print(n)
我们首先让用户输入要进行判断的字符串,然后打印出来查看一下。
n = input("Please input string: ") is_palidrome = n[::-1] if n == is_palidrome: print("This is a palidrome.") else: print("This is not a palidrome.")
我们可以用IF语句来进行判断,判断倒向的是否等于正向的即可。
n = input("Please input string: ") if n == n[::-1]: print("This is a palidrome.") else: print("This is not a palidrome.")
其实可以简化一下流程。
def reverse(n): a = "" for i in n[::-1]: a = a + i return a n = input("Please input string: ") a = reverse(n) if n == a: print("This is a palidrome.") else: print("This is not a palidrome.")
也可以定义一个新的FUNCTION,然后进行判断。
def reverse(n): a = "" for i in range(len(n)): a = a + n[len(n)-1-i] return a n = input("Please input string: ") a = reverse(n) if n == a: print("This is a palidrome.") else: print("This is not a palidrome.")
我们可以利用长度范围不断往回减去范围值,得到反向的字符串。
def reverse(n): a = "" for i in range(len(n)): a = a + n[len(n)-1-i] return a n = input("Please input string: ") a = reverse(n) if n == a: print("This is a palidrome.") else: print("This is not a palidrome.")
继续做多种输入来进行判断。