Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (Retired) Lists Redux Shopping List Take Three

Iskander Ismagilov
Iskander Ismagilov
13,298 Points

String exception for adding item to a certain spot in shopping_list3.py

I wanna make an exception with while loop for adding item to a certain spot if there is a string:

else:
    new_list = new_stuff.split(",")
    index = input("Add this to a cerain spot? Press enter for the end of the list, "
                  "or give me a number. Currently {} items in list.".format(len(shopping_list)))
    try:
      if index:
        spot = int(index) - 1 
        for item in new_list:
          shopping_list.insert(spot, item.strip())
          spot += 1
      else:             
        for item in new_list:
          shopping_list.append(item.strip())
    except:
      if index == str(index):
# Here I made a loop if user put in string it give a prompt with an input:
        while True:
          index = input("Please, put in a number: ")
          if index == int(index):
            break
          elif index == str(index):
            continue
      if index:
        spot = int(index) - 1 
        for item in new_list:
          shopping_list.insert(spot, item.strip())
          spot += 1
      else:             
        for item in new_list:
          shopping_list.append(item.strip())

after user put a word in input("Please, put in a number: "), 2 errors show up:

  1. spot = int(index) - 1
    ValueError: invalid literal for int() with base 10: 'asdf'

2.if index == int(index):
ValueError: invalid literal for int() with base 10: 'asdf'

Why these 2 errors come up? How to make the string exception work?

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,030 Points

Your current flow isn't DRY since it is using the same code in two places to add items to the list:

  • get input
  • try to add items to list
  • ask for proper input
  • add items to list

You could use the flow:

  • get and approve input
  • add items to list
else:
    new_list = new_stuff.split(",")
    index = input("Add this to a cerain spot? Press enter for the end of the list, "
                  "or give me a number. Currently {} items in list.".format(len(shopping_list)))
    # verify index
    while True:
        if index:
            # index is not empty string
            try:
                # test convert index to int
                int(index)
                # successful, break loop
                break
            except:
                # conversion failed ask for new input
                index = input("Please, give a number or <Enter> for end of the list: ")
        else:
            # index is empty string, allow to fall through
            break
    # index is now either an empty string or a string of numbers
    # try/except should no longer be needed
    try:
      if index:
        spot = int(index) - 1 
        for item in new_list:
          shopping_list.insert(spot, item.strip())
          spot += 1
      else:             
        for item in new_list:
          shopping_list.append(item.strip())
    except:
        # catch any other errors
        print("Unexpected error!")
        # re-raise error to user
        raise
Iskander Ismagilov
Iskander Ismagilov
13,298 Points

Thank you for clear answer, Chris.