Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Python Master Level

The document provides an introduction to Python programming, covering its history, unique features, installation, and basic concepts such as variables, data types, and control statements. It emphasizes Python's applications in various fields, including artificial intelligence, and outlines the steps to set up the programming environment and write simple programs. Additionally, it discusses Python identifiers, keywords, indentation, comments, and user input methods.

Uploaded by

ohhitzme47
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Python Master Level

The document provides an introduction to Python programming, covering its history, unique features, installation, and basic concepts such as variables, data types, and control statements. It emphasizes Python's applications in various fields, including artificial intelligence, and outlines the steps to set up the programming environment and write simple programs. Additionally, it discusses Python identifiers, keywords, indentation, comments, and user input methods.

Uploaded by

ohhitzme47
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 310

PYTHON

RAJ SOFTWARE SOLUTION


SOFTWARE DEVELOPMENT
&
TRAINING
CONCEPTS
1. INTRODUCTION TO PYTHON 11. DATA VISUALIAZATION USING PYPLOT
2. CONTROL AND LOOPING STATEMENTS 12. PYTHON WITH MYSQL
3. PYTHON ARRAYS
4. PYTHON STRINGS
5. PYTHON FUNCTIONS
6. LIST, TUPLES, DICTIONARIES, SETS
7. PYTHON MODULES & PACKAGES
8. PYTHON CLASSES AND OBJECTS
9. DATA SCIENCE USING PYTHON
10. PYTHON AND CSV FILES

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CHAPTER -1
INTRODUCTION TO PYTHON

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CONCEPTS
INTRODUCTION TO PYTHON

• What is Python and history of Python


• Unique features of Python
• Install Python and Environment Setup
• First Python Program
• Python Print function
• Python Identifiers, Keywords and Indentation
• Comments and document interlude in Python
• Getting User Input
• What are variables?
• Python Data Types
• Python Core objects and Functions
• Python Operators - Arithmetic, Logical, Comparison,
Assignment, Bitwise & Precedence
• Assignments

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON

What is Python and history of Python?

Python is an high-level, interpreted, interactive and object-oriented scripting language


created by Guido van Rossum in 1991. It is ideally designed for rapid prototyping of complex
applications. It has interfaces to many OS system calls and libraries and is extensible to C or
C++. Many large companies use the Python programming language, including NASA, Google,
YouTube, BitTorrent, etc.

Guido van Rossum formally released the Python language in 1991. In the time since, it has
become one of the most popular in the world, primarily because it is open source, relatively
easy to use, and quite flexible.

Guido van Rossum began working on Python in the late 1980s as a successor to the ABC
programming language and first released it in 1991 as Python 0.9.0. Python 2.0 was released
in 2000. Python 3.0, released in 2008 and so on.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON

Why Learn Python Programming?

Python programming is widely used in Artificial Intelligence, Natural Language Generation,


Neural Networks, and other advanced fields of Computer Science. Moreover, Python is one
of the most demanded programming languages in the market, so there are huge job
opportunities for candidates having knowledge of Python programming.

Unique features of Python

• It provides rich data types and easier to read syntax than any other programming
languages.

• It is a platform-independent scripted language with full access to operating system API’s.

• Compared to other programming languages, it allows more run-time flexibility

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON

• It includes the basic text manipulation facilities of Perl and Awk.

• A module in Python may have one or more classes and free functions.

• Libraries in Pythons are cross-platform compatible with Linux, Macintosh, and Windows.

• For building large applications, Python can be compiled to byte-code

• Python supports functional and structured programming as well as OOP.

• It supports interactive mode that allows interacting Testing and debugging of snippets of
code.

• In Python, since there is no compilation step, editing, debugging, and testing are fast.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Install Python and Environment Setup

How to Install Python on Windows [Pycharm IDE]

Step 1) To download and install Python, visit the official website of


Python https://www.python.org/downloads/ and choose your version. We have chosen
Python version python-3.10.4-amd64

Step 2) Once the download is completed, run the .exe file to install Python. Now click on
Install Now.

Step 3) You can see Python installing at this point.

Step 4) When it finishes, you can see a screen that says the Setup was successful. Now click
on “Close”.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
How to Install Pycharm

Here is a step by step process on how to download and install Pycharm IDE on Windows:

Step 1) To download PyCharm visit the


website https://www.jetbrains.com/pycharm/download/ and Click the “DOWNLOAD” link
under the Community Section.

Step 2) double click and install the pycharm-community-2021.3.3.exe

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
First Python Program

Create Your First Python Program on IDE.

1. Open Editor and save the file named as first.py

# This program print the Hello World.

Print(‘Hello World’) or Print(“Hello World”)

2. Run the first.py . (Shift + F10) in PyCharm IDE

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Python Print Function

Python print() function prints the message to the screen or any other standard output
device.

Syntax: print(values(s),sep=‘’,end=‘\n’,file=file,flush=flush)
• values(s): Any value can print. Will be converted to String before printed.
• Sep=‘separator’: (optional) Specify how to separate the objects, if there is more than one.
Default:’’
• end=‘end’: (optional) Specify what to print at the end.Default :’\n’

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Python New Line: How to Print WITHOUT Newline in Python
Python print() built-in function is used to print the given content inside the command
prompt. The default functionality of Python print is that it adds a newline character at the
end.
Working of Normal print() function
The print() function is used to display the content in the command prompt or console.
print("Hello World")
print("Welcome to Raj Software Solution")

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Working with end

print (“RAJ SOFTWARE SOLUTION”)


print(“Salem”,end=“-”)
print(“636001”)

Working with sep

X=10
print(“x=“,x)
print (‘Raj’,’software’,’solution’,sep=‘ ’)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
How to print without a newline in Python?
From Python 3+, there is an additional parameter introduced for print() called end=. This
parameter takes care of removing the newline that is added by default in print().

print("Hello World ", end="")


print("Welcome to Raj Software Solution")

Print Without Newline in Python 2.x


print "Hello World ", print "Welcome to Raj Software Solution."

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Python Identifiers, Keywords and Indentation

Identifier is a user-defined name given to a variable, function, class, module, etc. The
identifier is a combination of character digits and an underscore. They are case-sensitive i.e.,
‘num’ and ‘Num’ and ‘NUM’ are three different identifiers in python. It is a good
programming practice to give meaningful names to identifiers to make the code
understandable.

Rules for Naming Python Identifiers

• It cannot be a reserved python keyword.


• It should not contain white space.
• It can be a combination of A-Z, a-z, 0-9, or underscore.
• It should start with an alphabet character or an underscore ( _ ).
• It should not contain any special character other than an underscore ( _ ).
For ex: empname, emp_age, salary_1.
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
1. INTRODUCTION TO PYTHON
Python Identifiers, Keywords and Indentation
Keywords are some predefined and reserved words in Python that have special meanings.
• Keywords are used to define the syntax of the coding.
• The keyword cannot be used as an identifier, function, or variable name.
• All the keywords in Python are written in lowercase except True and False.
• There are 35 keywords in Python 3.11.
Keywords in Python programming language
False await else import pass
None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while


assert del global not with

async elif if or yield


© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
1. INTRODUCTION TO PYTHON
Python Identifiers, Keywords and Indentation
Indentation is a very important concept of Python because without properly indenting the
Python code, you will end up seeing IndentationError and the code will not get compiled.

In Python, indentation is the leading whitespace (spaces or/and tabs) before any statement.

Rules of Indentation in Python


• Python’s default indentation spaces are four spaces. The number of spaces, however, is entirely up
to the user. However, a minimum of one space is required to indent a statement.

• Indentation is not permitted on the first line of Python code.

• Python requires indentation to define statement blocks.

• A block of code must have a consistent number of spaces.

• To indent in Python, whitespaces are preferred over tabs. Also, use either whitespace or tabs to
indent; mixing tabs and whitespaces in indentation can result in incorrect indentation errors.
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
1. INTRODUCTION TO PYTHON
Comments and document interlude in Python

Comments in Python are the lines in the code that are ignored by the interpreter during the
execution of the program. Comments enhance the readability of the code and help the
programmers to understand the code very carefully.

Types of Comments in Python

• Single-Line Comments in Python


• Multi-Line Comments in Python
• Docstring in Python

Python single-line comment starts with the hashtag symbol (#) with no white spaces and
lasts till the end of the line.
Multiline comments using multiple hashtags (#).
Docstring in Python """RAJ SOFTWARE SOLUTION"""
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
1. INTRODUCTION TO PYTHON
In Python, you can use triple-quoted strings to create a multiline comment or documentation
interlude. This is often referred to as a docstring. Docstrings are used to provide
documentation for functions, classes, modules, or methods in your code.

They are accessible through the __doc__ attribute of the corresponding object.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Getting User Input
• input ( prompt )
• raw_input ( prompt )

input (): This built-in function function first takes the input from the user and converts it into
a string.

For ex:
name = input('What is your name?\n’)
age = int(input('What is your age?\n’))

raw_input(): This function works in older version (like Python 2.x). This function takes exactly
what is typed from the keyboard, converts it to string, and then returns it to the variable in
which we want to store it.

name = raw_input("Enter your name : ")


© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
1. INTRODUCTION TO PYTHON
What are variables?
• A variable in programming is used to store information that you want to re-use in your
code.

• Python is not “statically typed”. We do not need to declare variables before using them or
declare their type.

• A variable is created the moment we first assign a value to it.

• A variable is a name given to a memory location. It is the basic unit of storage in a


program.

• The value stored in a variable can be changed during program execution.

• A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
1. INTRODUCTION TO PYTHON
Rules for creating variables in Python:
• A variable name must start with a letter or the underscore character.
• A variable name cannot start with a number.
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ ).
• Variable names are case-sensitive (name, Name and NAME are three different variables).
• The reserved words(keywords) cannot be used naming the variable.

Declare the Variable:


age = 100
print(age)

Re-declare the Variable:


We can re-declare the python variable once we have declared the variable already.
age = 120.3
print("After re-declare:", age)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
1. INTRODUCTION TO PYTHON
# An integer assignment
age=45

# A floating point
salary=2345.8

# A string
name="RAJ SOFTWARE SOLUTION"

print(age)
print(salary)
print(name)

Assigning a single value to multiple variables:


Python allows assigning a single value to several variables simultaneously with “=”
operators. For ex : a = b = c = 10
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
1. INTRODUCTION TO PYTHON
Assigning different values to multiple variables:
Python allows adding different values in a single line with “,”operators.

a, b, c = 1, 20.2, "Raj Software"


print(a) print(b) print(c)

Can we use the same name for different types?


If we use the same name, the variable starts referring to a new value and type.
a = 10
a = "Raj Software"
print(a)

How does + operator work with variables?


a = 10
b = 20
print(a+b) a = "Raj" b = "Software" print(a+b)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
1. INTRODUCTION TO PYTHON
Global and Local Variables in Python:
Local variables are the ones that are defined and declared inside a function. We can not call
this variable outside the function.

def f():
s = "Welcome Raj"
print(s)
f()
Global variables are the ones that are defined and declared outside a function, and we need
to use them inside a function.
# Name same as s. # Global scope
def f():
global s = "I love Raj
global s
print(s) Software"
f()

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
casting
x=str(3)
y=int(3)

type()
x=5
y="Raj"
print(type(x))
print(type(y))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Python Data Types
Data types are the classification or categorization of data items. It represents the kind of
value that tells what operations can be performed on a particular data.

built-in data types in Python:


• Numeric
• Sequence Type
• Boolean
• Set
• Dictionary
• Binary Types( memoryview, bytearray, bytes)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Numeric Data Types in Python
The numeric data type in Python represents the data that has a numeric value. A numeric
value can be an integer, a floating number, or even a complex number.

a=5
print("Type of a: ", type(a)) # int

b = 5.0
print("\nType of b: ", type(b)) # float

c = 2 + 4j
print("\nType of c: ", type(c)) # complex

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Sequence Data Type in Python
The sequence Data Type in Python is the ordered collection of similar or different data types.
• Python String
• Python List
• Python Tuple

String
Str1 = 'Welcome to RAJ SOFTWARE SOLUTION'
print("String with the use of Single Quotes:")
print(Str1)

Str2 = "I'm a Software Enginner"


print("String with the use of Double Quotes:")
print(Str2)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Str3 = '''I'm a Rishanth and I like "RAJ SOFTWARE"'''
print("\nString with the use of Triple Quotes: ")
print(Str3)

Str4 = '''RAJ
SOFTWARE
SOLUTION'''
print("\nCreating a multiline String: ")
print(Str4)

How to access element of String?


print("\nFirst character of String is: ")
Str5 = "RAJ SOFTWARE SOLUTION" print(Str5[0])
print("Initial String: ")
print(Str5) print("\nLast character of String is: ")
print(Str5[-1])
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
1. INTRODUCTION TO PYTHON
List Data Type
Lists are just like arrays, declared in other languages which is an ordered collection of data.
List = []
print("Initial blank List: ")
print(List)
List = ['RAJ SOFTWARE SOLUTION']
print("\nList with the use of String: ")
print(List)
List = ["RAJ", "SOFTWARE", "SOLUTION"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])
List = [['RAJ', 'SOFTWARE'], ['SOLUTION']]
print("\nMulti-Dimensional List: ")
print(List)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
How to access List Items?

List = ["RAJ", "SOFTWARE", "SOLUTION"]


print("Accessing element from the list")
print(List[0])
print(List[2])
print("Accessing element using negative indexing")
print(List[-1])
print(List[-3])

Tuple Data Type


A tuple is also an ordered collection of Python objects. The only difference between a tuple
and a list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is
represented by a tuple class.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)
Tuple1 = ('RAJ', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
Tuple1 = tuple('RAJ')
print("\nTuple with the use of function: ")
print(Tuple1)
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('raj', 'software')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ") print(Tuple3)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
1. INTRODUCTION TO PYTHON
How to access tuple Items?

tuple1 = tuple([1, 2, 3, 4, 5])


print("First element of tuple")
print(tuple1[0])
print("\nLast element of tuple")
print(tuple1[-1])

print("\nThird last element of tuple")


print(tuple1[-3])

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Boolean Data Type in Python
Data type with one of the two built-in values, True or False.

print(type(True))
print(type(False))

print(type(true)) // error should be case sensitive

Set Data Type


Set is an unordered collection of data types that is iterable, mutable and has no duplicate
elements.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
set1 = set()
print("Initial blank Set: ")
print(set1)
set1 = set("RAJ SOFTWARE SOLUTION")
print("\nSet with the use of String: ")
print(set1)
set1 = set(["RAJ", "SOFTWARE", "SOLUTION"])
print("\nSet with the use of List: ")
print(set1)
set1 = set([1, 2, 'RAJ', 4, 'For', 6, 'SOFTWARE'])
print("\nSet with the use of Mixed Values")
print(set1)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
How to access set Items?
set1 = set(["RAJ", "SOFTWARE", "SOLUTION"])
print("\nInitial set")
print(set1)
print("\nElements of set: ")
for i in set1:
print(i, end=" ")
print("RAJ" in set1)

Dictionary Data Type


A dictionary in Python is an unordered collection of data values, used to store data values like
a map, unlike other Data Types that hold only a single value as an element, a Dictionary holds
a key: value pair.
Key-value is provided in the dictionary to make it more optimized.
Each key-value pair in a Dictionary is separated by a colon : , whereas each key is separated
by a ‘comma’.
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
1. INTRODUCTION TO PYTHON
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict = {1: 'RAJ', 2: 'Software', 3: 'RAJ'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Dict = {'Name': 'RAJ', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Dict = dict({1: 'RAJ', 2: 'Software', 3: 'RAJ'})
print("\nDictionary with the use of dict(): ")
print(Dict)
Dict = dict([(1, 'RAJ'), (2, 'Software')])
print("\nDictionary with each item as a pair: ")
print(Dict)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
How to access Key-value in Dictionary?

Dict = {1: 'RAJ', 'name': 'Software', 3: 'RAJ'}


print("Accessing a element using key:")
print(Dict['name'])
print("Accessing a element using get:")
print(Dict.get(3))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Python Core objects and Functions

Object type Example literals/creation


Numbers 1234, 3.1415, 999L, 3+4j, Decimal

Strings 'spam', "raj's"

Lists [1, [2, 'three'], 4]

Dictionaries {'food': 'spam', 'taste': 'yum'}

Tuples (1,'spam', 4, 'U')

Files myfile = open('eggs', 'r')

Other types Sets, types, None, Booleans

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Python Core objects and Functions

Python type() is a built-in function that returns the type of the objects/data elements stored
in any data type or returns a new type object depending on the arguments passed to the
function.

type(object)
x=12
type(x)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Python Operators - Arithmetic, Logical, Comparison, Assignment, Bitwise & Precedence

Arithmetic Operators
Example: For arithmetic operators we will take simple example of addition where we will add
two-digit 4+5=9
x= 4
y= 5
print(x + y)
Comparison Operators
Various comparison operators in python are ( ==, != , <>, >,<=, etc.)
x=4
y=5
print(('x > y is',x>y))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Python Operators - Arithmetic, Logical, Comparison, Assignment, Bitwise & Precedence

Assignment Operators
Assignment Operators in Python are used for assigning the value of the right operand to the
left operand. Various assignment operators used in Python are (+=, – = , *=, /= , etc.).
num1 = 4
num2 = 5
num1+=10
num2+=30

print(("Line 1 - Value of num1 : ", num1))


print(("Line 2 - Value of num2 : ", num2))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Logical Operators or Bitwise Operators
Logical operators in Python are used for conditional statements are true or false. Logical
operators in Python are AND, OR and NOT. For logical operators following condition are
applied.
For AND operator – It returns TRUE if both the operands (right side and left side) are true
For OR operator- It returns TRUE if either of the operand (right side or left side) is true
For NOT operator- returns TRUE if operand is false
a = True
b = False
print(('a and b is',a and b))
print(('a or b is',a or b))
print(('not a is',not a))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Membership Operators
These operators test for membership in a sequence such as lists, strings or tuples. There are
two membership operators that are used in Python. (in, not in). It gives the result based on
the variable present in specified sequence or string.
Example: For example here we check whether the value of x=4 and value of y=8 is available in
list or not, by using in and not in operators.
x=4
y=8 if ( y not in list ):
list = [1, 2, 3, 4, 5 ]; print("Line 2 - y is not available in
if ( x in list ): the given list")
print("Line 1 - x is available in the given list") else:
else: print("Line 2 - y is available in the
print("Line 1 - x is not available in the given list") given list")

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Identity Operators
Identity Operators in Python are used to compare the memory location of two objects. The
two identity operators used in Python are (is, is not).
Operator is: It returns true if two variables point the same object and false otherwise
Operator is not: It returns false if two variables point the same object and true otherwise
x = 20
y = 20
if ( x is y ):
print("x & y SAME identity")
y=30
if ( x is not y ):
print("x & y have DIFFERENT identity“)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Operator precedence

The operator precedence determines which operators need to be evaluated first. To avoid
ambiguity in values, precedence operators are necessary. Just like in normal multiplication
method, multiplication has a higher precedence than addition. For example in 3+ 4*5, the
answer is 23, to change the order of precedence we use a parentheses (3+4)*5, now the
answer is 35. Precedence operator used in Python are (unary + – ~, **, * / %, + – , &) etc.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Operators (Decreasing order of precedence) Meaning
**
Exponent
*, /, //, % is is not
Multiplication, Division, Floor division, Modulus Identity operators
+, –
Addition, Subtraction in not in
<= < > >= Membership operators
Comparison operators
= %= /= //= -= += *= **=
Assignment Operators not or and
Logical operators

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Python Not Equal (!=) Operator with Examples
Types of Not equal to operators with Syntax in Python
There are two types of not equal operators in python:-
!= <>

!=
A = 44
B = 284
C = 284
print(B!=A)
print(B!=C)

<>
X = 5 Y = 5 if ( X <> Y ): print("X is not equal to Y") else: print("X is equal to Y")

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Assignments
Different Forms of Assignment Statements
1. Basic form:
myname = 'RAJ'
print(myname)

2. Tuple assignment:
# equivalent to: (x, y) = (50, 100)
x, y = 50, 100

print('x = ', x)
print('y = ', y)
3. List assignment:
[x, y] = [2, 4]
print('x = ', x)
print('y = ', y)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
1. INTRODUCTION TO PYTHON
Assignments
Different Forms of Assignment Statements
4. Sequence assignment:
a, b, c = 'RAJ'
print('a = ', a)
print('b = ', b)
print('c = ', c)

5. Extended Sequence unpacking:


f, *r = 'RAJ'
print('f = ', f)
print('r = ', r)
6. Multiple- target assignment:
x = y = 75
print(x, y)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


1. INTRODUCTION TO PYTHON
Assignments
Different Forms of Assignment Statements
7. Augmented assignment (shorthand assignment)
x=2

# equivalent to: x = x + 1
x += 1

print(x)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CHAPTER -2
CONTROL AND LOOPING
STATEMENTS

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CONCEPTS
CONTROL AND LOOPING STATEMENTS

• The if statement
• The if-else statement
• The nested-if statement
• The if-elif-else ladder
• Short Hand if statement
• Short Hand if-else statement
• while loop
• for loop
• Nested loop
• break
• continue
• pass
• return

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


2. CONTROL AND LOOPING STATEMENTS

if statement
Syntax:
if condition:
# Statements to execute if True
If execute if statements
# condition is true (condition) block

# python program to illustrate If statement False


age = 10

if (age < 15): Next statement


print("child")
print("I am Not in if")

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


2. CONTROL AND LOOPING STATEMENTS
if else statement
Syntax:
if (condition):
# Executes this block if True
If execute if statements
# condition is true (condition) block
else:
# Executes this block if
# condition is false
False

# python program to illustrate If else statement


age = 10 execute else statements
if (age < 15): block
print("child")
else:
print("Adult")
print("I am Not in if")
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
2. CONTROL AND LOOPING STATEMENTS
Nested if statement
Syntax:
if (condition1):
False
# Executes when condition1 is true Outer
if (condition2): If
True
# Executes when condition2 is true Code inside outer if statements
# if Block is end here
False
# if Block is end here Inner
If
# python program to illustrate If else statement True
age = 17 Code inside inner if statements
if(age>10):
if (age < 18):
print("child") Code after outer if statements
else:
print("Adult")
else:
print("Invalid Age")
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
2. CONTROL AND LOOPING STATEMENTS
if elif else statement
Syntax: # python program to illustrate If..elif..else
if (condition): statement
statement month=1
elif (condition): if(month==1): If False
statement print("Jan") (condition)
. elif(month==2):
. print("Feb") True

else: elif(month==3): execute if statements


block
statement print("Mar")
else:
print("Not a valid month")
After if

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


2. CONTROL AND LOOPING STATEMENTS
Short Hand if statement
Syntax:
if condition: statement

# Python program to illustrate short hand if


age = 19
if age>18 :print("Adult")

Short Hand if-else statement


Syntax:
statement_when_True if condition else statement_when_False
# Python program to illustrate short hand if else
age = 19
print("Adult") if age>18 else print("Child")

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


2. CONTROL AND LOOPING STATEMENTS

And
The and keyword is a logical operator, and is used to combine conditional statements:
a = 100
b = 14
c = 700
if a > b and c > a:
print("Both conditions are True")

Or
The or keyword is a logical operator, and is used to combine conditional statements:
a = 100
b = 13
c = 200
if a > b or a > c:
print("At least one of the conditions is True")

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


2. CONTROL AND LOOPING STATEMENTS
while Loop
Syntax:
while expression:
statement(s)
# Python program to illustrate while loop
count = 0
while (count < 5):
count = count + 1
print("Hello RAJ")

Using else statement with While Loop in Python


Syntax:
while condition:
# execute these statements
else:
# execute these statements
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
2. CONTROL AND LOOPING STATEMENTS
while Loop
# Python program to illustrate while loop with else
count = 0
while (count < 5):
count = count + 1
print("Hello RAJ")
else:
print("Thank U")

for Loop
Syntax:
# Python program to illustrate for loop
for iterator_var in sequence:
cnt = 4
statements(s)
for i in range(0, cnt):
print(i)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


2. CONTROL AND LOOPING STATEMENTS
Example with List, Tuple, String, and Dictionary Iteration Using for Loops
print("List Iteration") print("\nDictionary Iteration")
l = ["RAJ", "SOFTWARE", "SOLUTION"] d = dict()
for i in l: d['Qty'] = 123
print(i) d['Rate'] = 345
for i in d:
print("\nTuple Iteration") print("%s %d" % (i, d[i]))
t = ("RAJ", "SOFTWARE", "SOLUTION")
for i in t: print("\nSet Iteration")
print(i) set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
print("\nString Iteration") print(i)
s = "RAJ SOFTWARE"
for i in s:
print(i)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


2. CONTROL AND LOOPING STATEMENTS
Iterating by the Index of Sequences
list = ["RAJ", "SOFTWARE", "SOLUTION"]
for index in range(len(list)):
print(list[index])

Using else Statement with for Loop in Python

list = ["RAJ", "SOFTWARE", "SOLUTION"]


for index in range(len(list)):
print(list[index])
else:
print("Thank U")

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


2. CONTROL AND LOOPING STATEMENTS
Nested Loops
Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)

while expression:
while expression:
statement(s)
statement(s)

for i in range(1, 5):


for j in range(1,5):
print("*", end=' ')
print()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
2. CONTROL AND LOOPING STATEMENTS
Break Statement
Return Statement
for i in range(1, 5):
A return statement is used to end the execution of
if(i==4):
the function call and "returns" the result (value of
break
the expression following the return keyword) to the
print(i, end=' ‘)
caller.
Continue Statement
def cube(x):
for i in range(1, 5):
r=x**3
if(i==2):
return r
continue
print(i, end=' ‘)

Pass Statement
for i in range(1, 5):
pass

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CHAPTER -3
PYTHON ARRAYS

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CONCEPTS
ARRAYS

• Python Arrays [Create, Reverse, Pop with Python Array Examples]


• Python 2D Arrays — Python 2D Arrays: Two-Dimensional List Examples

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


3. PYTHON ARRAYS
ARRAYS
What is Python Array?
A Python Array is a collection of common type of data structures having elements with
same data type. It is used to store collections of data. In Python programming, an arrays are
handled by the “array” module. If you create arrays using the array module, elements of the
array must be of the same numeric type.

Creating a Array
Array in Python can be created by importing array module. array(data_type, value_list) is
used to create an array with data type and value list specified in its arguments.
# creating an array
importing "array" for array module # printing original array
import array as arr print ("The new created array is : ", end =" ")
integer type for i in range (0, 3):
a = arr.array('i', [1, 2, 3]) print (a[i], end =" ")
print()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
3. PYTHON ARRAYS
# creating an array with float type (f,d)
b = arr.array('d', [2.5, 3.2, 3.3])

# printing original array


print ("The new created array is : ", end =" ")
for i in range (0, 3):
print (b[i], end =" ")

Adding Elements to a Array


• Elements can be added to the Array by using built-in insert() function.
• Insert is used to insert one or more data elements into an array. Based on the
requirement, a new element can be added at the beginning, end, or any given index of
array.
• append() is also used to add the value mentioned in its arguments at the end of the
array.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


3. PYTHON ARRAYS
# importing "array" for array creations
import array as arr

# array with int type


a = arr.array('i', [1, 2, 3])
print ("Array before insertion : ", end =" ")
for i in range (0, 3):
print (a[i], end =" ")
print()
# array with float type
# inserting array using insert() function b = arr.array('d', [2.5, 3.2, 3.3])
a.insert(1, 4) print ("Array before insertion : ", end
print ("Array after insertion : ", end =" ") =" ")
for i in (a): for i in range (0, 3):
print (i, end =" ") print (b[i], end =" ")
print() print()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
3. PYTHON ARRAYS
# adding an element using append()
b.append(4.4)

print ("Array after insertion : ", end =" ")


for i in (b):
print (i, end =" ")
print()

Accessing elements from the Array


In order to access the array items refer to the index number. Use the index operator [ ] to
access an item in a array. The index must be an integer.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


3. PYTHON ARRAYS
# importing array module # array with float type
import array as arr b = arr.array('d', [2.5, 3.2, 3.3])

# array with int type # accessing element of array


a = arr.array('i', [1, 2, 3, 4, 5, 6]) print("Access element is: ", b[1])

# accessing element of array # accessing element of array


print("Access element is: ", a[0]) print("Access element is: ", b[2])

# accessing element of array


print("Access element is: ", a[3])

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


3. PYTHON ARRAYS
Removing Elements from the Array
• Elements can be removed from the array by using built-in remove() function but an
Error arises if element doesn’t exist in the set.

• Remove() method only removes one element at a time, to remove range of elements,
iterator is used.

• pop() function can also be used to remove and return an element from the array, but by
default it removes only the last element of the array, to remove element from a specific
position of the array, index of the element is passed as an argument to the pop()
method.
• Note – Remove method in List will only remove the first occurrence of the searched
element

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


3. PYTHON ARRAYS
# importing "array" for array operations
import array

# initializing array with array values


# initializes array with signed integers
arr = array.array('i', [1, 2, 3, 1, 5])

# printing original array


print ("The new created array is : ", end ="")
for i in range (0, 5):
print (arr[i], end =" ")

print ("\r")

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


3. PYTHON ARRAYS
# using pop() to remove element at 2nd position
print ("The popped element is : ", end ="")
print (arr.pop(2))

# printing array after popping


print ("The array after popping is : ", end ="")
for i in range (0, 4):
print (arr[i], end =" ")

print("\r")

# using remove() to remove 1st occurrence of 1


arr.remove(1)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


3. PYTHON ARRAYS
# printing array after removing
print ("The array after removing is : ", end ="")
for i in range (0, 3):
print (arr[i], end =" ")

Slicing of a Array
In Python array, there are multiple ways to print the whole array with all the elements, but
to print a specific range of elements from the array, we use Slice operation.
Slice operation is performed on array with the use of colon(:). To print elements from
beginning to a range use [:Index],
to print elements from end use [:-Index],
to print elements from specific Index till the end use [Index:],
to print elements within a range, use [Start Index:End Index] and to print whole List with
the use of slicing operation, use [:]. Further, to print whole array in reverse order, use [::-1].

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


3. PYTHON ARRAYS
# importing array module
import array as arr
# creating a list
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

a = arr.array('i', l)
print("Initial Array: ")
for i in (a):
print(i, end =" ")
# Print elements of a range, using Slice operation
Sliced_array = a[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_array)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


3. PYTHON ARRAYS
# Print elements from a
# pre-defined point to end
Sliced_array = a[5:]
print("\nElements sliced from 5th element till the end: ")
print(Sliced_array)

# Printing elements from


# beginning till end
Sliced_array = a[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_array)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


3. PYTHON ARRAYS
Searching element in a Array
In order to search an element in the array we use a python in-built index() method. This
function returns the index of the first occurrence of value mentioned in arguments.
# importing array module
import array

# initializing array with array values # initializes array with signed integers
arr = array.array('i', [1, 2, 3, 1, 2, 5])

# printing original array


print ("The new created array is : ", end ="")
for i in range (0, 6):
print (arr[i], end =" ") print ("\r")

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


3. PYTHON ARRAYS
# using index() to print index of 1st occurrence of 2
print ("The index of 1st occurrence of 2 is : ", end ="")
print (arr.index(2))

# using index() to print index of 1st occurrence of 1


print ("The index of 1st occurrence of 1 is : ", end ="")
print (arr.index(1))

# reverse an array in python


arr=[11,22,33,55,66]
print(“array is:”,arr)
rev=arr[::-1]
print(rev);

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


3. PYTHON ARRAYS
Updating Elements in a Array
In order to update an element in the array we simply reassign a new value to the desired
index we want to update.
# importing array module
import array

# initializing array with array values


# initializes array with signed integers
arr = array.array('i', [1, 2, 3, 1, 2, 5])

# printing original array


print ("Array before updation : ", end ="")
for i in range (0, 6):
print (arr[i], end =" “) print ("\r“)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


3. PYTHON ARRAYS
# updating a element in a array
arr[2] = 6
print("Array after updation : ", end ="")
for i in range (0, 6):
print (arr[i], end =" ")
print()

# updating a element in a array


arr[4] = 8
print("Array after updation : ", end ="")
for i in range (0, 6):
print (arr[i], end =" ")

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


3. PYTHON ARRAYS
Two-Dimensional List Examples

Example: Following is the example for creating 2D array with 4 rows and 5 columns.
array=[[23,45,43,23,45],[45,67,54,32,45],[89,90,87,65,44],[23,45,67,32,10]]
#display
print(array)
#get the first row
print(array[0])
#get the third row
print(array[2])
#get the first row third element
print(array[0][2])
#get the third row forth element
print(array[2][3])

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


3. PYTHON ARRAYS
We can also access elements using for loop
Create 2D array with 4 rows and 5 columns

array=[[23,45,43,23,45],[45,67,54,32,45],[89,90,87,65,44],[23,45,67,32,10]]

#use for loop to iterate the array


for rows in array:
for columns in rows:
print(columns,end=" ")
print()

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


3. PYTHON ARRAYS
Inserting the values into the two-dimensional array
Here we are going to insert values into two dimensional array using insert() function.
#creare 2D array with 4 rows and 5 columns
array=[[23,45,43,23,45],[45,67,54,32,45],[89,90,87,65,44],[23,45,67,32,10]]

#insert the row at 5 th position


array.insert(4, [1,2,3,4,5])

#insert the row at 6 th position


array.insert(5, [1,2,3,4,5])

#insert the row at 7 th position


array.insert(6, [1,2,3,4,5])

#display
print(array)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
3. PYTHON ARRAYS
Deleting the values from two-dimensional array
You can delete rows using the del function

del array[index]
#creare 2D array with 4 rows and 5 columns
array=[[23,45,43,23,45],[45,67,54,32,45],[89,90,87,65,44],[23,45,67,32,10]]

#delete row values in the 3rd row


del array[2]

#delete row values in the 2nd row


del array[1]

#display
print(array)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


3. PYTHON ARRAYS
Get the size of two-dimensional array
You can get the size of the two-dimensional array using the line() function. It will return the
number of rows in the array
len(array)

#creare 2D array with 4 rows and 5 column


array=[[23,45,43,23,45],[45,67,54,32,45],[89,90,87,65,44],[23,45,67,32,10]]

#display
print(len(array))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CHAPTER -4
PYTHON STRINGS

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CONCEPTS
STRINGS

• Python Strings — Replace, Join, Split, Reverse, Uppercase & Lowercase


• Python String strip() Function — What is, Examples of strip() Function
• Python String count() — Python String count() Method with Examples
• Python String format() — What is, How works & Examples
• Python String len() Method — Python string length | len() method Example
• Python String find() Method — Python string.find() Method With Examples
• Python String split() Method — Python String split(): List, By Character, Delimiter EXAMPLE

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


4. PYTHON STRING
STRING
Strings are arrays of bytes representing Unicode characters. However, Python does not
have a character data type, a single character is simply a string with a length of 1. Square
brackets can be used to access elements of the string.
# Creating a String with single Quotes
String1 = 'Welcome to the Raj IT World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String with double Quotes
String1 = "I'm a Raj"
print("\nString with the use of Double Quotes: ")
print(String1)
# Creating a String with triple Quotes
String1 = '''I'm a Raj Software and I live in a world of "Computer"'''
print("\nString with the use of Triple Quotes: “) print(String1)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


4. PYTHON STRING

# Creating String with triple Quotes allows multiple lines


String1 = '''Raj
For
IT'''
print("\nCreating a multiline String: ")
print(String1)

Accessing characters in Python


String1 = "RAJSOFTWARE"
print("Initial String: ")
print(String1)
# Printing First character
print("\nFirst character of String is: ") # Printing Last character
print(String1[0]) print("\nLast character of String is: ")
print(String1[-1])

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


4. PYTHON STRING
String Slicing
# Creating a String
String1 = "RAJSOFTWARE"
print("Initial String: ")
print(String1)

# Printing 3rd to 12th character


print("\nSlicing characters from 3-12: ")
print(String1[3:12])

# Printing characters between 3rd and 2nd last character


print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


4. PYTHON STRING
Deleting/Updating from a String

Updation or deletion of characters from a String is not allowed. This will cause an error
because item assignment or item deletion from a String is not supported. Although deletion
of the entire String is possible with the use of a built-in del keyword. This is because Strings
are immutable, hence elements of a String cannot be changed once it has been assigned.
Only new strings can be reassigned to the same name.

String1 = "Hello, I'm a RAJ" # Updating a character


print("Initial String: ") # of the String
print(String1) String1[2] = 'p'
print("\nUpdating character at 2nd Index: ")
print(String1)
Error: 'str' object does not support item assignment

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


4. PYTHON STRING
Updating Entire String:
String1 = "Hello, I'm a RAJ"
print("Initial String: ")
print(String1)

# Updating a String
String1 = "Welcome to the RAJ World"
print("\nUpdated String: ")
print(String1)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


4. PYTHON STRING
Deleting Entire String:
Deletion of the entire string is possible with the use of del keyword. Further, if we try to
print the string, this will produce an error because String is deleted and is unavailable to be
printed.

String1 = "Hello, I'm a Raj"


print("Initial String: ")
print(String1)

# Deleting a String with the use of del


del String1
print("\nDeleting entire String: ")
print(String1)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


4. PYTHON STRING
Escape Sequencing in Python

While printing Strings with single and double quotes in it causes SyntaxError because String
already contains Single and Double Quotes and hence cannot be printed with the use of
either of these.

Hence, to print such a String either Triple Quotes are used or Escape sequences are used to
print such Strings.

# Initial String
String1 = '''I'm a "RAJ"'''
print("Initial String with use of Triple Quotes: ")
print(String1)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


4. PYTHON STRING
# Escaping Single Quote
String1 = 'I\'m a "RAJ"'
print("\nEscaping Single Quote: ")
print(String1)

# Escaping Double Quotes


String1 = "I'm a \"RAJ\""
print("\nEscaping Double Quotes: ")
print(String1)

# Printing Paths with the use of Escape Sequences


String1 = "C:\\Python\\RAJ\\"
print("\nEscaping Backslashes: ")
print(String1)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


4. PYTHON STRING
Formatting of Strings
# Default order
String1 = "{} {} {}".format('RAJ', 'Solution', 'Software')
print("Print String in default order: ")
print(String1)

# Positional Formatting
String1 = "{1} {0} {2}".format('Software', 'Raj', 'Solution')
print("\nPrint String in Positional order: ")
print(String1)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


4. PYTHON STRING
# Keyword Formatting
String1 = "{l} {f} {g}".format(g='Good', f='For', l='Life')
print("\nPrint String in order of Keywords: ")
print(String1)

# Formatting of Integers
String1 = "{0:b}".format(16)
print("\nBinary representation of 16 is ")
print(String1)

# Formatting of Floats
String1 = "{0:e}".format(165.6458)
print("\nExponent representation of 165.6458 is ")
print(String1)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


4. PYTHON STRING
# Rounding off Integers
String1 = "{0:.2f}".format(1/6)
print("\none-sixth is : ")
print(String1)

Case Changing of Strings


1.lower() 2.upper() 3.title()
text = 'Raj Software Solution’

# upper() function to convert string to upper case


print("\nConverted String:")
print(text.upper())

# lower() function to convert string to lower case


print("\nConverted String:")
print(text.lower())
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
4. PYTHON STRING
# Prints the string by replacing only occurrence of RAJ
print(string.replace("raj", "RAJ", 3))
print(string.replace("r", "J"))

Join
list1 = ['1','2','3','4']
s = "-“

# joins elements of list1 by '-‘ and stores in string s


s = s.join(list1)

# join use to join a list of strings to a separator s


print(s)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


4. PYTHON STRING
Split
text = 'Raj Software'
# Splits at space
print(text.split())
word = 'Raj, Software, Solution‘
# Splits at ','
print(word.split(','))
word = 'Raj:Software:Solution'
# Splitting at ':'
print(word.split(':'))
word = 'CatBatSatFatOr'
# Splitting at t
print(word.split('t'))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


4. PYTHON STRING
Reversed
# Function to reverse a string
def reverse(string):
string = "".join(reversed(string))
return string

s = "RajSoftware"

print ("The original string is : ",end="")


print (s)
print ("The reversed string(using reversed) is : ",end="")
print (reverse(s))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


4. PYTHON STRING
strip() is an inbuilt function in Python programming language that returns a copy of the
string with both leading and trailing characters removed (based on the string argument
passed).

string = """ raj software solution """

# prints the string without stripping


print(string)

# prints the string by removing leading and trailing whitespaces


print(string.strip())

# prints the string by removing raj


print(string.strip(' raj'))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


4. PYTHON STRING
count()
# string in which occurrence will be checked
string = "raj software solution"

# counts the number of times substring occurs in the given string and returns an integer
print(string.count("raj"))

len()
# Length of below string is 5 # with list
string = "rajsoftware" l = [1,2,3,4]
print(len(string)) print(len(l))

# with tuple
tup = (1,2,3)
print(len(tup))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


4. PYTHON STRING
find()
word = 'raj software solution'
# returns first occurrence of Substring
result = word.find('raj')
print ("Substring 'raj' found at index:", result )

result = word.find('solution')
print ("Substring 'solution' found at index:", result )

# How to use find()


if (word.find('test') != -1):
print ("Contains given substring ")
else:
print ("Doesn't contains given substring“)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CHAPTER -5
PYTHON FUNCTIONS

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CONCEPTS
PYTHON FUNCTIONS

• Python Functions
• Types of Python Functions
• Python Lambda Functions(Anonymous) with EXAMPLES
• What is the map() function in Python?
• Generator & Yield vs Return Example
• type() and isinstance() in Python — What is, Syntax & Examples
• Python time.sleep() — Add Delay to Your Code (Example)
• Python Timer Function — Measure Elapsed Time with EXAMPLES

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
Python Functions
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing.
Defining a Function
• Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).

• Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.

• The first statement of a function can be an optional statement - the documentation


string of the function or docstring.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
The code block within every function starts with a colon (:) and is indented.

The statement return [expression] exits a function, optionally passing back an expression to
the caller.

A return statement with no arguments is the same as return None.

Syntax:
def function_name(parameters):
"""docstring"""
statement(s)
return expression

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
Creating a Function
We can create a Python function using the def keyword.

Funuction
# A simple Python function
def fun():
print("Welcome to RAJ SOFTWARE")

Types of Python Functions.


• Built-in library function: These are Standard functions in Python that are available to
use.
• User-defined function: We can create our own functions based on our requirements.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
• Simple Function
• Function with Parameters
• Return Statement in Python Function
• Pass by Reference and Pass by Value
• Function within Functions

Simple Function
Python Function Declaration :
def fun():
print("Welcome to RAJ SOFTWARE")

Calling a Python Function


def fun():
print("Welcome to RAJ SOFWARE")
# Driver code to call a function
fun()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
5. PYTHON FUNCTIONS
Function with Parameters

def add(num1, num2): #def add(num1: int, num2: int):


"""Add two numbers"""
num3 = num1 + num2
print(f"The addition of {num1} and {num2} results {num3}.")

# Driver code
num1, num2 = 5, 15
add(num1, num2)
#Note : f for format function

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
Types of Python Function Arguments
• Default arguments
• Keyword arguments
• Variable-length arguments
• Variable length non-keywords argument
• Variable length keyword arguments

Default arguments
A default argument is a parameter that assumes a default value if a value is not provided in
the function call for that argument. The following example illustrates Default arguments.
# Python program to demonstrate default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
# Driver code (We call myFun() with only argument)
myFun(10)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
5. PYTHON FUNCTIONS
Keyword arguments
The idea is to allow the caller to specify the argument name with values so that caller does
not need to remember the order of parameters.
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)

student(firstname='Raj', lastname='Software')
student(lastname='Software', firstname='Raj’)

Variable-length arguments
In Python, we can pass a variable number of arguments to a function using special symbols.
There are two special symbols:

*args (Non-Keyword Arguments) (Variable length non-keywords argument)


**kwargs (Keyword Arguments) (Variable length keywords argument)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
5. PYTHON FUNCTIONS
Variable length non-keywords argument
# Python program to illustrate *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print(arg)

myFun('Hello', 'Welcome', 'to', 'Raj Software solution')

Variable length keyword arguments


# Python program to illustrate *kwargs for variable number of keyword arguments
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))

myFun(first='Raj', mid='Software', last='Solution')

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
Docstring

The first string after the function is called the Document string or Docstring in short. This is
used to describe the functionality of the function. The use of docstring in functions is
optional but it is considered a good practice.

The below syntax can be used to print out the docstring of a function:
Syntax: print(function_name.__doc__)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
Adding Docstring to the function
# A simple Python function to check whether x is even or odd

def evenOdd(x):
"""Function to check if the number is even or odd"""

if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function


print(evenOdd.__doc__)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
The return statement

The function return statement is used to exit from a function and go back to the function
caller and return the specified value or data item to the caller.
Syntax: return [expression_list]

Python Function Return Statement


def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2
print(square_value(2))
print(square_value(-4))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
Is Python Function Pass by Reference or pass by value?
One important thing to note is, in Python every variable name is a reference. When we
pass a variable to a function, a new reference to the object is created. Parameter passing in
Python is the same as reference passing in Java.

# Here x is a new reference to same list lst


def myFun(x):
x[0] = 20

# Driver Code (Note that lst is modified


# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
Python Function within Functions
A function that is defined inside another function is known as the inner function or nested
function. Nested functions are able to access variables of the enclosing scope. Inner
functions are used so that they can be protected from everything happening outside the
function.
# Python program to demonstrate accessing of variables of nested functions

def f1():
s = 'I love RAJ SOFTWARE'
# Driver's code
def f2(): f1()
print(s)

f2()

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
Python Lambda Functions(Anonymous) with EXAMPLES

In Python, an anonymous function means that a function is without a name. As we already


know the def keyword is used to define the normal functions and the lambda keyword is
used to create anonymous functions.

# Python code to illustrate the cube of a number


# using lambda function

def cube(x): return x*x*x

cube_v2 = lambda x : x*x*x

print(cube(7))
print(cube_v2(7))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
# Double all numbers using map and lambda

numbers = (1, 2, 3, 4)
result = map(lambda x: x + x, numbers)
print(list(result))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
map()
map() function returns a map object(which is an iterator) of the results after applying the
given function to each item of a given iterable (list, tuple etc.)

Returns a list of the results after applying the given function to each item of a given iterable
(list, tuple etc.)
# Python program to demonstrate working of map. # Return double of n
def addition(n):
return n + n
# We double all numbers using map() # Driver's code
numbers = (1, 2, 3, 4) f1()
result = map(addition, numbers)
print(list(result))
We can also use lambda expressions with map to achieve above result.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
Generator & Yield vs Return Example

A generator function in Python is defined like a normal function, but whenever it needs to
generate a value, it does so with the yield keyword rather than return. If the body of a def
contains yield, the function automatically becomes a Python generator function.

When to use yield instead of return in Python?


The yield statement suspends function’s execution and sends a value back to the caller, but
retains enough state to enable function to resume where it is left off. When resumed, the
function continues execution immediately after the last yield run. This allows its code to
produce a series of values over time, rather than computing them at once and sending
them back like a list.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
# Generator Syntax
def function_name():
yield statement

# A generator function that yields 1 for the first time, # 2 second time and 3 third time
def simpleGeneratorFun():
yield 1
yield 2
yield 3

# Driver code to check above generator function


for value in simpleGeneratorFun():
print(value)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
Python Counter
Python Counter takes in input a list, tuple, dictionary, string, which are all iterable objects,
and it will give you output that will have the count of each element.

# A Python program to show different ways to create Counter


from collections import Counter
list1 = ['x','y','z','x','x','x','y', 'z']
print(Counter(list1))
# A Python program to demonstrate update()
from collections import Counter
coun = Counter()
coun.update([1, 2, 3, 1, 2, 1, 1, 2])
print(coun)
coun.update([1, 2, 4])
print(coun)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
# Python program to demonstrate that counts in
# Counter can be 0 and negative

from collections import Counter

c1 = Counter(A=4, B=3, C=10)


c2 = Counter(A=10, B=3, C=4)

c1.subtract(c2)
print(c1)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
type() and isinstance() in Python

Python has a built-in function called type() that helps you find the class type of the variable
given as input. For example, if the input is a string, you will get the output as <class ‘str’>,
for the list, it will be <class ‘list’>, etc.
Using type() command, you can pass a single argument, and the return value will be the
class type of the argument given, example: type(object).

str_list = "Welcome to Raj Software Solution“


print("The type is : ",type(str_list))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
isinstance() in Python
Python isinstance is part of python built-in functions.
Python isinstance() takes in two arguments, and it returns true if the first argument is an
instance of the classinfo given as the second argument.

age = isinstance(51,int) my_tuple = isinstance((1,2,3,4,5),tuple)


print("age is an integer:", age) print("my_tuple is a tuple:",my_tuple)

pi = isinstance(3.14,float) my_set = isinstance({1,2,3,4,5},set)


print("pi is a float:", pi) print("my_set is a set:", my_set)

message = isinstance("Hello World",str) my_list = isinstance([1,2,3,4,5],list)


print("message is a string:", message) print("my_list is a list:", my_list)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
Python time sleep()

Python sleep() is a function used to delay the execution of code for the number of seconds
given as input to sleep().

The sleep() command is a part of the time module. You can use the sleep() function to
temporarily halt the execution of your code.

For example, you are waiting for a process to complete or a file upload.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


5. PYTHON FUNCTIONS
import time
time.sleep(seconds)

import time
print("Welcome to Raj Software Solution")
time.sleep(5)
print("This message will be printed after a wait of 5 seconds")

import time
my_message = "RAJ SOFTWARE SOLUTION“
for i in my_message:
print(i)
time.sleep(1)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CHAPTER -6
LIST, TUPLES, DICTIONARIES,
SETS

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CONCEPTS
LIST, TUPLES, DICTIONARIES, SETS

• Lists in Python
• More about Lists
• Understanding List Comprehensions and Lambda Expressions
• Next and Ranges
• Understanding and using Ranges
• More About Ranges
• Working with Tupes - Pack, Unpack, Compare, Slicing, Delete, Key
• Python Dictionaries
• Working with Other datatypes list, tuble, integer.
• Exploring Python Sets and Frozen Set
• Functions in Set
• Operators in Set

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
LISTS in Python
Python Lists are just like the arrays, declared in other languages which is an ordered
collection of data. also can change and allow duplicate in the list. It is very flexible as
the items in a list do not need to be of the same type.

List = [1, 2, 3, "KFG2", 2.3]


print(List)
List elements can be accessed by the assigned index. In python starting index of the
list, sequence is 0 and the ending index is (if N elements are there) N-1.

Ordered, Allow Duplicate, Changeable.

Can store different datatypes:

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS

Creating Python List

li1 = ["Java", "C", "Python"]


li2 = [3, 4, 6, 8, 7]
li3 = [False, False,True]

li1 = [“java”,88,True,89,”Male”]

all_list = ["Java ", "C", " Python"]


print(type(all_list))

list() Constructor
mylist = list(("Java", "C", "Python"))
print(mylist)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS

# Creating a List of numbers


List = []
print("Blank List: ")
print(List)

List = [10, 20, 14]


print("\nList of numbers: ")
print(List)

# Creating a List of strings and accessing using index


List = ["RAJ", "SOFTWARE", "SOLUTION"]
print("\nList Items: ")
print(List[0])
print(List[2])

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS

# Creating a Multi-Dimensional List (By Nesting a list inside a List)


List = [['Raj', 'Software'], ['Solution']]
print("\nMulti-Dimensional List: ")
print(List)

Creating a list with multiple duplicate elements


# Creating a List with the use of Numbers (Having duplicate values)

List = [1, 2, 6, 6, 4, 4, 4, 7, 5]
print("\nList with the use of Numbers: ")
print(List)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS

# Creating a List with mixed type of values (Having numbers and strings)

List = [1, 2, 'Raj', 4, 'Software', 6, 'Solution']


print("\nList with the use of Mixed Values: ")
print(List)
Knowing the size of List
# Creating a List
List1 = []
print(len(List1))

# Creating a List of numbers


List2 = [10, 20, 14]
print(len(List2))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS

Adding Elements to a List Using append() method


# Creating a List
List = []
print("Initial blank List: ")
print(List)
# Addition of Elements in the List
List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS

# Adding elements to the List using Iterator


for i in range(1, 4):
List.append(i)
print("\nList after Addition of elements from 1-3: ")
print(List)
# Adding Tuples to the List
List.append((5, 6))
print("\nList after Addition of a Tuple: ")
print(List)
# Addition of List to a List
List2 = ['For', 'Raj']
List.append(List2)
print("\nList after Addition of a List: ")
print(List)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS

Using insert() method


# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)

# Addition of Element at specific Position (using Insert Method)


List.insert(3, 12)
List.insert(0, 'Raj')
print("\nList after performing Insert Operation: ")
print(List)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS

Using extend() method


# Creating a List
List = [1, 2, 3, 4]
print("Initial List: ")
print(List)
# Addition of multiple elements to the List at the end (using Extend Method)
List.extend([8, 'Raj', 'Software'])
print("\nList after performing Extend Operation: ")
print(List)
# Reverse
List.reverse()
#sort
List.sort()

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS

Accessing elements from the List


# Creating a List with the use of multiple values
List = ["RAJ", "SOFTWARE", "SOLUTION"]

# accessing a element from the list using index number


print("Accessing a element from the list")
print(List[0])
print(List[2])

# Creating a Multi-Dimensional List (By Nesting a list inside a List)


List = [['Raj', 'Software'], ['Solution']]

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS

# accessing an element from the Multi-Dimensional List using index number


print("Accessing a element from a Multi-Dimensional list")
print(List[0][1])
print(List[1][0])

Negative indexing
List = [1, 2, 'Raj’, 4, 'For', 6, ‘Software’]

# accessing an element using negative indexing


print("Accessing element using negative indexing")
# print the last element of list
print(List[-1])

# print the third last element of list


print(List[-3])
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
6. LIST, TUPLES, DICTIONARIES, SETS

Removing Elements from the List


Using remove() method
# Python program to demonstrate Removal of elements in a List

# Creating a List
List = [1, 2, 3, 4, 5, 6,7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(List)
# Removing elements from List using Remove() method
List.remove(5)
List.remove(6)
print("\nList after Removal of two elements: ")
print(List)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS

# Removing elements from List using iterator method


for i in range(1, 5):
List.remove(i)
print("\nList after Removing a range of elements: ")
print(List)
Using pop() method
List = [1,2,3,4,5]
List.pop()
print("\nList after popping an element: ")
print(List)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS

Removing duplicates from List.


Li=[1,2,2,3,3,4,5,6,6]
Li1 =[]
print("List before", Li)
for i in Li:
if i not in Li1:
Li1.append(i)

Li=Li1
print("After Removing duplicates",Li)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS

# Removing element at a specific location from the Set using the pop() method
List.pop(2)
print("\nList after popping a specific element: ")
print(List)

# Removing using the clear() and del() method


clear() just clear the List
li = [1,"raj",3,"test",5]
li.clear()
print(li)
del() delete the List object from memory
li = [1,"raj",3,"test",5]
del(li)
print(li)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS

Slicing of a List
# Creating a List
List = ['R', 'A', 'J', 'S', 'O', 'F',’T', 'W', 'A', 'R', 'E', 'S', 'O', 'L', 'U']
print("Initial List: ")
print(List)

# Print elements of a range using Slice operation


Sliced_List = List[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_List)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS

# Print elements from a pre-defined point to end


Sliced_List = List[5:]
print("\nElements sliced from 5th "
"element till the end: ")
print(Sliced_List)

# Printing elements from beginning till end


Sliced_List = List[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_List)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS

Negative index List slicing


# Creating a List
List = ['R', 'A', 'J', 'S', 'O', 'F',’T', 'W', 'A', 'R', 'E', 'S', 'O', 'L', 'U']
print("Initial List: ")
print(List)

# Print elements from beginning to a pre-defined point using Slice


Sliced_List = List[:-6]
print("\nElements sliced till 6th element from last: ")
print(Sliced_List)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS

# Print elements of a range using negative index List slicing


Sliced_List = List[-6:-1]
print("\nElements sliced from index -6 to -1")
print(Sliced_List)

# Printing elements in reverse using Slice operation


Sliced_List = List[::-1]
print("\nPrinting List in reverse: ")
print(Sliced_List)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
List Comprehension
A Python list comprehension consists of brackets containing the expression, which is
executed for each element along with the for loop to iterate over each element in the
Python list.

Example
numbers = [12, 13, 14,]
doubled = [x *2 for x in numbers]
print(doubled)

# Using list comprehension to iterate through loop


List = [character for character in [1, 2, 3]]

# Displaying list
print(List)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
list = [i for i in range(11) if i % 2 == 0]
print(list)

# Using list comprehension to iterate through loop


List = [character for character in 'RAJ SOFTWARE']

# Displaying list
print(List)

List Comprehensions and Lambda


Lambda Expressions are nothing but shorthand representations of Python functions.
Using list comprehensions with lambda creates an efficient combination.

# using lambda to print table of 10


numbers = list(map(lambda i: i*10, [i for i in range(1, 6)]))
print(numbers)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
6. LIST, TUPLES, DICTIONARIES, SETS
Next and Range
Python’s next() function returns the next item of an iterator.

li = [1, 2, 3]
l_iter = iter(li)
print(next(l_iter))
print(next(l_iter))
print(next(l_iter))
print(next(l_iter),"No more elements")

The Python range() function returns a sequence of numbers, in a given range. The
most common use of it is to iterate sequences on a sequence of numbers
using Python loops.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
for i in range(5): # 0 to 5
print(i, end=" ")
print()

range() function takes can be initialized in 3 ways.

• range (stop) takes one argument.


• range (start, stop) takes two arguments.
• range (start, stop, step) takes three arguments.

Incrementing the Range using a Positive Step


for i in range(5):
Python range() using Negative Step
for i in range(25, 2, -2):
Python range() with Float Values (Not supported)
for i in range(3.3):
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
6. LIST, TUPLES, DICTIONARIES, SETS
Accessing range() with an Index Value
r_ele = range(10)[0]
print("First element:", r_ele)

r_ele = range(10)[-1]
print("\nLast element:", r_ele)

r_ele = range(10)[4]
print("\nFifth element:", r_ele)

Concatenation of two range() functions using itertools chain() method


from itertools import chain
print("Concatenating the result")
res = chain(range(5), range(10, 20, 2))
for i in res:
print(i, end=" ")
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
6. LIST, TUPLES, DICTIONARIES, SETS
Accessing range() with an Index Value
r_ele = range(10)[0]
print("First element:", r_ele)

r_ele = range(10)[-1]
print("\nLast element:", r_ele)

r_ele = range(10)[4]
print("\nFifth element:", r_ele)

Concatenation of two range() functions using itertools chain() method


from itertools import chain
print("Concatenating the result")
res = chain(range(5), range(10, 20, 2))
for i in res:
print(i, end=" ")
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
6. LIST, TUPLES, DICTIONARIES, SETS
Tuples
A Tuple is a collection of Python objects separated by commas. In someways a tuple is similar
to a list in terms of indexing, nested objects and repetition but a tuple is immutable unlike
lists which are mutable.

Creating Tuples
# An empty tuple
empty_tuple = ()
print (empty_tuple)

# Creating non-empty tuples One way of creation


tup = 'python', 'raj'
print(tup)

# Another for doing the same


tup = ('python', 'raj’) print(tup)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
6. LIST, TUPLES, DICTIONARIES, SETS
Packing and Unpacking
In packing, we place value into a new tuple while in unpacking we extract those values back
into variables.
# tuple packing
x = (“RAJ SOFTWARE SOLUTION", 20, "Education")
# tuple unpacking
(company, emp, profile) = x

print(company)
print(emp)
print(profile)

Concatenation of Tuples
# Code for concatenating 2 tuples # Concatenating above two
tuple1 = (0, 1, 2, 3) print(tuple1 + tuple2)
tuple2 = ('python', 'raj')
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
6. LIST, TUPLES, DICTIONARIES, SETS
Nesting of Tuples
# Code for creating nested tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'raj')
tuple3 = (tuple1, tuple2)
print(tuple3)

Repetition in Tuples
# Code to create a tuple with repetition
tuple3 = ('python',)*3
print(tuple3)

Immutable Tuples
#code to test that tuples are immutable
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4 print(tuple1)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
6. LIST, TUPLES, DICTIONARIES, SETS
Slicing in Tuples
# code to test slicing
tuple1 = (0 ,1, 2, 3)
print(tuple1[1:])
print(tuple1[::-1])
print(tuple1[2:4])

Deleting a Tuple
# Code for deleting a tuple
tuple3 = (0, 1)
del tuple3
print(tuple3)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
Finding Length of a Tuple
# Code for printing the length of a tuple
tuple2 = ('python', 'raj')
print(len(tuple2))

Converting list to a Tuple


# Code for converting a list and a string into a tuple
list1 = [0, 1, 2]
print(tuple(list1))
print(tuple('python')) # string 'python’

Finding Length of a Tuple


# Code for printing the length of a tuple
tuple2 = ('python', 'raj')
print(len(tuple2))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
Converting list to a Tuple
# Code for converting a list and a string into a tuple
list1 = [0, 1, 2]
print(tuple(list1))
print(tuple('python')) # string 'python’
Comparing tuples
A comparison operator in Python can work with tuples.The comparison starts with a first
element of each tuple. If they do not compare to =,< or > then it proceed to the second
element and so on.
#case 1
a=(5,6)
b=(1,4) Case1: Comparison starts with a first element of each
if (a>b): tuple. In this case 5>1, so the output “a is bigger”
print("a is bigger")
else:
print("b is bigger")
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
6. LIST, TUPLES, DICTIONARIES, SETS
#case 2
a=(5,6)
b=(5,4) Case 2: Comparison starts with a first element of each
if (a>b): tuple. In this case 5>5 which is inconclusive. So it proceeds
print("a is bigger") to the next element. 6>4, so the output a is bigger.
else:
print ("b is bigger")

#case 3
a=(5,6)
Case 3: Comparison starts with a first element of each
b=(6,4)
tuple. In this case 5>6 which is false. So it goes into the
if (a>b):
else block and prints “b is bigger.”
print("a is bigger")
else:
print("b is bigger“)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
Tuples in a loop
#python code for creating tuples in a loop
tup = ('raj',)
n=5
#Number of time loop runs
for i in range(int(n)):
tup = (tup,)
print(tup)

Using max() , min()


# A python program to demonstrate the use of
# cmp(), max(), min()
tuple1 = (12, 34)
tuple2 = (35, 1)
print ('Maximum element in tuples 1,2: ' +str(max(tuple1)) + ',' + str(max(tuple2)))
print ('Minimum element in tuples 1,2: ' +str(min(tuple1)) + ',' + str(min(tuple2)))
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
6. LIST, TUPLES, DICTIONARIES, SETS
Dictionary

• Python Dictionary is used to store the data in a key-value pair format.

• The dictionary is the data type in Python, which can simulate the real-life data
arrangement where some specific value exists for some particular key.

• It is the mutable data-structure.

• The dictionary is defined into element Keys and values.

• Keys must be a single element Value can be any type such as list, tuple, integer, etc.

• A dictionary is a collection which is unordered, changeable and indexed.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
Creating the dictionary
Dict = {"Name": "RAJ", "Age": 25}

# Creating a Dictionary
Dict = {'Name': 'RAJ', 1: [1, 2, 3, 4]}
print("Creating Dictionary: ")
print(Dict)

# accessing a element using key


print("Accessing a element using key:")
print(Dict['Name'])

# accessing a element using get() method


print("Accessing a element using get:")
print(Dict.get(1))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
dict() function creates a dictionary.

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary with dict() method


Dict = dict({1: 'RAJ', 2: 'For', 3:'RAJ'})
print("\nDictionary with the use of dict(): ")
print(Dict)

# Creating a Dictionary with each item as a Pair


Dict = dict([(1, 'RAJ'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
6. LIST, TUPLES, DICTIONARIES, SETS
Nested Dictionary:
# Creating a Nested Dictionary as shown in the below image
Dict = {1: 'RAJ', 2: 'For',3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'RAJ'}}
print(Dict)

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Adding elements one at a time


Dict[0] = 'RAJ'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
6. LIST, TUPLES, DICTIONARIES, SETS
# Adding set of values to a single Key
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Updating existing Key's Value


Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)

# Adding Nested Key value to Dictionary


Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'RAJ'}}
print("\nAdding a Nested Key: ")
print(Dict)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
Accessing elements from a Dictionary

# Python program to demonstrate accessing a element from a Dictionary

# Creating a Dictionary
Dict = {1: 'RAJ', 'name': 'For', 3: 'RAJ’}

# accessing a element using key


print("Accessing a element using key:")
print(Dict['name’])

# accessing a element using key


print("Accessing a element using key:")
print(Dict[1])

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
There is also a method called get() that will also help in accessing the element from a dictionary.
# Creating a Dictionary
Dict = {1: 'RAJ', 'name': 'For', 3: 'RAJ’}

# accessing a element using get() method


print("Accessing a element using get:")
print(Dict.get(3))

Accessing an element of a nested dictionary Creating a Dictionary


Dict = {'Dict1': {1: 'RAJ'},
'Dict2': {'Name': 'For’}}

# Accessing element using key


print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
6. LIST, TUPLES, DICTIONARIES, SETS
Removing Elements from Dictionary Using del keyword

# Initial Dictionary
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'RAJ',
'A' : {1 : 'RAJ', 2 : 'For', 3 : 'RAJ'},
'B' : {1 : 'RAJ', 2 : 'Life'}}
print("Initial Dictionary: ")
print(Dict)

# Deleting a Key value


del Dict[6]
print("\nDeleting a specific key: ")
print(Dict)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
# Deleting a Key from Nested Dictionary
delDict['A'][2]
print("\nDeleting a key from Nested Dictionary: ")
print(Dict)

Using pop() method


Dict = {1: 'RAJ', 'name': 'For', 3: 'RAJ’}

# Deleting a key using pop() method


pop_ele = Dict.pop(1)
print('\nDictionary after deletion: ' + str(Dict))
print('Value associated to poped key is: ' + str(pop_ele))

Using popitem() method


Dict = {1: 'RAJ', 'name': 'For', 3: 'RAJ'}

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
# Deleting an arbitrary key using popitem() function
pop_ele = Dict.popitem()
print("\nDictionary after deletion: " + str(Dict))
print("The arbitrary pair returned is: " + str(pop_ele))

Using clear() method


# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks’}

# Deleting entire Dictionary


Dict.clear()
print("\nDeleting Entire Dictionary: ")
print(Dict)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
SET
A Python set is the collection of the unordered items. Each element in the set must be unique,
mutable, and the sets remove the duplicate elements. Sets are mutable which means we can
modify it after its creation.

# Same as {"a", "b", "c"}


myset = set(["a", "b", "c"])
print(myset)

# Adding element to the set


myset.add("d")
print(myset)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
Frozen Sets
Frozen sets in Python are immutable objects that only support methods and operators that
produce a result without affecting the frozen set or sets to which they are applied.
# Python program to demonstrate differences between normal and frozen set Same as {"a",
"b","c"}
normal_set = set(["a","b","c"])
print("Normal Set")
print(normal_set)

# A frozen set
frozen_set = frozenset(["e", "f", "g"])
print("\nFrozen Set")
print(frozen_set)
# Uncommenting below line would cause error as we are trying to add element to a frozen
set #
frozen_set.add("h")
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
6. LIST, TUPLES, DICTIONARIES, SETS
Adding elements
# A Python program to demonstrate adding elements in a set Creating a Set
people = {"Raj", "Anand", "Sree"}

print("People:", end = " ")


print(people)

people.add("Vettri")

# Adding elements to the set using iterator


for i in range(1, 6):
people.add(i)
print("\nSet after adding element:", end = " ")
print(people)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
Union
Two sets can be merged using union() function or | operator.
# Python Program to demonstrate union of two sets

people = {"Jay", "Idrish", "Archil"}


vampires = {"Karan", "Arjun"}
dracula = {"Deepanshu", "Raju"}

# Union using union() function


population = people.union(vampires)
print("Union using union() function")
print(population)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
# Union using "|" operator
population = people|dracula
print("\nUnion using '|' operator")
print(population)
Intersection
This can be done through intersection() or & operator.
# Python program to demonstrate intersection of two sets
set1 = set()
set2 = set()
for i in range(5):
set1.add(i)

for i in range(3,9):
set2.add(i)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
# Intersection using intersection() function
set3 = set1.intersection(set2)

print("Intersection using intersection() function")


print(set3)

# Intersection using "&" operator


set3 = set1 & set2

print("\nIntersection using '&' operator")


print(set3)

Difference
To find difference in between sets. Similar to find difference in linked list. This is done through
difference() or – operator

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
# Python program to demonstrate difference of two sets
set1 = set()
set2 = set()

for i in range(5):
set1.add(i)

for i in range(3,9):
set2.add(i)
# Difference of two sets using difference() function
set3 = set1.difference(set2)

print(" Difference of two sets using difference() function")


print(set3)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
# Difference of two sets using '-' operator
set3 = set1 - set2

print("\nDifference of two sets using '-' operator")


print(set3)

Clearing sets
Clear() method empties the whole set.
# Python program to demonstrate clearing of set

set1 = {1,2,3,4,5,6}

print("Initial set")
print(set1)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
# This method will remove all the elements of the set
set1.clear()

print("\nSet after using clear() function")


print(set1)

Operators for Sets


# Python program to demonstrate working of Set in Python

# Creating two sets


set1 = set()
set2 = set()

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
# Adding elements to set1
for i in range(1, 6):
set1.add(i)

# Adding elements to set2


for i in range(3, 8):
set2.add(i)

print("Set1 = ", set1)


print("Set2 = ", set2)
print("\n")

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
# Union of set1 and set2
set3 = set1 | set2 # set1.union(set2)
print("Union of Set1 & Set2: Set3 = ", set3)

# Intersection of set1 and set2


set4 = set1 & set2 # set1.intersection(set2)
print("Intersection of Set1 & Set2: Set4 = ", set4)
print("\n")

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
# Checking relation between set3 and set4
if set3 > set4: # set3.issuperset(set4)
print("Set3 is superset of Set4")
elif set3 < set4: # set3.issubset(set4)
print("Set3 is subset of Set4")
else : # set3 == set4
print("Set3 is same as Set4")

# displaying relation between set4 and set3


if set4 < set3: # set4.issubset(set3)
print("Set4 is subset of Set3")
print("\n")

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


6. LIST, TUPLES, DICTIONARIES, SETS
# difference between set3 and set4
set5 = set3 - set4
print("Elements in Set3 and not in Set4: Set5 = ", set5)
print("\n")

# check if set4 and set5 are disjoint sets


if set4.isdisjoint(set5):
print("Set4 and Set5 have nothing in common\n")

# Removing all the values of set5


set5.clear()

print("After applying clear on sets Set5: ")


print("Set5 = ", set5)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CHAPTER -7
PYTHON MODULES &
PACKAGES

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CONCEPTS
PYTHON MODULES & PACKAGES

• Python import statement, from..import statement, from..import * statement


• Python Executing Modules as scripts and Locating Modules
• Python PYTHONPATH Variable , Namespace and Scoping
• Python dir() function and globals() and locals() function
• Python reload() function
• Python Packages

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
What are the modules in Python?
A module is a file with python code. The code can be in the form of variables, functions, or
class defined.

The filename becomes the module name.

For example, if your filename is sample.py, the module name will be sample. With module
functionality, you can break your code into different files instead of writing everything inside
one file.
What is the Python import module?
• A file is considered as a module in python. To use the module, you have to import it
using the import keyword.
• The function or variables present inside the file can be used in another file by importing
the module.
• This functionality is available in other languages, like typescript, JavaScript, java, ruby, etc.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
How to create and import a module in Python?
Step 1 :
Create a file named as mymodule.py

Step 2 :
Type the following code in mymodule.py
def display():
return "from my module"
Step 3 :
Create a file named as testmodule.py

Step 4 :
Import the mymodule.py using following code.
import mymodule
print(mymodule.display())

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
Using from to import module
You can import only a small part of the module i.e., only the required functions and variable
names from the module instead of importing full code.

When you want only specific things to be imported, you can make use of "from" keyword to
import what you want.

So the syntax is
from module import your function_name , variables,... etc.

from test import display_message


print(display_message())

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
Importing everything from the module
Import allows you to import the full module by using import followed by module name, i.e.,
the filename or the library to be used.

Syntax:
import module def display_message1():
Or by using return "All about Python!"
from module import *

test.py
my_name = "RAJ SOFTWARE SOLUTION"
my_address = "Salem"

def display_message():
return "Welcome to RAJ SOFTWARE Tutorials!"

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
Using the import module

Using just import module name, to refer to the variables and functions inside the module, it
has to prefix with module name.

import test
print(test.display_message())
print(test.display_message1())
print(test.my_name)
print(test.my_address)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
Using import *
Let us see an example using import *.

Using import *, the functions and variables are directly accessible, as shown in the example
below:

from test import *


print(display_message())
print(display_message1())
print(my_name)
print(my_address)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
Locating the Modules in Python
When the modules are imported by the users, the Python interpreter will search for the
module in the current directory. If the module is not found in the directory, the interpreter
will search every directory present in the shell variable known as PYTHONPATH. If the
interpreter is unable to find it in the shell, then it will check the default path.

The PYTHONPATH Variable


The PYTHONPATH variable is a Platform based variable, which is consists of the list of
directories. Its syntax is the same as the PATH of the shell variable.

PYTHONPATH from the windows system:


set PYTHONPATH = c: \\python3\\lib;

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
Executing Modules in Python

From the command-line options, the -m option is used for locating the path of the given
module, and it executed the module as the __main__ module of the program.
The runpy module is the standard module of Python , which is used for internally supporting
this mechanism.

The runpy module allows a script to be located by using the namespace of the Python module
instead file system.

The runpy module defines two functions:


run_module()
run_path()

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
run_module()

The run_module() function is used for executing the code containing the specific module, and
it will return the result of the module globals dictionary.

The module_name argument should be the actual module name. Suppose the name of the
module referred to any package instead of the normal module. In that case, that package will
be imported, and the __main__ sub module inside the package will be executed, and it will
return the result of the module globals dictionary.

The special global variables, that is, __name__, __spec__, __file__, __cached__, __loader__
and __package__ are set in the globals dictionary before the execution of module.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
run_path()

The run_path() function is used for executing the program in the file at the given path, and it
will return the module globals dictionary as a result. The given path can refer to the Python
source file, a compiled bytecode file, or a valid sys.path entry that contains the __main__
module, such as a zipfile including the top-level __main__.py file.

The special global variables, that is, __name__, __spec__, __file__, __cached__, __loader__
and __package__ are set in the globals dictionary before the execution of module.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
For Ex. runpy_example.py
def add(p, q, r, s, t):
return p + q + r + s + t

def main():
p=4
q=6
r=2
s=8
t=7
print ("sum of p, q, r, s, t = ")
print (add(p,q,r,s,t))
return
if __name__=='__main__':
main()

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
And then, the user will execute the above file using the following command:

import runpy_example as runp


runp.main()

Although, the user can execute the above file without importing it:

import runpy
runpy.run_module('runpy_example', run_name='__main__')

The user can also user run_path() function:

runpy.run_path('runpy_example.py', run_name='__main__')

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
the runpy also supports the -m switch of the Python command line:
C:\python37>python -m runpy_example

Namespaces and Scope in Python


What is a Namespace in Python?
In Python, you can imagine a namespace as a mapping of every name you have defined to
corresponding objects.
1. Built-in- Namespace Built-in Namespace
2. Module : Global Namespace
Module: Global Namespace
3. Function : Local Namespace
Function:
Built Local
Namespace

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
Python Variable Scope
A scope is the portion of a program from where a namespace can be accessed directly
without any prefix.

There are at least three nested scopes.


• Scope of the current function which has local names
• Scope of the module which has global names
• Outermost scope which has built-in names

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
def outer_function():
a = 20
def inner_function():
a = 30
print('a =', a)
inner_function()
print('a =', a)
a = 10
outer_function()
print('a =', a)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
Python dir() function and globals() and locals() function.

dir() is a powerful inbuilt function in Python, which returns list of the attributes and methods
of any object (say functions , modules, strings, lists, dictionaries etc.)
print(dir())
------------------------
From Module
import random
import math
print(dir())
-------------------------
print("The contents of the random library are::“)
print(dir(random))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
From List :
RSS = ["RAJ SOFTWARE", "SOLUTION", "Computer Science",
"Data Structures", "Algorithms"]

print(dir(RSS))

From Class :
class Sales:
def __dir__(self):
return['customer_name', 'product',
'quantity', 'price', 'date']
my_cart = Sales()
print(dir(my_cart))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
globals() function in Python returns the dictionary of current global symbol table.

Symbol table: Symbol table is a data structure which contains all necessary information about
the program. These include variable names, methods, classes, etc.

Global symbol table stores all information related to the global scope of the program, and is
accessed in Python using globals() method.

# Python program to demonstrate global() function


# global variable
a=5 # Calling globals()
def func(): globals()['a'] = d
c = 10 print (d)
d=c+a # Driver Code
func()

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
# Python program to demonstrate global() function

# global variable
name = 'raj software'

print('Before modification:', name)

# Calling global()
globals()['name'] = raj software solution'
print('After modification:', name)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
Global keyword in Python
A global keyword is a keyword that allows a user to modify a variable outside of the current
scope.

It is used to create global variables in python from a non-global scope i.e inside a function.

Global keyword is used inside a function only when we want to do assignments or when we
want to change a variable.

Global is not needed for printing and accessing.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
Modifying Global Variable From Inside the Function
# Python program showing to modify
# a global value without using global
# keyword
a = 15

# function to change a global value


def change():
# increment value of a by 5
a=a+5
print(a)

change()
UnboundLocalError: local variable 'a' referenced before assignment

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
Changing Global Variable From Inside a Function using global
x = 15

def change():
# using a global keyword
global x

# increment value of a by 5
x=x+5
print("Value of x inside a function :", x)

change()
print("Value of x outside a function :", x)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
Python locals() function returns the dictionary of the current local symbol table.

Symbol table: It is a data structure created by a compiler for which is used to store all
information needed to execute a program.

Local symbol Table: This symbol table stores all information needed for the local scope of the
program and this information is accessed using python built-in function locals().

# Python program to understand about locals here no local variable is present


def demo1():
print("Here no local variable is present : ", locals())

# here local variables are present # driver code


def demo2(): demo1()
name = "RAJ" demo2()
print("Here local variables are present : ", locals())
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
7. PYTHON MODULES & PACKAGES
Reloading modules in Python
The reload() is a previously imported module.

If you’ve altered the module source file using an outside editor and want to test the updated
version without leaving the Python interpreter, this is helpful. The module object is the return
value.

import importlib
importlib.reload(module)

import sys
import importlib
importlib.reload(sys)
print(sys.path)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
Package (Collection of several modules)
A Python module may contain several classes, functions, variables, etc. whereas a Python
package can contains several module. In simpler terms a package is folder that contains
various modules as files.

Creating Package
Let’s create a package named mypckg that will contain two modules mod1 and mod2.
To create this module follow the below steps –

• Create a folder named mypckg.


• Inside this folder create an empty Python file i.e. __init__.py
• Then create two modules mod1 and mod2 in this folder.
Mod1.py Mod2.py
def raj(): def sum(a, b):
print("Welcome to raj") return a+b

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
The hierarchy of the our package looks like this –
mypckg
|
|
---__init__.py
|
|
---mod1.py
|
|
---mod2.py

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
Understanding __init__.py
__init__.py helps the Python interpreter to recognize the folder as package. It also specifies
the resources to be imported from the modules.
If the __init__.py is empty this means that all the functions of the modules will be imported.
We can also specify the functions from each module to be made available.

For example, we can also create the __init__.py file for the above module as –
__init__.py
from .mod1 import raj
from .mod2 import sum

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


7. PYTHON MODULES & PACKAGES
Import Modules from a Package
We can import these modules using the from…import statement and the dot(.) operator.
import package_name.module_name
from mypckg import mod1
from mypckg import mod2

mod1.raj()
res = mod2.sum(1, 2)
print(res)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CHAPTER -8
PYTHON CLASSES AND
OBJECTS

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CONCEPTS
PYTHON CLASSES AND OBJECTS

• Overview of OOP
• Creating Classes and Objects
• The self variable
• Constructor
• Types of Methods
• Instance Methods
• Static Methods
• Class Methods
• Built-In Class Attributes
• Destroying Objects
• Inheritance super() function and Type of Inheritance
• Encapsulation and Polymorphsim

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS
In Python, object-oriented Programming (OOPs) is a programming paradigm that uses objects
and classes in programming.

It aims to implement real-world entities like inheritance, polymorphisms, encapsulation, etc.


in the programming.

The main concept of OOPs is to bind the data and the functions that work on that together as
a single unit so that no other part of the code can access this data.

Main Concepts of Object-Oriented Programming (OOPs)


• Class
• Objects
• Polymorphism
• Encapsulation
• Inheritance

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS
Creating Classes and Objects
A class is a collection of objects. A class contains the blueprints or the prototype from which
the objects are being created. It is a logical entity that contains some attributes and methods.

Some points on Python class:


• Classes are created by keyword class.
• Attributes are the variables that belong to a class.
• Attributes are always public and can be accessed using the dot (.) operator.
• Eg.: Myclass.Myattribute

Class Definition Syntax:


class ClassName:
# Statement-1
.
.
# Statement-N
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
Creating an empty Class in Python
class SuperMarket:
pass

Objects
• The object is an entity that has a state and behavior associated with it.
• It may be any real-world object like a mouse, keyboard, chair, table, pen, etc.
• Integers, strings, floating-point numbers, even arrays, and dictionaries, are all objects.

An object consists of :
State: It is represented by the attributes of an object. It also reflects the properties of an
object.
Behavior: It is represented by the methods of an object. It also reflects the response of an
object to other objects.
Identity: It gives a unique name to an object and enables one object to interact with other
objects
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
Class Creation
class Person:
def print_name(self):
print("HelloWorld")

Object Creation
obj = Person()

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS
The self
1. Class methods must have an extra first parameter in the method definition. We do not
give a value for this parameter when we call the method, Python provides it

2. If we have a method that takes no arguments, then we still have to have one argument.

3. This is similar to this pointer in C++ and this reference in Java.

4. When we call a method of this object as myobject.method(arg1, arg2), this is


automatically converted by Python into MyClass.method(myobject, arg1, arg2) – this is all
the special self is about.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS
Constructor
The __init__ method
The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object of
a class is instantiated. The method is useful to do any initialization.

Syntax of constructor declaration :


def __init__(self):
# body of the constructor

Types of constructors :
default constructor: The default constructor is a simple constructor which doesn’t accept any
arguments.
parameterized constructor: constructor with parameters is known as parameterized
constructor. The parameterized constructor takes its first argument as a reference to the
instance being constructed known as self and the rest of the arguments are provided by the
programmer.
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
Example of default constructor :
class Person:
# default constructor
def __init__(self):
self.name = "Mr.Sethil Kumar"

# a method for printing data members


def print_name(self):
print(self.name)

# creating object of the class


obj = Person()

# calling the instance method using the object obj


obj.print_name()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
Example of parameterized constructor :
class Person:
# parameterized constructor
def __init__(self,firstname,lastname):
self.fname=firstname
self.lname=lastname

# a method for printing data members


def print_fullname(self):
print(self.fname+self.lname)

# creating object of the class


obj = Person("Anand","Raj")

# calling the instance method using the object obj


obj.print_fullname()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
Type of Methods

We can define three types of methods:


• Instance methods
• Class methods
• Static methods

Instance methods
Instance methods are the most used methods in a Python class. These methods are only
accessible through class objects. If we want to modify any class variable, this should be done
inside an instance method.

The first parameter in these methods is self. self is used to refer to the current class object’s
properties and attributes.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS
Type of Methods

We can define three types of methods:


• Instance methods
• Class methods
• Static methods

Instance methods
Instance methods are the most used methods in a Python class. These methods are only
accessible through class objects. If we want to modify any class variable, this should be done
inside an instance method.

The first parameter in these methods is self. self is used to refer to the current class object’s
properties and attributes.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS
class Cricket:
teamName = None

def setTeamName(self, name):


self.teamName = name

def getTeamName(self):
return self.teamName

c = Cricket()
c.setTeamName('India')
print(c.getTeamName())

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS
Class methods
Class methods are usually used to access class variables. You can call these methods directly
using the class name instead of creating an object of that class.

To declare a class method, we need to use the @classmethod decorator.

In class methods, we use use the cls variable to refer to the class.

class Cricket:
teamName = 'India'

@classmethod
def getTeamName(cls):
return cls.teamName

print(Cricket.getTeamName())
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
Static methods
Static methods are usually used as a utility function or when we do not want an inherited
class to modify a function definition. These methods do not have any relation to the class
variables and instance variables; so, are not allowed to modify the class attributes inside a
static method.
To declare a static method, we need to use the @staticmethod.
class Cricket:
teamName = 'India'

@staticmethod
def utility():
print("This is a static method.")

c1 = Cricket()
c1.utility()
Cricket.utility()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
Built-In Class Attributes

Attribute Description
__dict__ This is a dictionary holding the class namespace.

__doc__ This gives us the class documentation if documentation is


present. None otherwise.

__name__ This gives us the class name.


__module__ This gives us the name of the module in which the class is defined.
In an interactive mode it will give us __main__.

__bases__ A possibly empty tuple containing the base classes in the order of their
occurrence.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS

The __dict__ class attribute

# class
class Cricket:

def __init__(self):
print("Hello from __init__ method.")

# class built-in attribute


print(Cricket.__dict__)

O/P:
{'__module__': '__main__', '__doc__’: ‘……..

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS

The __doc__ class attribute The __name__ class attribute

# class # class
class Cricket: class Cricket:
'This is a sample class called Cricket.' 'This is a sample class called Awesome.'

def __init__(self): def __init__(self):


print("Hello from __init__ method.") print("Hello from __init__ method.")

# class built-in attribute # class built-in attribute


print(Cricket.__doc__) print(Cricket.__name__)

O/P: O/P:
This is a sample class called Cricket Cricket

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS

The __module__ class attribute The __base__ class attribute

# class # class
class Cricket: class Cricket:

def __init__(self): def __init__(self):


print("Hello from __init__ method.") print("Hello from __init__ method.")

# class built-in attribute # class built-in attribute


print(Cricket.__module__) print(Cricket.__base__)

O/P: O/P:
__main__ (<class 'object'>,)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS

Destroying Objects

Destructors are called when an object gets destroyed. In Python, destructors are not needed
as much as in C++ because Python has a garbage collector that handles memory
management automatically.

The __del__() method is a known as a destructor method in Python. It is called when all
references to the object have been deleted i.e when an object is garbage collected.

Syntax of destructor declaration :

def __del__(self):
# body of destructor

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS

# Python program to illustrate destructor


class Employee:

# Initializing
def __init__(self):
print('Employee created.')

# Deleting (Calling destructor)


def __del__(self):
print('Destructor called, Employee deleted.')

obj = Employee()
del obj

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS
Inheritance

Inheritance is the capability of one class to derive or inherit the properties from another
class.

Benefits of inheritance are:


• It represents real-world relationships well.
• It provides the reusability of a code. We don’t have to write the same code again and
again. Also, it allows us to add more features to a class without modifying it.
• It is transitive in nature, which means that if class B inherits from another class A, then all
the subclasses of B would automatically inherit from class A.
• Inheritance offers a simple, understandable model structure.
• Less development and maintenance expenses result from an inheritance.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS
The syntax of simple inheritance in Python is as follows:

Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS
Creating a Parent Class
A parent class is a class whose properties are inherited by the child class.

# A Python program to demonstrate inheritance


class Person(object):
# Constructor
def __init__(self, name, id):
self.name = name
self.id = id

# To check if this person is an employee


def Display(self):
print(self.name, self.id)
# Driver code
emp = Person("Anand", 102) # An Object of Person
emp.Display()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
Creating a Child Class
A child class is a class that drives the properties from its parent class. Here Emp is another
class that is going to inherit the properties of the Person class(base class).

class Emp(Person):

def Print(self):
print("Emp class called")

Emp_details = Emp("Anand", 103)

# calling parent class function


Emp_details.Display()

# Calling child class function


Emp_details.Print()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
# Base or Super class. Note object in bracket. (Generally, object is made ancestor of all
classes) # In Python 3.x "class Person" is equivalent to "class Person(object)"
# Inherited or Subclass (Note Person in bracket)
class Person(object): class Employee(Person):
# Constructor
def __init__(self, name): # Here we return true
self.name = name def isEmployee(self):
return True
# To get name
def getName(self): # Driver code
return self.name emp = Person("Anand") # An Object of Person
print(emp.getName(), emp.isEmployee())
# To check if this person is an employee
def isEmployee(self): emp = Employee("Sree") # An Object of
return False Employee
print(emp.getName(), emp.isEmployee())
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
# Base or Super class. Note object in bracket. (Generally, object is made ancestor of all
classes) # In Python 3.x "class Person" is equivalent to "class Person(object)"
# Inherited or Subclass (Note Person in bracket)
class Person(object): class Employee(Person):
# Constructor
def __init__(self, name): # Here we return true
self.name = name def isEmployee(self):
return True
# To get name
def getName(self): # Driver code
return self.name emp = Person("Anand") # An Object of Person
print(emp.getName(), emp.isEmployee())
# To check if this person is an employee
def isEmployee(self): emp = Employee("Sree") # An Object of
return False Employee
print(emp.getName(), emp.isEmployee())
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
The super() Function

The super() function is a built-in function that returns the objects that represent the parent
class. It allows to access the parent class’s methods and attributes in the child class.
# parent class # child class
class Person(): class Student(Person):
def __init__(self, name, age): def __init__(self, name, age):
self.name = name self.sName = name
self.age = age self.sAge = age
# inheriting the properties of parent class
def display(self): super().__init__("Anand", age)
print(self.name, self.age) Person.__init__(self,"nss", age)

def displayInfo(self):
print(self.sName, self.sAge)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS
#to access object
obj = Student("RAJ", 23)
obj.display()
obj.displayInfo()

Different types of Python Inheritance


• Single Inheritance
• Multiple Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS
1. Single Inheritance
# Python program to demonstrate single inheritance

# Base class
class Parent:
def func1(self):
print("This function is in parent class.")

# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")

# Driver's code
object = Child()
object.func1() object.func2()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
2. Multiple Inheritance
# Python program to demonstrate multiple inheritance
# Base class1 # Derived class
class Mother: class Son(Mother, Father):
mothername = "" def parents(self):
print("Father :", self.fathername)
def mother(self): print("Mother :",
print(self.mothername) self.mothername)

# Base class2
class Father: # Driver's code
fathername = "" s1 = Son()
s1.fathername = "RAM"
def father(self): s1.mothername = "SITA"
print(self.fathername) s1.parents()

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS
3. Multilevel Inheritance
# Python program to demonstrate multilevel inheritance

# Base class
class Grandfather:

def __init__(self, grandfathername):


self.grandfathername = grandfathername

# Intermediate class
class Father(Grandfather):
def __init__(self, fathername, grandfathername):
self.fathername = fathername

# invoking constructor of Grandfather class


Grandfather.__init__(self, grandfathername)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
3. Multilevel Inheritance continue….
# Derived class
class Son(Father):
def __init__(self, sonname, fathername, grandfathername):
self.sonname = sonname

# invoking constructor of Father class


Father.__init__(self, fathername, grandfathername)

def print_name(self):
print('Grandfather name :', self.grandfathername)
print("Father name :", self.fathername)
print("Son name :", self.sonname)
# Driver code
s1 = Son('Prince', 'Rampal', 'Lal mani')
print(s1.grandfathername) s1.print_name()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
4. Hierarchical Inheritance
# Python program to demonstrate Hierarchical inheritance
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")

# Derived class1
class Child1(Parent):
def func2(self): # Driver's code
print("This function is in child 1.") object1 = Child1()
object2 = Child2()
# Derivied class2 object1.func1()
class Child2(Parent): object1.func2()
def func3(self): object2.func1()
print("This function is in child 2.") object2.func3()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
5. Hybrid Inheritance
# Python program to demonstrate Hybrid inheritance
class School:
def func1(self):
print("This function is in school.")

class Student1(School):
def func2(self):
print("This function is in student 1. ")

class Student2(School):
def func3(self):
print("This function is in student 2.") # Driver's code
object = Student3()
class Student3(Student1, School): object.func1()
def func4(self): object.func2()
print("This function is in student 3.")
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
Encapsulation
Encapsulation describes the idea of wrapping data and the methods that work on data
within one unit. This puts restrictions on accessing variables and methods directly and can
prevent the accidental modification of data.

Protected members:-
Protected members (in C++ and JAVA) are those members of the class that cannot be
accessed outside the class but can be accessed from within the class and its subclasses. To
accomplish this in Python, just follow the convention by prefixing the name of the member
by a single underscore “_”.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS
# Python program to demonstrate protected members
class Base:
def __init__(self):
# Protected member
self._a = 2

class Derived(Base):
def __init__(self):
# Calling constructor of Base class
Base.__init__(self)
print("Calling protected member of base class: ",
self._a)

self._a = 3 #Modify the protected variable:


print("Calling modified protected member outside class: ",
self._a)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS

obj1 = Derived()
obj2 = Base()

# Calling protected member Can be accessed but should not be done due to
convention
print("Accessing protected member of obj1: ", obj1._a)

# Accessing the protected variable outside


print("Accessing protected member of obj2: ", obj2._a)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS
Private members
# Driver code
# Python program to demonstrate private members
obj1 = Base()
class Base:
print(obj1.a)
def __init__(self):
self.a = "RAJ"
# Uncommenting print(obj1.c) will
self.__c = "RAJ SOFT"
# raise an AttributeError
class Derived(Base):
def __init__(self):
# Uncommenting obj2 = Derived() will
# also raise an AttributeError as
# Calling constructor of
# private member of base class
# Base class
# is called inside derived class
Base.__init__(self)
print("Calling private member of base class: ")
print(self.__c)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS
Polymorphism
What is Polymorphism: The word polymorphism means having many forms. In
programming, polymorphism means the same function name (but different signatures)
being used for different types. The key difference is the data types and number of
arguments used in function.

Example of inbuilt polymorphic functions: User defined polymorphic functions

# len() being used for a string def add(x, y, z = 0):


print(len("geeks")) return x + y+z

# len() being used for a list # Driver code


print(len([10, 20, 30])) print(add(2, 3))
print(add(2, 3, 4))

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS
Polymorphism with class methods:
class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the most widely spoken language of India.")
def type(self):
print("India is a developing country.")

class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()

Polymorphism with class methods:


class Poly_fun:
def add(self,x1,y1,z1=10):
return x1+ y1 + z1

# Driver code
x = Poly_fun()
print(x.add(12, 3))
print(x.add(10,20,3))
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
8. PYTHON CLASSES AND OBJECTS
Polymorphism with Inheritance:
Polymorphism lets us define methods in the child class that have the same name as the
methods in the parent class.
class Bird:
def intro(self):
print("There are many types of birds.")
def flight(self):
print("Most of the birds can fly but some cannot.")

class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


8. PYTHON CLASSES AND OBJECTS
class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")

obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()

obj_bird.intro()
obj_bird.flight()

obj_spr.intro()
obj_spr.flight()

obj_ost.intro()
obj_ost.flight()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
CHAPTER -9
DATA SCIENCE
USING
PYTHON
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
CONCEPTS
DATA SCIENCE USING PYTHON

• Introduction to numpy
• Creating arrays
• Indexing Arrays
• Array Transposition
• Universal Array Function
• Array Processing
• Array Input and Output
• Python Matrix — Transpose, Multiplication, NumPy Arrays Examples
• SciPy in Python Tutorial — What is | Library & Functions Examples

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


9. DATA SCIENCE USING PYTHON

What is Data Science?

Data Science is the area of study which involves extracting insights from vast amounts of data
using various scientific methods, algorithms, and processes. It helps you to discover hidden
patterns from the raw data. The term Data Science has emerged because of the evolution of
mathematical statistics, data analysis, and big data.

Data Science is an interdisciplinary field that allows you to extract knowledge from structured
or unstructured data. Data science enables you to translate a business problem into a
research project and then translate it back into a practical solution.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


9. DATA SCIENCE USING PYTHON
NumPy is a general-purpose array-processing package. It provides a high-performance
multidimensional array object and tools for working with these arrays. It is the fundamental
package for scientific computing with Python. It is open-source software.

Install Python NumP


pip install numpy

Arrays in NumPy
• It is a table of elements (usually numbers), all of the same type, indexed by a tuple of
positive integers.
• In NumPy, dimensions are called axes. The number of axes is rank.

In this example, we are creating a two-dimensional array that has the rank of 2 as it has
2 axes.
arr = np.array( [[ 1, 2, 3],
[ 4, 2, 5]] )
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
9. DATA SCIENCE USING PYTHON
import numpy as np

# Creating array object


arr = np.array( [[ 1, 2, 3], [ 4, 2, 5]] )

# Printing type of arr object


print("Array is of type: ", type(arr))

# Printing array dimensions (axes)


print("No. of dimensions: ", arr.ndim)

# Printing shape of array


print("Shape of array: ", arr.shape)

# Printing size (total number of elements) of array


print("Size of array: ", arr.size)

# Printing type of elements in array


print("Array stores elements of type: ", arr.dtype)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
9. DATA SCIENCE USING PYTHON
NumPy Array Creation
You can create an array from a regular Python list or tuple using the array() function.

import numpy as np

# Creating array from list with type float


a = np.array([[1, 2, 4], [5, 8, 7]], dtype = 'float')
print ("Array created using passed list:\n", a)

# Creating array from tuple


b = np.array((1 , 3, 2))
print ("\nArray created using passed tuple:\n", b)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


9. DATA SCIENCE USING PYTHON
NumPy Array Indexing
NumPy array indexing is important for analyzing and manipulating the array object.

For example:

print(arr[1:5])
print(arr[4:])
print(arr[:4])
print(arr[-3:-1])

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


9. DATA SCIENCE USING PYTHON
NumPy Matrix Transformation
import numpy as np

# Original matrix
original_matrix = np.matrix([[1, 2, 3], [4, 5, 6]])

# Transposed matrix
transposed_matrix = original_matrix.transpose()

print("Original Matrix:")
print(original_matrix)
print("\nTransposed Matrix:")
print(transposed_matrix)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


9. DATA SCIENCE USING PYTHON
NumPy ufuncs | Universal functions

NumPy Universal functions (ufuncs in short) are simple mathematical functions that operate
on ndarray (N-dimensional array) in an element-wise fashion.

It supports array broadcasting, type casting, and several other standard features. NumPy
provides various universal functions like standard trigonometric functions, functions for
arithmetic operations, handling complex numbers, statistical functions, etc.

Array Input and Output


Here are some of the commonly used NumPy Input/Output functions:
save(), load(), savetxt(), loadtxt()

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


9. DATA SCIENCE USING PYTHON
Save()
import numpy as np
# create a NumPy array
array1 = np.array([[1, 3, 5],
[7, 9, 11]])

# save the array to a file


np.save('file1.npy', array1)

Load()
import numpy as np
# load the saved NumPy array
loaded_array = np.load('file1.npy')

# display the loaded array


print(loaded_array)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
9. DATA SCIENCE USING PYTHON
SciPy in Python Tutorial: What is | Library & Functions Examples

SciPy in Python is an open-source library used for solving mathematical, scientific,


engineering, and technical problems. It allows users to manipulate the data and visualize the
data using a wide range of high-level Python commands. SciPy is built on the Python NumPy
extention. SciPy is also pronounced as "Sigh Pi."
Sub-packages of SciPy:

• File input/output – scipy.io


• Special Function – scipy.special
• Linear Algebra Operation – scipy.linalg
• Interpolation – scipy.interpolate
• Optimization and fit – scipy.optimize
• Statistics and random numbers – scipy.stats
• Numerical Integration – scipy.integrate
• Fast Fourier transforms – scipy.fftpack
• Signal Processing – scipy.signal
• Image manipulation – scipy.ndimage
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
9. DATA SCIENCE USING PYTHON
SciPy – Installation and Environment Setup
Python3 -m pip install --user numpy scipy

File Input / Output package:


Scipy, I/O package, has a wide range of functions for work with different files format which
are Matlab, Arff, Wave, Matrix Market, IDL, NetCDF, TXT, CSV and binary format.

import numpy as np
from scipy import io as sio
array = np.ones((4, 4))
sio.savemat('example.mat', {'ar': array})
data = sio.loadmat(‘example.mat', struct_as_record=True)
data['ar']

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


9. DATA SCIENCE USING PYTHON
Python Matrix — Transpose, Multiplication, NumPy Arrays Examples
What is Python Matrix?
A Python matrix is a specialized two-dimensional rectangular array of data stored in rows
and columns. The data in a matrix can be numbers, strings, expressions, symbols, etc.
Matrix is one of the important data structures that can be used in mathematical and
scientific calculations.

How do Python Matrices work?


The data inside the two-dimensional
array in matrix format looks as follows:

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


9. DATA SCIENCE USING PYTHON
The python matrix makes use of arrays, and the same can be implemented.

• Create a Python Matrix using the nested list data type


• Create Python Matrix using Arrays from Python Numpy package

Create Python Matrix using a nested list data type


We will create a 3×3 matrix, as shown below:

M1 = [[8, 14, -6],


[12,7,4],
[-11,3,21]]
#To print the matrix
print(M1)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


9. DATA SCIENCE USING PYTHON

To read the last element from each row.


M1 = [[8, 14, -6],
[12,7,4],
[-11,3,21]]
matrix_length = len(M1)
#To read the last element from each row.
for i in range(matrix_length):
print(M1[i][-1])

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


9. DATA SCIENCE USING PYTHON
Create Python Matrix using Arrays from Python Numpy package
The python library Numpy helps to deal with arrays. Numpy processes an array a little
faster in comparison to the list.

To work with Numpy, you need to install it first. Follow the steps given below to install
Numpy.
Step 1)
The command to install Numpyis :
pip install NumPy

Step 2)
To make use of Numpy in your code, you have to import it.
import NumPy

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


9. DATA SCIENCE USING PYTHON
Step 3)
You can also import Numpy using an alias, as shown below:
import NumPy as np
Array in Numpy to create Python Matrix
importnumpy as np
M1 = np.array([[5, -10, 15], [3, -6, 9], [-4, 8, 12]])
print(M1)

Matrix Addition
To perform addition on the matrix, we will create two matrices using numpy.array() and
add them using the (+) operator.

import numpy as np

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


9. DATA SCIENCE USING PYTHON
M1 = np.array([[3, 6, 9], [5, -10, 15], [-7, 14, 21]])
M2 = np.array([[9, -18, 27], [11, 22, 33], [13, -26, 39]])
M3 = M1 + M2
print(M3)
Matrix Subtraction
To perform subtraction on the matrix, we will create two matrices using numpy.array() and
subtract them using the (-) operator.
import numpy as np
M1 = np.array([[3, 6, 9], [5, -10, 15], [-7, 14, 21]])
M2 = np.array([[9, -18, 27], [11, 22, 33], [13, -26, 39]])
M3 = M1 - M2
print(M3)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


9. DATA SCIENCE USING PYTHON
Matrix Transpose
The transpose of a matrix is calculated, by changing the rows as columns and columns as
rows.
The transpose() function from Numpy can be used to calculate the transpose of a matrix.
import numpy as np
M1 = np.array([[3, 6, 9], [5, -10, 15], [4,8,12]])
M2 = M1.transpose()
print(M2)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CHAPTER -10
PYTHON AND CSV FILES

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CONCEPTS
PYTHON AND CSV FILES

• Reading and Writing CSV Files in Python — Using Module & Pandas

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


10. PYTHON AND CSV FILES
How to Read CSV File in Python | CSV File Reading and Writing
What is a CSV file?
A CSV file is a simple type of plain text file which uses a specific structure to arrange tabular
data. The standard format of a CSV file is defined by rows and columns data where a newline
terminates each row to begin the next row, and each column is separated by a comma within
the row.
Table Data
Programming language Designed by Appeared Extension
Python Guido van Rossum 1991 .py
Java James Gosling 1995 .java
C++ BjarneStroustrup 1983 .cpp

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


10. PYTHON AND CSV FILES
CSV file format:
CSV Data
Programming language, Designed by, Appeared, Extension
Python, Guido van Rossum, 1991, .py
Java, James Gosling, 1995, .java
C++, Bjarne Stroustrup,1983,.cpp

Python CSV Module


Python provides a CSV module to handle CSV files. To read/write data, you need to loop
through rows of the CSV. You need to use the split method to get data from specified
columns.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


10. PYTHON AND CSV FILES
How to Read a CSV File in Python
import csv
with open('X:\data.csv','rt')as f:
data = csv.reader(f)
for row in data:
print(row)
How to write CSV File in Python
import csv

with open('X:\writeData.csv', mode='w') as file:


writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


10. PYTHON AND CSV FILES
#way to write to csv file
writer.writerow(['Programming language', 'Designed by', 'Appeared', 'Extension'])
writer.writerow(['Python', 'Guido van Rossum', '1991', '.py'])
writer.writerow(['Java', 'James Gosling', '1995', '.java'])
writer.writerow(['C++', 'BjarneStroustrup', '1985', '.cpp'])

Read CSV File using Pandas


Pandas is an opensource library that allows to you import CSV in Python and perform data
manipulation. Pandas provide an easy way to create, manipulate and delete the data.
You must install pandas library with command <code>pip install pandas</code>. In
Windows, you will execute this command in Command Prompt while in Linux in the
Terminal.
Reading the CSV into a pandas DataFrame is very quick and easy:
import pandas
result = pandas.read_csv('X:\data.csv')
print(result)
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
CHAPTER -11
DATA VISUALIZATION
USING
PYPLOT
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
CONCEPTS
DATA VISUALIZATION USING PYPLOT

• Matplotlib: Data Visualization Python for Data Visualization

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


11. DATA VISUALIZATION USING PYPLOT
Data Visualization using Matplotlib
Data Visualization is the process of presenting data in the form of graphs or charts. It helps to
understand large and complex amounts of data very easily.

Data visualization can be done with various tools like Tableau, Power BI, Python.

Matplotlib
Matplotlib is a low-level library of Python which is used for data visualization. It is easy to use
and emulates MATLAB like graphs and visualization.

To install Matplotlib type the below command in the terminal.

pip install matplotlib

Pyplot is a Matplotlib module that provides a MATLAB-like interface

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


11. DATA VISUALIZATION USING PYPLOT
import matplotlib.pyplot as plt
# initializing the data
x = [10, 20, 30, 40]
y = [20, 25, 35, 55]
# plotting the data
plt.plot(x, y)

plt.show()

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


CHAPTER -12
PYTHON
WITH
MYSQL
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
CONCEPTS
PYTHON WITH MYSQL
• Python MySql
• Installation
• Connecting to MySQL Server
• Creating Database
• Creating Tables
• Insert Data into Tables
• Fetching Data
• Where Clause, Order By Clause
• Update Data
• Delete Data from Table
• Drop Tables

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


12. PYTHON WITH MYSQL
What is MYSQL?
MySQL is a relational database management system (RDBMS) that adopts a client-
server model.

Python MySQL Connector


is a Python driver that helps to integrate Python and MySQL. This Python MySQL
library allows the conversion between Python and MySQL data types. MySQL
Connector API is implemented using pure Python and does not require any third-
party library.

Installation
To install the Python-mysql-connector module, one must have Python and PIP,
preinstalled on their system. If Python and pip are already installed type the below
command in the terminal.

pip3 install mysql-connector-python


© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
12. PYTHON WITH MYSQL
Connecting to MySQL Server
We can connect to the MySQL server using the connect() method.

# importing required libraries


import mysql.connector

dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password"
)

print(dataBase)

# Disconnecting from the server


dataBase.close()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
12. PYTHON WITH MYSQL
Creating Database
After connecting to the MySQL server. we will first create a cursor() object and will then pass
the SQL command as a string to the execute() method. The SQL command to create a
database is –

# importing required libraries


import mysql.connector

dataBase = mysql.connector.connect(host ="localhost",user ="user",passwd ="password")

# preparing a cursor object


cursorObject = dataBase.cursor()

# creating database
cursorObject.execute("CREATE DATABASE raj")

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


12. PYTHON WITH MYSQL
Creating MySQL database with Python
# importing required libraries
import mysql.connector

dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password"
)

# preparing a cursor object


cursorObject = dataBase.cursor()

# creating database
cursorObject.execute("CREATE DATABASE raj")

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


12. PYTHON WITH MYSQL
Creating Tables
we will follow the similar approach of writing the SQL commands as strings and then passing
it to the execute() method of the cursor object.

Creating MySQL table using Python


# importing required libraries
import mysql.connector

dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "raj"
)
# preparing a cursor object
cursorObject = dataBase.cursor()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
12. PYTHON WITH MYSQL
# creating table
studentRecord = """CREATE TABLE STUDENT (
NAME VARCHAR(20) NOT NULL,
BRANCH VARCHAR(50),
ROLL INT NOT NULL,
SECTION VARCHAR(5),
AGE INT
)"""

# table created
cursorObject.execute(studentRecord)

# disconnecting from server


dataBase.close()

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


12. PYTHON WITH MYSQL
Insert Data into Tables
To insert data into the MySQL table Insert into query is used.

# importing required libraries


import mysql.connector

dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "raj"
)

# preparing a cursor object


cursorObject = dataBase.cursor()

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


12. PYTHON WITH MYSQL

sql = "INSERT INTO STUDENT (NAME, BRANCH, ROLL, SECTION, AGE)\


VALUES (%s, %s, %s, %s, %s)"
val = ("Ram", "CSE", "85", "B", "19")

cursorObject.execute(sql, val)
dataBase.commit()

# disconnecting from server


dataBase.close()

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


12. PYTHON WITH MYSQL
Inserting Multiple Rows
To insert multiple values at once, executemany() method is used. This method iterates
through the sequence of parameters, passing the current parameter to the execute method.

sql = "INSERT INTO STUDENT (NAME, BRANCH, ROLL, SECTION, AGE)\


VALUES (%s, %s, %s, %s, %s)"
val = [("Nikhil", "CSE", "98", "A", "18"),
("Nisha", "CSE", "99", "A", "18"),
("Rohan", "MAE", "43", "B", "20"),
("Amit", "ECE", "24", "A", "21"),
("Anil", "MAE", "45", "B", "20"),
("Megha", "ECE", "55", "A", "22"),
("Sita", "CSE", "95", "A", "19")]

cursorObject.executemany(sql, val)
dataBase.commit()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
12. PYTHON WITH MYSQL
Fetching Data
We can use the select query on the MySQL tables in the following ways –

Select data from MySQL table using Python


# importing required libraries
import mysql.connector query = "SELECT NAME, ROLL FROM STUDENT"
cursorObject.execute(query)
dataBase = mysql.connector.connect(
host ="localhost", myresult = cursorObject.fetchall()
user ="user",
passwd ="password", for x in myresult:
database = "rss" print(x)
)
# disconnecting from server
# preparing a cursor object dataBase.close()
cursorObject = dataBase.cursor()
© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved
12. PYTHON WITH MYSQL
Where Clause
query = "SELECT * FROM STUDENT where AGE >=20"

Order By Clause
SELECT column1, column2
FROM table_name
ORDER BY column_name ASC|DESC;

query = "SELECT * FROM STUDENT ORDER BY NAME DESC“

Update Data
The update query is used to change the existing values in a database. By using
update a specific value can be corrected or updated.

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


12. PYTHON WITH MYSQL
Update MySQL table using Python

# importing required libraries query = "UPDATE STUDENT SET AGE = 23


import mysql.connector WHERE Name ='Ram'"
cursorObject.execute(query)
dataBase = mysql.connector.connect( dataBase.commit()
host ="localhost",
user ="user", # disconnecting from server
passwd ="password", dataBase.close()
database = "raj"
)

# preparing a cursor object


cursorObject = dataBase.cursor()

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


12. PYTHON WITH MYSQL
Delete Data from Table
We can use the Delete query to delete data from the table in MySQL.

Delete Data from MySQL table using Python

query = "DELETE FROM STUDENT WHERE NAME = 'Ram'"


cursorObject.execute(query)
dataBase.commit()

Drop Tables
Drop command affects the structure of the table and not data. It is used to delete an already
existing table.

DROP TABLE tablename;


DROP TABLE IF EXISTS tablename;

© copyright 2024, RAJ SOFTWARE SOLUTION, All Rights Reserved


Thank You

You might also like