Repository navigation
atoi.py: is n.isdigit missing its parentheses?
#10
|
In def atoi(n):
if n.isdigit:
print(int(n))
else:
n == 0
print(n)
atoi("123")
|
Replies: 1 comment
|
Yes — it's missing the parentheses, and your analysis of the consequence is exactly right. There's a second latent bug in that dead branch worth noting for the Given the prompt ("returning 0 if the conversion fails"), the faithful fix is: def atoi(s):
if s.isdigit():
return int(s)
return 0One subtlety: def atoi(s):
try:
return int(s)
except ValueError:
return 0That's also what I'd teach as the takeaway: for "convert or default", EAFP (try/except) beats a character-class gate you have to trust. |
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 theifbranch runs for every input and theelseis unreachable.There's a second latent bug in that dead branch worth noting for the
#REVISIT-style pass:n == 0is a comparison, not an assignment — it evaluates and throws the result away (probably meantn = 0).Given the prompt ("returning 0 if the conversion fails"), the faithful fix is:
One subtlety:
str.isdigit()accepts some charactersint()rejects (superscripts like"²", other Unicode digits)…