Sep. 21, 2012

Booleans, True or False in Python

What are Boolean?

Boolean values are the two constant objects False and True. 

They are used to represent truth values (other values can also be considered
false or true). 

In numeric contexts (for example, when used as the argument to an
arithmetic operator), they behave like the integers 0 and 1, respectively.

The built-in function bool() can be used to cast any value to a Boolean,
if the value can be interpreted as a truth value

They are written as False and True, respectively. 

Boolean Strings

A string in Python can be tested for truth value.

The return type will be in Boolean value (True or False)

Let’s make an example, by first create a new variable and give it a value.
my_string = "Hello World"

my_string.isalnum()		#check if all char are numbers
my_string.isalpha()		#check if all char in the string are alphabetic
my_string.isdigit()		#test if string contains digits
my_string.istitle()		#test if string contains title words
my_string.isupper()		#test if string contains upper case
my_string.islower()		#test if string contains lower case
my_string.isspace()		#test if string contains spaces
my_string.endswith('d')		#test if string endswith a d
my_string.startswith('H')	#test if string startswith H

To see what the return value (True or False) will be, simply print it out.	

my_string="Hello World"

print my_string.isalnum()		#False
print my_string.isalpha()		#False
print my_string.isdigit()		#False
print my_string.istitle()		#True
print my_string.isupper()		#False
print my_string.islower()		#False
print my_string.isspace()		#False
print my_string.endswith('d')		#True
print my_string.startswith('H')		#True

Boolean and logical operators

Boolean values respond to logical operators and / or

>>> True and False

>>> True and True

>>> False and True

>>> False or True

>>> False or False
Remember that the built-in type Boolean can hold only one of two possible
objects: True or False

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.


Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, only recommend products or services that we try personally and believe will add value to our readers.