Logical operators allow us to combine multiple boolean expressions
Operator
Description
and
Both expressions must be true
or
Either or both expressions must be true
not
Flips the expression from True to False or vice versa
Example: Positive Even Number
How then can we write a program to check if a given number is both positive and even?
x = 7
# Check if x is positive
isPos = x >= 0
# Check if x is even (divisible by 2)
isEven = x % 2 == 0
# Check if it is both
isPosAndEven = isPos and isEven
print(isPosAndEven)
You may be thinking what is the point of all this??
The answer is decision making!
We will almost always want our code to behavior differently based on its input
So far our programs have used different numbers to compute different results
However, they haven’t used different equations based on the input
To achieve this we need to learn a new statement, the if statement which is closely tied with boolean expressions and therefore, also with logical operators
If Statements
If statements allow us to make decisions in our code
We can choose a different path through our code depending on the value of variables
This ability is critical when writing non-trivial programs
The syntax of an if is:
if <<condition>>:
<<statements>>
Example: Positive or Negative
As an example let’s write a program which takes in an Int and prints “positive” if it is >=0 and “negative” otherwise.
x = int(input())
if x >= 0:
print("positive")
if x < 0:
print("negative")