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 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,441 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.