๐Ÿ“˜ Lesson 3 examples: Operators and Expressions


1๏ธโƒฃ Arithmetic Operators

Example 1: Basic Calculations

a = 10
b = 3

print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a % b)
print(a ** b)

Output

13
7
30
3.3333333333333335
1
1000

Explanation

  • + adds values
  • - subtracts
  • * multiplies
  • / divides (always gives float)
  • % gives remainder
  • ** is power

Example 2: Salary Calculation

salary = 30000
bonus = 5000

total_salary = salary + bonus
print("Total Salary:", total_salary)

Output

Total Salary: 35000

2๏ธโƒฃ Assignment Operators

Example

salary = 20000
salary += 5000
salary -= 2000

print(salary)

Output

23000

Explanation

  • += adds and stores
  • -= subtracts and stores

3๏ธโƒฃ Comparison (Relational) Operators

Example

age = 25

print(age > 18)
print(age < 18)
print(age == 25)
print(age != 30)

Output

True
False
True
True

Explanation

  • > greater than
  • < less than
  • == equal to
  • != not equal to

Example with Names

name1 = "Sameer"
name2 = "Ayesha"

print(name1 == name2)

Output

False

4๏ธโƒฃ Logical Operators

Example

age = 22
has_id = True

print(age >= 18 and has_id)
print(age < 18 or has_id)
print(not has_id)

Output

True
True
False

Explanation

  • and โ†’ both conditions must be true
  • or โ†’ any one condition true
  • not โ†’ reverses result

5๏ธโƒฃ Identity Operators (is, is not)

Example

a = 10
b = 10

print(a is b)
print(a is not b)

Output

True
False

Explanation
Checks if both variables refer to the same object


6๏ธโƒฃ Membership Operators (in, not in)

Example

students = ["Sameer", "Ayesha", "Saddam"]

print("Sameer" in students)
print("Chandini" in students)

Output

True
False

7๏ธโƒฃ Operator Precedence

Example

result = 10 + 5 * 2
print(result)

Output

20

Explanation

  • Multiplication happens first โ†’ 5 * 2 = 10
  • Then addition โ†’ 10 + 10 = 20

Example with Brackets

result = (10 + 5) * 2
print(result)

Output

30

8๏ธโƒฃ Expressions Using Variables

Example

name = "Gousya"
age = 20

message = name + " is " + str(age) + " years old"
print(message)

Output

Gousya is 20 years old

9๏ธโƒฃ Input + Operators

marks1 = int(input("Enter marks 1: "))
marks2 = int(input("Enter marks 2: "))

total = marks1 + marks2
average = total / 2

print("Total:", total)
print("Average:", average)

Sample Output

Enter marks 1: 80
Enter marks 2: 90
Total: 170
Average: 85.0

๐Ÿ”Ÿ Real-Life Mini Example

salary = 25000
expenses = 18000

savings = salary - expenses
print("Savings:", savings)

Output

Savings: 7000


Comments

Leave a Reply

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