Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert number 1 to a Boolean in python

Tags:

I have seen similar questions asked, but none have answered my question. I am relatively new to python, and have no idea what i'm doing.

like image 966
yeetthemhatersaway Avatar asked Nov 09 '18 01:11

yeetthemhatersaway


People also ask

How do you convert int to boolean in Python?

Integers and floating point numbers can be converted to the boolean data type using Python's bool() function. An int, float or complex number set to zero returns False . An integer, float or complex number set to any other number, positive or negative, returns True .

How do you convert numbers to boolean?

We convert a Number to Boolean by using the JavaScript Boolean() method. A JavaScript boolean results in one of the two values i.e true or false.

How do you replace true with 1 in Python?

In Python True and False are equivalent to 1 and 0. Use the int() method on a boolean to get its int values. int() turns the boolean into 1 or 0. Note: that any value not equal to 'true' will result in 0 being returned.

Is 1 true or False in Python?

Python Booleans as Numbers Because True is equal to 1 and False is equal to 0 , adding Booleans together is a quick way to count the number of True values.


2 Answers

Use:

>>> bool(1) True >>> bool(0) False >>> int(bool(1)) 1 >>> int(bool(0)) 0 

Can convert back too.

Or a clever hack that could be quicker would be:

>>> not not 1 True >>> not not 0 False >>>  

Converting back:

>>> int(not not 1) 1 >>> int(not not 0) 0 >>>  
like image 55
U12-Forward Avatar answered Oct 10 '22 01:10

U12-Forward


Only the following values will return False when passed as a parameter to bool()

  • None
  • False
  • Zero of any numeric type. For example, 0, 0.0, 0j
  • Empty sequence. For example, (), [], ''.
  • Empty mapping. For example, {}
  • objects of Classes which has bool() or len() method which returns 0 or False

Everything else returns True

Source1 Source2

like image 41
Anurag Pande Avatar answered Oct 10 '22 02:10

Anurag Pande