user3056783
user3056783

Reputation: 2626

Passing strings with numbers to Python - Why is my script failing?

I am doing LPTHW exercise 48 and I had rewritten my function several times. I deleted everything and wanted to start from scratch so I narrowed my problem to a one single one.

If I pass string containing number to the scan function, I want it to print string 'number' and the string that was passed. I'm having a problem where the string containing number is not recognized and instead returns None.

What am I doing wrong?

Here's the short script:

def scan(user_input):

    direction = ['north', 'south',
                 'east', 'west', 'down',
                  'up', 'left', 'right', 'back']

    number = range(0,99999)

    try:
        if user_input in direction:
            print 'direction', direction[direction.index(user_input)]

        else:
            return None

    except ValueError:

        if int(user_input) in number:
            print 'number', user_input

        else:
            return None


scan(raw_input("> "))

If you pass for example 'north' to the function, it works fine however when you pass '123' you get None.

Upvotes: 0

Views: 37

Answers (2)

user3056783
user3056783

Reputation: 2626

Actually I wanted to do this basically:

def scan(user_input):

    direction = ['north', 'south',
                 'east', 'west', 'down',
                  'up', 'left', 'right', 'back']

    number = range(0,99999)


    try:
        if int(user_input) in number:
                print 'number', user_input
    except ValueError:
        if user_input in direction:
                print 'direction', direction[direction.index(user_input)]

        else:
            return None


scan(raw_input("> "))

I found out that the best way is to check for integer first, that's why right after try: I added if int(user_input) in number:.

Whenever that fails (because the string 'north' cannot be changed to int) it goes straight away to exception. If there's nothing found it returns None.

I want to thank you for hints though because it made me go through the code again and figure it out.

Upvotes: 0

dparpyani
dparpyani

Reputation: 2493

That's because an exception never occurs, so the else part under try returns None.

try:
    if user_input in direction:
        print 'direction', direction[direction.index(user_input)]
    elif int(user_input) in number:
        print 'number', user_input
    else:
        return None
except ValueError:
    return None

Upvotes: 1

Related Questions