Lesson 3: Operators and Expressions

๐ŸŽฏ Lesson Objective

To understand different types of operators in Python and how to use them in expressions to perform calculations or logic.


๐Ÿง  1. What Are Operators?

Operators are special symbols that perform operations on variables and values.
Expressions are combinations of variables, operators, and values that produce a result.

Example:

x = 10
y = 5
result = x + y
print(result)  # Output: 15

โš™๏ธ 2. Types of Operators

A. Arithmetic Operators

Used for mathematical operations.

OperatorDescriptionExampleOutput
+Addition5 + 38
-Subtraction5 - 32
*Multiplication5 * 315
/Division10 / 33.3333
//Floor Division10 // 33
%Modulus (Remainder)10 % 31
**Exponentiation2 ** 38

Example:

a, b = 10, 3
print(a + b, a - b, a * b, a / b, a // b, a % b, a ** b)

B. Comparison Operators

Used to compare two values. They return either True or False.

OperatorMeaningExampleOutput
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than7 > 4True
<Less than3 < 5True
>=Greater or equal5 >= 5True
<=Less or equal4 <= 3False

Example:

x, y = 10, 20
print(x > y)  # False
print(x != y) # True

C. Logical Operators

Used to combine conditional statements.

OperatorDescriptionExampleOutput
andTrue if both are truex > 5 and y < 30True
orTrue if one is truex > 15 or y < 30True
notReverses the resultnot(x > 5)False

Example:

x, y = 10, 20
print(x > 5 and y < 25)  # True
print(x > 15 or y < 25)  # True
print(not(x > 5))        # False

D. Assignment Operators

Used to assign values to variables.

OperatorExampleEquivalent To
=x = 10x = 10
+=x += 2x = x + 2
-=x -= 3x = x - 3
*=x *= 2x = x * 2
/=x /= 2x = x / 2

Example:

x = 5
x += 3
print(x)  # Output: 8

E. Bitwise Operators (Advanced)

Used to perform operations on binary numbers.

OperatorDescriptionExampleOutput
&AND5 & 31
``OR`5
^XOR5 ^ 36
~NOT~5-6
<<Left shift5 << 110
>>Right shift5 >> 12

Example:

a, b = 5, 3
print(a & b, a | b, a ^ b)

๐Ÿงฉ 3. Expressions

An expression is a combination of values, variables, and operators that evaluates to a result.

Example:

x = 10
y = 5
z = (x + y) * 2
print(z)  # Output: 30

๐Ÿง  4. Practice Ideas

  1. Write a Python program to calculate the area of a rectangle using variables.
  2. Check if a number is positive and even using comparison and logical operators.
  3. Create a program that swaps two variables using assignment operators.

more examples


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *