我是一个新手python编码学习的乐趣。我想知道为什么这个程序很难输出正确的输出。我认为问题在于程序的结尾“if list==inverselist:”。 我总是得到一个输出,告诉我这个词是回文,即使它不是(例如老虎)
#Exercise 6 - Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.)
possiblepalindrome = str(input("Put in the possible palindromic statement here: "))
print(possiblepalindrome)
list=[]
for x in possiblepalindrome: #put each individual string character in a new list as its own element
list.append(x)
print ('this is list', list)
for x in list: #Removes all spaces so multiple word/sentences can be palindrome
if x is ' ':
list.remove(' ')
print('this is with removed spaces' , list)
def reverselist(argument): #This is a function. We put in some list, then the list is reversed, and is spat back out
argument.reverse()
return argument
inverselist = reverselist(list) #We use the reverselist function to make an inverse list of the palindrome
print('this is inverselist',inverselist)
if list == inverselist:
print('Congratulations ', '"', possiblepalindrome, '"', ' is a palindrome!')
else:
print('Unfortunately', '"', possiblepalindrome, '"', 'is not a palindrome.')
你发布了太多的代码,而没有费心去测试它
reverselist
没有按您期望的方式工作。它反转输入列表,这是一个可变对象输出:
简而言之,您颠倒了列表,然后将结果与列表本身进行比较
注:
list
改为word
李>您的功能可以是:
首先,在Python中为列表命名
list
很诱人,但很危险,因为您将无法调用list()
构造函数基本上你的代码可以这样简化
list
和inverselist
有对同一列表的引用。您需要克隆list
只需更改
reverselist
函数完整代码:
相关问题 更多 >
编程相关推荐