所以我在这里四处寻找,我找到了工作回文的代码
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()
Run Code Online (Sandbox Code Playgroud)
所以我已经将输入更改为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()
Run Code Online (Sandbox Code Playgroud)
我收到了回读:
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
Run Code Online (Sandbox Code Playgroud)
所以我把它改成了raw_input,我根本不会工作.我很好奇为什么会这样?
我的朋友,你有复制粘贴的问题.您复制了源,更改了变量名称但忘记检查整个程序中的变量使用:
def isPalindrome():
string1 = input('Enter a string: ')
string2 = string1[::-1] #notice it's string1, not string.
if string1 == string2:
[code]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
413 次 |
| 最近记录: |