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

NameError when Inputting to List

When I run the code below, the shopping list program runs mostly as expected. However, unless I surround the new items (including DONE, HELP and show) in quote marks, I get a NameError.

Why is this happening?

# List Creation
shopping_list = []

# Help
def show_help():
    print("""
Add items to the list when promted. 
To end the list type 'DONE'.
To view the list type 'SHOW'.
To view this help prompt, type 'HELP'.
""")

show_help()

# View
def view_list():
    print(shopping_list)

while True:
    new_item = input("> ")
    if new_item.upper() == 'DONE':
        break
    elif new_item.upper() == 'HELP':
        show_help()
        continue
    elif new_item.upper() == 'VIEW':
        view_list()
        continue
    shopping_list.append(new_item)
print(shopping_list)

2 Answers

The issue seems to be my Mac's default preference for Python 2. If I use the common python3 to open the file, it runs just fine.

Jakes-MacBook-Air:~ jakekeeley$ type -a python python3
python is /usr/bin/python
python3 is /Library/Frameworks/Python.framework/Versions/3.6/bin/python3

I'm not sure why it runs at all in Python 2, though.

You can change that but I don't think it's wise to. Just remember to call python3. Some pointers in here about changing this behaviour.

Hi Jacob,

This is working fine for me in PyCharm. One little thing; your instructions say to type SHOW to see the list, but the code wants you to use VIEW.

Steve.

Strange... This is what I get when I try and run it from Terminal.

Thanks for the heads-up on SHOW vs VIEW - I've changed that now.

bash output

Must be a local issue - here's my trace showing adding items and then printing them and exiting. I'm using Python 3.6.1 inside PyCharm.

Add items to the list when promted. 
To end the list type 'DONE'.
To view the list type 'SHOW'.
To view this help prompt, type 'HELP'.

> eggs
> bread
> milk
> view
['eggs', 'bread', 'milk']
> done
['eggs', 'bread', 'milk']

Process finished with exit code 0