什么是回文数:
有如许一类数,他们顺着看和倒着看是雷同的数,比方:12321,1221,2332等,如许的数字就称为:回文数。
例子:输入一个5位数,推断它是不是是回文数。即12321是回文数,个位与万位雷同,十位与千位雷同。找出5位数中一切的回文数:
要领一、运用for轮回
# 找出5位数中一切的回文数: for i in range(10000,100000): # 遍历一切的5位数 s = str(i) # 将数字转换成字符串范例,即可以用索引掏出每一位上的数字 if s[0] == s[-1] and s[1] == s[-2]: # 字符串的索引 print(i)
相干引荐:《Python视频教程》
要领二、定义函数
def is_huiwen(n): reversed_str= str(n) return reversed_str == reversed_str[-1::-1] # output = filter(is_huiwen,range(10000,100000)) print(list(output))
·用户本身输入一个5位数,推断是不是是回文数:
# 输入一个5位数,推断它是不是是回文数: a = int(input(" 请输入一个5位整数:")) s = str(a) if s[0] == s[-1] and s[1] == s[-2]: print(" %d 是一个回文数!" % a) else: print(" %d 不是一个回文数!" % a)
·推断恣意一个整数是不是是回文数:
n = int(input('请输入一个整数:')) s = str(n) f = True for i in range(len(s)//2): if s[i] != s[-1-i]: f = False break if f: print('%d 是一个回文数' % n) else: print('%d 不是一个回文数' % n)
以上就是python怎样推断是不是是回文数的细致内容,更多请关注ki4网别的相干文章!