Master Python operators with clear examples. Learn how arithmetic, assignment, logical, comparison, identity, membership, and bitwise operators work in Python.
+
(addition), -
(subtraction), *
(multiplication), /
(division), //
(floor division), %
(modulo), **
(exponentiation)video: Basic Mathematical Operations with Examples
result = 10 + 5 # Addition
difference = 15 - 7 # Subtraction
product = 4 * 6 # Multiplication
quotient = 12 / 3 # Division
integer_quotient = 17 // 4 # Floor division
remainder = 25 % 4 # Modulo
square = 5 ** 2 # Exponentiation
For more details on floor division, see What is the //
Operator in Python?
==
(equal to), !=
(not equal to), >
(greater than), <
(less than), >=
(greater than or equal to), <=
(less than or equal to)video: How to Use Comparision Operators in Python
Examples:
is_equal = 7 == 7 # True
is_greater = 12 > 9 # True
is_less_or_equal = 5 <= 5 # True
=
x = 10 # Simple assignment
A compound assignment is a combination of an operator and an assignment that performs an operation on a variable and then assigns the result back to that variable in a single step.
For example, in the code:
message += " Welcome!"
This is a compound assignment using the +=
operator. Here’s what it does:
" Welcome!"
to the existing value of the message
variable.message
.In general, the format of compound assignment operators is:
+=
: Adds and assigns-=
: Subtracts and assigns*=
: Multiplies and assigns/=
: Divides and assigns%=
: Takes the modulus and assignsThis shorthand avoids writing out the operation in a longer form, such as:
message = message + " Welcome!"
The +=
operator helps to keep the code more concise and readable.
Example:
x += 5 # Add 5 to x
x *= 2 # Multiply x by 2
Operators: and
, or
, not
is_valid = (age >= 18) and (has_license == True)
is_allowed = (is_member) or (has_ticket)
is
operator is used to compare the identities of two objects. It checks whether two references point to the same object in memory, not whether the values of the two objects are equal.is
, is not
Here’s a simple example to illustrate the difference between is
and ==
:
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # Output: True, because the lists have the same content
print(a is b) # Output: False, because they are different objects in memory
print(a is c) # Output: True, because both references point to the same object
In this example:
a == b
is True
because the values in both lists are the same.a is b
is False
because they are two different objects in memory, even though their contents are identical.a is c
is True
because c
is assigned to the same object as a
, so they reference the same memory location.Example 2
x = 5
y = 5
result = x is y # True (they refer to the same integer object)
Here’s an example to explain the concept:
# Assigning variables within the cached range
a = 100
b = 100
# Checking if the IDs are the same
print(id(a)) # Outputs the memory address of 'a'
print(id(b)) # Outputs the memory address of 'b'
# Since both 'a' and 'b' are within the cached range, their IDs are the same
print(a is b) # True, as both refer to the same cached object
# Assigning variables outside the cached range
x = 300
y = 300
# Checking if the IDs are the same
print(id(x)) # Outputs the memory address of 'x'
print(id(y)) # Outputs the memory address of 'y'
# Since 'x' and 'y' are outside the cached range, they are different objects
print(x is y) # False, as 'x' and 'y' refer to different objects
Explanation:
Cached Objects: The values a
and b
are both set to 100
, which falls within the default cached range of small integers. As a result, Python uses the same memory location for both, which is why id(a)
and id(b)
are the same, and a is b
returns True
.
Non-Cached Objects: The values x
and y
are both set to 300
, which is outside the cached range. Therefore, Python creates separate objects for each, and id(x)
and id(y)
are different, meaning x is y
returns False
.
This caching behavior saves memory for frequently used small integers and makes the comparison of such objects faster.
Operators: in
, not in
numbers = [1, 3, 5, 7]
is_present = 5 in numbers # True
is_missing = 2 not in numbers # True
&
(bitwise AND), |
(bitwise OR), ^
(bitwise XOR), ~
(bitwise NOT), <<
(left shift), >>
(right shift)id()
functionIn Python, the id()
function returns the “identity” of an object, which is a unique integer that serves as a constant for the object during its lifetime. The id
is often the memory address of the object. Here’s a simple example:
x = 10
print(id(x))
y = "hello"
print(id(y))
This code will print the unique identifiers for the variables x
and y
. If you have specific objects or variables in mind that you would like to see the id
for, please let me know!
Python operators examples:
Task: Write a program to calculate the area and perimeter of a rectangle.
Input:
length
, representing the length of the rectangle.width
, representing the width of the rectangle.Output:
Example:
length = 5.0
width = 3.0
Output:
Area: 15.0
Perimeter: 16.0
length = 7.5
width = 2.5
Area: 18.75
Perimeter: 20.0
Task: Create a program that converts temperature from Celsius to Fahrenheit using the formula: (Celsius * 9/5) + 32
.
Task: Write a program that takes two numbers and prints their sum, difference, product, and quotient.
Task: Assign the value 10
to the variable a
and print the value of a
.
+=
)Task:
15
to a variable x
.+=
operator to add 5
to x
.x
.-=
) [Easy]Task:
20
to a variable y
.-=
operator to subtract 7
from y
.y
.%=
)Task:
13
to a variable m
.%=
operator to assign the remainder when m
is divided by 5
.Task: Swap the values of two variables a = 10
and b = 20
without using a third variable or tuple assignment.
Task:
a = 4
, b = 5
, and c = 6
.a
is multiplied by 2
.b
is increased by 10
.c
is divided by 3
.Task: Write a program that checks if two variables point to the same object using the is
operator.
Task: Create a list of fruits and write a program that checks if “apple” is in the list using the in
operator.
Bitwise Operators
<<
) to multiply a number by 4 and the right shift operator (>>
) to divide a number by 2.+=
as items are added. Print the total cost when all items have been added.%
) to check if it is even or odd.[1] “Python memory management,” Discussions on Python.org, Apr. 02, 2023. https://discuss.python.org/t/python-memory-management/25391 (accessed Jul. 27, 2024).
Tutorials, Roadmaps, Bootcamps & Visualization Projects