Earlier quoted context omitted.
It's assumed the input is an int. If not you can do len(str(int(x))) to make sure it is which strips leading zeroes off in the process.
That's really my beef with languages like Python - typing is an afterthought. I literally get more safety from C than I do from Python: def numDigits(num): return len(str(num)) print (numDigits(1)) # Returns the correct answer print (numDigits("1")) # Returns the correct answer print (numDigits("01")) # Returns the incorrect answer The "returns the wrong answer" is the problem. If the input is the wrong type, I expec…
1+"1"
[]+{}
({}).foo
[]/2
Of course there's the type checkers for python like mypy and pyright but in my experience the type systems these provide are wildly underpowered for statically typing even slightly more complex idiomatic python.Re the num digits example: One way to go about this is to add asserts for checking the input types, though generally in python it's considered more idiomatic to check how an object behaves than what type it is.
In any case in practice I find that by far most type systems, bolted on or built in or otherwise, are more of a hassle than they are worth. One of the few exceptions I've found so far is D. When you rewrite the num digits function in D such that it accepts any type like the python example does, it should be of no surprise that it has the exact same bug as the python version:
int numDigits(T)(T num){
return num.to!string.length
}
I'm not entirely sure what my point is other than to point out that typing in python isn't an afterthought. it just uses a different type system to what you're used to which allows for bugs you're not used to.