Skip to content Skip to sidebar Skip to footer

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 e

Solution 1:

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

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

Solution 2:

2 Ways to go about this:

This old, classical try catch approach:

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

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))
        breakelse:
        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.

Solution 3:

I prefer using functions for everything:

defprocessNames(nameString):
  namesList = nameString.split()
  iflen(namesList) == 3:
    try:
        namesList[2] = int(namesList[2])
    except:
        print"Third item not an integer"returnNoneelse:
    print"Invalid input"returnNonereturn 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.

Solution 4:

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.

Post a Comment for "Python Exception/valueerror/error Handling"