Gli operatori logici principali sono:
and: entrambe le condizioni devono essere vere.or: almeno una condizione deve essere vera.not: inverte il valore di una condizione booleana.and — entrambe le condizioni devono essere vereprice = 5
stock = 20
if price < 10 and stock > 0:
print("The product is affordable AND available.")
or — almeno una condizione veraage = 16
has_parent = True
if age >= 18 or has_parent:
print("User can enter.")
not — inverte una condizioneis_expired = False
if not is_expired:
print("Product is still valid.")
and e orLe parentesi aiutano a rendere chiara la logica.
price = 3.5
stock = 50
category = "Produce"
if (price < 5 and stock > 20) or category == "Produce":
print("Special discount available!")
La precedenza indicata nel promemoria è:
notandorx = True or False and False
print(x) # True, perché AND viene prima
Controllare se un valore è dentro un intervallo usando and.
temp = 22
if temp > 18 and temp < 30:
print("Comfortable temperature.")
if 18 < temp < 30:
print("Same result, more Pythonic!")
product = "milk"
if product.startswith("m") and len(product) < 5:
print("Product qualifies.")
cart = ["milk", "bread", "eggs"]
if "milk" in cart and "eggs" in cart:
print("Breakfast items complete!")
stock = {"milk": 10, "eggs": 0}
if stock["milk"] > 0 and stock["eggs"] == 0:
print("Milk available but eggs out of stock.")
or per gestire valori di fallbackuser_input = ""
username = user_input or "Guest"
print(username)
not con and / oravailable = False
price = 4.0
if not available or price > 10:
print("Cannot purchase.")
Esempio annidato:
if price < 5:
if stock > 10:
print("OK")
Stessa logica, in forma combinata:
if price < 5 and stock > 10:
print("OK")
age = 25
has_id = True
banned = False
if has_id and (age >= 18) and not banned:
print("Access granted.")