HomeBooks

En

Chapter 1
§1.0 Running Python
Chapter 2
§2.0 Basics
§2.2 Operators and Expressions
KM
bykarutt

2025-06-03

Operators and Expressions

In programming, you use "operators" to perform calculations, comparisons, and make decisions. Here are the main types and how to use them.

Arithmetic Operators (Calculations)

  • What You Can Do: Perform addition (+), subtraction (-), multiplication (*), division (/), and more.
a = 5
b = 3

print(a + b)  # 8
print(a - b)  # 2
print(a * b)  # 15
print(a / b)  # 1.666...

Comparison Operators (Comparing Values)

  • What You Can Do: Compare two values and get True or False as a result. Used in "conditionals" you'll learn next.
OperatorMeaningExampleResult
==Equal to (is also works)5 == 1False
!=Not equal to (is not also)5 != 3True
>Greater than1 > 4False
<Less than2 < 8True
>=Greater than or equal to5 >= 5True
<=Less than or equal to3 <= 5True

The result of a comparison operator is always a Boolean value: True or False.

x = 5
y = 5

print(x == y)  # True
print(x != y)  # False
print(x > 3)   # True
print(x < 10)  # True

Logical Operators (Combining Conditions)

  • What You Can Do: Use "and," "or," and "not" to combine or reverse conditions.
OperatorMeaningExampleResult
andBoth are TrueTrue and FalseFalse
orEither is TrueTrue or FalseTrue
notReversenot FalseTrue
flag1 = True
flag2 = False

print(flag1 and flag2)  # False
print(flag1 or flag2)   # True
print(not flag2)        # True
# Example combining with comparison operators
age = 12
is_student = False

print(age <= 18 or is_student)      # True
print(10 < age and age < 30)        # True

Assignment Operators (Storing/Updating Values)

  • What You Can Do: Assign values to variables or update them with calculations.
OperatorMeaningExampleSame as
=Assign valuex = 5
+=Add and assignx += 2x = x + 2
-=Subtract and assignx -= 1x = x - 1
*=Multiply and assignx *= 3x = x * 3
/=Divide and assignx /= 2x = x / 2
x = 4         # Assign 4 to x
y = x + 5     # Assign x + 5 to y

x += 2        # Add 2 to x (x = x + 2)
print(x)      # 6
print(y)      # 9
count = 0
Prev
§2.1 Variables and Data Types