Operators and Modules in Python

1. Operators in Python

Definition: Operators in Python are special symbols or keywords used to perform different types of operations on variables and values.

Python supports the following types of operators:

  1. Arithmetic Operators
  2. Relational Operators
  3. Logical Operators
  4. Bitwise Operators
  5. Assignment Operators
  6. Membership Operators

1.1 Arithmetic Operators

Definition: Arithmetic operators are used to perform mathematical operations such as addition, subtraction, multiplication and division.

Operator

Name

Example

Output

+

Addition

5 + 6

11

-

Subtraction

5 - 6

-1

*

Multiplication

5 * 6

30

/

Division

5 / 2

2.5

//

Floor Division

5 // 2

2

%

Modulus

5 % 2

1

**

Exponentiation

5 ** 2

25

Example program:

# Arithmetic Operators

print(5 + 6)

print(5 - 6)

print(5 * 6)

print(5 / 2)

print(5 // 2)

print(5 % 2)

print(5 ** 2)

Output:

11

-1

30

2.5

2

1

25

Important points:

  • / returns the division result as a floating-point number.
  • // returns the quotient after floor division.
  • % returns the remainder.
  • ** is used to calculate the power of a number.

1.2 Relational Operators

Definition: Relational operators are used to compare two values. They return either True or False.

Operator

Name

Example

Output

> 

Greater than

4 > 5

False

< 

Less than

4 < 5

True

>=

Greater than or equal to

4 >= 4

True

<=

Less than or equal to

4 <= 4

True

==

Equal to

4 == 4

True

!=

Not equal to

4 != 4

False

Example program:

# Relational Operators

print(4 > 5)

print(4 < 5)

print(4 >= 4)

print(4 <= 4)

print(4 == 4)

print(4 != 4)

 

Output:

False

True

True

True

True

False

Important point: Relational operators always produce a Boolean result (True or False).

1.3 Logical Operators

Definition: Logical operators are used to combine conditional statements or reverse a logical result.

Python provides three logical operators:

Operator

Description

Example

Output

and

Returns True if both conditions are true

1 and 0

0

or

Returns True if at least one condition is true

1 or 0

1

not

Reverses the logical result

not 1

False

Example program:

# Logical Operators

print(1 and 0)

print(1 or 0)

print(not 1)

 

Output:

0

1

False

Important points:

  • and requires both operands to be true.
  • or requires at least one operand to be true.
  • not reverses the truth value.

Note: In Python, and and or can return operand values (not necessarily Boolean values). The examples above demonstrate this behaviour.

1.4 Bitwise Operators

Definition: Bitwise operators are used to perform operations on the individual bits of integer values.

Operator

Name

Example

Output

&

Bitwise AND

2 & 3

2

|

Bitwise OR

2 | 3

3

^

Bitwise XOR

2 ^ 3

1

~

Bitwise NOT

~3

-4

>> 

Right Shift

4 >> 2

1

<< 

Left Shift

5 << 2

20

Example program:

# Bitwise Operators

 

# Bitwise AND

print(2 & 3)

 

# Bitwise OR

print(2 | 3)

 

# Bitwise XOR

print(2 ^ 3)

 

# Bitwise NOT

print(~3)

 

# Right Shift

print(4 >> 2)

 

# Left Shift

print(5 << 2)

 

Output:

2

3

1

-4

1

20

Important points:

  • AND (&) returns 1 when both corresponding bits are 1.
  • OR (|) returns 1 when at least one corresponding bit is 1.
  • XOR (^) returns 1 when corresponding bits are different.
  • NOT (~) reverses the bits.
  • Right shift (>>) shifts bits towards the right.
  • Left shift (<<) shifts bits towards the left.

1.5 Assignment Operators

Definition: Assignment operators are used to assign values to variables and update the values of variables.

Operator

Description

Example

=

Assigns a value

a = 2

+=

Adds and assigns

a += 2

-=

Subtracts and assigns

a -= 2

*=

Multiplies and assigns

a *= 2

/=

Divides and assigns

a /= 2

//=

Floor divides and assigns

a //= 2

%=

Calculates remainder and assigns

a %= 2

**=

Calculates power and assigns

a **= 2

Example program:

# Assignment Operators

 

a = 2

 

# a = a % 2

a %= 2

 

print(a)

Output:

0

Important point: The expression a %= 2 is equivalent to a = a % 2.

Note: The uploaded PDF shows output 4 for this example, but the displayed statements produce 0 when executed in sequence.

Note: Python does not support the increment operators a++ or ++a as they work in some other programming languages.

1.6 Membership Operators

Definition: Membership operators are used to check whether a particular value or element is present in a sequence such as a string, list or tuple.

Python provides two membership operators:

Operator

Description

in

Returns True if an element is present in a sequence.

not in

Returns True if an element is not present in a sequence.

Example program:

# Membership Operators

 

# in / not in

 

print('D' not in 'Delhi')

 

print(1 in [2, 3, 4, 5, 6])

Output:

False

False

Explanation:

  • 'D' not in 'Delhi' returns False because D is present in Delhi.
  • 1 in [2, 3, 4, 5, 6] returns False because 1 is not present in the list.

2. Python Program: Find the Sum of a Three-Digit Number

Question: Write a Python program to accept a three-digit number from the user and calculate the sum of its digits.

Program:

# Program - Find the sum of a 3 digit number entered by the user

 

number = int(input('Enter a 3 digit number'))

 

# 345 % 10 -> 5

a = number % 10

 

number = number // 10

 

# 34 % 10 -> 4

b = number % 10

 

number = number // 10

 

# 3 % 10 -> 3

c = number % 10

 

print(a + b + c)

Output:

Enter a 3 digit number 666

18

Explanation step by step:

Suppose the user enters 345.

Step

Statement

Result

1

number = 345

345

2

a = number % 10

5

3

number = number // 10

34

4

b = number % 10

4

5

number = number // 10

3

6

c = number % 10

3

7

a + b + c

12

Final answer: The sum of digits of 345 is 12.

Important concepts used:

  • % (Modulus) extracts the last digit of a number.
  • // (Floor Division) removes the last digit of a number.

3. Modules in Python

Definition: A module in Python is a file containing Python code, such as functions, variables and classes, which can be imported and used in another Python program.

Python provides many built-in modules that help programmers perform different tasks.

The following modules are covered in the uploaded material:

  1. Math Module
  2. Keyword Module
  3. Random Module
  4. Datetime Module

3.1 Math Module

Definition: The math module provides mathematical functions to perform different mathematical operations such as square root, factorial, power and more.

Syntax:

import math

Example program:

# math

import math

 

print(math.sqrt(196))

Output:

14.0

Explanation:

  • import math imports the math module.
  • math.sqrt(196) calculates the square root of 196.
  • The result is 14.0.

Other commonly used math functions:

Function

Description

Example

math.sqrt()

Calculates square root

math.sqrt(25)

math.factorial()

Calculates factorial

math.factorial(5)

math.pow()

Calculates power

math.pow(2, 3)

math.ceil()

Rounds a number upward

math.ceil(4.2)

math.floor()

Rounds a number downward

math.floor(4.8)

3.2 Keyword Module

Definition: The keyword module is used to display and work with Python's reserved keywords.

Syntax:

import keyword

Example program:

# keyword

import keyword

 

print(keyword.kwlist)

Output:

['False', 'None', 'True', 'and', 'as', 'assert',

 'async', 'await', 'break', 'class', 'continue',

 'def', 'del', 'elif', 'else', ...]

Explanation:

  • import keyword imports the keyword module.
  • keyword.kwlist displays the list of Python keywords.

Important point: Keywords are reserved words in Python and cannot be used as ordinary identifiers.

3.3 Random Module

Definition: The random module is used to generate random numbers and perform random selections.

Syntax:

import random

Example program:

# random

import random

 

print(random.randint(1, 100))

Output:

88

Explanation:

  • import random imports the random module.
  • random.randint(1, 100) generates a random integer between 1 and 100, including both 1 and 100.

Important point: The output may be different each time the program is executed.

3.4 Datetime Module

Definition: The datetime module is used to work with dates and times in Python.

Syntax:

import datetime

Example program:

# datetime

import datetime

 

print(datetime.datetime.now())

Output:

2022-11-08 15:50:21.228643

Explanation:

  • import datetime imports the datetime module.
  • datetime.datetime.now() returns the current date and time of the system.

Important point: The output changes according to the current system date and time.

3.5 Help Function – Display Available Modules

Python provides a built-in help() function to display information about Python objects, modules and functions.

Example program:

help('modules')

Output:

This command displays the list of available Python modules installed in the Python environment.

Some examples shown in the uploaded PDF are:

cgi

cgitb

chardet

ipywidgets

isympy

itertools

pyrsistent

pysndfile

pytest

xlrd

xlwt

xml

Important point: The available modules may differ depending on the Python installation and environment.


4. Quick Revision

Types of Python Operators

Operator

Purpose

Arithmetic

Performs mathematical operations

Relational

Compares two values

Logical

Combines or reverses logical conditions

Bitwise

Performs operations on individual bits

Assignment

Assigns or updates variable values

Membership

Checks whether an element exists in a sequence

 

 

Python Modules – Quick Revision

Module

Purpose

Example

math

Mathematical operations

math.sqrt(196)

keyword

Displays Python keywords

keyword.kwlist

random

Generates random numbers

random.randint(1,100)

datetime

Works with date and time

datetime.datetime.now()


Post a Comment

0 Comments