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

How would I add a try statement to this to ensure the user's input is valid?

For the extension question on one of the Python courses it says, allow user to move item in shopping list. Here is my code to allow a user to move an item but how would I add a try statement to make sure they do enter a string for the name of the item or an integer for the position of the item to move to?

def show_move():
  show_list
  itemToMove = input("Please enter the name of the item you wish to move: ").lower()
  where = int(input("Please enter which position in the list you would like this item moved to: ")) 
  whereSpot = where - 1
  for item in shopping_list:
    if item == itemToMove:
      itemIndex = shopping_list.index(itemToMove)
      moveMe = shopping_list.pop(itemIndex)
      shopping_list.insert(whereSpot, itemToMove)
      show_list()
    else:
      print("Invalid item or position out of range!")
      show_move()

1 Answer

Wrap the try: ... except: ... blocks around the lines where you assign the result from the input.

input() can raise EOFError and KeyboardInterrupt Exceptions if the user somehow escapes the input prompt (with Ctrl + D, Ctrl + C, etc).

int() can also raise ValueError if it can't convert the value to an integer.

The Python docs have a tutorial on handling exceptions.

You should also check to make sure the value of where doesn't equal 0 or less, since a negative number entered by the user will be successfully converted to a negative integer, and then be used to insert the item based on the end of the list. Either that or allow negative integers, but don't subtract in whereSpot.

And I think your loop will print that message for every item that isn't the one being moved. You could instead check:

if itemToMove in shopping_list:
  itemIndex = shopping_list.index(itemToMove)
  moveMe = shopping_list.pop(itemIndex)
  shopping_list.insert(whereSpot, itemToMove)
  show_list()
else:
  print("Invalid item or position out of range!")
  show_move(

Also note that your first reference to the show_list method is missing the parentheses to call it.