[Go to site: main page, start]

0% found this document useful (0 votes)
5 views9 pages

Python Operators Explained: Types & Examples

My notes about different different types of operator which we used in programming language like python

Uploaded by

mr.upadhyay4091
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)
5 views9 pages

Python Operators Explained: Types & Examples

My notes about different different types of operator which we used in programming language like python

Uploaded by

mr.upadhyay4091
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

1

What are
Operators?
Operators are
special symbols in Python that perform operations on values
(operands).

Types of Operators in Python


Python operators can be divided into 7 main categories:
1. Arithmetic Operators
Used for mathematical operations.
Operator Meaning Example Result

+ Addition 5+3 8

- Subtraction 5-3 2

* Multiplication 5*3 15

/ Division 5/2 2.5

// Floor Division 5 // 2 2

% Modulus (remainder) 5 % 2 1

** Exponentiation 2 ** 3 8
# + addition add to operands
# - substraction to operand
# * multiplication opreand
# / division to operand return to float division
# // floor division to operand remove decimal part
# % modulus to operand retain remainder
2

# ** exponentiation to operand (power of number)

1. Comparison (Relational) Operators


Used to compare values → returns True or False.
# These operators are used to compare two values; they
always return in Boolean value True or False.
# Used commonly in condition, loops and decision making.
Operator Meaning Example Result

== Equal 5 == 5 True

Not
!= 5 != 3 True
Equal

Greater
> 5>3 True
than

< Less than 5 < 3 False

Greater
>= 5 >= 5 True
or equal

Less or
<= 5 <= 3 False
equal
EX:
age = 18
if age >= 18:
print("You are eligible to vote")
else:
print("you are not eligible to
vote")
3

Operator Meaning Example Result

You are eligible to vote

[Link] Operators
Used to combine conditions.
Operator Meaning Example Result

(5 > 2)
True if
and and (3 < True
both true
4)

True if at
(5 < 2) or
or least one True
(3 < 4)
true

Reverses not(5 >


not False
result 2)

x=8

print (x > 5 and x < 10) # True (both are true)


print (x > 5 or x < 3) # True (one is true)
print (not (x > 5)) # False (x > 5 is true, not makes it false)

EX:
username = "admin"
password = "1234"
4

if username == "admin" and password == "1234":


print("Login successful")
else:
print("Login failed")

user = "admin"
passw = "1234"

if user == "admin" and passw == "admin":


print("Access Granted")
else:
print("Access Denied")

[Link] Operators
Used to assign values.
Operator Meaning Example

= Assign a = 10

+= Add & assign a += 5 → a = a + 5

-= Subtract & assign a -= 3

*= Multiply & assign a *= 2

/= Divide & assign a /= 2

%= Modulus & assign a %= 3


5

Operator Meaning Example

**= Power & assign a **= 2

//= Floor divide & assign a //= 2

#additional assignment
x=5 # we provide x variable value 5
x+=3 # x=x+3
print(x)

#subtraction assignment
z=5
z-=3 #z=z-3
print(z)

#multiplication assignment
a=5
a*=6 #a=a*5
print(a)

#division assignment
b=5
b/=3 #b=b/3
print(b)
#modulus assignment
6

c=10
c%=3
print(c)

[Link] Operators
Work at binary level (0s and 1s).
Operator Meaning Example

& AND 5&3→1

` ` OR

^ XOR 5^3→6

~ NOT (invert bits) ~5 → -6

<< Left shift 5 << 1 → 10

>> Right shift 5 >> 1 → 2

a = 10 # Binary: 1010
b = 4 # Binary: 0100
print(a & b)

print (a | b) # 1110 → 14

print (a ^ b) # 1110 → 14

print(~a) # -11 (inverts bits + adds 1 to it – uses 2's


complement)
7

print (a << 1) # 10100 → 20

print (a >> 1) # 0101 → 5

[Link] Operators
Used to test membership in sequences (list, string, etc.).
Used to test whether a value exists in a sequence like a list,
string, or tuple.
Operator Example Result

'a' in
in True
'apple'

'x' not in
not in True
'apple'

fruits = ["apple", "banana", "cherry"]

print ("banana" in fruits) # True


print ("mango" not in fruits) # True

text = "hello"
print ("h" in text) # True
print ("z" not in text) # True

[Link] Operators
Used to compare memory location (not
values).
8

Operator Example Result

Operator Example Result

True if
is a is b same
object

True if not
a is not
is not same
b
object
Used to compare the memory locations (i.e.,
object identity) of two objects.
a = [1, 2, 3]
b=a
c = [1, 2, 3]

print (a is b) # True (same object)


print (a is c) # False (same content, different
objects)
print (a == c) # True (values are same)
print (a is not c) # True

Summary:

# Arithmetic → +, -, *, /, %, //, **
# Relational → ==, !=, >, <, >=, <=
# Logical → and, or, not
9

Operator Example Result

# Assignment → =, +=, -=, etc.


# Bitwise → &, |, ^, ~, <<, >>
# Membership → in, not in
# Identity → is, is not

Common questions

Powered by AI

Identity operators 'is' and 'is not' test whether two variables reference the same object in memory. For example, if 'a = [1, 2, 3]' and 'b = a', then 'a is b' returns True because both variables point to the same list object. Conversely, 'a is not b' would return False . They are significant in assessing whether two objects are identical not only in value but by reference, helping avoid unintended data alterations. In large-scale applications involving complex data structures, using 'is' helps ascertain object identity, ensuring functions operate on correct object references, crucial in memory management and resource optimization .

Bitwise operators are foundational in encryption algorithms due to their efficiency in manipulating data at the bit level. Operations like 'XOR' ('^') are particularly valuable in cipher creation, as they can combine binary data streams rapidly. For example, bitwise XOR plays a crucial role in symmetric key methods such as one-time pad encryption to mix plaintext and key effectively. Their principles involve bit comparison at negligible resource cost, providing fast computation with minimal memory usage. Effective in generating cryptographic keys and masks, these operators empower algorithms with strong, resource-efficient means to transform readable data to ciphertext, crucial in secure communications .

The power assignment operator '**=' modifies a variable in-place, calculating the power and updating the variable simultaneously, as in 'a **= 2', which squares 'a'. Compared to executing 'a = a ** 2', using '**=' can be more efficient in loop constructs because it condenses computation and assignment into a single operation, reducing overhead. In loops where iterations involve large datasets or repeated exponentiations, utilizing '**=' minimizes computation steps, enhancing performance by diminishing the number of temporary variables and intermediary results generated, leading to efficient memory usage and execution speeds .

In Python, the 'and' operator returns True if both operands are True, whereas the 'or' operator returns True if at least one of the operands is True. In decision-making constructs like 'if' statements, 'and' is used when all conditions in the condition chain must be satisfied to proceed. For example, 'if age >= 18 and has_ID:' both 'age' and 'has_ID' must be True to execute the subsequent block . In contrast, 'or' allows passage if any condition is met, such as 'if is_student or is_teacher:', granting access if the subject is either a student or a teacher .

Bitwise operators perform operations on the binary representations of integers, evaluating each bit position. 'AND', 'OR', 'XOR', 'NOT', 'left shift', and 'right shift' manipulate binary digits directly. For example, '5 & 3' translates to binary '0101 & 0011', resulting in '0001' which equals 1 . Bitwise operations are crucial in embedded systems programming, where memory and performance are critical constraints. Here, bitwise operators are used to control hardware by setting, clearing, or toggling individual flags within a register, enabling efficient manipulation of data at the bit level .

Arithmetic operators in Python are used to perform mathematical operations such as addition, subtraction, multiplication, and division. For example, the expression '5 + 3' uses the addition operator to compute the sum of two numbers . In contrast, assignment operators are used to assign values to variables. For instance, 'a = 10' assigns the value 10 to the variable 'a'. An example where arithmetic operators are appropriate is computing a user's age additional of years, e.g., 'age + 5'. Assignment operators are used when you need to initialize or update variables in a loop, like 'i += 1' to increment a counter in a loop .

Comparison operators such as '==', '!=', '>', '<', '>=', and '<=' support conditional logic by evaluating relationships between values, returning Boolean expressions. These operators drive control flows in constructs like loops and conditionals by allowing statements to execute based on true-false evaluations. For example, 'if temperature > 100:' executes an alert once temperature exceeds a defined critical point . Practically, they're used in input validation, such as ensuring user input meets specific criteria ('if password_length >= 8'), or in sorting algorithms that compare elements to ensure order .

Membership operators 'in' and 'not in' check for the presence of values within sequences like lists, strings, or tuples, returning True or False. For example, '"banana" in fruits' verifies if the string "banana" exists within the list 'fruits' . They are important in data handling because they allow for concise and efficient checks to prevent data processing on missing elements. This is crucial in applications that require validation or filtering of data inputs, such as ensuring user-provided data includes mandatory fields or checking if an item is already present in a collection before adding .

Floor division in Python, denoted by the '//' operator, divides two numbers and returns the largest integer less than or equal to the division result. For example, '5 // 2' returns 2, as the floor of 2.5 is 2 . In contrast, standard division denoted by '/' returns a float, such as '5 / 2' yielding 2.5. Floor division is useful in integer-based computations where decimal values are not desired, such as calculating how many full items can be created from a given total or arranging groups evenly without splitting .

Logical operators such as 'and', 'or', and 'not' determine the control flow by enabling complex condition combinations in decision-making structures like 'if' statements. 'and' is true if both operand conditions are true, 'or' if at least one condition is true, and 'not' inverts the Boolean value . They are practically applied in situations like user authentication where both username and password must be correct, e.g., 'if username == "admin" and password == "1234":' allows 'Login successful' when both conditions are true, otherwise 'Login failed' .

You might also like