Skip to content
Discussion options

You must be logged in to vote

Yes — it's missing the parentheses, and your analysis of the consequence is exactly right. n.isdigit (no parens) is a bound method object, and every method object is truthy, so the if branch runs for every input and the else is unreachable.

There's a second latent bug in that dead branch worth noting for the #REVISIT-style pass: n == 0 is a comparison, not an assignment — it evaluates and throws the result away (probably meant n = 0).

Given the prompt ("returning 0 if the conversion fails"), the faithful fix is:

def atoi(s):
    if s.isdigit():
        return int(s)
    return 0

One subtlety: str.isdigit() accepts some characters int() rejects (superscripts like "²", other Unicode digits)…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by dab00gieman
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants