Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object is a number or boolean

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?

like image 207
Joakim Avatar asked Feb 22 '13 08:02

Joakim


People also ask

How do you know if an object is boolean?

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!

How do you check if a value is boolean or not in JavaScript?

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.

How do you check if a value is a boolean in Python?

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.

Is boolean an object in JavaScript?

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.


2 Answers

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()
  • built-in numeric types

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' 
like image 136
Lev Levitsky Avatar answered Oct 11 '22 00:10

Lev Levitsky


Easiest i would say:

type(x) == type(True) 
like image 41
CurlyMo Avatar answered Oct 11 '22 00:10

CurlyMo