PYTHON_PROGRAMMING
PYTHON_PROGRAMMING
125C1A
21
PYTHON PROGRAMMING
Unit – 1
4
PYTHON PROGRAMMING
PYTHON
Python was created in the late 1980s, and first released in 1991, by
Guido van Rossum.
5
PYTHON PROGRAMMING
INTERPRETER COMPILER
6
PYTHON PROGRAMMING
SYNTACTIC RULES FOR WRITING
PYTHON
number of solutions.
• Techniques
8
PYTHON PROGRAMMING
ALGORITHMS
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
Step 1: Start
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
15
PYTHON PROGRAMMING
STATE
16
PYTHON PROGRAMMING
NOTATIONS
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
19
PYTHON PROGRAMMING
20
PYTHON PROGRAMMING
FLOWCHARTS
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
No well-defined standards.
27
PYTHON PROGRAMMING
PROGRAMMING
LANGUAGES
• It is a set of symbols and rules for instructing a computer to
• The programmer must follow the rules to get the desired output.
system
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
1.Iteration
2.Recursion
33
PYTHON PROGRAMMING
Iteration
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
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
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
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
• 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:
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.
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:
Parameter values:
Parameter Description
stop Required. An integer number specifying at which position to stop (not included).
85
PYTHON PROGRAMMING
RANGE FUNCTION
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
9
PYTHON PROGRAMMING 1
FUNCTIONS
9
PYTHON PROGRAMMING 2
FUNCTIONS
Line reduction
Code reuse
Data hiding
Easy understanding
9
PYTHON PROGRAMMING 3
Main Function Sub function
94
PYTHON PROGRAMMING
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
99
PYTHON PROGRAMMING
SOFTWARE OBJECTS
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).
print(Audi.model)
print(Audi.price)
Output:
R8
100000
102
PYTHON PROGRAMMING
TURTLE PROGRAMMING IN PYTHON
103
PYTHON PROGRAMMING
TURTLE PROGRAMMING IN PYTHON
fillcolor() Color name Changes the color of the turtle will use to fill a polygon
end_fill() None Close the polygon and fill with the current fill color
105
PYTHON PROGRAMMING
MODULES IN PYTHON
106
PYTHON PROGRAMMING
MODULES IN PYTHON
To create a Python module, write the desired code and save that
107
PYTHON PROGRAMMING
MODULES IN PYTHON
IMPORTING MODULE:
print(calc.add(10, 2))
108
PYTHON PROGRAMMING
TEXT FILES IN PYTHON
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
are raised when some internal events occur which change the
113
PYTHON PROGRAMMING
EXCEPTION HANDLING IN PYTHON
111
PYTHON PROGRAMMING 6
Unit – V
117
PYTHON PROGRAMMING
A Story of Two Collections..
List
Dictionary
Dictionaries are like lists except that they use keys instead of
positions to look up values
Dictionary literals use curly braces and have key : value pairs
You can make an empty dictionary using empty curly braces
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.
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:
# parent class
class Person(object):
def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))
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()
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.
135
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
# Python program to
# demonstrate private members
# "__" double underscore represents private attribute.
# Private attributes start with "__".
# 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)
Data Abstraction
abstract classes.
137
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
PYTHON LIBRARIES:
138
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
broader SciPy stack and consists of several plots like line, bar,
library in Python.
139
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
# as y axis
plt.plot(x, y)
plt.title("Line Chart")
plt.legend(["Line"])
plt.show()
140
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
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
142
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
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
Features of NumPy
NumPy has various features which make them popular over lists.
144
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
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.
Data Preparation
scipy as sp.
148
PYTHON PROGRAMMING
OBJECT ORIENTED PROGRAMMING IN
PYTHON
# Example of a t-test
Regression Analysis
Utilize the linregress function for linear regression analysis.
# Linear regression
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
Optimization
Employ the optimization functions in SciPy to find optimal parameter values.
from scipy.optimize import minimize
def objective_function(x):
151
PYTHON PROGRAMMING