Python报错TypeError: 'str' object is not callable的原因及解决求助
问题分析与解决
错误原因
你在代码里误用Python内置的input()函数名作为变量名:
input = input('What would you like to buy?\n')
第一次执行这行时,input被赋值为用户输入的字符串。后续执行answer = input('Would you like to continue shopping?\n')时,你实际是在尝试调用一个字符串对象,而字符串无法被当作函数调用,因此抛出TypeError: 'str' object is not callable错误。
修复步骤
修改变量名,避免覆盖内置函数
将存储用户输入的变量名从input改为其他名称,比如user_input,同步更新后续引用该变量的代码:user_input = input('What would you like to buy?\n') user_input = user_input.lower() # 同步修改判断逻辑中的变量名 for item in store: if user_input == item[0]: print(f'That will be {item[1]} dollars.')修正条件判断的逻辑错误
你代码中的if answer == 'n' or 'no':写法存在逻辑漏洞——无论answer是什么值,这个条件都会返回True(因为'no'本身是布尔真值)。正确写法应为:if answer == 'n' or answer == 'no': isBuying = False # 或者更简洁的写法 if answer in ['n', 'no']: isBuying = False
完整修复后的代码
isBuying = True # Create a map for our store's inventory. Each item in our store will have a string name and a floating point number for its price. store = [('arrows', 20.00), ('bombs', 40.00), ('heart container', 120.00), ('sword', 100.00), ('potion', 15.00)] # Define a function to print out the store's inventory. This function will take in an inventory. def PrintStore(inventory): # For every item in the inventory, it will print out the item name and price in our formatted way. for item in inventory: print(' ' * 4 + item[0] + '.' * 3 + ' ' * 4 + str(item[1])) while isBuying: # Use our function to print out our store's inventory. PrintStore(store) # Ask the user what they would like to buy and store the input in a variable. Lowercase it to prevent case sensitivity. user_input = input('What would you like to buy?\n') user_input = user_input.lower() # For every item in our store, check to see if our input is equal to the item's name. If it is, print out the item's price. for item in store: if user_input == item[0]: print(f'That will be {item[1]} dollars.') answer = input('Would you like to continue shopping?\n') answer = answer.lower() if answer in ['n', 'no']: isBuying = False
内容的提问来源于stack exchange,提问作者Rodrigo Ponce
相关产品推荐
相关产品推荐

