Programming fundamentalsLesson 3 of 7 in the course Decisions

Python Logical Operators and Combined Conditions

5 flashcards · 5 quiz questions · 5 match pairs · 3 fill-in sentences · English

Lesson progress
0 / 5

Your progress is kept in this browser only.Sign up to save it

Summary

Programs often need to make decisions based on more than one condition. Logical operators let Python combine or reverse conditions so that an if statement can represent decisions such as whether a business is open or a car is within a speed range.

A condition is an expression that evaluates to True or False, such as hour >= 9. A logical operator uses one or more Boolean conditions to produce a Boolean result. Python has three logical operators: and, or, and not.

All flashcards

What does a logical operator do?
It operates on one or more Boolean conditions and produces a Boolean result. Python's logical operators are `and`, `or`, and `not`.
When is `p and q` true?
`p and q` is true only when both `p` and `q` are true.
When is `p or q` false?
`p or q` is false only when both `p` and `q` are false. It is true if either or both conditions are true.
How does `not` affect a Boolean value?
`not` reverses it: `not True` is `False`, and `not False` is `True`. It can also toggle a Boolean variable, as in `is_on = not is_on`.
How does the freeway-speed condition work?
`speed >= 45 and speed <= 70` is true only when the speed is at least 45 mph and at most 70 mph. Because both comparisons are inclusive, speeds of exactly 45 and 70 pass the check.

Quiz questions

  1. What does `p and q` evaluate to when `p` is `True` and `q` is `False`?Answer: `False`
  2. What does `p or q` evaluate to when both `p` and `q` are `True`?Answer: `True`
  3. What is the result of `not True` in Python?Answer: `False`
  4. A car's speed is 70 mph. In a program that checks `speed >= 45 and speed <= 70`, which branch runs?Answer: The `if` branch, because both comparisons are true.
  5. In a Python `if-else` statement, what happens when the condition evaluates to `False`?Answer: The `else` branch runs, if one is provided.

Based on Introduction to Python Programming by Udayan Das, Aubrey Lawson, Chris Mayfield, Narges Norouzi (OpenStax), licensed CC BY 4.0. Adapted into a summary, flashcards and quizzes.

All Programming fundamentals lessons