Introduction to Python Operators and Expressions
Course: Python Training
Topic: Introduction to Python Operators and Expressions
Course Link: Python Training Course at JustAcademy
Demo Link: Register for a Python Course Demo
Website: JustAcademy Official Website
1. Introduction to Python Operators and Expressions
Python is a versatile programming language used in web development, automation, data analytics, artificial intelligence, machine learning, and software development. Operators and expressions are fundamental concepts that allow programmers to perform calculations, compare values, make decisions, manipulate data, and control program behavior.
An operator is a symbol or keyword that performs an operation on one or more values. An expression is a combination of values, variables, operators, and sometimes function calls that Python evaluates to produce a result.
For example, in the expression 10 + 5, the plus sign is an operator, the numbers are operands, and the complete expression evaluates to 15.
first_number = 10
second_number = 5
result = first_number + second_number
print(result)
Output:
15
In this program, + is the addition operator, first_number and second_number are operands, and first_number + second_number is an expression.
Why Are Operators and Expressions Important?
- They help perform mathematical calculations.
- They allow programs to compare values and evaluate conditions.
- They support decision-making using Boolean logic.
- They help update variables efficiently.
- They allow programmers to check membership in collections.
- They support bitwise operations on integer values.
- They help build complex calculations from smaller expressions.
- They are essential for loops, conditional statements, functions, and data processing.
2. Learning Objectives
After completing this topic, learners should be able to:
- Define operators, operands, and expressions.
- Understand the major categories of Python operators.
- Perform arithmetic calculations using Python.
- Compare values using comparison operators.
- Combine conditions using logical operators.
- Use assignment and augmented assignment operators.
- Understand identity and membership operators.
- Perform bitwise operations on integers.
- Understand operator precedence and associativity.
- Evaluate expressions involving multiple operators.
- Identify common operator-related errors.
- Apply operators and expressions in practical Python programs.
3. Understanding Operators, Operands, and Expressions
3.1 What Is an Operator?
An operator instructs Python to perform a specific operation. Depending on the operator, the operation may involve arithmetic, comparison, logical evaluation, assignment, or another supported action.
total = 20 + 10
In this statement, + is the operator that adds two numbers.
3.2 What Is an Operand?
An operand is a value or object on which an operator acts.
result = 8 * 4
Here, 8 and 4 are operands, while * is the multiplication operator.
3.3 What Is an Expression?
An expression is a combination of literals, variables, operators, and other elements that Python evaluates to produce a value.
price = 500
quantity = 3
total_cost = price * quantity
discounted_cost = total_cost - 100
print(discounted_cost)
Output:
1400
In this example, price * quantity and total_cost - 100 are expressions.
3.4 Simple Expression Structure
| Element |
Example |
Meaning |
| Operator |
+ |
Performs addition. |
| Operand |
10 |
A value used by an operator. |
| Expression |
10 + 5 |
Combines values and an operator. |
| Result |
15 |
The value produced by evaluating the expression. |
4. Categories of Python Operators
Python provides several categories of operators. Each category is used for a different type of operation.
| Operator Category |
Operators |
Purpose |
| Arithmetic |
+, -, *, /, //, %, ** |
Perform mathematical calculations. |
| Comparison |
==, !=, >, <, >=, <= |
Compare two values. |
| Logical |
and, or, not |
Combine or reverse logical conditions. |
| Assignment |
=, +=, -=, *=, /=, and others |
Assign or update variable values. |
| Identity |
is, is not |
Check whether two references point to the same object. |
| Membership |
in, not in |
Check whether a value is present in a container. |
| Bitwise |
&, |, ^, ~, <<, >> |
Operate on integer bits. |
| Conditional expression |
value_if_true if condition else value_if_false |
Select a value based on a condition. |
| Assignment expression |
:= |
Assign a value within an expression in supported contexts. |
5. Arithmetic Operators in Python
Arithmetic operators are used to perform mathematical calculations such as addition, subtraction, multiplication, division, and exponentiation. They are frequently used in financial calculations, data analysis, billing systems, and scientific applications.
5.1 Addition Operator (+)
The addition operator adds numeric values. With compatible sequences, it can also concatenate values, such as joining two strings or two lists.
a = 10
b = 5
print(a + b)
Output: 15
String concatenation example:
first_name = "Asha"
last_name = "Patel"
full_name = first_name + " " + last_name
print(full_name)
Output: Asha Patel
5.2 Subtraction Operator (-)
The subtraction operator calculates the difference between numeric values.
total_amount = 1000
expense = 250
remaining_amount = total_amount - expense
print(remaining_amount)
Output: 750
5.3 Multiplication Operator (*)
The multiplication operator multiplies numeric values. It can also repeat certain sequences, such as strings and lists.
price = 200
quantity = 4
total_price = price * quantity
print(total_price)
Output: 800
String repetition example:
print("Python " * 3)
Output: Python Python Python
5.4 Division Operator (/)
The division operator divides one number by another and produces a floating-point result for ordinary numeric operands.
total_marks = 450
subjects = 5
average = total_marks / subjects
print(average)
Output: 90.0
Division by zero raises a ZeroDivisionError.
5.5 Floor Division Operator (//)
Floor division returns the quotient rounded down toward negative infinity. It is useful when a program needs the whole-number quotient of a division operation.
print(17 // 5)
print(-17 // 5)
Output:
3
-4
For negative values, floor division is not the same as truncating toward zero. The result of -17 // 5 is -4 because the mathematical quotient is rounded down.
5.6 Modulus Operator (%)
The modulus operator returns the remainder from division. It is commonly used to check whether numbers are even or odd, determine divisibility, and cycle through positions.
print(17 % 5)
print(20 % 2)
Output:
2
0
Checking whether a number is even:
number = 24
if number % 2 == 0:
print("Even number")
else:
print("Odd number")
5.7 Exponentiation Operator (**)
The exponentiation operator raises a number to a power.
print(2 ** 3)
print(5 ** 2)
print(9 ** 0.5)
Output:
8
25
3.0
The expression 2 ** 3 means two raised to the power of three.
Arithmetic Operator Summary
| Operator |
Name |
Example |
Result |
+ |
Addition |
10 + 3 |
13 |
- |
Subtraction |
10 - 3 |
7 |
* |
Multiplication |
10 * 3 |
30 |
/ |
Division |
10 / 4 |
2.5 |
// |
Floor division |
10 // 4 |
2 |
% |
Modulus |
10 % 4 |
2 |
** |
Exponentiation |
2 ** 4 |
16 |
6. Comparison Operators
Comparison operators compare two values and ordinarily produce a Boolean result: True or False. They are commonly used in conditions, loops, validation, filtering, and decision-making.
6.1 Equal To (==)
The equal-to operator checks whether two values compare equal.
first_value = 10
second_value = 10
print(first_value == second_value)
Output: True
6.2 Not Equal To (!=)
The not-equal operator checks whether two values compare unequal.
print(10 != 5)
Output: True
6.3 Greater Than (>)
age = 25
print(age > 18)
Output: True
6.4 Less Than (<)
temperature = 15
print(temperature < 20)
Output: True
6.5 Greater Than or Equal To (>=)
marks = 75
print(marks >= 75)
Output: True
6.6 Less Than or Equal To (<=)
items_in_stock = 10
print(items_in_stock <= 10)
Output: True
Comparison Operator Summary
| Operator |
Meaning |
Example |
Result |
== |
Equal to |
5 == 5 |
True |
!= |
Not equal to |
5 != 3 |
True |
> |
Greater than |
8 > 4 |
True |
< |
Less than |
3 < 7 |
True |
>= |
Greater than or equal to |
5 >= 5 |
True |
<= |
Less than or equal to |
4 <= 6 |
True |
Important Difference Between = and ==
The single equals sign = is used for assignment, while the double equals sign == is used for comparison.
score = 90
print(score == 90)
Output: True
7. Logical Operators
Logical operators combine conditions or reverse a truth value. They are frequently used with if statements and loops.
7.1 Logical AND
The and operator evaluates the second operand only if the first operand is truthy. In Boolean conditions, the result is true only when both conditions are true.
age = 25
has_license = True
if age >= 18 and has_license:
print("Allowed to drive")
Output: Allowed to drive
7.2 Logical OR
The or operator evaluates the second operand only if the first operand is falsy. In Boolean conditions, the result is true if at least one condition is true.
is_weekend = False
is_holiday = True
if is_weekend or is_holiday:
print("No regular office work")
Output: No regular office work
7.3 Logical NOT
The not operator reverses the truth value of its operand.
is_logged_in = False
print(not is_logged_in)
Output: True
Truth Table for Logical Operators
| A |
B |
A and B |
A or B |
not A |
| True |
True |
True |
True |
False |
| True |
False |
False |
True |
False |
| False |
True |
False |
True |
True |
| False |
False |
False |
False |
True |
Short-Circuit Evaluation
Python's logical operators use short-circuit evaluation. With and, the second operand is not evaluated if the first operand is falsy. With or, the second operand is not evaluated if the first operand is truthy.
number = 0
if number != 0 and 10 / number > 1:
print("Condition satisfied")
else:
print("Condition not satisfied")
The program does not divide by zero because the first condition is false and Python skips the second condition.
Important: The operators and and or return one of their operands, not necessarily a Boolean value. In an if condition, their truthiness determines the branch that executes.
8. Assignment Operators
Assignment operators assign values to variables. Python also provides augmented assignment operators that combine an operation with reassignment.
8.1 Simple Assignment (=)
student_name = "Riya"
marks = 85
The assignment operator binds each variable name to the value on the right-hand side.
8.2 Addition Assignment (+=)
count = 10
count += 5
print(count)
Output: 15
This is equivalent to count = count + 5 for this integer example.
8.3 Subtraction Assignment (-=)
balance = 1000
balance -= 200
print(balance)
Output: 800
8.4 Multiplication Assignment (*=)
price = 50
price *= 3
print(price)
Output: 150
8.5 Division Assignment (/=)
total = 100
total /= 4
print(total)
Output: 25.0
8.6 Other Augmented Assignment Operators
| Operator |
Example |
Typical Effect |
+= |
x += 3 |
Adds 3 to x. |
-= |
x -= 3 |
Subtracts 3 from x. |
*= |
x *= 3 |
Multiplies x by 3. |
/= |
x /= 3 |
Divides x by 3. |
//= |
x //= 3 |
Applies floor division. |
%= |
x %= 3 |
Stores the remainder. |
**= |
x **= 3 |
Raises x to the power of 3. |
&= |
x &= 3 |
Applies bitwise AND. |
|= |
x |= 3 |
Applies bitwise OR. |
^= |
x ^= 3 |
Applies bitwise XOR. |
<<= |
x <<= 1 |
Applies a left shift. |
>>= |
x >>= 1 |
Applies a right shift. |
@= |
matrix_a @= matrix_b |
Applies matrix multiplication and assignment for supported types. |
Augmented assignment can behave differently from writing a longer assignment expression for mutable objects. For example, list_a += list_b can update the existing list in place.
9. Identity Operators
Identity operators check whether two references point to the same object in memory. Python provides is and is not.
9.1 The is Operator
first_list = [1, 2, 3]
second_list = first_list
print(first_list is second_list)
Output: True
Both variables refer to the same list object.
9.2 The is not Operator
first_list = [1, 2, 3]
second_list = [1, 2, 3]
print(first_list is not second_list)
Output: True
The two lists contain equal values but are separate list objects.
Difference Between == and is
| Operator |
Purpose |
Example |
== |
Checks value equality. |
[1, 2] == [1, 2] gives True. |
is |
Checks object identity. |
Two separately created lists are generally not identical. |
Use == to compare values and is to check identity. A common recommended use is checking whether a value is None:
result = None
if result is None:
print("No result available")
10. Membership Operators
Membership operators check whether a value is present in a sequence, collection, or another object that supports membership testing.
10.1 The in Operator
languages = ["Python", "Java", "JavaScript"]
print("Python" in languages)
Output: True
10.2 The not in Operator
available_colors = ["red", "green", "blue"]
print("yellow" not in available_colors)
Output: True
Membership Testing With Strings
message = "Learn Python Programming"
print("Python" in message)
print("Java" in message)
Output:
True
False
Membership Testing With Dictionaries
Membership testing on a dictionary checks its keys by default, not its values.
student = {
"name": "Riya",
"age": 21
}
print("name" in student)
print("Riya" in student)
print("Riya" in student.values())
Output:
True
False
True
11. Bitwise Operators
Bitwise operators work on the binary representation of integers. They are used in low-level programming, bit flags, embedded systems, networking, and certain performance-sensitive tasks.
Understanding Binary Numbers
Binary is a number system that uses only two digits: 0 and 1. For example, decimal number 5 is represented as binary 0101 when shown with four bits.
| Decimal |
Binary (4-bit illustration) |
| 1 |
0001 |
| 2 |
0010 |
| 3 |
0011 |
| 4 |
0100 |
| 5 |
0101 |
| 6 |
0110 |
11.1 Bitwise AND (&)
The AND operator sets a bit to 1 only when both corresponding bits are 1.
a = 6 # Binary: 0110
b = 3 # Binary: 0011
print(a & b)
Output: 2
Binary calculation: 0110 & 0011 = 0010.
11.2 Bitwise OR (|)
The OR operator sets a bit to 1 when either corresponding bit is 1.
a = 6
b = 3
print(a | b)
Output: 7
11.3 Bitwise XOR (^)
The XOR operator sets a bit to 1 when the corresponding bits differ.
a = 6
b = 3
print(a ^ b)
Output: 5
11.4 Bitwise NOT (~)
The bitwise NOT operator inverts the bits of an integer. Python integers behave as though they have an unbounded sign extension, so the result may look different from a fixed-width binary example.
number = 5
print(~number)
Output: -6
For Python integers, ~x is equivalent to -x - 1.
11.5 Left Shift (<<)
The left-shift operator shifts the bits to the left by the specified number of positions. For non-negative integers, shifting left by one position is equivalent to multiplying by two.
number = 5
print(number << 1)
Output: 10
11.6 Right Shift (>>)
The right-shift operator shifts bits to the right. For integers, a right shift by one position corresponds to floor division by two.
number = 10
print(number >> 1)
Output: 5
12. Conditional Expressions
A conditional expression selects one of two values depending on whether a condition is true or false. It is often called the ternary operator in Python tutorials, although Python expresses it with the words if and else.
Syntax
value_if_true if condition else value_if_false
Example: Pass or Fail
marks = 65
result = "Pass" if marks >= 40 else "Fail"
print(result)
Output: Pass
Example: Find the Larger Number
a = 20
b = 15
larger = a if a > b else b
print(larger)
Output: 20
Conditional expressions are useful for short choices. For more complicated decision-making, a normal if/elif/else statement is usually clearer.
13. Assignment Expressions (:=)
The assignment expression operator, also called the walrus operator, assigns a value to a variable as part of an expression. It was introduced in Python 3.8.
Example: Capture a Value While Checking a Condition
user_name = input("Enter your name: ")
if (name_length := len(user_name)) > 0:
print("Name length:", name_length)
else:
print("No name was entered")
The expression assigns the length to name_length and then checks whether it is greater than zero.
The walrus operator is useful in selected situations, but it should not be used when a regular assignment would make the code easier to understand.
14. Understanding Expressions in Python
Expressions can be simple or complex. A simple expression may contain a single value or variable, while a complex expression combines multiple operators, operands, and function calls.
14.1 Simple Expressions
x = 10
y = 20
print(x)
print(x + y)
print(x > y)
14.2 Complex Expressions
price = 1000
quantity = 3
discount_rate = 0.10
total = price * quantity
discount = total * discount_rate
final_price = total - discount
print(final_price)
Output:
2700.0
14.3 Expressions Using Function Calls
numbers = [10, 20, 30, 40]
average = sum(numbers) / len(numbers)
print(average)
Output: 25.0
14.4 Expressions Using Comparisons and Logic
age = 22
has_id = True
eligible = age >= 18 and has_id
print(eligible)
Output: True
15. Operator Precedence
Operator precedence determines which operations are evaluated first when an expression contains multiple operators. Understanding precedence helps avoid unexpected results.
For example:
result = 10 + 5 * 2
print(result)
Output: 20
Multiplication has higher precedence than addition, so Python evaluates 5 * 2 first and then adds 10.
Common Operator Precedence Order
The following table presents common operator groups from higher precedence to lower precedence. Operators within the same group generally follow the associativity rules described below.
| Priority |
Operator Group |
Examples |
| 1 |
Grouping, indexing, function calls, attributes |
( ), [], function calls |
| 2 |
Exponentiation |
** |
| 3 |
Unary operators |
+x, -x, ~x |
| 4 |
Multiplication and division family |
*, /, //, %, @ |
| 5 |
Addition and subtraction |
+, - |
| 6 |
Bit shifting |
<<, >> |
| 7 |
Bitwise AND |
& |
| 8 |
Bitwise XOR |
^ |
| 9 |
Bitwise OR |
| |
| 10 |
Comparisons, membership, identity |
==, <, in, is |
| 11 |
Logical NOT |
not |
| 12 |
Logical AND |
and |
| 13 |
Logical OR |
or |
| 14 |
Conditional expression |
x if condition else y |
| 15 |
Lambda expression |
lambda |
| 16 |
Assignment expression |
:= |
This is a simplified reference. For exact rules and less common operators, consult the official Python language reference.
Example 1: Multiplication Before Addition
result = 2 + 3 * 4
print(result)
Output: 14
Example 2: Using Parentheses
result = (2 + 3) * 4
print(result)
Output: 20
Parentheses override the normal precedence and can make an expression easier to read.
Example 3: Exponentiation and Unary Minus
print(-2 ** 2)
print((-2) ** 2)
Output:
-4
4
Exponentiation binds more tightly than a unary minus on its left. Therefore, -2 ** 2 is interpreted as -(2 ** 2).
16. Associativity of Operators
Associativity determines how operators of the same precedence are grouped when parentheses are not present. Many arithmetic operators group from left to right, while exponentiation groups from right to left.
Left-to-Right Example
result = 20 - 5 - 3
print(result)
Output: 12
The expression is evaluated as (20 - 5) - 3.
Right-to-Left Example
result = 2 ** 3 ** 2
print(result)
Output: 512
The expression is evaluated as 2 ** (3 ** 2), which is 2 ** 9.
Chained Comparisons
Python supports chained comparisons, which can make range checks easier to read.
age = 25
print(18 <= age <= 60)
Output: True
This expression checks whether the age is at least 18 and at most 60. The middle expression is evaluated only once.
17. Common Mistakes When Using Operators
| Mistake |
Incorrect Example |
Correct Approach |
| Using assignment instead of comparison |
if age = 18: |
if age == 18: |
| Dividing by zero |
result = 10 / 0 |
Check the divisor before division. |
| Incorrect use of AND and OR |
if age >= 18 or age <= 60: |
Use and when both range conditions must hold. |
| Confusing identity and equality |
first_list is second_list to compare contents |
Use first_list == second_list to compare values. |
| Assuming input is numeric |
input("Number: ") + 5 |
Convert valid input with int() or float(). |
| Ignoring precedence |
10 + 5 * 2 when addition should happen first |
Use (10 + 5) * 2. |
| Using incompatible operand types |
"10" - 2 |
Convert the string to a number if numeric subtraction is intended. |
| Misunderstanding floor division |
Assuming -7 // 2 returns -3 |
Remember that floor division rounds down, so the result is -4. |
18. Practical Example: Student Grade Calculator
This program demonstrates arithmetic, comparison, assignment, and logical operators in a simple student grading application.
student_name = input("Enter student name: ")
try:
marks_one = float(input("Enter marks for subject 1: "))
marks_two = float(input("Enter marks for subject 2: "))
marks_three = float(input("Enter marks for subject 3: "))
if not all(0 <= mark <= 100
for mark in [marks_one, marks_two, marks_three]):
print("Marks must be between 0 and 100.")
else:
total_marks = marks_one + marks_two + marks_three
average_marks = total_marks / 3
if average_marks >= 90:
grade = "A"
elif average_marks >= 75:
grade = "B"
elif average_marks >= 40:
grade = "C"
else:
grade = "F"
print("Student:", student_name)
print("Total marks:", total_marks)
print("Average:", round(average_marks, 2))
print("Grade:", grade)
except ValueError:
print("Please enter valid numeric marks.")
Operators Used in This Program
+ adds the marks.
/ calculates the average.
>= compares the average against grade boundaries.
<= checks whether marks fall within the allowed range.
and is used implicitly through chained comparisons in 0 <= mark <= 100.
= assigns values to variables.
not reverses the result of the all() check.
19. Practical Example: Shopping Bill Calculator
This project uses arithmetic and comparison operators to calculate a bill, apply a discount, and determine the final amount.
try:
product_name = input("Enter product name: ")
unit_price = float(input("Enter unit price: "))
quantity = int(input("Enter quantity: "))
if unit_price < 0 or quantity < 0:
print("Price and quantity cannot be negative.")
else:
subtotal = unit_price * quantity
if subtotal >= 5000:
discount_rate = 0.10
else:
discount_rate = 0.05
discount_amount = subtotal * discount_rate
final_amount = subtotal - discount_amount
print("Product:", product_name)
print("Subtotal:", round(subtotal, 2))
print("Discount:", round(discount_amount, 2))
print("Final amount:", round(final_amount, 2))
except ValueError:
print("Enter a valid price and whole-number quantity.")
Learning Outcomes
- Accepting and converting user input.
- Performing arithmetic calculations.
- Comparing values against business rules.
- Using conditional logic to apply discounts.
- Handling invalid numeric input.
- Displaying calculated results clearly.
20. Hands-On Exercises
Exercise 1: Arithmetic Operators
Create two variables, a = 25 and b = 4. Display their sum, difference, product, division, floor division, remainder, and exponentiation result.
Exercise 2: Comparison Operators
Given age = 20, write expressions to check whether the age is equal to 20, greater than 18, less than 30, and between 18 and 60 inclusive.
Exercise 3: Logical Operators
Create variables named has_ticket and has_id. Write a condition that permits entry only when both values are true.
Exercise 4: Assignment Operators
Start with balance = 1000. Use augmented assignment to add 500, subtract 200, and then multiply the result by 2.
Exercise 5: Membership Operators
Create a list of programming languages and check whether "Python" and "Ruby" are present in the list.
Exercise 6: Identity Versus Equality
Create two separate lists containing the same values. Compare them using == and is. Explain the results.
Exercise 7: Operator Precedence
Predict the results of the following expressions before running them:
print(5 + 3 * 2)
print((5 + 3) * 2)
print(2 ** 3 ** 2)
print(17 // 5)
print(-17 // 5)
Expected output:
11
16
512
3
-4
Exercise 8: Discount Calculator
Ask the user to enter a product price. Apply a 10% discount if the price is at least 2,000; otherwise, apply a 5% discount. Display the original price, discount amount, and final price.
21. Python Operators and Expressions: Interview Questions and Answers
Q1. What is an operator in Python?
Answer: An operator is a symbol or keyword that performs an operation on one or more operands, such as addition, comparison, assignment, or logical evaluation.
Q2. What is an expression in Python?
Answer: An expression combines values, variables, operators, and other elements to produce a value when evaluated.
Q3. What is the difference between an operator and an operand?
Answer: An operator performs an operation, while an operand is the value or object on which the operator acts.
Q4. What are arithmetic operators?
Answer: Arithmetic operators perform mathematical operations. Python's common arithmetic operators include +, -, *, /, //, %, and **.
Q5. What is the difference between / and //?
Answer: The / operator performs division and returns a floating-point result for ordinary numeric operands. The // operator performs floor division and rounds the quotient down toward negative infinity.
Q6. What is the purpose of the modulus operator?
Answer: The modulus operator % returns the remainder from division. It is useful for checking divisibility and determining whether an integer is even or odd.
Q7. What is the difference between = and ==?
Answer: The = operator assigns a value to a variable. The == operator compares two values for equality.
Q8. What are logical operators?
Answer: Python's logical operators are and, or, and not. They combine conditions or reverse truth values.
Q9. What is short-circuit evaluation?
Answer: Short-circuit evaluation means Python skips evaluating the second operand of and when the first is falsy, and skips the second operand of or when the first is truthy.
Q10. What is the difference between == and is?
Answer: The == operator checks value equality, while is checks whether two references point to the same object.
Q11. What are membership operators?
Answer: The in and not in operators test whether a value is present in a container or supported sequence.
Q12. What are bitwise operators?
Answer: Bitwise operators work on the binary representation of integers. Examples include &, |, ^, ~, <<, and >>.
Q13. What is operator precedence?
Answer: Operator precedence determines which operations are evaluated first in an expression containing multiple operators.
Q14. What is associativity?
Answer: Associativity determines how operators of the same precedence are grouped when parentheses are absent. Most arithmetic operators group from left to right, while exponentiation groups from right to left.
Q15. What is a conditional expression?
Answer: A conditional expression selects one of two values based on a condition, using the form value_if_true if condition else value_if_false.
Q16. What does the += operator do?
Answer: The += operator performs augmented assignment. For a simple integer variable, x += 5 adds 5 to the current value of x and assigns the result back.
Q17. What is the walrus operator?
Answer: The := operator assigns a value to a variable as part of an expression. It was introduced in Python 3.8.
Q18. What happens when a number is divided by zero?
Answer: Ordinary numeric division by zero raises a ZeroDivisionError. Programs should validate the divisor when zero is possible.
22. Quick Revision Notes
- Operators perform operations on operands.
- Expressions combine values and operators to produce results.
- Arithmetic operators include
+, -, *, /, //, %, and **.
- Comparison operators return Boolean results for ordinary built-in comparisons.
- Logical operators are
and, or, and not.
- The assignment operator
= is different from the equality operator ==.
- Augmented assignment operators update a variable using an operation.
- Identity operators are
is and is not.
- Membership operators are
in and not in.
- Bitwise operators operate on integer bits.
- Conditional expressions select values based on conditions.
- The walrus operator
:= assigns a value inside an expression.
- Operator precedence determines evaluation order.
- Parentheses can clarify or change how an expression is evaluated.
- Exponentiation groups from right to left.
- Floor division rounds down toward negative infinity.
- Use
== for value comparison and is for object identity.
- Validate values and avoid division by zero.
23. Conclusion
Python operators and expressions are essential building blocks of programming. Arithmetic operators perform calculations, comparison operators evaluate relationships, logical operators combine conditions, and assignment operators store or update values. Identity, membership, and bitwise operators provide additional ways to work with objects, collections, and integer bits.
Understanding expressions also requires knowledge of operator precedence, associativity, and short-circuit evaluation. By practicing these concepts through calculations, validation conditions, and small projects, learners can write clearer and more reliable Python programs. These fundamentals provide a strong foundation for learning control flow, loops, functions, data structures, and advanced Python development.
24. Further Learning Resources