C'è un operatore "not equal" in Python?

Come diresti che non è uguale?

Come

if hi == hi:
    print "hi"
elif hi (does not equal) bye:
    print "no hi"

C'è qualcosa di equivalente a == che significa "non uguale"?

Soluzione

Usare !=. Vedere operatori di confronto. Per confrontare le identità degli oggetti, puoi usare la parola chiave is e la sua negazione is not.

ad es.

1 == 1 #  -> True
1 != 1 #  -> False
[] is [] #-> False (distinct objects)
a = b = []; a is b # -> True (same object)
Commentari (5)

Non uguale != (vs uguale ==)

Stai chiedendo qualcosa di simile a questo?

answer = 'hi'

if answer == 'hi':     # equal
   print "hi"
elif answer != 'hi':   # not equal
   print "no hi"

Questo grafico Python - Operatori di base potrebbe essere utile.

Commentari (0)

C'è l'operatore != (not equal) che restituisce True quando due valori differiscono, anche se bisogna fare attenzione ai tipi perché "1" != 1. Questo restituirà sempre True e "1" == 1 restituirà sempre False, poiché i tipi differiscono. Python è dinamicamente, ma fortemente tipizzato, e altri linguaggi staticamente tipizzati si lamenterebbero di confrontare tipi diversi.

C'è anche la clausola else:

# This will always print either "hi" or "no hi" unless something unforeseen happens.
if hi == "hi":     # The variable hi is being compared to the string "hi", strings are immutable in Python, so you could use the 'is' operator.
    print "hi"     # If indeed it is the string "hi" then print "hi"
else:              # hi and "hi" are not the same
    print "no hi"

L'operatore is è l'operatore di identità dell'oggetto usato per controllare se due oggetti sono effettivamente uguali:

a = [1, 2]
b = [1, 2]
print a == b # This will print True since they have the same values
print a is b # This will print False since they are different objects.
Commentari (0)