I am writing a program where a user inputs a number in base 10 to be converted into that number in a different (or same) base.
def convert(a,b)
Where a is the input and b is the new base. I am instructed to have the program return the value “-1” if b is not an integer, if b assumes no value (ie blank), or if b is an integer that is less than 1.
I know how to convert the number, and I know how to have the program return -1 if b is less than 1, but how do I get the program to return -1 if b is empty or not an integer?
Short answer: Don’t.
Type checking is not Pythonic. Try doing what you want to do, and if it works, it works, if it doesn’t, it throws an exception.
Likewise, returning
-1on failure is not very Pythonic, generally, you want to throw an exception on a failure. There are some (rare) cases where this makes sense, but in general it means that you have to check the value (rather than just catching the exception where needed) and makes for a harder to spot bug (the value is-1rather than getting an exception).Long answer: If you really need to, then you can use
isinstance(value, int)to check if a value is an integer, however, this undermines Python’s duck-typing, and is therefore a bad idea 99.9% of the time. It also doesn’t necessarily work how you expect – for example,boolis a subclass ofint, soisinstance(True, int)will returnTrue– which may or may not be what you want.