The study of operators and expressions in Python: arithmetic, logical and comparative operations

онлайн тренажер по питону
Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

Python provides a variety of operators for working with data and variables. Understanding these operators is crucial for effective Python programming. In this article, we will take a detailed look at all types of operators and expressions in Python with practical examples.

Python arithmetic operators

Arithmetic operators perform mathematical calculations on numeric values.

Arithmetic operator Sign Description
Addition + Adds two numbers
Subtraction - Subtracts the second number from the first
Multiplication * Multiplies two numbers
Division / Divides the first number by the second (float result)
The remainder of the division % Returns the remainder of the division
Integer division // Returns the whole part of the division
Exponentiation ** Raises the first number to the power of the second
a = 10
b = 3

sum_result = a + b  # 13
difference_result = a - b  # 7
product_result = a * b  # 30
division_result = a / b  # 3.3333333333333335
remainder_result = a % b  # 1
integer_division_result = a // b  # 3
power_result = a ** b  # 1000

Comparison operators in Python

Comparison operators are used to compare values and return boolean values True or False.

operator
The Sign Description
Is equal to == Checks the equality of values
Not equal to != Checks the disparity of values
More > Checks whether the first value is greater than the second
Less < Checks whether the first value is less than the second
Is greater than or equal to >= Checks whether the first value is greater than or equal to the second
Less than or equal to <= Checks whether the first value is less than or equal to the second
x = 5
y = 10

equal_result = x == y  # False
not_equal_result = x != y  # True
greater_than_result = x > y  # False
less_than_result = x < y  # True
greater_than_or_equal_result = x >= y  # False
less_than_or_equal_result = x <= y  # True

Python Logical Operators

Logical operators are used to combine conditional expressions.

Logical operator The word Description
Logical And and Returns True if both conditions are true
Logical OR or Returns True if at least one condition is true
Logical NOT not Inverts the boolean value
a = True
b = False

and_result = a and b  # False
or_result = a or b  # True
not_result = not a  # False

# Practical example
age = 25
has_license = True

can_drive = age >= 18 and has_license  # True

Python Assignment Operators

Assignment operators are used to assign values to variables and perform operations simultaneously.

operator
The Sign Description
Assignment = Assigns a value to a variable
Addition with assignment += Adds a value to a variable
Subtraction with assignment -= Subtracts a value from a variable
Multiplication with assignment *= Multiplies a variable by the value
Division with assignment /= Divides a variable by a value
The remainder of the division with assignment %= Assigns the remainder of the division
Integer division with assignment //= Assigns the result of integer division
Exponentiation with assignment **= Raises a variable to a power
x = 5
x += 3 # x = x + 3, now x is 8
x -= 2 # x = x - 2, now x is 6
x *= 2 # x = x * 2, now x is 12
x /= 4 # x = x / 4, now x is 3.0
x %= 2 # x = x % 2, now x is 1.0

Membership and identity operators

These operators check whether the elements belong to sequences and whether the objects are identical.

operator
The The word Description
Belongs to in Returns True if the element is present in the sequence
Does not belong to not in Returns True if the element is missing from the sequence
Identical is Returns True if both operands point to the same object
Is not identical is not Returns True if the operands point to different objects
my_list = [1, 2, 3, 4, 5]
x = 2

in_result = x in my_list  # True
not_in_result = x not in my_list  # False

# Example with the operator is
a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a is b) # True (one object)
print(a is c) # False (different objects)
print(a ==c) # True (same values)

Python bitwise operators

Bitwise operators work with the binary representation of numbers.

operator
The Sign Description
Bitwise And & Bitwise operation And
Bitwise OR | Bitwise operation OR
Bitwise exclusive OR ^ Bitwise operation exclusive OR
Bitwise negation ~ Bitwise inversion
Left shift << Shifts the bits to the left
Right shift >> Shifts the bits to the right
a = 5 # 101 in binary system
b = 3 # 011 in binary

print(a & b)  # 1 (001)
print(a | b)  # 7 (111)
print(a ^ b)  # 6 (110)
print(~a)     # -6
print(a << 1) # 10 (1010)
print(a >> 1) # 2 (10)

Expressions in Python: examples and explanations

Expressions in Python are combinations of operators and operands that are evaluated by the interpreter to obtain a value.

1. Arithmetic expressions

a = 2 + 3 * 4 # Result: 14 (multiplication first, then addition)
b = (2 + 3) * 4 # Result: 20 (parentheses first)

2. String expressions

greeting = 'Hello' + ' ' + 'world'  # "Hello world"
name = "Python"
message = f"Learning {name}!" # "Learning Python!"

3. Logical expressions

x = 6
is_valid = x > 5 and x < 10  # True
is_even = x % 2 == 0  # True

4. Comparison expressions

a = 3
b = 3
are_equal = a == b  # True
is_greater = a > b  # False

5. Element access expressions

my_list = [1, 2, 3, 4, 5]
first_element = my_list[0]  # 1
last_element = my_list[-1]  # 5

my_dict = {'name': 'Alice', 'age': 30}
name = my_dict['name']  # 'Alice'

6. Function call expressions

numbers = [1, 2, 3, 4, 5]
length = len(numbers)  # 5
maximum = max(numbers)  # 5
total = sum(numbers)  # 15

7. List generator expressions

squares = [x**2 for x in range(5)]  # [0, 1, 4, 9, 16]
even_numbers = [x for x in range(10) if x % 2 == 0]  # [0, 2, 4, 6, 8]

8. Conditional expressions (ternary operator)

x = -5
result = x if x > 0 else -x # 5 (absolute value)
status = "adult" if age>= 18 else "minor"

9. Tuple generation expressions

coordinates = [(x, y) for x in range(3) for y in range(3)]
# [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

10. Attribute expressions

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("Alice", 30)
name = person.name  # "Alice"
age = person.age  # 30

11. Slice expressions

my_list = [10, 20, 30, 40, 50]
sub_list = my_list[1:4]  # [20, 30, 40]
reversed_list = my_list[::-1]  # [50, 40, 30, 20, 10]

12. Expressions with lambda functions

square = lambda x: x**2
result = square(5)  # 25

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))  # [1, 4, 9, 16, 25]

Operator precedence in Python

When working with expressions, it is important to understand operator precedence.:

  1. Brackets ()
  2. Exponentiation **
  3. Unary operators +x, -x, ~x
  4. Multiplication, division *, /, //, %
  5. Addition, subtraction +, -
  6. Bitwise shifts ,
  7. Bitwise And &
  8. Bitwise exclusive OR ^
  9. Bitwise OR |
  10. Comparisons ==, !=, , =, , , ;=, is, is not, in, not in
  11. Logical NOT not
  12. Logical And and
  13. Logical OR or

Conclusion

Understanding operators and expressions in Python is fundamental to writing effective code. These concepts are used in all aspects of Python programming, from simple calculations to complex data processing algorithms. Practice with different types of operators to apply them confidently in your programs.

categories

  • Introduction to Python
  • Python Programming Basics
  • Control Structures
  • Data Structures
  • Functions and Modules
  • Exception Handling
  • Working with Files and Streams
  • File System
  • Object-Oriented Programming (OOP)
  • Regular Expressions
  • Additional Topics
  • General Python Base