所以我在这里四处寻找并找到了工作回文的代码
def isPalindrome():
string = input('Enter a string: ')
string1 = string[::-1]
if string[0] == string[(len(string)-1)] and string[1:(len(string)-2)] == string1[1:(len(string)-2)]:
print('It is a palindrome')
else:
print('It is not a palindrome')
isPalindrome()
所以我已经将输入更改为raw_input。它有效。
但是在评论中有一个更简单的代码:
def isPalindrome():
string1 = input('Enter a string: ')
string2 = string[::-1]
if string1 == string2:
return 'It is a palindrome'
return 'It is not a palindrome'
isPalindrome()
我收到了回读:
Traceback (most recent call last):
File "C:\Python27\idk1.py", line 8, in <module>
isPalindrome()
File "C:\Python27\idk1.py", line 2, in isPalindrome
string1 = input('Enter a string: ')
File "<string>", line 1, in <module>
NameError: name 'racecar' is not defined
所以我把它改成了raw_input,我根本不会工作。我很好奇为什么会这样?
答案 0 :(得分:5)
我的朋友,你有复制粘贴的问题。您复制了源代码,更改了变量名称但忘记检查整个程序中的变量使用情况:
def isPalindrome():
string1 = input('Enter a string: ')
string2 = string1[::-1] #notice it's string1, not string.
if string1 == string2:
[code]
答案 1 :(得分:0)
def isPalindrome():
string1 = raw_input('Enter a string: ')
string2 = string1[::-1]
if string1 == string2:
return 'It is a palindrome'
return 'It is not a palindrome'
在第3行中,它说string
而不是string1
。
答案 2 :(得分:0)
此代码对我有用...对于之前的帖子感到抱歉......
def isPalindrome():
string1 = raw_input('Enter a string: ')
string2 = string1[::-1]
if string1 == string2:
return 'It is a palindrome'
return 'It is not a palindrome'
print isPalindrome()
<强>输出:强>
Enter a string: madam
It is a palindrome