0% found this document useful (0 votes)
6 views

PYTHON_PROGRAMMING

Uploaded by

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

PYTHON_PROGRAMMING

Uploaded by

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

PYTHON PROGRAMMING

125C1A

Ms. M.K.Sree Swarnalatha,


Assistant Professor,
Department of Computer Science,
Shri Shankarlal Sundarbai Shasun
Jain College for Women.
11
PYTHON PROGRAMMING
UNIT: I

21
PYTHON PROGRAMMING
Unit – 1

Introduction: The essence of computational


problem solving – Limits of computational
problem solving-Computer algorithms-
Computer Hardware-Computer Software-The
process of computational problem solving-
Python programming language - Literals -
Variables and Identifiers - Operators -
Expressions and Data types, Input / output.
3
PYTHON PROGRAMMING
PROBLEM SOLVING

Input Process Output

4
PYTHON PROGRAMMING
PYTHON

Python is an interpreted, high-level, object-oriented programming


language.

Python was created in the late 1980s, and first released in 1991, by
Guido van Rossum.

Python 2.0, released in 2000, introduced new features and was


discontinued.

Later Python 3.0, released in 2008, was a major revision of the


language.

Python interpreters are available for many operating systems.

5
PYTHON PROGRAMMING
INTERPRETER COMPILER

Interpreter translates just one Compiler scans the entire


statement of the program at a program and translates the
time into machine code. whole of it into machine code
at once.

An interpreter does not A compiler always generates an


generate an intermediary code. intermediary object code. It
Hence, an interpreter is highly will need further linking. Hence
efficient in terms of its more memory is needed.
memory.

6
PYTHON PROGRAMMING
SYNTACTIC RULES FOR WRITING
PYTHON

• Python is case sensitive.


• In python, there is no command terminator, which means no
semicolon ; or anything.
• Code Indentation(tab): python doesn't use brackets. Python uses
indentation for defining a block of code.
• In one line only a single executable statement should be written. To
write two separate executable statements in a single line, you
should use a semicolon ; to separate the commands.
• In python, you can use single quotes ‘‘,double quotes “ " and even
triple quotes ''' """ to represent string literals.
• you can write comments in your program using a # at the start. A
comment is ignored while the python script is executed. 7
PYTHON PROGRAMMING
PROBLEM SOLVING

• It is a systematic approach to define the problem and creates a

number of solutions.

• Techniques

• It helps in providing logic for solving a problem.


Algorithms
Flowcharts
Pseudocodes
Programs

8
PYTHON PROGRAMMING
ALGORITHMS

• Algorithm is a step by step procedure.

• It defines a set of instructions to be executed in a certain order to

get the desired output.

• It is independent of programming languages i.e the algorithm can

be implemented in one or more programming languages.

9
PYTHON PROGRAMMING
10
PYTHON PROGRAMMING
11
PYTHON PROGRAMMING
CHARACTERISTICS OF AN
ALGORITHM
• Well-defined: The instructions in the algorithm should be simple
and well defined.
• Unambiguous: Algorithm should be clear and must lead to only
one meaning.
• Finiteness: Algorithm must terminate after a finite number of
steps.
• Input: The algorithm must receive an input.
• Output: After the algorithm gets terminated, the desired result
must be obtained.
• Independent: The algorithm can be applied to various set of
inputs.

12
PYTHON PROGRAMMING
EXAMPLE

Algorithm to add two numbers.

Step 1: Start

Step 2: Declare the variable a,b and c

Step 3: read values for a and b

Step 4: Add the values of a and b and store in c.

Step 5: Write c

Step 6: Stop

13
PYTHON PROGRAMMING
BUILDING BLOCKS
OF ALGORITHM
Any algorithm can be constructed using the following building
blocks.

• Statement / Instruction
• State / Selection
• Control Flow
• Function

14
PYTHON PROGRAMMING
STATEMENT

It describes the action and its sequence that the program carries.
The action can be

• Input data

• Process data

• Output processed data

15
PYTHON PROGRAMMING
STATE

It makes a transition or selection from one process to another under


a specified condition.
Eg:
If(a%2==0)
Print a is even
Or
Print a is odd

16
PYTHON PROGRAMMING
NOTATIONS

The algorithm can be represented using

Pseudo code

Flow chart

Programming languages

17
PYTHON PROGRAMMING
PSEUDOCODE
Pseudocode is a compact and informal high-level description of an algorithm
that uses the structural conventions of a programming language.
• It facilitates designers to focus on the logic of the
algorithm without getting bogged down by the
details of language syntax.
• It consist of short English phrases that explain
specific tasks within a program’s algorithm. They
should not include keywords in any specific
computer language.
• The sole purpose of pseudocodes is to enhance
human understandability of the solution.
18
PYTHON PROGRAMMING
Rules for Writing Psuedocode

1. Write only one stmt per line. Each stmt in


your pseudocode should express just one
action for the computer. ...
2. Capitalize initial keyword. In the example
above, READ and WRITE are in caps.
3. Indent to show hierarchy. ...
4. End multiline structures. ...
5. Keep statements language independent.

19
PYTHON PROGRAMMING
20
PYTHON PROGRAMMING
FLOWCHARTS

 A flowchart is a graphical or symbolic representation of a process.

 A flowchart is a diagrammatic representation that illustrates the sequence

of steps that must be performed to solve a problem.

 It is usually drawn in the early stages of formulating computer solutions.

 Each step in the process is depicted by a different symbol and is associated

with a short description.

21
PYTHON PROGRAMMING
22
PYTHON PROGRAMMING
23
PYTHON PROGRAMMING
24
PYTHON PROGRAMMING
25
PYTHON PROGRAMMING
26
PYTHON PROGRAMMING
Advantages

 Communication is easy

 Effective analysis

 Documentation

 Easy to backtrack

 Limitations

 Difficult to implement for large and complex programs

 Modifications may require redrawing of flowchart

 No well-defined standards.

27
PYTHON PROGRAMMING
PROGRAMMING
LANGUAGES
• It is a set of symbols and rules for instructing a computer to

perform specific tasks.

• The programmer must follow the rules to get the desired output.

• It is used to create programs that control the behavior of the

system

• Eg. C, C++, FORTRAN, Python

• Each language has unique syntax and semantics.

28
PYTHON PROGRAMMING
TYPES

• Machine language
• Low level or assembly level language
• High level language
Irrespective of the language that a programmer uses, a program written
using any programming language has to be converted into machine
language so that the computer can understand it.
This can be done using compiler or an interpreter.

29
PYTHON PROGRAMMING
Programming Languages
 Though high-level programming languages are easy for humans to read and
understand, the computer can understand only machine language, which
consists of only numbers.
 In between machine languages and high-level languages, there is another type
of language known as assembly language.
 irrespective of the language that a programmer uses, a program written using
any programming language has to be converted into machine language so that
the computer can understand it. There are two ways to do this: compile the
program or interpret the program.

30
PYTHON PROGRAMMING
Selecting a Particular Programming
Language
 The type of computer hardware and software on which the program is to
be executed.
 The type of program.
 The expertise and availability of the programmers.
 Features to write the application.
 The built-in features that support the development of software that are
reliable and less prone to crash.
 Lower development and maintenance costs. Stability and capability to
support even more than the expected simultaneous users.
 Elasticity of a language that implies the ease with which new features or
can be added to the existing program.
 Portability.
 Better speed of development that includes the time it takes to write a
code, time taken to find a solution to the problem at hand, time taken to
find the bugs, availability of development tools etc.

31
PYTHON PROGRAMMING
Algorithmic Problem Solving
- Sequence of steps to be followed for designing an effective algorithm

• Understanding the Problem


1

• Determining the Capabilities of Computational Device


2

• Exact / Approximate Solution


3

• Select the appropriate data structure


4

• Algorithm Design Techniques


5

• Methods of Specifying an Algorithm


6
32
PYTHON PROGRAMMING
Simple Strategies for
Developing an Algorithm

1.Iteration

2.Recursion

33
PYTHON PROGRAMMING
Iteration

Loops to repeat some part of code

1. Start
2. Set I=1, N=10
3. Repeat step 3 & 4 While I <=N
4. Print I for Loop
5. Set I = I+1 End of Loop
6. Stop
while Loop

do – while Loop

34
PYTHON PROGRAMMING
Recursion
It is a problem solving approach by which a function call itself
repeatedly until some specified condition has been satisfied.
It reduces unnecessary calling of function. Also written with less
number of codes.

Factorial(n) 4! = 4 * 3!
{ = 4*3*2!
if n==0 = 4*3*2*1!
return 1 = 4*3*2*1
else = 12
Print ( n * Factorial(n-1) )
}

35
PYTHON PROGRAMMING
36
PYTHON PROGRAMMING
Pseudo code
Main function:
BEGIN
GET n
Algorithm for factorial of n numbers CALL factorial(n)
using recursion: PRINT fact
Main function: BIN
Step1: Start Sub function factorial(n):
Step2: Get n
IF(n==1) THEN
Step3: call factorial(n)
fact=1
Step4: print fact
RETURN fact
Step5: Stop
ELSE
Sub function factorial(n):
Step1: if(n==1) then fact=1 return fact RETURN fact=n*factorial(n-1)
Step2:
else fact=n*factorial(n-1) and return
fact

37
PYTHON PROGRAMMING
38
PYTHON PROGRAMMING
PROPERTY RECURSION ITERATION

Definition Function calls itself. A set of instructions repeatedly


executed.
Application For functions. For loops.
Through base case, When the termination condition
Termination where there will be no for the Iterator ceases to be
function call. satisfied.
Used when code size Used when time complexity needs
Usage needs to be small, and to be balanced against an
time complexity is not an expanded code size.
issue.
Code Size Smaller code size Larger Code Size.
Very high (generally Relatively lower time complexity
Time exponential) time (generally polynomial-
Complexity complexity. logarithmic).

39
PYTHON PROGRAMMING
To Find greatest of three numbers

Algorithm
Step1: Start
Step2: Get A, B, C
Step3: if(A>B) goto Step4 else goto step5
Step4: If(A>C) print A else print C
Step5: If(B>C) print B else print C
Step6: Stop

Psuedocode
BEGIN
READ a, b, c
IF (a>b) THEN
IF(a>c) THEN
DISPLAY a is greater
ELSE
DISPLAY c is greater
END IF
ELSE
IF(b>c) THEN
DISPLAY b is greater
ELSE
DISPLAY c is greater
END IF
END IF
END 40
PYTHON PROGRAMMING
41
PYTHON PROGRAMMING
Flowchart
Algorithm
Step 1: Start
Step 2: Declare variable a,b,c,n,i
Step 3: Initialize variable a=1, b=1, i=2
Step 4: Read n from user
Step 5: Print a and b
Step 6: Repeat until i<n
6.1 c=a+b
6.2 print c
6.3 a=b, b=c
6.4 i=i+1
Stop 7: Stop

42
PYTHON PROGRAMMING
Find Minimum in a List

43
PYTHON PROGRAMMING
Find Minimum in a List

44
PYTHON PROGRAMMING
Insert a Card in a List of Sorted Cards

45
PYTHON PROGRAMMING
Insert a Card in a List of Sorted Cards

46
PYTHON PROGRAMMING
Guess an Integer Number in a Range

47
PYTHON PROGRAMMING
GUESS AN INTEGER NUMBER IN A
RANGE

Approaches
Linear search – Guess the number as 1,2,3,… guessed number.
Disadvantage: Compilation cost is high if the guessed number falls on the higher side.
Binary search – Guess by N/2 and the user tells the guessed value is > or <.
If < then eliminate N/2 to N
If > then eliminate 1 to N/2.

48
PYTHON PROGRAMMING
Guess an Integer Number in a Range

49
PYTHON PROGRAMMING
Guess an Integer Number in a Range

50
PYTHON PROGRAMMING
Guess an Integer Number in a Range

51
PYTHON PROGRAMMING
TOWER OF HANOI

Only one disk can be moved at a time


Only top disk can be removed
No large disk can be placed over a small disk.

52
PYTHON PROGRAMMING
DISK = 1

53
PYTHON PROGRAMMING
DISK = 2

54
PYTHON PROGRAMMING
DISK = 3

55
PYTHON PROGRAMMING
Tower of Hanoi

56
PYTHON PROGRAMMING
1. A-> C
2. A -> B
3. C -> B
4. A -> C
5. B -> A
6. B -> C
7. A ->C

58
PYTHON PROGRAMMING
Tower of Hanoi

59
PYTHON PROGRAMMING
Tower of Hanoi

60
PYTHON PROGRAMMING
INSERTION SORT

Insertion sort is a simple sorting algorithm that works similar to the


way you sort playing cards in your hands.
Select the first unsorted element.
Shift the other elements to the right to create the correct position and
shift the unsorted elements to the correct position.
Repeat until all the elements are sorted.

61
PYTHON PROGRAMMING
62
PYTHON PROGRAMMING
63
PYTHON PROGRAMMING
64
PYTHON PROGRAMMING
UNIT: II

1
65
PYTHON PROGRAMMING
Unit – II
Control Structures: Boolean Expressions - Selection
Control - If Statement - Indentation in Python- Multi-Way
Selection -- Iterative Control- While Statement- Infinite
loops- Definite vs. Indefinite Loops- Boolean Flag.
String, List and Dictionary, Manipulations Building
blocks of python programs, Understanding and using
ranges.

66
PYTHON PROGRAMMING
CONTROL FLOW

The order of execution is called control flow.


The control flow can be

• Sequence

• Selection and

• Iteration

67
PYTHON PROGRAMMING
68
PYTHON PROGRAMMING
69
PYTHON PROGRAMMING
If Statement

70
PYTHON PROGRAMMING
If – else - statement

71
PYTHON PROGRAMMING
Switch Statement

72
PYTHON PROGRAMMING
Iteration / Looping

for Loop

73
PYTHON PROGRAMMING
74
PYTHON PROGRAMMING
75
PYTHON PROGRAMMING
Sequence: Instructions are executed one after another. Eg. Addition
of two numbers.

76
PYTHON PROGRAMMING
Selection: Control will be transferred to a part of a program based
on the condition. The other part will not be executed or it remains
untouched. Eg. Odd or Even.

77
PYTHON PROGRAMMING
Iteration: It allows set of instructions to get executed repeatedly
based on condition more than once.

78
PYTHON PROGRAMMING
STRING
Strings:

A string is a sequence of characters enclosed in matching pain of

single or double quotation marks. A string may contain zero or more

characters, including letters, digits, special characters, and blanks. A

string consisting of only a pair of matching quotes (with nothing in

between) is called the empty string


Examples:
'Hello' 'Smith, John' "Baltimore, Maryland 21210"

79
PYTHON PROGRAMMING
OPERATIONS ON STRING

i. Indexing

ii. Slicing

iii. Concatenation

iv. Repetitions

v. Membership

80
PYTHON PROGRAMMING
OPERATIONS ON STRING

Creating a string >>> s="good morning" Creating the list with elements of
different data types.
Indexing >>>print(s[2])  Accessing the item in the
o position0
>>>print(s[6])  Accessing the item in the
O position2
Slicing( ending >>>print(s[2:]) - Displaying items from 2nd till
position-1) od morning last.
Slice operator is >>>print(s[:4]) - Displaying items from
used to extract Good 1stposition till 3rd.
part of a data
type
Concatenation >>>print(s+"friends") -Adding and printing the
good morning friends characters of two strings.

Repetition >>>print(s*2) Creates new strings,


good morninggood concatenating multiple copies of
morning the samestring
in, not in >>> s="good morning" Using membership operators to
(membership >>>"m" in s check a particular character is in
operator) True string or not. Returns true if
>>> "a" not in s present.
True

8
PYTHON PROGRAMMING 1
8
PYTHON PROGRAMMING 2
8
PYTHON PROGRAMMING 3
BUILDING BLOCKS OF PYTHON
PROGRAMMING

8
PYTHON PROGRAMMING 4
RANGE FUNCTION
The range() function returns a sequence of numbers, starting from 0 by

default, and increments by 1 (by default), and stops before a specified number.

Syntax:

range(start, stop, step)

Parameter values:
Parameter Description

start Optional. An integer number specifying at which position to start. Default is 0

stop Required. An integer number specifying at which position to stop (not included).

step Optional. An integer number specifying the incrementation. Default is 1

85
PYTHON PROGRAMMING
RANGE FUNCTION

When the user call range() with one


argument, the user will get a series of
numbers that starts at 0 and includes every
whole number up to, but not including, the
number that the user has provided as the
stop.

86
PYTHON PROGRAMMING
RANGE FUNCTION
When the user call range() with two
arguments, the user gets to decide not only
where the series of numbers stops but also
where it starts, so the user doesn’t have to
start at 0 all the time. Users can use range()
to generate a series of numbers from X to Y
using range(X,Y).

87
PYTHON PROGRAMMING
RANGE FUNCTION
When the user call range() with three arguments, the
user can choose not only where the series of numbers will
start and stop, but also how big the difference will be
between one number and the next. If the user doesn’t
provide a step, then range() will automatically behave as
if the step is 1. In this example, we are printing even
numbers between 0 and 10, so we choose our starting
point from 0(start = 0) and stop the series at 10(stop =
10). For printing an even number the difference between
one number and the next must be 2 (step = 2) after
providing a step we get the following output (0, 2, 4, 8).

88
PYTHON PROGRAMMING
RANGE FUNCTION

89
PYTHON PROGRAMMING
UNIT: III

1
90
PYTHON PROGRAMMING
Unit – III

Functions: Program Routines- Defining


Functions- More on Functions: Calling Value-
Returning Functions- Calling Non-Value-
Returning Functions- Parameter Passing -
Keyword Arguments in Python - Default
Arguments in Python-Variable Scope.
Recursion: Recursive Functions.

9
PYTHON PROGRAMMING 1
FUNCTIONS

Python Functions is a block of statements that return


the specific task. The idea is to put some commonly or
repeatedly done tasks together and make a function so
that instead of writing the same code again and again
for different inputs, we can do the function calls to
reuse code contained in it over and over again.
Some Benefits of Using Functions
•Increase Code Readability
•Increase Code Reusability

9
PYTHON PROGRAMMING 2
FUNCTIONS

It allows a large task to divide into smaller blocks.


Function is a sub program that consists of block of code.
Advantages

 Line reduction
 Code reuse
 Data hiding
 Easy understanding

9
PYTHON PROGRAMMING 3
Main Function Sub function

Start Read a,b & c


Call add() Add a and b and store in c
Stop Print c
Return

94
PYTHON PROGRAMMING
FUNCTIONS

Types of Functions in Python


Below are the different types of functions in Python:
•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.
9
PYTHON PROGRAMMING 5
FUNCTIONS

Output:
Output of our functions is: 5

9
PYTHON PROGRAMMING 6
BUILT-IN STRING FUNCTIONS

9
PYTHON PROGRAMMING 7
UNIT: IV

1
98
PYTHON PROGRAMMING
Unit – IV

Objects and their use: Software Objects - Turtle


Graphics – Turtle attributes-Modular Design:
Modules - Top-Down Design - Python Modules -
Text Files: Opening, reading and writing text
files – Exception Handling.

99
PYTHON PROGRAMMING
SOFTWARE OBJECTS

An Object is an instance of a Class. A class is like a


blueprint while an instance is a copy of the class with
actual values. Python is an object-oriented
programming language that stresses objects i.e. it
mainly emphasizes functions. Python Objects are
basically an encapsulation of data variables and
methods acting on that data into a single entity.

100
PYTHON PROGRAMMING
Creating a Python Object
Working of the Program: Audi = Cars()
•A block of memory is allocated on the heap. The size
of memory allocated is decided by the attributes and
methods available in that class(Cars).

•After the memory block is allocated, the special


method __init__() is called internally. Initial data is
stored in the variables through this method.

•The location of the allocated memory address of the


instance is returned to the object(Cars).

•The memory location is passed to self.


101
PYTHON PROGRAMMING
Creating a Python Object
class Cars:
def __init__(self, m, p):
self.model = m
self.price = p

Audi = Cars("R8", 100000)

print(Audi.model)
print(Audi.price)

Output:
R8
100000

102
PYTHON PROGRAMMING
TURTLE PROGRAMMING IN PYTHON

“Turtle” is a Python feature like a drawing board, which lets us


command a turtle to draw all over it! We can use functions like
turtle.forward(…) and turtle.right(…) which can move the turtle
around.

103
PYTHON PROGRAMMING
TURTLE PROGRAMMING IN PYTHON

Method Parameter Description

Turtle() None Creates and returns a new turtle object

forward() amount Moves the turtle forward by the specified amount

backward() amount Moves the turtle backward by the specified amount

right() angle Turns the turtle clockwise

left() angle Turns the turtle counterclockwise

penup() None Picks up the turtle’s Pen

pendown() None Puts down the turtle’s Pen

up() None Picks up the turtle’s Pen

down() None Puts down the turtle’s Pen

color() Color name Changes the color of the turtle’s pen

fillcolor() Color name Changes the color of the turtle will use to fill a polygon

heading() None Returns the current heading

position() None Returns the current position

goto() x, y Move the turtle to position x,y

begin_fill() None Remember the starting point for a filled polygon

end_fill() None Close the polygon and fill with the current fill color

dot() None Leave the dot at the current position

stamp() None Leaves an impression of a turtle shape at the current location

shape() shapename Should be ‘arrow’, ‘classic’, ‘turtle’ or ‘circle’


104
PYTHON PROGRAMMING
TURTLE PROGRAMMING IN PYTHON

105
PYTHON PROGRAMMING
MODULES IN PYTHON

106
PYTHON PROGRAMMING
MODULES IN PYTHON

What is Python Module

A Python module is a file containing Python definitions and

statements. A module can define functions, classes, and

variables. A module can also include runnable code.

Grouping related code into a module makes the code easier to

understand and use. It also makes the code logically organized.

Create a Python Module

To create a Python module, write the desired code and save that

in a file with .py extension.

107
PYTHON PROGRAMMING
MODULES IN PYTHON

# A simple module, calc.py


def add(x, y):
return (x+y)

def subtract(x, y):


return (x-y)

IMPORTING MODULE:

# importing module calc.py


import calc

print(calc.add(10, 2))

108
PYTHON PROGRAMMING
TEXT FILES IN PYTHON

Python provides built-in functions for creating, writing, and


reading files. Two types of files can be handled in Python,
normal text files and binary files (written in binary language,
0s, and 1s).
•Text files: In this type of file, Each line of text is terminated
with a special character called EOL (End of Line), which is
the new line character (‘\n’) in Python by default.
•Binary files: In this type of file, there is no terminator for a
line, and the data is stored after converting it into machine-
understandable binary language.

109
PYTHON PROGRAMMING
TEXT FILES IN PYTHON
File Access Modes
Access modes govern the type of operations possible in the opened
file. It refers to how the file will be used once its opened. These modes
also define the location of the File Handle in the file. The file handle
is like a cursor, which defines from where the data has to be read or
written in the file and we can get Python output in text file.
There are 6 access modes in Python:
•Read Only (‘r’)
•Read and Write (‘r+’)
•Write Only (‘w’)
•Write and Read (‘w+’)
•Append Only (‘a’)
•Append and Read (‘a+’)
110
PYTHON PROGRAMMING
TEXT FILES IN PYTHON
Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning
of the file. If the file does not exist, raises the I/O error. This is also the default mode in
which a file is opened.
Read and Write (‘r+’): Open the file for reading and writing. The handle is positioned
at the beginning of the file. Raises I/O error if the file does not exist.
Write Only (‘w’) : Open the file for writing. For the existing files, the data is truncated
and over-written. The handle is positioned at the beginning of the file. Creates the file if
the file does not exist.
Write and Read (‘w+’) : Open the file for reading and writing. For an existing file,
data is truncated and over-written. The handle is positioned at the beginning of the file.
Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The
handle is positioned at the end of the file. The data being written will be inserted at the
end, after the existing data.
Append and Read (‘a+’) : Open the file for reading and writing. The file is created if
it does not exist. The handle is positioned at the end of the file. The data being written
will be inserted at the end, after the existing data.
111
PYTHON PROGRAMMING
TEXT FILES IN PYTHON

112
PYTHON PROGRAMMING
EXCEPTION HANDLING IN PYTHON

Error in Python can be of two types i.e. Syntax errors and

Exceptions. Errors are problems in a program due to which the

program will stop the execution. On the other hand, exceptions

are raised when some internal events occur which change the

normal flow of the program.

Different types of exceptions in python:

In Python, there are several built-in Python exceptions that can be

raised when an error occurs during the execution of a program.

113
PYTHON PROGRAMMING
EXCEPTION HANDLING IN PYTHON

•SyntaxError: This exception is raised when the interpreter


encounters a syntax error in the code, such as a misspelled
keyword, a missing colon, or an unbalanced parenthesis.
•TypeError: This exception is raised when an operation or
function is applied to an object of the wrong type, such as
adding a string to an integer.
•NameError: This exception is raised when a variable or
function name is not found in the current scope.
•IndexError: This exception is raised when an index is out of
range for a list, tuple, or other sequence types.
•KeyError: This exception is raised when a key is not found in a
dictionary.
114
PYTHON PROGRAMMING
EXCEPTION HANDLING IN PYTHON

•ValueError: This exception is raised when a function or method is


called with an invalid argument or input, such as trying to convert a
string to an integer when the string does not represent a valid
integer.
•AttributeError: This exception is raised when an attribute or
method is not found on an object, such as trying to access a non-
existent attribute of a class instance.
•IOError: This exception is raised when an I/O operation, such as
reading or writing a file, fails due to an input/output error.
•ZeroDivisionError: This exception is raised when an attempt is
made to divide a number by zero.
•ImportError: This exception is raised when an import statement
fails to find or load a module. 115
PYTHON PROGRAMMING
UNIT: V

111
PYTHON PROGRAMMING 6
Unit – V

Dictionaries and Sets: Dictionary type in Python


- Set Data type. Object Oriented Programming
using Python: Encapsulation - Inheritance –
Polymorphism. Python packages: Simple
programs using the built-in functions of
packages matplotlib, NumPy, pandas etc.

117
PYTHON PROGRAMMING
A Story of Two Collections..
List

A linear collection of values


Lookup by position 0 .. length-1

Dictionary

A linear collection of key-value pairs


Lookup by "tag" or "key"
Dictionaries
• Dictionaries are Python’s most powerful data collection

• Dictionaries allow us to do fast database-like operations in Python

• Similar concepts in different programming languages

- Associative Arrays - Perl / PHP

- Properties or Map or HashMap - Java

- Property Bag - C# / .Net


Dictionaries over
time in Python
Prior to Python 3.7 dictionaries did not
keep entries in the order of insertion
Python 3.7 (2018) and later dictionaries
keep entries in the order they were
inserted
"insertion order" is not "always sorted
order"
Below the
Abstraction
Python lists, dictionaries, and tuples are "abstract
objects" designed to be easy to use.

Creating the code to support them is tricky and uses


Computer Science concepts like dynamic memory,
arrays, linked lists, hash maps and trees.
Lists

We append values to the >>> cards = list()


>>> cards.append(12)
end of a List and look them >>> cards.append(3)
up by position >>> cards.append(75)
>>> print(cards)
[12, 3, 75]
We insert values into a >>> print(cards[1])
3
Dictionary using a key and >>> cards[1] = cards[1] + 2
retrieve them using a key >>> print(cards)
[12, 5, 75]
Dictionaries

We append values to the >>> cabinet = dict()


>>> cabinet['summer'] = 12
end of a List and look them >>> cabinet['fall'] = 3
up by position >>> cabinet['spring'] = 75
>>> print(cabinet)
{'summer': 12, fall': 3, spring': 75}
We insert values into a >>> print(cabinet['fall'])
3
Dictionary using a key and >>> cabinet['fall'] = cabinet['fall'] + 2
retrieve them using a key >>> print(cabinet)
{'summer': 12, 'fall': 5, 'spring': 75}
Comparing Lists
and Dictionaries

Dictionaries are like lists except that they use keys instead of
positions to look up values

>>> lst = list() >>> ddd = dict()


>>> lst.append(21) >>> ddd['age'] = 21
>>> lst.append(183) >>> ddd['course'] = 182
>>> print(lst) >>> print(ddd)
[21, 183] {'age': 21, 'course': 182}
>>> lst[0] = 23 >>> ddd['age'] = 23
>>> print(lst) >>> print(ddd)
[23, 183] {'age': 23, 'course': 182}
Dictionary Literals
(Constants)

Dictionary literals use curly braces and have key : value pairs
You can make an empty dictionary using empty curly braces

>>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}


>>> print(jjj)
{'chuck': 1, 'fred': 42, 'jan': 100}
>>> ooo = { }
>>> print(ooo)
{}
>>>
The get Method
for Dictionaries
The pattern of checking to see if a
key is already in a dictionary and
if name in counts:
assuming a default value if the x = counts[name]
key is not there is so common else :
x = 0
that there is a method called get()
that does this for us.
x = counts.get(name, 0)

Default value if key does not exist


(and no Traceback). {'csev': 2, 'cwen': 2 , 'zqian': 1}
OBJECT ORIENTED PROGRAMMING IN
PYTHON

127
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON

Python Class
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.
•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
# Python3 program to
# demonstrate defining
# a class

class Dog:
pass

128
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
Python Objects
In object oriented programming Python, 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. More specifically, any single integer
or any single string is an object. The number 12 is an object, the
string “Hello, world” is an object, a list is an object that can hold
other objects, and so on. You’ve been using objects all along and
may not even realize it.

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.
129
PYTHON PROGRAMMING
Rodger is a mammal Tommy is also a mammal My name is Rodger My name is Tommy

OBJECT ORIENTED PROGRAMMING IN


PYTHON
The Python __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 you want to do with your object. Now let us

define a class and create some objects using the self and __init__ method.

class Dog:

# class attribute
attr1 = "mammal"
OUTPUT:

# Instance attribute Rodger is a mammal


def __init__(self, name):
self.name = name Tommy is also a mammal
My name is Rodger
# Driver code
# Object instantiation My name is Tommy
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")

# Accessing class attributes


print("Rodger is a {}".format(Rodger.__class__.attr1))
print("Tommy is also a {}".format(Tommy.__class__.attr1))

# Accessing instance attributes


print("My name is {}".format(Rodger.name))
print("My name is {}".format(Tommy.name))
130
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
Python Inheritance
In Python object oriented Programming, Inheritance is the capability of
one class to derive or inherit the properties from another class. The
class that derives properties is called the derived class or child class
and the class from which the properties are being derived is called the
base class or parent class. The 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.
131
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
Types of Inheritance

 Single Inheritance: Single-level inheritance enables a derived


class to inherit characteristics from a single-parent class.
 Multilevel Inheritance: Multi-level inheritance enables a
derived class to inherit properties from an immediate parent
class which in turn inherits properties from his parent class.
 Hierarchical Inheritance: Hierarchical-level inheritance
enables more than one derived class to inherit properties from a
parent class.
 Multiple Inheritance: Multiple-level inheritance enables one
derived class to inherit properties from more than one base
class.
132
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
# Python code to demonstrate how parent constructors
# are called.

# parent class
class Person(object):

# __init__ is known as the constructor


def __init__(self, name, idnumber):
self.name = name
self.idnumber = idnumber

def display(self): Output


print(self.name)
print(self.idnumber) Rahul
def details(self): 886012
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber)) My name is Rahul
# child class IdNumber: 886012
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
Post: Intern
self.post = post

# invoking the __init__ of the parent class


Person.__init__(self, name, idnumber)

def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))

# creation of an object variable or an instance


a = Employee('Rahul', 886012, 200000, "Intern")

# calling a function of the class Person using


# its instance
a.display()
a.details()
133
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
Python Polymorphism
class Bird:
In object oriented Programming Python,
def intro(self):
print("There are many types of birds.")
Polymorphism simply means having many forms.
def flight(self):
For example, we need to determine if the given print("Most of the birds can fly but some
cannot.")
species of birds fly or not, using polymorphism we
class sparrow(Bird):
can do this using a single function.
def flight(self):
Output print("Sparrows can fly.")

There are many types of birds. class ostrich(Bird):

Most of the birds can fly but some cannot. def flight(self):
print("Ostriches cannot fly.")
There are many types of birds.
Sparrows can fly. obj_bird = Bird()
obj_spr = sparrow()
There are many types of birds. obj_ost = ostrich()

Ostriches cannot fly. obj_bird.intro()


obj_bird.flight()

obj_spr.intro()
obj_spr.flight()

obj_ost.intro()
obj_ost.flight()

134
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
Python Encapsulation
In Python object oriented programming, Encapsulation is one of the
fundamental concepts in object-oriented programming (OOP). It
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.
To prevent accidental change, an object’s variable can only be
changed by an object’s method. Those types of variables are known as
private variables.

A class is an example of encapsulation as it encapsulates all the data


that is member functions, variables, etc.

135
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
# Python program to
# demonstrate private members
# "__" double underscore represents private attribute.
# Private attributes start with "__".

# Creating a Base class


class Base:
ENCAPSULATION def __init__(self):
self.a = "GeeksforGeeks"
self.__c = "GeeksforGeeks"

# Creating a derived class


class Derived(Base):
def __init__(self):

# Calling constructor of
# Base class
Base.__init__(self)
Output print("Calling private member of base class: ")
print(self.__c)
GeeksforGeeks
# Driver code
obj1 = Base()
print(obj1.a)

# Uncommenting print(obj1.c) will


# raise an AttributeError

# Uncommenting obj2 = Derived() will


# also raise an AtrributeError as
# private member of base class
# is called inside derived class
136
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON

Data Abstraction

 It hides unnecessary code details from the user. Also, when

we do not want to give out sensitive parts of our code

implementation and this is where data abstraction came.

 Data Abstraction in Python can be achieved by creating

abstract classes.

137
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
PYTHON LIBRARIES:

138
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON

Matplotlib is easy to use and an amazing visualizing library in

Python. It is built on NumPy arrays and designed to work with the

broader SciPy stack and consists of several plots like line, bar,

scatter, histogram, etc.

Creating Different Types of Plot

In data visualization, creating various types of plots is essential for

effectively conveying insights from data. Below, we’ll explore how to

create different types of plots using Matplotlib, a powerful plotting

library in Python.
139
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON

import matplotlib.pyplot as plt


Line Graph in Matplotlib

# data to display on plots Line graphs are commonly used to visualize


x = [3, 1, 3] trends over time or relationships between
y = [3, 2, 1] variables. We’ll learn how to create visually
appealing line graphs to represent such data.
# This will plot a simple line chart

# with elements of x as x axis and y

# as y axis

plt.plot(x, y)

plt.title("Line Chart")

# Adding the legends

plt.legend(["Line"])

plt.show()
140
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON

Stem Plot in Matplotlib


A stem plot, also known as a stem-and-leaf plot, is a type of plot used to display data
along a number line. Stem plots are particularly useful for visualizing discrete data
sets, where the values are represented as “stems” extending from a baseline, with
data points indicated as “leaves” along the stems. let’s understand the components
of a typical stem plot:

Stems: The stems represent the main values of the data and are typically drawn
vertically along the y-axis.
Leaves: The leaves correspond to the individual data points and are plotted
horizontally along the stems.
Baseline: The baseline serves as the reference line along which the stems are drawn.
141
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
# importing libraries
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0.1, 2 * np.pi, 41)


y = np.exp(np.sin(x))

plt.stem(x, y, use_line_collection = True)


plt.show()

142
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON

Bar chart in Matplotlib import matplotlib.pyplot as plt


# data to display on plots
x = [3, 1, 3, 12, 2, 4, 4]
A bar plot or bar chart is a graph that y = [3, 2, 1, 4, 5, 6, 7]

represents the category of data with # This will plot a simple bar chart
plt.bar(x, y)
rectangular bars with lengths and
# Title to the plot
plt.title("Bar Chart")
heights that is proportional to the
# Adding the legends
values which they represent. The bar plt.legend(["bar"])
plt.show()
plots can be plotted horizontally or
vertically. A bar chart describes the
comparisons between the discrete
categories. It can be created using the
bar() method.

143
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
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.

Features of NumPy
NumPy has various features which make them popular over lists.

Some of these important features include:

• A powerful N-dimensional array object


• Sophisticated (broadcasting) functions
• Tools for integrating C/C++ and Fortran code
• Useful linear algebra, Fourier transform, and random number capabilities

144
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON

• Arrays in NumPy import numpy as np

• NumPy’s main object is the # Creating array object


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

# Printing type of arr object


print("Array is of type: ", type(arr))
• It is a table of elements (usually
# Printing array dimensions (axes)
numbers), all of the same type, print("No. of dimensions: ", arr.ndim)
indexed by a tuple of positive integers. # Printing shape of array
• In NumPy, dimensions are called axes. print("Shape of array: ", arr.shape)

The number of axes is rank. # Printing size (total number of elements) of array
print("Size of array: ", arr.size)
• NumPy’s array class is called ndarray. It
# Printing type of elements in array
is also known by the alias array. print("Array stores elements of type: ", arr.dtype)

145
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
Scipy is a Python library useful for solving many mathematical equations and
algorithms. It is designed on the top of Numpy library that gives more extension of
finding scientific mathematical formulae like Matrix Rank, Inverse, polynomial
equations, LU Decomposition, etc. Using its high-level functions will significantly
reduce the complexity of the code and helps better in analyzing the data.

SciPy is an interactive Python session used as a data-processing


library that is made to compete with its rivalries such as MATLAB,
Octave, R-Lab, etc. It has many user-friendly, efficient, and easy-to-
use functions that help to solve problems like numerical integration,
interpolation, optimization, linear algebra, and statistics. The benefit
of using the SciPy library in Python while making ML models is that it
makes a strong programming language available for developing
fewer complex programs and applications. 146
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON

How does Data Analysis work with SciPy?

Data Preparation

•Import the necessary libraries: import numpy as np and import

scipy as sp.

•Load or generate your dataset using NumPy or pandas.

Exploratory Data Analysis (EDA)

•Use descriptive statistics from SciPy’s stats module to gain insights

into the dataset.

•Calculate measures such as mean, median, standard deviation,


147
skewness,
PYTHON kurtosis, etc.
PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON

from scipy import stats


data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
# Calculate mean and standard deviation
mean_val = np.mean(data) Output:
std_dev = np.std(data)
t_stat: 0.0
# Perform basic statistical tests p_value: 1.0
t_stat, p_value = stats.ttest_1samp(data,
popmean=5)
print("t_stat:" , t_stat)
print("p_value:", p_value)

148
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON

Statistical Hypothesis Testing


Use SciPy’s stats module for various hypothesis tests such as t-tests, chi-square
tests, ANOVA, etc.

# Example of a t-test

t_stat, p_value = stats.ttest_ind(group1, group2)

Regression Analysis
Utilize the linregress function for linear regression analysis.

# Linear regression

slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)

149
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
Signal and Image Processing
Use the scipy.signal module for signal processing operations.
Explore scipy.ndimage for image processing.
from scipy import signal, ndimage
# Example of convolution using signal processing

result = signal.convolve2d(image, kernel, mode=’same’, boundary=’wrap’)

Optimization
Employ the optimization functions in SciPy to find optimal parameter values.
from scipy.optimize import minimize

# Define an objective function

def objective_function(x):

return x[0]**2 + x[1]**2

result = minimize(objective_function, [0, 0])


150
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON

Compute pivoted LU decomposition P, L, U = linalg.lu(A)


of a Matrix print(P)
LU decomposition is a method that print(L)
reduce matrix into constituent parts print(U)
that helps in easier calculation of # print LU decomposition
complex matrix operations. The print(np.dot(L,U))
decomposition methods are also
called matrix factorization methods, Output:
are base of linear algebra in [[0. 1. 0.]
computers, even for basic operations [0. 0. 1.]
such as solving systems of linear [1. 0. 0.]]
[[1. 0. 0. ]
equations, calculating the inverse, and [0.14285714 1. 0. ]
calculating the determinant of a [0.57142857 0.5 1. ]]
matrix. The decomposition is: A = P L [[7. 8. 8. ]
U where P is a permutation matrix, L [0. 0.85714286 1.85714286]
[0. 0. 0.5 ]]
lower triangular with unit diagonal [[0.14285714 1. 0. ]
elements, and U upper triangular. [0.57142857 0.5 1. ]
[1. 0. 0. ]]

151
PYTHON PROGRAMMING

You might also like