我认为这与使用 input(( 函数有关吗? 我读过其他答案,表明这是因为您正在尝试重新定义str,但正如您所看到的,我在这里没有这样做。我知道有更好的方法可以实现此任务的目标,但我只是用它来探索python,而不是寻求最佳状态。
#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.)
repeat = True
while repeat == True:
print(" enter a string " )
input = str(input())
#split string into an array of characters
string = list(input)
print(string)
stringReverse = list(input[::-1])
print(stringReverse)
#loop an check if the first char matches last char up to the halfway
length = len(string)
#get the halfway point
if length%2 == 0:
#halfway point is even
halfway = length/2
else:
halfway=(length+1)/2 #we are going to ignore this character
print(halfway)
print(stringReverse)
#loop through each character in string
currentpost = 0
palindrome=True
for index, letter in enumerate(string):
#print(str(index)+ ' ' + letter)
#print(stringReverse[index])
print( letter +stringReverse[index])
if letter == stringReverse[index]:
print('match')
else:
print('break')
palindrome = False
print(palindrome)
print("continue y/n")
answer = str(input())
print(answer)
if answer =="n":
repeat = False
错误消息如下
Traceback (most recent call last):
File "/Users/nigel/Desktop/pythonshit/exercises6.py", line 48, in <module>
answer = str(input())
TypeError: 'str' object is not callable
这是因为您在代码的第二行上命名了变量input
。发生的情况是,变量input
由于input = str(input())
而成为str
,当你试图稍后在answer = str(input())
上调用它时,Python认为你正在尝试input
调用该字符串。
使用input = str(input())
将字符串分配给变量input
并隐藏函数input
。然后,当您调用input()
时,它是一个字符串对象,不可调用。
您的问题是scope
和变量阴影问题。
总之:
当你试图answer = str(input())
python认为input
是你在那里定义的变量input = str(input())
当你打算input()
函数时。
要解决您的问题,请执行以下操作:
将input = str(input())
更改为类似于my_input = str(input())
的内容,这样您就不会遇到阴影问题。