Операторы Python — краткий справочник
Операторы Python позволяют нам выполнять стандартную обработку переменных. Мы рассмотрим различные типы операторов с примерами, а также приоритеты операторов. Это специальные символы, которые могут манипулировать значениями одного или нескольких операндов.
Список операторов Python
Операторы Python можно разделить на несколько категорий.
- Операторы присваивания
- Арифметические операторы
- Логические операторы
- Операторы сравнения
- Побитовые операторы
Операторы присваивания Python
Операторы присваивания включают базовый оператор присваивания, равный знаку (=).
Но чтобы упростить код и уменьшить избыточность, Python также включает арифметические операторы присваивания.
Это включает в себя оператор += в Python, используемый для присваивания сложения, оператор присваивания деления на пол //= и другие.
Вот список всех арифметических операторов присваивания в Python.
Operator | Description |
---|---|
+= | a+=b is equivalent to a=a+b |
*= | a*=b is equivalent to a=a*b |
/= | a/=b is equivalent to a=a/b |
%= | a%=b is equivalent to a=a%b |
**= | a**=b is equivalent to a=a**b (exponent operator) |
//= | a//=b is equivalent to a=a//b (floor division) |
Использование операторов присваивания
# take two variable, assign values with assignment operators
a=3
b=4
print("a: "+str(a))
print("b: "+str(b))
# it is equivalent to a=a+b
a+=b
print("a: "+str(a))
print("b: "+str(b))
# it is equivalent to a=a*b
a*=b
print("a: "+str(a))
print("b: "+str(b))
# it is equivalent to a=a/b
a/=b
print("a: "+str(a))
print("b: "+str(b))
# it is equivalent to a=a%b
a%=b
print("a: "+str(a))
print("b: "+str(b))
# it is equivalent to a=a**b ( exponent operator)
a**=b
print("a: "+str(a))
print("b: "+str(b))
# it is equivalent to a=a//b ( floor division)
a//=b
print("a: "+str(a))
print("b: "+str(b))
Арифметические операторы Python
Operator | Description | Example |
---|---|---|
+ | used to add two numbers | sum = a + b |
– | used for subtraction | difference = a – b |
* | used to multiply two numbers. If a string and int is multiplied then the string is repeated the int times. | mul = a*b>>> “Hi”*5 |
‘HiHiHiHiHi’ | ||
/ | used to divide two numbers | div = b/a |
% | modulus operator, returns the remainder of division | mod = a%b |
** | exponent operator |
#create two variables
a=100
b=200
# addition (+) operator
print(a+b)
# subtraction (-) operator
print(a-b)
# multiplication (*) operator
print(a*b)
# division (/) operator
print(b/a)
# modulus (%) operator
print(a%b) # prints the remainder of a/b
# exponent (**) operator
print(a**b) #prints a^b
Операторы сравнения Python
Operator | Description | Example |
---|---|---|
== | returns True if two operands are equal, otherwise False. | flag = a == b |
!= | returns True if two operands are not equal, otherwise False. | flag = a != b |
> | returns True if left operand is greater than the right operand, otherwise False. | flag = a > b |
< | returns True if left operand is smaller than the right operand, otherwise False. | flag = a < b |
>= | returns True if left operand is greater than or equal to the right operand, otherwise False. | flag = a > b |
<= | returns True if left operand is smaller than or equal to the right operand, otherwise False. | flag = a < b |
# create two variables
a=100
b=200
# (==) operator, checks if two operands are equal or not
print(a==b)
# (!=) operator, checks if two operands are not equal
print(a!=b)
# (>) operator, checks left operand is greater than right operand or not
print(a>b)
# (<) operator, checks left operand is less than right operand or not
print(a<b)
#(>=) operator, checks left operand is greater than or equal to right operand or not
print(a>=b)
# (<=) operator, checks left operand is less than or equal to right operand or not
print(a<=b)
Побитовые операторы Python
Operator | Description | Example |
---|---|---|
& | Binary AND Operator | x = 10 & 7 = 2 |
Binary OR Operator | ||
^ | Binary XOR Operator | x = 10 ^ 7 = 13 |
~ | Binary ONEs Compliment Operator | x = ~10 = -11 |
<< | Binary Left Shift operator | x = 10<<1 = 20 |
>> | Binary Right Shift Operator | x = 10>>1 = 5 |
#create two variables
a=10 # binary 1010
b=7 # binary 0111
# Binary AND (&) operator, done binary AND operation
print(a&b)
# Binary OR (|) operator, done binary OR operation
print(a|b)
# Binary XOR (^) operator, done binary XOR operation
print(a^b)
# Binary ONEs Compliment (~) operator, done binary One's Compliment operation
print(~a)
# Binary Left Shift (<<) operator, done binary Left Shift operation
print(a<<1)
# Binary Right Shift (>>) operator, done binary Right Shift operation
print(a>>1)
Логические операторы Python
Operator | Description | Example |
---|---|---|
and | Logical AND Operator | flag = exp1 and exp2 |
or | Logical OR Operator | flag = exp1 or exp2 |
not | Logical NOT Operator | flag = not(True) = False |
#take user input as int
a=int(input())
# logical AND operation
if a%4==0 and a%3==0:
print("divided by both 4 and 3")
# logical OR operation
if a%4==0 or a%3==0:
print("either divided by 4 or 3")
# logical NOT operation
if not(a%4==0 or a%3==0):
print("neither divided by 4 nor 3")
Приоритет оператора Python
Приоритет этих операторов означает уровень приоритета операторов. Это становится жизненно важным, когда выражение содержит несколько операторов. Например, рассмотрим следующее выражение:
>>> 2+3*4
Теперь, как вы думаете, какой будет серия операций? Мы можем сложить 2 и 3, а затем умножить результат на 4. Также мы можем сначала умножить 3 и 4, а затем добавить к ним 2. Здесь мы видим, что приоритет операторов важен.
Ниже приведен список операторов с указанием уровня приоритета. Это в порядке убывания. Это означает, что верхняя группа имеет больший приоритет, чем нижняя группа.
- Скобка –
()
- Возведение в степень –
**
- Комплимент, унарный плюс и минус –
~
,+
,-
- Умножить, разделить, по модулю –
*
,/
,%
- Сложение и вычитание –
+
,-
- Сдвиг вправо и влево —
>>
,<
- Побитовое И –
&
- Побитовое ИЛИ и XOR –
|
,^
- Операторы сравнения —
==
,!=
,>
,<
,>=
,<=
- Оператор назначения-
=