Logical Operators Part 3
Part of the Fundamentals section of Coddy's Python journey. Lesson 18 of 77.
In Python, you can combine multiple conditions using logical operators (and, or, not) to create more complex expressions.
Let's create a condition that checks if a number is both positive and even:
number = 6Now let's check if the number is positive:
is_positive = number > 0Let's also check if the number is even:
is_even = number % 2 == 0We can combine these conditions using the and operator:
result = is_positive and is_evenThis evaluates to True because 6 is both positive and even.
For a more direct approach, you can combine conditions without intermediate variables:
result = number > 0 and number % 2 == 0Similarly, you can use the or operator to check if at least one condition is true:
number = -4
is_negative_or_odd = number < 0 or number % 2 != 0This evaluates to True because -4 is negative (even though it's not odd).
Challenge
EasyWrite code that checks if a person is eligible to drive. A person is eligible if ALL of the following are true:
- The person is at least 18 years old
- The person has a license
- The person has insurance
Use the variables age, has_license and has_insurance, and store the answer in result.
Try it yourself
age = int(input())
has_license = input() == "true"
has_insurance = input() == "true"
result = False # <-- your condition goes here
print(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 2Practice on your own: Online Python compiler