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 to drive if ALL of the following conditions are met:
- The person is at least 18 years old
- The person has a license
- The person has insurance
The following starter code is already provided for you — it reads the inputs and converts them to the correct types:
age = int(input())— reads the age as an integerhas_license = input() == "true"— reads the license string and converts it to a booleanhas_insurance = input() == "true"— reads the insurance string and converts it to a boolean
Your task is to:
- Check all three conditions using the variables
age,has_license, andhas_insurance, and store the result in a variable namedresult
Try it yourself
age = int(input())
has_license = input() == "true"
has_insurance = input() == "true"
result = # Complete this line to check if all conditions are met
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 2