Python lesson 13

Logical Operators

Combine conditions with and, or, and not to make smarter decisions!

Combining Conditions

Python has three logical operators. "and" requires both conditions to be True. "or" requires at least one to be True. "not" flips a boolean. True becomes False, False becomes True. These let you write richer conditions without nesting lots of if statements inside each other.

x = 15
if x > 10 and x < 20:
print("x is between 10 and 20")

x = 15
if x > 10 and x < 20:
    print("x is between 10 and 20")

And Means Both

age = 14
ticket = False
print(age > 12 and ticket)
print(age > 12 or ticket)
print(not ticket)

Login Check

Click Run to see how "and" checks two conditions at the same time. Both must be True for access to be granted.

Hint: Click Run! Change the password to something wrong and run again. "and" means both must match.

username = "admin"
password = "secret123"
if username == "admin" and password == "secret123":
    print("Access granted")
else:
    print("Access denied")

In Range Check

Use "and" to check that a number sits between 10 and 20. Try changing the number to test the boundary edges.

Hint: Both conditions must be True at the same time. Try number = 10 (boundary), number = 20 (boundary), then number = 21 (out of range).

number = 15
if number >= 10 and number <= 20:
    print(number, "is between 10 and 20")
else:
    print(number, "is out of range")

Grade Classifier

This program uses "and" to give a grade based on a score range. Change the score and run to see different grades!

Hint: Try score = 95, then 72, then 55, then 40. The "and" in each elif makes sure the score falls in exactly one band.

score = 78
if score >= 90:
    print("Grade: A")
elif score >= 70 and score < 90:
    print("Grade: B")
elif score >= 50 and score < 70:
    print("Grade: C")
else:
    print("Grade: F")

What you can do on CodeIt

Run the example, change one part, and use the result to check your understanding before moving to the next lesson.