0

Can anybody tell me why the following fails:

teststr = "foo"
if not teststr.isdigit() and int(teststr) != 1:
   pass

with:

ValueError: invalid literal for int() with base 10: 'foo'

In C if the first part in an && test fails the right hand side is not evaluated anymore. Is this different in Python?

EDIT: I am being stupid. The and should be an or of course.....

4

4 回答 4

8

not teststr.isdigit() is True, so the first test doesn't fail.

于 2012-09-28T14:59:42.410 回答
2
if not teststr.isdigit() and int(teststr) != 1:

is evaluated as

if ((not teststr.isdigit()) and (int(teststr) != 1)):

well, but teststr is not a digit, so isdigit() is false, so (not isdigit()) is true. And for True and B, you have to eval B. That's why it tries the cast to int.

于 2012-09-28T15:00:48.713 回答
0

if not teststr.isdigit() is True, so then it needs to evaluate int(teststr) to complete the requirements of the and - hence the exception.

Instead of pre-checking data, utilise EAFP - and use something like the following...

try:
    val = int(teststr)
    if val != 1:
        raise ValueError("wasn't equal to 1")
except (ValueError, TypeError) as e:
    pass # wasn't the right format, or not equal to one - so handle
# carry on here...
于 2012-09-28T15:00:31.597 回答
0

The code you probably want to use would probably be

try:
    int(teststr)
except ValueError:
    print "Not numeric!"

It's generally more pythonic to try something and catch exceptions rather than use type-checking methods like you did.

于 2012-09-28T15:08:08.150 回答