When would I want to use a boolean?


#1

Question

What are some common uses for booleans?

Answer

Unlike other data types we’ve learned about like numbers and strings, the use of booleans might not be as immediately obvious. There are lots of times we want to control how our program behaves with boolean conditions. For example, if we want to continue asking a question until the user provides valid input, we might use a boolean variable that is set to False and only becomes True when their input is checked and is valid.


FAQ: Learn Python - Python Syntax - Booleans
#2

Hi, do you have any real example of the use of Booleans? I believe True/False term is something that might be important, but still don’t get it when to use it on real case…

Thanks…


#3

Two things to understand about booleans, primitive and expression.

primitive

True
False

Primitives are literal.

expressions

a == b
a or b
a and b

where the entire thing is an expression, but also where a and b can be literals or expressions.

Expressions yield a value, and boolean expressions yield a boolean.

 a + b  =>  a value (the sum of a and b)
 s + t  =>  a value (the concatenation of two strings)

a == b  =>  a boolean (True or False)
a or b   => a value, `a` or `b` whichever is True first (`b` if both False).
a and b  =>  a value, `a` if it is *falsy*, else `b`.

Expressions are considered truthy when they resolve to a number that is non-zero, a string that is not empty, or not None.

"A" and "B"

will evaluate to B since they are both strings with length greater than zero.

1 and 2

will evaluate to 2 since both numbers are non-zero, so the yield with be the last operand.

1 or 2

will evaluate to 1 since it is the first non-zero operand.

Some more examples…

>>> "" and True
''
>>> "" and False
''
>>> '' or True
True
>>> '' or False
False
>>> 

if and while

if expression:
    print ("%r is True") % expression
else:
    print ("%r is False") % expression
while expression:
    # code block
    if condition: break

expression above is any expression, but it is evaluated before proceeding to determine truthiness (yields a boolean).

The above may be a little confusing. Ask if you still don’t understand.


#4

I with you i really dont know what i would use it for other than True or False


#5

Well thank you it help alot


#6

well, thank you it will help me when in use


#7

So maybe in if statements?