Boolean expressions are the building blocks of decision-making in programming. They evaluate to either true
or false
, allowing your code to make choices and control the flow of execution.
At the core of boolean expressions are boolean operators:
and
: Returns true
only if both operands are true
.
true and true -> true
true and false -> false
false and true -> false
false and false -> false
or
: Returns true
if at least one operand is true
.
true or true -> true
true or false -> true
false or true -> true
false or false -> false
not
: Negates the truth value of its operand.
not true -> false
not false -> true
You often use comparison operators to compare values and generate boolean results:
==
: Equal to.!=
: Not equal to.>
: Greater than.<
: Less than.>=
: Greater than or equal to.<=
: Less than or equal to.Boolean expressions can be combined using parentheses to control order of operations and create complex logic:
(a > 10) and (b < 5) or (c == 0)
This expression checks if:
a
is greater than 10, andb
is less than 5, orc
is equal to 0.The entire expression will evaluate to true
if at least one of the conditions is met.
password = input("Enter your password: ")
if len(password) >= 8 and any(char.isdigit() for char in password) and any(char.isupper() for char in password):
print("Valid password!")
else:
print("Invalid password. Password must be at least 8 characters long, contain at least one number, and at least one uppercase letter.")
This code checks if a user-entered password meets the following criteria:
The if
statement uses a boolean expression to determine if the password is valid.
Boolean expressions are essential for writing programs that make decisions and control flow. Mastering boolean operators and comparison operators allows you to create complex logic that can handle various scenarios in your code.