An Introduction to the Art of Computer Programming Using Python in the Age of Generative AI

IV. Booleans and Logical Operations

Introduction

Boolean and logical operations are crucial in programming for making decisions and controlling the flow of execution. This chapter explores these concepts in Python, providing a basic understanding and practical examples to illustrate their applications.

Understanding Boolean Values

In Python, boolean values are represented by two keywords: True and False. These values are the result of 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

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

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)
        

Using Boolean and Logical Operations in Control Flow

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.")
        
Back to Home