2

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

1
  • What is the code you have so far? Commented Jun 18, 2013 at 9:39

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Don't forget also the IndexError :) and I don't think your code ever raises TypeError.
Thanks, right. :) Casting to int causes a TypeError for argument None, but this won't ever be the case here.
1

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.

Comments

0

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.

Comments

0

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.

1 Comment

blank except clauses are a bad idea. You should be explicit on which exception to catch.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.