🐍

Operators and Expressions

Beginner
70 XP
30 min
Lesson Content

Operators: Performing Operations

Operators are special symbols that perform operations on values. Python has many types of operators for different purposes.

Arithmetic Operators

Perform mathematical calculations:

# Addition
result = 10 + 5 # 15

# Subtraction
result = 10 - 5 # 5

# Multiplication
result = 10 * 5 # 50

# Division (always returns float)
result = 10 / 5 # 2.0

# Floor Division (returns integer)
result = 10 // 3 # 3

# Modulus (remainder)
result = 10 % 3 # 1

# Exponentiation (power)
result = 2 ** 3 # 8 (2 to the power of 3)

Comparison Operators

Compare values and return True or False:

# Equal to
5 == 5 # True
5 == 3 # False

# Not equal to
5 != 3 # True
5 != 5 # False

# Greater than
5 > 3 # True
3 > 5 # False

# Less than
3 < 5 # True
5 < 3 # False

# Greater than or equal
5 >= 5 # True
5 >= 3 # True

# Less than or equal
3 <= 5 # True
3 <= 3 # True

Logical Operators

Combine boolean values:

# AND - both must be True
True and True # True
True and False # False

# OR - at least one must be True
True or False # True
False or False # False

# NOT - reverses the value
not True # False
not False # True

Assignment Operators

Assign values to variables:

# Basic assignment
x = 10

# Add and assign
x += 5 # Same as: x = x + 5

# Subtract and assign
x -= 3 # Same as: x = x - 3

# Multiply and assign
x *= 2 # Same as: x = x * 2

# Divide and assign
x /= 2 # Same as: x = x / 2

String Operators

Work with text:

# Concatenation (+)
first = "Hello"
second = " World"
greeting = first + second # "Hello World"

# Repetition (*)
repeat = "Hi" * 3 # "HiHiHi"

Operator Precedence

Python follows mathematical order of operations:

  1. Parentheses: ()
  2. Exponentiation: **
  3. Multiplication, Division, Floor Division, Modulus: * / // %
  4. Addition, Subtraction: + -
result = 2 + 3 * 4      # 14 (not 20)
result = (2 + 3) * 4 # 20
Example Code

Practice using different operators to perform calculations.

# Calculate the area of a rectangle
# length = 10, width = 5
length = 10
width = 5

# Calculate area (length * width)
area = length * width
print("Area:", area)

# Calculate perimeter (2 * (length + width))
perimeter = 2 * (length + width)
print("Perimeter:", perimeter)

Expected Output:

Area: 50
Perimeter: 30
Study Tips
  • Read the theory content thoroughly before practicing
  • Review the example code to understand key concepts
  • Proceed to the Practice tab when you're ready to code