8.Booleans and Comparisons in Python

In Python, Booleans and comparison operators are fundamental for decision-making and control flow. This tutorial explains Boolean values, logical operators, comparison operators, truth tables, and examples combining Boolean logic with comparisons.

Boolean Values

Python has two Boolean values: True and False. These represent truth and falsity in logical expressions. They are case-sensitive and must be capitalized.

Example:

is_active = True
is_logged_in = False

Logical Operators

Logical operators allow combining Boolean expressions:

Truth Tables

Here are truth tables for ‘and’ and ‘or’:

A

B

A and B

True

True

True

True

False

False

False

True

False

False

False

False

Here are truth tables for ‘and’ and ‘or’:

Similarly, for ‘or’:

A

B

A or B

True

True

True

True

False

True

False

True

True

False

False

False

Comparison Operators

Comparison operators compare values and return Boolean results:

Here are truth tables for ‘and’ and ‘or’:

Similarly, for ‘or’:

A

B

A or B

True

True

True

True

False

True

False

True

True

False

False

False

Examples Combining Boolean Logic with Comparisons

Example 1:

age = 20
is_adult = age >= 18
print(is_adult)  # True

Example 2:

score = 85
passed = score >= 50
excellent = score > 90
print(passed and not excellent)  # True

Example 3:

x = 10
y = 5
print(x > y or y > 0)  # True

Conclusion

Booleans and comparisons are essential for controlling program flow. Understanding logical and comparison operators helps in writing clear and effective conditions.

Scroll to Top
Tutorialsjet.com