What Use are Booleans?


#1

i have not yet understood what is the use of booleans


FAQ: Learn Python - Python Syntax - Booleans
#2

Hi @taruntejaa,

Booleans store a True/False value. Usually, you’ll use them in if statements to decide whether to do something or not, but sometimes you’ll just print out the value itself. For example:

budget = 1250 # $12.50
cost = 1100 # $11.00

if cost < budget: # not stored in a variable, but this is also a 
                  # boolean - it's either True or False
  can_buy = True
else:
  can_buy = False

print(can_buy)

# result: True

#3

Are you asking why to use boolean in lieu of alternatives? Like why not have an integer assigned to either 0 or 1, serving the same purpose? If so…

The reasons are:

  1. storage: boolean takes up less space than int and other data types, and…
  2. error detection: if a boolean can only be assigned true or false, there’s only one way for it to get screwed up by a bug in your code and not equal what it is supposed to equal. If you use an int for the same purpose, although you want it to be a 0 or a 1 to represent possible outcomes in your program… your code won’t crash and show you a clear error, because int works for values up to ~2 billion.

Hopefully that helps.