简体   繁体   中英

How to fix “TypeError: 'str' object is not callable” from list

I'm currently learning Python and I'm currently trying to create an item selection system where the item a user wants can manually input a single item from a list to have that item assigned to the variable "item". However, when I tried to input an item that doesn't exist, instead of the code looping back to the start of the code (it uses a "while" function), it produces an error message:

TypeError: 'str' object is not callable

I'm currently trying to practice manipulating python code in order to gain experience for a potential project; I've only learn't Python through the "Solo Learn" website for a few days now.

`

inventory=["SWORD","STEAK","BOMB"]
item="NONE"
inventoryselection=1
while inventoryselection==1:
 print("\nINVENTORY:")
 print(inventory)
 item=input("SELECT ITEM:")
 if(item in inventory):
  inventoryselection=0
 else:
  print=("ITEM NOT FOUND.")
  item="NONE"
print("ITEM:"+str(item))

`

The expected result would be that when the items above ("SWORD") is input into the item variable, that it will display the item name and finish the code and when a non-existent item is input, that it will print "ITEM NOT FOUND".

Instead, whilst inputting "SWORD" gives the expected result, inputting "APPLE" (A nonexistent entry in the list) gives out an error:

line 5, in <module> print("\\nINVENTORY:") TypeError: 'str' object is not callable

inventory=["SWORD","STEAK","BOMB"]
item="NONE"
inventoryselection=1
while inventoryselection==1:
 print("INVENTORY:")
 print(inventory)
 item=input("SELECT ITEM:")
 if(item in inventory):
  inventoryselection=0
 else:
  print("ITEM NOT FOUND.")
  item="NONE"
print("ITEM:"+item)

This will work you just use print function as str in your code after else condition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM