Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading