Boolean and logical operations are crucial for making decisions and controlling the flow of execution in programming. This chapter explores these concepts in Python, providing a basic understanding and practical examples to illustrate their applications.
In Python, boolean values are represented by two keywords: True
and False
. These
values result from comparison operations and are used to make decisions in control structures such as if
statements.
# Boolean values example
is_adult = True
is_teenager = False
print("Is adult: ", is_adult)
print("Is teenager: ", is_teenager)
Comparison operators are used to compare two values and return a boolean result. Common comparison operators
include ==
(equal to), !=
(not equal to), <
(less than),
>
(greater than), <=
(less than or equal to), and
>=
(greater than or equal to).
# Comparison operators example
x = 10
y = 20
print("x == y: ", x == y)
print("x != y: ", x != y)
print("x < y: ", x < y)
print("x > y: ", x > y)
print("x <= y: ", x <= y)
print("x >= y: ", x >= y)
Logical operators allow you to combine boolean values and expressions to make more complex decisions. The
three most important logical operators in Python are and
, or
, and
not
.
# Logical operators example
x = True
y = False
print("x and y: ", x and y)
print("x or y: ", x or y)
print("not x: ", not x)
Boolean and logical operations are essential for controlling the flow of execution in your programs through structures such as if statements, while loops, and more.
# Using boolean and logical operations in if statements
age = 20
if age >= 18:
print("You are an adult.")
else:
print("You are a teenager.")