[Tutor] ASCII Conversion

Peter Otten __peter__ at web.de
Tue Jan 31 08:40:38 CET 2012


Michael Lewis wrote:

> I am trying to do a simple test but am not sure how to get around ASCII
> conversion of characters. I want to pass in y have the function test to
> see if y is an integer and print out a value if that integer satisfies the
> if statement. However, if I pass in a string, it's converted to ASCII and
> will still satisfy the if statement and print out value. How do I ensure
> that a string is caught as a ValueError instead of being converted?
> 
> def TestY(y):
>     try:
>         y = int(y)
>     except ValueError:
>         pass
>     if y < -1 or y > 1:
>         value = 82
>         print value
>     else:
>         pass

You have to remember somehow whether you have an integer or a string. A 
straightforward way is

def test(y):
    try:
        y = int(y)
        isint = True 
    except ValueError:
        isint = False
    if isint and y < -1 or y > 1:
        print 82


However, Python's try..except statement features an else suite that is only 
invoked when no exception is raised. So the idiomatic way is to drop the 
helper variable and change the control flow instead:

def test(y):
    try:
        y = int(y)
    except ValueError:
        pass
    else:
        if y < -1 or y > 1:
            print 82



More information about the Tutor mailing list