Why do I get this error, and how do I fix it?

Question:

Here is my code:

list1 = ['monkey', 'banana', 'pizza']
list2 = []

for x in list1:
    input = input(f"Do you want to add {x} to list 2? [y/n] ")
    if input == "y" or input == "Y":
        list2.append(x)
    if input == "n" or input == "N":
        continue

print(list2)

I want to go through list1 and ask if each thing should be added to list2, but I get this error:

example.py 5 <module>
input = input(f"Do you want to add {x} to list 2? [y/n] ")

TypeError:
'str' object is not callable

The error happens when I give a input. Why do I get this error, and what can I do to fix it?

Asked By: MoonGoose

||

Answers:

You are reassigning input, a default function in Python. You are then trying to call this function, but it has been reassigned to a string, causing your error. This is not recommended, and to mitigate this issue choose another variable name.

You can also simplify your code by using str.lower(). Along with this, the second if condition is not needed.

list1 = ['monkey', 'banana', 'pizza']
list2 = []

for x in list1:
    user_input = input(f"Do you want to add {x} to list 2? [y/n]")
    if user_input.lower() == "y":
        list2.append(x)

print(list2)
Answered By: KetZoomer

On the second iteration of your list, you are trying to use the function "input".

But on the first iteration of your list, you’ve already assigned a string to input.

So during your second iteration, "input" no longer gives you the function, it gives you the string and you are trying to "call" it using the parens()

Answered By: dameshgarm
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.