Design a logical expression equivalent to the following statement:
x
is a list of three or five elements, the second element of which is the string'Hip'
and the first of which is not a number or Boolean.
What I have:
x = ['Head', 'Hip', 10] print x[1] is 'Hip'
My question: How do you check for whether or not it is a Boolean or a number?
With pure JavaScript, you can just simply use typeof and do something like typeof false or typeof true and it will return "boolean" ... const isBoolean = val => 'boolean' === typeof val; and call it like!
Using the typeof Operator The typeof operator is used to check the variable type in JavaScript. It returns the type of variable. We will compare the returned value with the “boolean” string, and if it matches, we can say that the variable type is Boolean.
We can evaluate values and variables using the Python bool() function. This method is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure.
The Boolean object represents two values, either "true" or "false". If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.
To answer the specific question:
isinstance(x[0], (int, float))
This checks if x[0]
is an instance of any of the types in the tuple (int, float)
.
You can add bool
in there, too, but it's not necessary, because bool
is itself a subclass of int
.
Doc reference:
isinstance()
To comment on your current code, you shouldn't rely on interning of short strings. You are supposed to compare strings with the ==
operator:
x[1] == 'Hip'
Easiest i would say:
type(x) == type(True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With