1

I'm trying to call a function that I defined in the code, however, it's saying that it's not defined? The error is where I have "add_to()" it's saying it's not defined. What am I doing wrong here?

grocery_list = ['salmon', 'beef', 'eggs', 'milk']

print(grocery_list)
question = input("Would you like to add anything to the list?: ")
if question == "yes" or "y" or "Y":
    add_to()
else:
    print("Enjoy your shopping")


def add_to():
    input("Please enter the item you'd like to add: ")
    grocery_list.append(str(input))


print(grocery_list)
2
  • Put the definition of add_to at the top. Commented Mar 28, 2019 at 6:00
  • Wow, I feel stupid. thank you Commented Mar 28, 2019 at 6:07

1 Answer 1

1

You did function declaration after the function call. Please follow :PEP8 for more information and secondly if take any input from user, you need to store in some variable to use any way. Here is the code that add item perfectly.

grocery_list = ['salmon', 'beef', 'eggs', 'milk']

def add_to():
    s= input("Please enter the item you'd like to add: \n")
    grocery_list.append(str(s))

print(grocery_list)
question = input("Would you like to add anything to the list?: \n")
if question == "yes" or "y" or "Y":
    add_to()
else:
    print("Enjoy your shopping")



print(grocery_list)

Output :

['salmon', 'beef', 'eggs', 'milk']
Would you like to add anything to the list?:
yes
Please enter the item you'd like to add: 
yourhead
['salmon', 'beef', 'eggs', 'milk', 'yourhead']
Sign up to request clarification or add additional context in comments.

5 Comments

That's another thing I wasn't struggling to figure out. Thank you! Can you explain why I need to add the (str part? Also what's the point of using \n to start a new line when I don't need a new line? Is it just good in practice?
Had to wait to be able to do it. Just did both, thanks.
Thanks, Okay \n is for good code readability. You need to give \n with input() and lets say in future if their is more confusing input user is giving which is long input and mixture of string and int, then you have to give \n
Okay and the point of (str) is just to let it know that they are inputting text and that it can only be text, correct?
Its depend on developer(you), whether in which form you want to grab input from the user whether in form of int, float, string..etc

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.