Skip to main content

Logical Operators in Python for Beginners with Examples

Concepts about variables in Python

Learn what basic Python operators are and how to use them: arithmetic, comparison, logical, and assignment operators, with simple examples.

If variables are names, logical operators are decision verbs. Without them, you couldn't create a login system, a search engine, or a price filter.

In Python, logic is based on Boolean algebra, where everything boils down to two states:True(True) orFalse(False).

Arithmetic Operators

| Operator | Meaning | Example | Result |

| :------- | :-------------- | :-------- | :-------- |

|+| Sum |10 + 3|13|

|-| Subtraction |10 - 3|7|

|*| Multiplication |10 * 3|30|

|/| Division |10 / 3|3.3333|

|%| Module |10 % 3|1|

|**| Powering |10 ** 3|1000|

|//| Integer division |10 // 3|3|

Assignment Operators

These operators are used to assign a value to a variable. Most combine an arithmetic operation with an assignment in a single step.

Assuming we start withx = 10:

| Operator | Example | Equivalent to | Final Result ofx|

| :------- | :-------- | :------------ | :--------------------- |

|=|x = 5|x = 5|5|

|+=|x += 3|x = x + 3|13|

|-=|x -= 2|x = x - 2|8|

|*=|x *= 4|x = x * 4|40|

|/=|x /= 2|x = x / 2|5.0|

|%=|x %= 3|x = x % 3|1|

|//=|x //= 3|x = x // 3|3|

|**=|x **= 2|x = x ** 2|100|

Building Blocks: Comparison Operators

Before delving into pure logic, we need to compare data. These operators always return a Boolean value (True either False).

| Operator | Meaning | Example | Result |

| :------- | :------------ | :--------- | :-------- |

|==| Equal to |5 == 5|True|

|!=| Different from |5 != 3|True|

|>| Greater than |10 > 20|False|

|<| Less than |10 < 20|True|

|>=| Greater than or equal to |18 >= 18|True|

|<=| Less than or equal to |15 <= 10|False|


The 3 Pillars of Logic:and,or,not

This is where Python shines in terms of readability. Other languages use...&& either ||But in Python we use English words, which makes the code read like natural language.

The operatorand(And)

ReturnsTrueOnly if both conditions are true. It's a strict filter.

Python
edad = 25
tiene_licencia = True

# Para conducir, necesitas ambas cosas
puede_conducir = edad >= 18 and tiene_licencia
print(f"¿Puede conducir?: {puede_conducir}") # True

The OR Operator

Returns True if at least one of the conditions is true. It is a flexible filter.

Python
es_fin_de_semana = True
esta_de_vacaciones = False

# Descansamos si es finde O si estamos de vacaciones
descanso = es_fin_de_semana or esta_de_vacaciones
print(f"¿Hoy se descansa?: {descanso}") # True

Short-Circuit Evaluation

Python is smart and lazy (in a good way). This optimizes performance:

  • In an AND statement: If the first condition is False, Python doesn't look at the second, because it knows the final result will be False anyway.

  • In an OR statement: If the first condition is True, Python ignores the second, because it already knows the result will be True.

Python
# Ejemplo de seguridad
divisor = 0
# Si no fuera por el cortocircuito, esto daría error (división por cero)
# Pero como divisor != 0 es False, Python no evalúa la segunda parte.
resultado = divisor != 0 and (10 / divisor > 1)
print(resultado) # False (sin errores)

Operator Precedence

Just like in mathematics (where multiplication comes before addition), logic has a hierarchy. The order of evaluation is:

  • not (Highest priority)

  • and

  • or (Lowest priority)

Pro Tip: Always use parentheses to avoid confusion and make your code readable for others.

Python
# ¿Qué crees que da esto?
resultado = True or False and False
# Primero evalúa: False and False -> False
# Luego: True or False -> True
print(resultado) # True

# Mucho mejor con paréntesis:
resultado = (True or False) and False # False

Special Operators: is and in

Python has two additional very powerful logical operators:

  • in: Checks if an element is within a collection (list, string, etc.).

  • is: Checks if two variables point to the same object in memory (identity).

Python
frutas = ["manzana", "banana", "uva"]
print("manzana" in frutas) # True

a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True (tienen el mismo contenido)
print(a is b) # False (son dos listas distintas en memoria)

Practical Challenge: "The Club Guardian"

Write a script that decides whether a person can enter a VIP club. The rules are:

  • Must be over 18 years old.

  • Must have a valid ticket OR be on the guest list.

  • Must not be blacklisted (banned).

Test variables:

Python
edad = 20
tiene_entrada = False
esta_invitado = True
esta_banned = False

# Tu lógica aquí
# puede_entrar = ...
Resources