English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriales básicos de Python

Control de flujo de Python

Funciones en Python

Tipos de datos en Python

Operaciones de archivos de Python

Objetos y clases de Python

Fecha y hora de Python

Conocimientos avanzados de Python

Manual de referencia de Python

Operadores en Python

En este artículo, aprenderá todo lo relacionado con los diferentes tipos de operadores en Python, su sintaxis y cómo usarlos en ejemplos.

¿Qué son los operadores en Python?

Los operadores son símbolos especiales en Python que realizan cálculos aritméticos o lógicos. Los valores sobre los que operan se llaman operandos.

Por ejemplo:

>> 2+3
5

Aquí,+Es el operador que realiza la adición.2and3Son los operandos,5Es la salida de la operación.

Operadores aritméticos

Los operadores aritméticos se utilizan para realizar operaciones matemáticas, como suma, resta, multiplicación, etc.

OperatorMeaningExample
+Suma - Suma los dos operandos o el signo unario de sumax + y + 2
-Resta - Resta el operando derecho al operando izquierdo (o al signo unario de restar)x-y- 2
*Multiplicación -Multiplica los dos operandosx * y
/División - Divide el operando izquierdo por el operando derecho (el resultado siempre es float)x / y
%Módulo -El resto del operando izquierdo dividido por el operando derechox % y(x / El resto de y)
//División entera - Devuelve la parte entera del cociente (redondea hacia abajo)x // y
**Potencia - Devuelve el poder de y de xx ** y(x elevado a la potencia de y)

Example1:Operadores aritméticos en Python

x = 15
y = 4
# Salida: x + y = 19
print('x + y =', x+y)
# Salida: x - y = 11
print('x - y =', x-y)
# Salida: x * y = 60
print('x * y =', x*y)
# Salida: x / y = 3.75
print('x / y =', x/y)
# Salida: x // y = 3
print('x // y =', x//y)
# Salida: x ** y = 50625
print('x ** y =', x**y)

Al ejecutar el programa, la salida es:

x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625

Operadores de comparación

Los operadores de comparación se utilizan para comparar valores. Devuelven True o False según la condición.

OperatorMeaningExample
>Mayor-Si el operando izquierdo es mayor que el derecho,则为Truex > y
<Menor-Si el operando izquierdo es menor que el derecho,则为Truex < y
==Igual-Si los dos operandos son iguales,则为Truex == y
!=No es igual-Si los operandos son diferentes,则为Truex != y
>=Mayor o igual-Si el operando izquierdo es mayor o igual que el derecho,则为Truex >= y
<=Menor o igual-Si el operando izquierdo es menor o igual que el derecho,则为Truex <= y

Example2:Operadores de comparación en Python

x = 10
y = 12
# Salida: x > y es False
print('x > y es', x > y)
# Salida: x < y es True
print('x < y es', x < y)
# Salida: x == y es False
print('x == y es', x == y)
# Salida: x != y es True
print('x != y es', x != y)
# salida: x >= y es False
print('x >= y es ', x>=y)
# salida: x <= y es True
print('x <= y es ', x<=y)

Output result

x > y es False
x < y es True
x == y es False
x != y es True
x >= y es False
x <= y es True

operadores lógicos

los operadores lógicos son and, or, no operadores.

OperatorMeaningExample
ysi ambos operandos son verdaderos,则为真x y
osi cualquier operando es verdadero,则为真x o y
nosi el operando es false,则为True(对操作数进行补充)no x

Example3:operadores lógicos en Python

x = True
y = False
print('x and y es ', x and y)
print('x or y es ', x or y)
print('not x es ', not x)

Output result

x and y es False
x or y es True
not x es False

es esta tabla detabla de verdad

operadores bit a bit

los operadores bit a bit actúan sobre los operandos, como si fueran cadenas de números binarios. Se ejecutan paso a paso, por lo que reciben este nombre.

por ejemplo,2es10binario,7es111。

en la siguiente tabla:dejarx= 10(0000 1010binario)yy= 4(0000 0100binario)

OperatorMeaningExample
&y bitx&y = 0(0000 0000)
|o bitx | y = 14(0000 1110)
~no bit〜x = -11(1111 0101)
^operación bit a bitx ^ y = 14(0000 1110)
>>desplazamiento bit a la derechax >> 2 = 2(0000 0010)
<<desplazamiento bit a la izquierdax << 2 = 40(0010 1000)

Operador de asignación

Se utiliza el operador de asignación en Python para asignar valores a las variables.

a = 5es un operador de asignación simple, que asigna el valor5asignado al variable de izquierdaa

En Python hay muchos operadores compuestos similares, a += 5Se agregarán a la variable y luego se asignarán a ellas. Equivalente a a = a + 5。

OperatorExampleequivalente
=x = 5x = 5
+=x + = 5x = x + 5
-=x-= 5x = x-5
*=x * = 5x = x * 5
/=x / = 5x = x / 5
%=x%= 5x = x%5
//=x // = 5x = x // 5
**=x ** = 5x = x ** 5
&=x&= 5x = x&5
|=x | = 5x = x | 5
^=x ^ = 5x = x ^ 5
>>=x >> = 5x = x >> 5
<<=x << = 5x = x << 5

Operador especial

Python provides some special types of operators, such as identity operators or membership operators. Below, they are described through examples.

Identity operator

is and is not are identity operators in Python. They are used to check if two values (or variables) are in the same part of memory. Two equal variables do not necessarily mean they are the same.

OperatorMeaningExample
isIf the operands are the same, it is true (referring to the same object)x is true
is notIf the operands are not the same, it is true (not referring to the same object)x is not true

Example4:Python中的身份运算符

x1 = 5
y1 = 5
x2 ='Hello'
y2 ='Hello'
x3 =[1:2:3,
y3 =[1:2:3,
# Output: False
is not y1 ]1is y
# Output: True
is not y2 print(x2is y
# Output: False
is not y3 print(x3is y

Output result

False
True
False

)x1andy1Here, we seex2andy2(string)is the same. They are integers with the same value, so they are both equal and the same.

Butx3andy3They are lists. They are equal but not the same. This is because although they are equal, the interpreter still locates them separately in memory.

Membership operator

in and not in are membership operators in Python. They are used to test whether a value (or variable) is in a sequence (String,List,Tuple,SetandDictionary)to find the value or variable.

In dictionaries, we can only test the existence of keys, not values.

OperatorMeaningExample
inIf the value is found in the sequence/If the variable exists, it is true5 in x
not inIf the value is not found in the sequence/If the variable exists, it is true5 not in x

Example #5:Membership operator in Python

x = 'Hello world'
y = {1: 'a',2: 'b'}
# Output: True
print('H' in x)
# Output: True
print('hello' not in x)
# Output: True
print(1 in y)
# Output: False
print('a' in y)

Output result

True
True
True
False

Here, 'H' is in x, but 'hello' is not in x (remember that Python is case-sensitive). Similarly,1a is the value and b is the key in the dictionary y, therefore b in y returns False.