Blup Ditzz
Blup Ditzz

Reputation: 63

Python exception/ValueError/Error Handling

I have an input (called names) and that input is split up into three parts (.split) and then the third (last) element is converted into an integer and placed into a list

i.e. for example names = "John Smith 3" it is split up into three parts "John" "Smith" 3 and put into a list: list1 = ["John", "Smith", 3]

Now my question is if the third element is inputted as a string and cannot be converted into and integer ("John Smith Three"), how can I go about displaying an error and making the user re-input (names) and also how can I go about handling error if the user inputs "John Jacob Smith 3" (more than three elements).

Upvotes: 2

Views: 3470

Answers (4)

Johannes Charra
Johannes Charra

Reputation: 29913

I suggest you ask the user for two inputs: his/her name first and then the magic number.

If you definitely want to get this from a single input, you could try it like this

while True:
    name_and_num = raw_input("Your input: ")
    parts = name_and_num.split()
    try:
        firstname, lastname, num = parts[0], parts[1], int(parts[2])
        break
    except (IndexError, ValueError):
        print "Invalid input, please try again"

print firstname, lastname, num

Upvotes: 2

Harry
Harry

Reputation: 394

For first part: one easy way of doing this is:

try:
    float(l[2])
except ValueError:
    #error - bad input. user must re enter...

For second part: just check the length of the list formed from the split.

Upvotes: 0

jniles
jniles

Reputation: 1

I prefer using functions for everything:

def processNames(nameString):
  namesList = nameString.split()
  if len(namesList) == 3:
    try:
        namesList[2] = int(namesList[2])
    except:
        print "Third item not an integer"
        return None
  else:
    print "Invalid input"
    return None
  return namesList

Say you have a long list of names to loop through:

processed = []
for name in longList:
  processed.append(processNames(name))

which will gracefully return a list of items with Nones filled in the incorrect entries.

Upvotes: 0

Samy Arous
Samy Arous

Reputation: 6814

2 Ways to go about this:

This old, classical try catch approach:

message = 'Please enter ...'
while(True):
    print message
    user_input = raw_input().split()
    if len(user_input) != 3:
        message = 'Incorrect number of arguments please try again'
        continue
    try:
        num_value = int(user_input[2])
    except ValueError:
        message = 'Incorrect int value'
        continue
    break

The other approach is to simply use a regex, it should look like this:

import re    
regex = '^\s*(\w+)\s+(\w+)\s+(\d+)\s*$'
p = re.compile(regex)
print 'Please enter ...'
while(True):
    user_input = raw_input()
    m = p.match(user_input)
    if m:
        value1 = m.group(1)
        value2 = m.group(2)
        int_value = int(m.group(3))
        break
    else:
        print 'Incorrect input format, it should be ...'

Not that using this regex, you can match any string having 3 elements separated by any number of spaces and ending with an int value. So 'a b 10' and ' a b 10 ' are both matched.

Upvotes: 1

Related Questions