and – both must be True
age = 25
has_ticket = True
if age >= 18 and has_ticket:
print("Welcome to the concert!")Output
Welcome to the concert!
or – at least one must be True
day = "Sunday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")Output
It's the weekend!
not – flips True and False
is_logged_in = False
if not is_logged_in:
print("Please log in first.")Output
Please log in first.
| Expression | Result |
|---|---|
True and True | True |
True and False | False |
True or False | True |
False or False | False |
not True | False |
Checking a range
Python lets you chain comparisons, which reads just like maths:
score = 65
if 50 <= score <= 100:
print("You passed")Output
You passed
Decisions inside decisions
You can put an if inside another if. Each level adds 4 more spaces:
username = "admin"
password = "1234"
if username == "admin":
if password == "1234":
print("Access granted")
else:
print("Wrong password")
else:
print("Unknown user")Output
Access granted
Common mistake:
if day == "Saturday" or "Sunday":is always True! Each side oformust be a full comparison:day == "Saturday" or day == "Sunday".
Tip: Real security tip: never write real passwords in your code like the example above. It's only to show nesting.