Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (2015) Shopping List App Second Shopping List App

Youssef Moustahib
Youssef Moustahib
7,779 Points

inside the function or outside?

When I add "mylist = []" to the outside of a function and run the script and add an item, it works fine, but when I add "mylist = []" to the inside of function "newlist()" I get an error saying " name 'mylist' is not defined"

Why is this? Please check screen shot, under "shoppinglist2.py" Thank you.

ps. is there a simpler way to post screenshots also? Thanks

https://w.trhou.se/z8dq3dakqg

1 Answer

Hi, Youssef! The reason you're getting that error is that a variable of any kind created inside one function is not automatically a global variable. So even though the addtolist function is called inside the newlist function, it can't see the mylist variable because it isn't globally available when it moves to that part of your code. The fix is super easy: Inside your newlist() function, before you define the mylist variable, globalize the mylist variable. An example with your code would be:

    showhelp()
    global mylist
    mylist =[]
    while True:

Also: sharing your workspace is - in my opinion - the best way to do something like this because it allows people to fork it, run it and see exactly what's happening, make sure their suggestion for fixing it will work before they post it, etc. and that's exactly what you'd do in a working environment where you're using github or some other repository to share code with your peers.