English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
En este artículo, aprenderá todo lo relacionado con los diferentes tipos de operadores en Python, su sintaxis y cómo usarlos en ejemplos.
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.
Los operadores aritméticos se utilizan para realizar operaciones matemáticas, como suma, resta, multiplicación, etc.
Operator | Meaning | Example |
---|---|---|
+ | Suma - Suma los dos operandos o el signo unario de suma | x + y + 2 |
- | Resta - Resta el operando derecho al operando izquierdo (o al signo unario de restar) | x-y- 2 |
* | Multiplicación -Multiplica los dos operandos | x * 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 derecho | x % 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 x | x ** y(x elevado a la potencia de y) |
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
Los operadores de comparación se utilizan para comparar valores. Devuelven True o False según la condición.
Operator | Meaning | Example |
---|---|---|
> | Mayor-Si el operando izquierdo es mayor que el derecho,则为True | x > y |
< | Menor-Si el operando izquierdo es menor que el derecho,则为True | x < y |
== | Igual-Si los dos operandos son iguales,则为True | x == y |
!= | No es igual-Si los operandos son diferentes,则为True | x != y |
>= | Mayor o igual-Si el operando izquierdo es mayor o igual que el derecho,则为True | x >= y |
<= | Menor o igual-Si el operando izquierdo es menor o igual que el derecho,则为True | x <= y |
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
los operadores lógicos son and, or, no operadores.
Operator | Meaning | Example |
---|---|---|
y | si ambos operandos son verdaderos,则为真 | x y |
o | si cualquier operando es verdadero,则为真 | x o y |
no | si el operando es false,则为True(对操作数进行补充) | no x |
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。
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)
Operator | Meaning | Example |
---|---|---|
& | y bit | x&y = 0(0000 0000) |
| | o bit | x | y = 14(0000 1110) |
~ | no bit | 〜x = -11(1111 0101) |
^ | operación bit a bit | x ^ y = 14(0000 1110) |
>> | desplazamiento bit a la derecha | x >> 2 = 2(0000 0010) |
<< | desplazamiento bit a la izquierda | x << 2 = 40(0010 1000) |
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。
Operator | Example | equivalente |
---|---|---|
= | x = 5 | x = 5 |
+= | x + = 5 | x = x + 5 |
-= | x-= 5 | x = x-5 |
*= | x * = 5 | x = x * 5 |
/= | x / = 5 | x = x / 5 |
%= | x%= 5 | x = x%5 |
//= | x // = 5 | x = x // 5 |
**= | x ** = 5 | x = x ** 5 |
&= | x&= 5 | x = x&5 |
|= | x | = 5 | x = x | 5 |
^= | x ^ = 5 | x = x ^ 5 |
>>= | x >> = 5 | x = x >> 5 |
<<= | x << = 5 | x = x << 5 |
Python provides some special types of operators, such as identity operators or membership operators. Below, they are described through examples.
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.
Operator | Meaning | Example |
---|---|---|
is | If the operands are the same, it is true (referring to the same object) | x is true |
is not | If the operands are not the same, it is true (not referring to the same object) | x is not true |
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.
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.
Operator | Meaning | Example |
---|---|---|
in | If the value is found in the sequence/If the variable exists, it is true | 5 in x |
not in | If the value is not found in the sequence/If the variable exists, it is true | 5 not in x |
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.