Logical Operators Part 1
Part of the Fundamentals section of Coddy's Python journey — lesson 15 of 77.
Logical operators are used to combine conditional statements.
Python has three logical operators:
andornot
Let's see how the and operator works:
The and operator returns True if both statements are true.
# Create two boolean variables
x = True
y = True
# Check if both x and y are True
result = x and yAfter executing the above code, result contains:
TrueIf one of the values is False, the result will be False:
# Create two boolean variables
x = True
y = False
# Check if both x and y are True
result = x and yThis gives us:
FalseChallenge
EasyComplete the code to determine if a person is eligible to drive based on their age and license status.
A person is eligible to drive when:
- They are at least 18 years old AND
- They have a valid driving license
Fill in the blanks with the correct values:
- Fill in the age variable with 20
- Fill in the has_license variable with True
- Fill in the minimum age requirement in the comparison
Cheat sheet
Logical operators in Python:
| Operator | Meaning | Example |
|---|---|---|
and | True if all operands are True | a and b |
or | True if any operand is True | a or b |
not | True if the operand is False | not a |
Examples:
b1 = (5 > 3) and (1 == 1) # True
b2 = not 5 == 4 or 5 == 2 # True
b3 = not 1 == 1 or False # False
b4 = not (3 > 4) # True
b5 = not (5 > 10 or 5 > 1) # FalseTry it yourself
age = ?
has_license = ?
result = age >= ? and has_license
# Don't change the line below
print("Eligible to drive:", result)This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2