Tutorial on Python Operators

In Python, operators are special symbols that perform arithmetic or logical computation. The operand is the value on which the operator operates.

Examples of operators and operands are given below:

>>> 2+3

5

+ is the addition operator in this case. 2 and 3 are the operands, and 5 is the operation’s output.

In this article, we will look at various Python operators.

Arithmetic Operators

Arithmetic operators are employed in the execution of mathematical operations such as addition, subtraction, multiplication, and division.

Operator Description Syntax
+ Addition: adds two operands x + y
Subtraction: subtracts two operands x-y
*
Multiplication: multiplies two operands
X*y
/
Division (float): divides the first operand by the second
x/y
// Division (floor): divides the first operand by the second x//y
% Modulus: returns the remainder when the first operand is divided by the second x%y
** Power: Returns first raised to power second x**y

 

Precedence

  1. P – Parentheses
  2. E – Exponentiation
  3. M – Multiplication (Multiplication and division have the same precedence)
  4. D – Division
  5. A – Addition (Addition and subtraction have the same precedence)
  6.  S – Subtraction

The modulus operator assists us in determining the last digit/s of a number. As an example:

  1.  x % 10 -> yields the last digit
  2.  x % 100 -> yield last two digits

Example: Arithmetic operators in Python

# Examples of Arithmetic Operator
a = 9
b = 4

# Addition of numbers
add = a + b

# Subtraction of numbers
sub = a - b

# Multiplication of number
mul = a * b

# Division(float) of number
div1 = a / b

# Division(floor) of number
div2 = a // b

# Modulo of both number
mod = a % b

# Power
p = a ** b

# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
print(p)

Output

13

5

36

2.25

2

1

6561

 

Comparison Operators

Comparison of Relational operators compares the values. Depending on the condition, it either returns True or False.

Operator Description Syntax
> Greater than: True if the left operand is greater than the right x>y
< Less than: True if the left operand is less than the right x<y
==
Equal to: True if both operands are equal
x==y
!=
Not equal to – True if operands are not equal
x!=y
>= Greater than or equal to True if the left operand is greater than or equal to the right x>=y
<= Less than or equal to True if the left operand is less than or equal to the right x<=y
is x is the same as y x is y
Is not x is not the same as y x is not y

 

= is an assignment operator and == comparison operator.

Example: Comparison Operators in Python

# Examples of Relational Operators
a = 13
b = 33

# a > b is False
print(a > b)

# a < b is True
print(a < b)

# a == b is False
print(a == b)

# a != b is True
print(a != b)

# a >= b is False
print(a >= b)

# a <= b is True
print(a <= b)

Output

False

True

False

True

False

True

Logical Operators

Logical operators carry out operations such as Logical AND, Logical OR, and Logical NOT. It is used to join conditional statements together.

Operator Description Syntax
and
Logical AND: True if both the operands are true
x and y
or Logical OR: True if either of the operands is true x or y
not Logical NOT: True if the operand is false not x

Example: Logical Operators in Python

# Examples of Logical Operator
a = True
b = False

# Print a and b is False
print(a and b)

# Print a or b is True
print(a or b)

# Print not a is False
print(not a)

Output

False

True

False

Bitwise Operators

Bitwise operators operate on bits and perform bit-by-bit operations. These are used to perform binary number operations.

Operator Description Syntax
& Bitwise AND x&y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>>
<<
Bitwise left shift
x<<

Example: Bitwise Operators in Python

# Examples of Bitwise operators
a = 10
b = 4

# Print bitwise AND operation
print(a & b)

# Print bitwise OR operation
print(a | b)

# Print bitwise NOT operation
print(~a)

# print bitwise XOR operation
print(a ^ b)

# print bitwise right shift operation
print(a >> 2)

# print bitwise left shift operation
print(a << 2)

Output

0

14

-11

14

2

40

Assignment Operators

Assignment operators are used to assigning values to variables.

Operator Description Syntax
= Assign value of right side of expression to left side operand
x = y + z
+= Add AND: Add right-side operand with left side operand and then assign to left operand
a+=b     a=a+b
-= Subtract AND: Subtract right operand from left operand and then assign to left operand a-=b     a=a-b
*= Multiply AND: Multiply right operand with left operand and then assign to left operand a*=b     a=a*b
/= Divide AND: Divide left operand with right operand and then assign to left operand a/=b     a=a/b
%=
Modulus AND: Takes modulus using left and right operands and assigns the result to the left operand
a%=b

a=a%b

//= Divide(floor) AND: Divide the left operand with the right operand and then assign the value(floor) to the left operand  a//=b

a=a//b

**= Exponent AND: Calculate exponent(raise power) value using operands and assign value to left operand a**=b

a=a**b

&= Performs Bitwise AND on operands and assigns value to left operand a&=b

a=a&b

|=
Performs Bitwise OR on operands and assigns value to left operand
 

a|=b     a=a|b

^= Performs Bitwise xOR on operands and assigns value to left operand  

a^=b     a=a^b

>>= Performs Bitwise right shift on operands and assigns value to left operand a>>=b

a=a>>b

<<= Performs Bitwise left shift on operands and assigns value to left operand a <<= b     a= a

<< b

Example: Assignment Operators in Python

# Examples of Assignment Operators
a = 10

# Assign value
b = a
print(b)

# Add and assign value
b += a
print(b)

# Subtract and assign value
b -= a
print(b)

# multiply and assign
b *= a
print(b)

# bitwise lishift operator
b <<= a
print(b)

Output

10

20

10

100

102400

Identity Operators

The identity operators is and is not are used to determine whether two values are in the same part of memory. The fact that two variables are equal does not imply that they are identical.

is          True if the operands are identical

is not      True if the operands are not identical

Example: Identity Operator

a = 10
b = 20
c = a

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

Output

True

True

Membership Operators

The membership operators in and not in are used to determine whether a value or variable is in a sequence.

in            True if value is found in the sequence

not in        True if value is not found in the sequence

Example: Membership Operator

# Python program to illustrate
# not 'in' operator
x = 24
y = 20
list = [10, 20, 30, 40, 50]

if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")

if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")

Output

x is NOT present in given list
y is present in given list

Precedence and Associativity of Operators

Operator Precedence and Associativity: Operator precedence and associativity determine the operator’s priorities.

Operator Precedence

This is used to determine which operation to perform first in an expression with multiple operators with different precedence.

Example: Operator Precedence

# Examples of Operator Precedence

# Precedence of '+' & '*'
expr = 10 + 20 * 30
print(expr)

# Precedence of 'or' & 'and'
name = "Alex"
age = 0

if name == "Alex" or name == "John" and age >= 2:
print("Hello! Welcome.")
else:
print("Good Bye!!")

Output

610
Hello! Welcome.

Operator Associativity

Operator Associativity is used to determine if an expression contains two or more operators with the same precedence. It can either be Left to Right or from Right to Left.

Example: Operator Associativity

# Examples of Operator Associativity

# Left-right associativity
# 100 / 10 * 10 is calculated as
# (100 / 10) * 10 and not
# as 100 / (10 * 10)
print(100 / 10 * 10)

# Left-right associativity
# 5 - 2 + 3 is calculated as
# (5 - 2) + 3 and not
# as 5 - (2 + 3)
print(5 - 2 + 3)

# left-right associativity
print(5 - (2 + 3))

# right-left associativity
# 2 ** 3 ** 2 is calculated as
# 2 ** (3 ** 2) and not
# as (2 ** 3) ** 2
print(2 ** 3 ** 2)

Output

100.0

6

0

512

Division Operators

Division Operators allow you to divide two numbers and return the quotient; that is, the first number or number on the left is divided by the second number or number on the right, and the quotient is returned.

Division operators are classified into two types:

  1. Float division:

The quotient returned by this operator is always a float number, regardless of whether the two numbers are integers or not. As an example:

>>>5/5

1.0

>>>10/2

5.0

>>>-10/2

-5.0

>>>20.0/2

10.0
  1. Integer division( Floor division):

The quotient returned by this operator is determined by the argument passed. If any of the numbers is a float, the output is in float. It is also known as floor division because if any number is negative, the output is floored. For instance:

>>>5//5

1

>>>3//2

1

>>>10//3

3

Consider the Python statements below:

# A Python program to demonstrate the use of
# "//" for integers
print (5//2)
print (-5//2)

Output

2

-3

The first output is satisfactory, but the second may surprise us if we are in the Java/C++ world. The “//” operator in Python acts as a floor division for integer and float arguments. The division operator ‘/’, on the other hand, always returns a float value.

Note: To return the closest integer value that is less than or equal to a specified expression or value, use the “//” operator. As a result of the preceding code, 5/2 returns 2. You already know that 5/2 equals 2.5, and the nearest integer that is less than or equal to 5/2 is 2. (It is the inverse of normal math; the value in normal math is 3).

Example

# A Python program to demonstrate use of
# "/" for floating point numbers
print (5.0/2)
print (-5.0/2)

Output

2.5

-2.5

“//” is the correct floor division operator. For both integer and floating-point arguments, it returns the floor value.

# A Python program to demonstrate use of
# "//" for both integers and floating points
print (5//2)
print (-5//2)
print (5.0//2)
print (-5.0//2)

Output

2

-3

2.0

-3.0

Take a look at this.

Ternary Operators

Ternary operators, also known as conditional expressions, evaluate something based on whether a condition is true or false. Python version 2.5 included it.

It simply allows you to test a condition in a single line instead of a multiline if-else, making the code more compact.

Syntax

[on_true] if [expression] else [on_false]

A simple way to use the ternary operator:

# Program to demonstrate conditional operator
a, b = 10, 20

# Copy value of a in min if a < b else copy b
min = a if a < b else b

print(min)

Output

10

Direct Method with Tuples, Dictionary, and Lambda

# Python program to demonstrate ternary operator
a, b = 10, 20

# Use tuple for selecting an item
# (if_test_false,if_test_true)[test]
# if [a<b] is true it return 1, so element with 1 index will print
# else if [a<b] is false it return 0, so element with 0 index will print
print( (b, a) [a < b] )

# Use Dictionary for selecting an item
# if [a < b] is true then value of True key will print
# else if [a<b] is false then value of False key will print
print({True: a, False: b} [a < b])

# lambda is more efficient than above two methods
# because in lambda we are assure that
# only one expression will be evaluated unlike in
# tuple and Dictionary
print((lambda: b, lambda: a)[a < b]())

Output

10

10

10

Ternary operators can be expressed as nested if-else statements:

# Python program to demonstrate nested ternary operator
a, b = 10, 20

print ("Both a and b are equal" if a == b else "a is greater than b"
if a > b else "b is greater than a")

The preceding strategy can be written as follows:

# Python program to demonstrate nested ternary operator
a, b = 10, 20

if a != b:
if a > b:
print("a is greater than b")
else:
print("b is greater than a")
else:
print("Both a and b are equal")

Output

b is greater than a

To use the print function in the ternary operator, do the following:

Example: In Python3, find the greater of two numbers using the ternary operator.

a=5
b=7

# [statement_on_True] if [condition] else [statement_on_false]

print(a,"is greater") if (a>b) else print(b,"is Greater")

Output

7 is Greater

Important Notes:

  1. The given condition is first evaluated (a<b), and then either an or b is returned based on the condition’s Boolean value.
  2. The order of the arguments in the operator differs from that of other languages such as C/C++.
  3. Conditional expressions are the least important Python operation.

Prior to 2.5, this method was used when the ternary operator was not present.

In an expression like the one below, the interpreter looks for the expression and evaluates on_true if it is true, otherwise, on_false is evaluated.

Syntax

'''When condition becomes true, expression [on_false]

is not executed and value of "True and [on_true]"   

is returned.  Else value of "False or [on_false]"   

is returned.   

Note that "True and x" is equal to x.    

And "False or x" is equal to x. '''

[expression] and [on_true] or [on_false]

Example

# Program to demonstrate conditional operator
a, b = 10, 20

# If a is less than b, then a is assigned
# else b is assigned (Note : it doesn't
# work if a is 0.
min = a < b and a or b

print(min)

Output

10

Note: The only disadvantage of this method is that on_true cannot be 0 or False. If this occurs, on_false will always be evaluated. The reason for this is that if the expression is true, the interpreter will check for on_true; if it is zero or_false, the interpreter will check for on false to give the final result of the entire expression.

Source link

Most Popular