1 / 1
Indice della lezione

Introduzione agli operatori logici

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.

1. Operatore and — entrambe le condizioni devono essere vere

price = 5
stock = 20
if price < 10 and stock > 0:
    print("The product is affordable AND available.")

2. Operatore or — almeno una condizione vera

age = 16
has_parent = True
if age >= 18 or has_parent:
    print("User can enter.")

3. Operatore not — inverte una condizione

is_expired = False
if not is_expired:
    print("Product is still valid.")

4. Combinazione di and e or

Le 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!")

5. Precedenza degli operatori

La precedenza indicata nel promemoria è:

  1. not
  2. and
  3. or
x = True or False and False
print(x)   # True, perché AND viene prima

6. Condizioni multiple con range

Controllare se un valore è dentro un intervallo usando and.

temp = 22
if temp > 18 and temp < 30:
    print("Comfortable temperature.")

7. Controllare un range con una forma più leggibile

if 18 < temp < 30:
    print("Same result, more Pythonic!")

8. Combinazione di condizioni su stringhe

product = "milk"
if product.startswith("m") and len(product) < 5:
    print("Product qualifies.")

9. Combinazione di condizioni con liste

cart = ["milk", "bread", "eggs"]
if "milk" in cart and "eggs" in cart:
    print("Breakfast items complete!")

10. Condizioni su dizionari

stock = {"milk": 10, "eggs": 0}
if stock["milk"] > 0 and stock["eggs"] == 0:
    print("Milk available but eggs out of stock.")

11. Usare or per gestire valori di fallback

user_input = ""
username = user_input or "Guest"
print(username)

12. Combinazione di not con and / or

available = False
price = 4.0
if not available or price > 10:
    print("Cannot purchase.")

13. Condizioni annidate vs condizioni combinate

Esempio annidato:

if price < 5:
    if stock > 10:
        print("OK")

Stessa logica, in forma combinata:

if price < 5 and stock > 10:
    print("OK")

14. Condizioni con più operatori logici: caso reale

age = 25
has_id = True
banned = False

if has_id and (age >= 18) and not banned:
    print("Access granted.")
← → per navigare F fullscreen