0% found this document useful (0 votes)
4 views36 pages

Python Operators and Expressions Guide

The document presents an introduction to Python operators, expressions, and error handling, emphasizing their importance in programming. It covers various types of operators (arithmetic, relational, logical, assignment, and special), expressions versus statements, and the significance of understanding errors in coding. The content is structured into units with learning objectives and hands-on activities to reinforce the concepts.

Uploaded by

mkumarbsr42
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views36 pages

Python Operators and Expressions Guide

The document presents an introduction to Python operators, expressions, and error handling, emphasizing their importance in programming. It covers various types of operators (arithmetic, relational, logical, assignment, and special), expressions versus statements, and the significance of understanding errors in coding. The content is structured into units with learning objectives and hands-on activities to reinforce the concepts.

Uploaded by

mkumarbsr42
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python 🐍

Operators, Expressions & Errors


Presented by: Jaskaran Singh

➕➖🟰💥
Why does this matter? 🤔
Learning operators and expressions is like learning the grammar of a language. You
can have all the words (data), but without grammar (operators), you can't form
meaningful sentences (programs).

Analogy: Making Chai ☕


Your ingredients (tea, milk, sugar, water) are the **data**. The steps like 'boil', 'mix', 'stir', and
'pour' are the **operators**. The final delicious chai is the **result** of your expression!
A little joke to start...

Why did the Python programmer break up with the C++ programmer?

Because he didn't like her pointers! 😉

(Don't worry, Python makes things much simpler!)


Unit 1: Operators - Our Coding Toolkit 🛠️

Learning Objectives

By the end of this unit, I can...

✅ Identify and use **Arithmetic** operators for calculations.


✅ Compare values using **Relational** operators.
✅ Combine conditions with **Logical** operators.
✅ Assign and update values using **Assignment** operators.
✅ Check for identity and membership with **Special** operators.
Arithmetic Operators: The Calculators
These are the basic math symbols you already know and love.

a = 10
b = 3

print(a + b) # Addition -> 13


print(a - b) # Subtraction -> 7
print(a * b) # Multiplication -> 30
print(a / b) # Division -> 3.333...
print(a // b) # Floor Division (Quotient) -> 3
print(a % b) # Modulus (Remainder) -> 1
print(a ** b) # Exponent (a to the power of b) -> 1000

Pro Tip
Use // when you want an integer result from division (like splitting toffees among friends),
and % to check for even/odd numbers!
Hands-On Activity 💻 (2 mins)

Calculate a Cricketer's Strike Rate

A batsman scored 90 runs off 45 balls. Write a single line of Python code to
calculate and print their strike rate.

Formula
Strike Rate = (Runs Scored / Balls Faced) * 100

Click for Hint


Click for Solution
Quick Check! 🧠

1. What is the result of `13 % 4` in Python?

3.25

2. Which operator is used for exponentiation (power)?

**

//
Relational Operators: The Comparers
These operators compare two values and return a Boolean result: True or False .

marks = 85

print(marks > 90) # Greater than -> False


print(marks < 90) # Less than -> True
print(marks == 85) # Equal to -> True
print(marks != 100) # Not equal to -> True
print(marks >= 33) # Greater than or equal to -> True
print(marks <= 85) # Less than or equal to -> True

Common Pitfall!
Don't mix up = (assignment) and == (comparison).
x = 5 means "put 5 into x".
x == 5 means "is x equal to 5?".
Logical Operators: The Decision Makers
Combine multiple True / False conditions.

AND OR NOT

True only if both are True if at least one Flips the value. not
true. Like needing a is true. Like needing a True is False , and
ticket AND a passport PAN card OR an not False is True .
to fly internationally. Aadhaar card for ID.
is_raining =
False
age = 20 is_sunday = True print(not
has_license = is_holiday = is_raining) # ->
True False True
print(age > 18 print(is_sunday
and has_license) or is_holiday) #
# -> True -> True
Micro-Activity: Predict the Output! 🔮
Work with a partner. What will Python print for each of these lines?

x = 10
y = 5
z = 10

# Expression 1
print((x > y) and (z == y))

# Expression 2
print((x == z) or (y > x))

# Expression 3
print(not (x != z))

Click for Answers


Quick Check! 🧠

1. What is the value of `(5 > 10) or (10 == 10)`?

True

False

Error

2. Which expression checks if a number `n` is NOT between 10 and 20?

`n > 10 and n < 20`

`n == 10 or n == 20`

`n < 10 or n > 20`


Assignment Operators: The Shortcuts
Used to assign and update variable values concisely.

Standard Way Augmented (Shortcut) Way

score = 0 score = 0
score = score + 10 # Add 10 score += 10 # Add 10

price = 100 price = 100


price = price - 5 # Discount price -= 5 # Discount

multiplier = 2 multiplier = 2
multiplier = multiplier * 3 multiplier *= 3

Both columns do the exact same thing! The right side is just faster to type.
Special Operators: `is` and `in`

Identity Operators: is , is Membership Operators:


not in , not in

Checks if two variables refer to the Checks if a value exists within a


exact same object in memory. It's sequence (like a list, tuple, or
stricter than == . string).

Analogy: Identical twins might look Analogy: Checking if a student's


the same ( == ), but they are two name is in the class register.
different people ( is is false).
team_india = ["Rohit", "Virat",
"Bumrah"]
a = [1, 2, 3] player = "Virat"
b = [1, 2, 3] absentee = "Dhoni"
c = a
print(player in team_india)
print(a == b) # -> True # -> True
(values are same) print(absentee in team_india) #
print(a is b) # -> False -> False
(different objects) print("h" in "Rohit") #
print(a is c) # -> True (same -> True
object)
Unit 1 Summary
We've covered the fundamental building blocks for making your code *do* things!

Arithmetic: For math ( + , - , * , / , // , % , ** )

Relational: For comparisons ( == , != , > , < )

Logical: For combining conditions ( and , or , not )

Assignment: For shortcuts ( += , -= , etc.)

Special: For identity ( is ) and membership ( in )

Fun Fact 🤯
In Python, you can "chain" comparisons! To check if `marks` are between 80 and 90, you can
simply write `80 < marks < 90`. This is much cleaner than `marks > 80 and marks < 90`.
Unit 2: Expressions, I/O & Conversions 📜

Learning Objectives

By the end of this unit, I can...

✅ Explain the difference between an **expression** and a **statement**.


✅ Understand and apply the **order of operations** (BODMAS).
✅ Convert data from one type to another (**Type Conversion**).
✅ Get user data using `input()` and display results with `print()`.
Expressions vs. Statements
A simple but crucial distinction.

Expression Statement

A combination of values, variables, A complete instruction that Python


and operators that **evaluates to a can execute. It performs an
single value**. **action**.

Think of it as a "phrase". Think of it as a full "sentence".

5 + 10 # Evaluates to # Statements that perform


15 actions
x / 2 # Evaluates to x = 20
a number print("Hello, world!")
age > 18 # Evaluates to import math
True or False if x > 10:
"Hello" + "!" # Evaluates to print("Greater")
"Hello!"

Key Idea
An expression can be part of a statement (e.g., `x = 5 + 10`), but a statement is a complete
command on its own.
Operator Precedence: Python's BODMAS
Python doesn't just calculate left-to-right. It follows a strict order of operations, just
like in math class!

1. Parentheses `()`

2. Exponents `**`

3. Multiplication `*`, Division `/`, Floor `//`, Modulus `%` (Left-to-Right)

4. Addition `+`, Subtraction `-` (Left-to-Right)

A common mnemonic is PEMDAS.

result = 5 + 2 * 3 ** 2 - 1
# 1. Exponent: 3 ** 2 -> 9
# 2. Multiplication: 2 * 9 -> 18
# 3. Addition: 5 + 18 -> 23
# 4. Subtraction: 23 - 1 -> 22
print(result) # -> 22
Quick Check! 🧠

1. What is the value of `100 / 10 * 2`?

5.0

20.0

10.0

2. Which part of `(5 + 3) * 2 > 15` is an expression?

The entire line is an expression.

Only `(5 + 3)`.

This is a statement, not an expression.


Type Conversion: Changing Hats 🎩
Sometimes you need to convert data from one type to another.

Implicit Conversion Explicit Conversion


(Automatic) (Manual)

Python does this automatically to You force the conversion using


prevent data loss. Usually when functions like int() , float() ,
mixing integers and floats. str() .

num_int = 10 num_str = "100"


num_float = 5.5
# Convert string to integer for
result = num_int + num_float math
# Python converts 10 to 10.0 num_int = int(num_str)
# result is 15.5 (a float) print(num_int + 50) # -> 150
print(type(result)) #
# Convert integer to string for
joining
age = 21
message = "I am " + str(age) +
" years old."
print(message)
Input and Output: Chatting with your
Program
How to get data from the user and display results.

Displaying Output: print()

name = "Arjun"
score = 95
# You can print multiple items, separated by commas
print("Player:", name, "Score:", score)
# Output: Player: Arjun Score: 95

# Use sep to change separator, and end to change ending


print("Hello", "World", sep="---", end="!")
# Output: Hello---World!

Accepting Input: input()

name = input("Enter your name: ")


print("Welcome,", name)

CRITICAL Pitfall!
input() ALWAYS returns a string! If you need a number, you MUST convert it.

age_str = input("Enter your age: ")


# This will cause an error: age_str + 5
age_num = int(age_str)
print("Next year you will be", age_num + 1)
Hands-On Activity 💻 (3 mins)

Simple Area Calculator

Write a short program that does the following:

1. Asks the user to enter the length of a rectangle.

2. Asks the user to enter the width of a rectangle.

3. Calculates the area (length * width).

4. Prints the result in a user-friendly format, like "The area is: [result]".

Click for Solution


Unit 3: Errors - The Three Musketeers of
Mistakes 💥

Learning Objectives

By the end of this unit, I can...

✅ Differentiate between **Syntax**, **Runtime**, and **Logical** errors.


✅ Read an error message (traceback) to understand what went wrong.
✅ Apply basic debugging strategies to fix my code.

Pro Mindset
Errors aren't failures; they are helpful clues from the computer! Learning to read them is a
superpower.
The Three Main Types of Errors

1. Syntax 2. Runtime 3. Logical


Errors Errors Errors

Analogy: Bad Analogy: A Analogy: A perfectly


grammar. Python grammatically correct valid sentence that
doesn't understand sentence that is says the wrong thing.
your instruction impossible to The program runs
before the program perform. The code successfully but gives
even runs. starts running but the wrong answer.
then crashes.
Examples: Missing Example: Calculating
colon, mismatched Examples: Dividing average of two
parentheses, incorrect by zero, trying to add numbers but dividing
spelling of keywords. a number and a by 3.
string, using a
# Missing colon variable that doesn't num1 = 10
at the end of if num2 = 20
if x > 5 exist. # Oops, should be
/ 2
print("Hello") average = (num1 +
# num2) / 3
# Mismatched ZeroDivisionError print(average) #
quotes print(10 / 0) Prints 10.0, but
print('Hello") should be 15.0
# TypeError
print("Age: " +
✅ Easiest to fix! 21) ❌ Hardest to fix!
The error message Python doesn't know
🤔 Medium you made a mistake.
difficulty. The error
tells you the exact message (traceback) You must find it
line. points to the problem yourself.
Debugging 101:area.
Becoming a Code
Detective 🕵️
When you encounter an error, don't panic! Follow these steps:

1. Read the Error Message Carefully: The last line is usually the most important.
It tells you the type of error (e.g., `TypeError`) and a description.

2. Check the Line Number: The message will point to the exact line where the
program crashed.

3. Use `print()` statements: The simplest debugging tool! Print out your
variables at different stages to see their values and find where things go
wrong.

4. Rubber Duck Debugging: Explain your code, line-by-line, to an inanimate


object (like a rubber duck). You'll often find your own mistake while explaining
it! 🦆

Fun Fact 🐛
The term "bug" in computing originated in 1947 when a real moth got stuck in a relay of the
Harvard Mark II computer, causing it to malfunction. The operators "debugged" the computer
by removing the moth!
Micro-Activity: Spot the Bug! 🐞
Identify the type of error (Syntax, Runtime, or Logical) in each code snippet.

Snippet 1 Snippet 2 Snippet 3

price = "250" name = # Calculate


discount = 50 input("Name: ") perimeter of a
final_price = print("Hello, " square
price - discount name) side = 10
print(final_price) perimeter = 2 *
side
print(perimeter)

Click for Answers


Quick Check! 🧠

1. The code `x = int('hello')` will cause what type of error?

Runtime Error

Syntax Error

Logical Error

2. Your program calculates an exam average as 110 out of 100. It runs


without crashing. What kind of error is this?

Syntax Error

Runtime Error

Logical Error
Session Wrap-Up & Summary 🎁

What We've Learned Today

Operators are the verbs of Python, allowing us to perform actions like math ( + ,
* ), comparison ( > , == ), and logic ( and , or ).

An Expression evaluates to a single value, while a Statement is a full command.

Python follows **BODMAS/PEMDAS** to evaluate expressions. When in doubt,


use parentheses `()`!

Use `input()` to get user data (always a string!) and `print()` to display results.
Remember to convert types with `int()`, `float()`, etc.

**Errors** are your friends! Syntax errors are grammar mistakes, Runtime errors
are impossible commands, and Logical errors are flaws in your thinking.

3 Key Takeaways

1. Always be mindful of data types ( int , str , float ).

2. The most common bug for beginners is `input()` returning a string. Always
convert it for math!

3. Don't be afraid of error messages. Read them! They tell you exactly where to
look.
Further Practice & Homework 🏡
Solidify your understanding with these challenges.

🟢 Easy 🟡 Medium 🔴 Challenge


Write a program that Create a simple Write a program to
takes a temperature calculator that asks calculate a Simple
in Celsius from the the user for two Interest. Ask the user
user and converts it numbers and an for Principal, Rate of
to Fahrenheit. operator (+, -, *, /) Interest (per year),
and then prints the and Time (in years).
Formula: F = (C *
result. Check if any input is
9/5) + 32
less than or equal to
zero and print an
error message if it is.

Formula: SI = (P * R *
T) / 100
Final Quiz! 🏆
Let's see what you've learned. Answer these questions to test your knowledge.

Start Final Quiz


Final Quiz (1/5)

What is the output of `print(3 * (1 + 2) ** 2)`?

18

36

27
Final Quiz (2/5)

A user enters "25" at an `input()` prompt. What is the data type of the
variable that stores this input?

str

int

float
Final Quiz (3/5)

The expression `not (age >= 18 and has_id)` is `True`. What can you say for
sure?

The person is 18 or older AND has an ID.

At least one of the conditions (`age >= 18`, `has_id`) is false.

The person is younger than 18 AND has no ID.


Final Quiz (4/5)

What does the `is` operator check?

If two values are equal.

If a value is present in a list.

If two variables point to the exact same object in memory.


Final Quiz (5/5)

The code `for i in range(5)` (with a missing colon) will cause a:

Runtime Error

Syntax Error

Logical Error
Quiz Complete!
Your final score is:

0/0
Review Suggestions
If you struggled with any questions, revisit the slides on Operator Precedence, Type
Conversion with `input()`, and the three types of Errors. Practice makes perfect!

Reset and Start Over


Thank You! 🙏
Questions?
Happy Coding!

- Jaskaran Singh

Deck created with vanilla HTML, CSS, and JS.

You might also like