0% found this document useful (0 votes)
11 views7 pages

Python Operators and Expressions Guide

The document provides an overview of Python operators and expressions, detailing various types of operators including arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators. It explains the syntax and precedence of these operators, along with examples for better understanding. Additionally, it introduces the ternary operator and discusses operator precedence and associativity in Python.

Uploaded by

mujeem000
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)
11 views7 pages

Python Operators and Expressions Guide

The document provides an overview of Python operators and expressions, detailing various types of operators including arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators. It explains the syntax and precedence of these operators, along with examples for better understanding. Additionally, it introduces the ternary operator and discusses operator precedence and associativity in Python.

Uploaded by

mujeem000
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

Module No. 04

Operators and Expressions

Quick visit or a revisit:


Variables: A name that refers to a value.
Assignment: A statement that assigns a value to a variable.
Keywords: A reserved word that is used to parse a program; you cannot use keywords like if,
def, and while as variable names.
Operand: One of the values on which an operator operates.
Expression: A combination of variables, operators, and values that represents a single result.
Evaluate: To simplify an expression by performing the operations in order to yield a single value.
Statement: A section of code that represents a command or action. So far, the statements we
have seen are assignments and print statements.
Execute: To run a statement and do what it says.
Order of operation: A way of using the Python interpreter by typing code at the prompt.

Operators
Python Operators are covered in this article. According to one definition, the operator is a symbol that
executes a certain operation between two operands. An operator is the building block on which logic is
built in a programme written in a particular programming language. Some operators can carry out several
operations in every programming language. The operators that Python contains are listed below. They are
similar to those found in other languages.

Python language supports the following types of operators.

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
1. Arithmetic Operators

Arithmetic operators used between two operands for a particular operation. There are many
arithmetic operators. It includes the exponent (**) operator as well as the + (addition), -
(subtraction), * (multiplication), / (divide), % (reminder), and // (floor division) operators.

Consider the following table for a detailed explanation of arithmetic operators.

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 of Arithmetic Operators in Python

The precedence of Arithmetic Operators in python is as follows:

P – Parentheses

E – Exponentiation

M – Multiplication (Multiplication and division have the same precedence)

D – Division

A – Addition (Addition and subtraction have the same precedence)

S – Subtraction

2. Comparison (Relational) Operators

Python comparison operators compare the values on either sides of them and decide the relation
among them. They are also called relational operators. These operators are equal, not equal, greater
than, less than, greater than or equal to and less than or equal to.

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
Precedence of Comparison Operators in Python

In python, the comparison operators have lower precedence than the arithmetic operators. All the
operators within comparison operators have same precedence order.
3. Assignment Operators

Python assignment operators are used to assign values to variables. These operators include simple
assignment operator, addition assign, subtraction assign, multiplication assign, division and assign
operators etc.

Operator Name Example


= Assignment Operator a = 10
+= Addition Assignment a += 5 (Same as a = a + 5)
-= Subtraction Assignment a -= 5 (Same as a = a - 5)
*= Multiplication Assignment a *= 5 (Same as a = a * 5)
/= Division Assignment a /= 5 (Same as a = a / 5)
%= Remainder Assignment a %= 5 (Same as a = a % 5)
**= Exponent Assignment a **= 2 (Same as a = a ** 2)
//= Floor Division Assignment a //= 3 (Same as a = a // 3)

Example 1:

For example, if we divide 10 by 3 using floor division, we get:

10 // 3 = 3

Here, the quotient is 3.33, but since we are using floor division, the result is rounded down to the
nearest integer, 3.

Example 2:

x = -10

y=3

result = x // y

print(result)

In this example, we are using the floor division operator to divide -10 by 3. Since the quotient is -
3.33, the floor division operator rounds it down to -4 and assigns the result to the variable 'result'.
The print statement then displays the value of 'result' as -4.

4. Logical Operators

Logical operators are often used in the evaluation of expressions to reach choices. The logical
operators and, or, and not are some instances. If the first one is 0, the second one does not matter
in the case of logical AND. If the first value in a logical OR is 1, the second value is not affected. The
following logical operators are supported by Python. We describe how the logical operators function
in the table below.

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
The precedence of Logical Operators in python is as follows:

1. Logical not
2. logical and
3. logical or

5. Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now
in the binary format their values will be 0011 1100 and 0000 1101 respectively. Following table lists
out the bitwise operators supported by Python language with an example each in those, we use the
above two variables (a and b) as operands −

a = 0011 1100
b = 0000 1101
--------------------------
a&b = 12 (0000 1100)
a|b = 61 (0011 1101)
a^b = 49 (0011 0001)
~a = -61 (1100 0011)
a << 2 = 240 (1111 0000)
a>>2 = 15 (0000 1111)
There are following Bitwise operators supported by Python language:

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<<

The precedence of Bitwise Operators in python is as follows:

1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR

6. Membership Operator

Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples.
There are two membership operators as explained below –

Operator Description Example


in Evaluates to true if it finds a variable in x in y, here in results in a 1 if x
the specified sequence and false is a member of sequence y.
otherwise.
not in Evaluates to true if it does not finds a x not in y, here not in results
variable in the specified sequence and in a 1 if x is not a member of
false otherwise. sequence y.

Example:
# Python program to illustrate
# Finding common member in list
# using 'in' operator
list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9]
for item in list1:
if item in list2:
print("overlapping")
else:
print("not overlapping")

7. Identity Operators

Identity operators compare the memory locations of two objects. There are two Identity operators
explained below –

Operator Description Example


Evaluates to true if the variables on
is either side of the operator point to the x is y, here is results in 1 if
same object and false otherwise. id(x) equals id(y).
Evaluates to false if the variables on
is not either side of the operator point to the x is not y, here is not results in
same object and true otherwise. 1 if id(x) is not equal to id(y).

Example:
x = 200
y = 500
z=y

print(z is y)
print(x is not y)

8. Ternary Operator in Python

in Python, Ternary operators also known as conditional expressions are operators that evaluate
something based on a condition being true or false. It was added to Python in version 2.5.

It simply allows testing a condition in a single line replacing the multiline if-else making the code
compact.
Syntax : [on_true] if [expression] else [on_false]
Examples of Ternary Operator in Python:

Here is a simple example of Ternary Operator in Python.


Python3
# 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)

Precedence and Associativity of Operators in Python


In Python, Operator precedence and associativity determine the priorities of the operator.

Operator Precedence in Python

This is used in an expression with more than one operator with different precedence to determine
which operation to perform first. Below is a list of the Python operators' precedence tables.

Operator Description
Overall other operators employed in the expression, the
**
exponent operator is given precedence.
~+- the minus, unary plus, and negation.
the division of the floor, the modules, the division, and the
* / % //
multiplication.
+- Binary plus, and minus
>> << Left shift. and right shift
& Binary and.
^| Binary xor, and or
Comparison operators (less than, less than equal to, greater
<= < > >=
than, greater then equal to).
<> == != Equality operators.
= %= /= //=
-= +=
*= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators
Operator Associativity in Python

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

Practice Problem

1. The volume of a sphere with radius r 4/3 πR3. What is the volume of a sphere with radius 5?
2. Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs
$3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for
60 copies?
3. If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at
tempo (7:12 per mile) and 1 mile at an easy pace again, what time do I get home for breakfast?

You might also like