Professional Documents
Culture Documents
PPC unit-II
PPC unit-II
concepts
Subject Code: 8FC22
B. Tech-ECE
II Year II Semester
Dr G. Prasad Acharya,
Associate Professor & Associate HoD, ECE Dept,
Sreenidhi Institute of Science and Technology, Hyderabad.
Course Objectives:-
Use Python interactively, execute a Python script at the shell
prompt, use Python types, expressions, and None, use string
literals and string type, use Python statements (if...elif..else,
for, pass, continue, . . . ), understand the difference between
expressions and statements, understand assignment semantics,
write and call a simple function., utilize high-level data types
such as lists and dictionaries, understand the difference
between mutable and immutable types, write a simple class and
access methods and attributes, import and utilize a module,
read from and write to a text file.
Learn the basic concepts and the ability to understand
and design algorithms using greedy strategy, divide and
conquer approach and dynamic programming.
Course Outcomes:-
CO1: Gains exposure towards Python versions and their specifications and
build programs
using primitive data types.
CO2: Write applications that include functions, modules, packages along
with respective exceptional handling mechanism.
CO3: Writes applications using features of Python and applications using
Files.
CO4: Hands on exposure on NumPy/Tkinter/Plotpy modules
CO5: Analyze worst-case running times of algorithms using asymptotic
analysis. Describe the divide-and-conquer paradigm and explain when an
algorithmic design situation calls for it. Recite algorithms that employ this
paradigm. Synthesize divide and-conquer algorithms.
CO6: Describe the dynamic-programming paradigm and the greedy paradigm
and explain when an algorithmic design situation calls for it. Synthesize
dynamic programming and greedy algorithms and analyze them.
Detailed syllabus:-
UNIT I: Introduction to Python:
History, Features, Modes of Execution, Setting up path, working with Python Basic
Syntax, Variable and Data Types, Operators. Conditional Statements (If, If- else, Nested
if-else) Looping (for, While Nested loops) Control Statements (Break, Continue, Pass).
Functions: Defining a function, calling a function, Types of functions, Function
Arguments
UNIT II: String Manipulation:
Accessing Strings, Basic Operations, String slices, Lists: Accessing list, Operations,
Tuple: Accessing tuples, Operations, Dictionaries: Accessing values in dictionaries,
Modules: Importing module, Math module, Random module, Packages Exception
Handling:Exception, Exception Handling, Except clause, Try? Finally clause User
Defined Exceptions
UNIT III: Python- OOPs concept:
Class and object, Attributes, Inheritance, Overloading Overriding, Data hiding, Regular
expressions: Match function, Search function, Matching VS Searching, Modifiers
Patterns.
UNIT IV: Case Study with NumPy/PlotPy/SciPy/GUI Programming, Introduction,
Tkinter programming, Tkinter widgets
Detailed syllabus:-
UNIT V:
Introduction: Algorithm, Performance Analysis-Space complexity, Time complexity,
Asymptotic Notation- Big oh notation, Omega notation, Theta notations, Divide and
conquer: General method, applications-Binary search, Merge sort, Applications:
Implementing Algorithms ,performance analysis and sorting techniques using Python
UNIT VI:
Greedy method: General method, applications- 0/1 knapsack problem, Minimum cost
spanning trees. Dynamic Programming: General method, applications- Travelling sales
person problem, Reliability design. Applications: Implementing some Greedy method and
Dynamic programming techniques using Python
Text books:
1. Think Python: How to Think Like a Computer Scientist Allen B. Downey, O'Relly
publications.
2. Learning with Python by Jeffrey Elkner, Chris Meyers Allen Downey, Dreamtech Press.
3. Fundamentals of Computer Algorithms, Ellis Horowitz,Satraj Sahni and
Rajasekharam,Galgotia publications pvt. Ltd.
Unit-II
o String Manipulation: Accessing Strings, Basic Operations, String slices,
o Lists: Accessing list, Operations,
o Tuple: Accessing tuples, Operations,
o Dictionaries: Accessing values in dictionaries,
o Modules: Importing module, Math module, Random module, Packages
o Exception Handling:Exception, Exception Handling, Except clause, Try?
Finally clause User Defined Exceptions
String
Strings in python are surrounded by either single
quotation marks, or double quotation marks.
'hello' is the same as "hello“
print() function is used to display a string
Example
print("Hello")
A multiline string to a variable by using three quotes:
a=‘’’hello!
how
are Python does not have a character data type, a single
you’’’ character is simply a string with a length of 1.
print(a)
Strings are Arrays
Square brackets can be used to access elements of
the string
a="Hello, World!"
print(a[1]) -- e
From Python's perspective, lists are defined as objects with the data type 'list‘ and
the same can be obtained using type() function.
o mylist = [‘apple’, ’banana’, ’cherry’]
print(type(mylist))
Accessing Elements in a List
You can access individual elements in a list using indexing.
Python uses zero-based indexing, which means the first element
is at position 0, the second element is at position 1, and so on.
To access the nth element in a list, use the indexing operator []
with the index n-1.
For example:
o my_list = [1, 2, 3, "apple", "orange"]
print(my_list[0]) # Output: 1
print(my_list[3]) # Output: apple
Basic Operations
Python provides several basic operations that can be performed on lists.
These include concatenation (+), repetition (*), and membership testing (in).
For example:
o list1 = [1, 2, 3]
list2 = ["apple", "orange"]
list3 = list1 + list2 Concatenation
print(list3) # Output: [1, 2, 3, ‘apple’, ‘orange’]
You can also use negative indexing to slice a list from the end. For example:
o my_list = [1, 2, 3, "apple", "orange"]
print(my_list[-2:]) # Output: [‘apple’, ‘orange’]
You can specify a step value in the slicing operator to select
alternate elements. The syntax for step value is [start:end:step].
For example:
o my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(my_list[::2]) # Output: [0, 2, 4, 6, 8]
Modifying Lists
In Python, lists are mutable, which means you can modify them
directly.
You can modify the elements in a list by accessing them using
indexing or slicing, and then assigning new values.
For example:
o my_list = [1, 2, 3, "apple", "orange"]
my_list[3] = "banana"
print(my_list) # [1, 2, 3, ‘banana’, ‘orange’]
Loops for Lists
for loop
a = ["apple","banana","cherry"]
for x in a:
print(x, end=' ')
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
insert() Adds an element at the specified position
extend() Add the elements of a list (or any iterable), to the end of the
current list
remove() Removes the item with the specified value
pop() Removes the element at the specified position
index() Returns the index of the first element with the specified value
count() Returns the number of elements with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
To append an item to the end of the list, use
the append() method.
o a = ["apple", "banana", "cherry"]
a.append("orange")
print(a)
clear() - Removes all the elements from the list
o a = ['a', 'b', 'c', 'd', 'e', 'f']
a.clear()
print(a)
copy() - Returns a copy of the list
o list1 = ['a', 'b', 'c', 'd', 'e', 'f']
o list2=list1.copy()
o print(list2)
insert() method inserts an item at the specified index
o a = ["apple", "banana", "cherry"]
a.insert(1, "orange")
print(a)
Example:
def greeting(name): Save this code in a file
print("Hello, " + name) named mymodule.py
Now we can use the module we just created, by using
the import statement.
Import the module named mymodule, and call the greeting
function
import mymodule
mymodule.greeting("Jonathan")
def fib_rec(n): Save the entire program with a name fib.py
"recursive fibonacci"
if (n<=1):
return n
else:
return fib_rec(n-1)+fib_rec(n-2)
def fib_iter(n):
"iterative fibonacci"
cur,nxt=0,1
for k in range(n):
cur,nxt=nxt,cur+nxt
return cur
def fib_upto(n):
"given n, return list of fibonacci numbers <=n" Within a module, the module’s name is
cur, nxt=0,1 available as the value of the global
lst=[] variable __name__
while (cur<n):
lst.append(cur)
cur,nxt=nxt,cur+nxt
return lst
Variables in Module
The module can contain functions but also variables of all
types (arrays, dictionaries, objects etc)
Example:
person1 = {
"name": "John",
"age": 36, Save this code in the file mymodule.py
"country": "Norway"
}
Import the module named mymodule, and access the person1 dictionary
Example:
import mymodule
a = mymodule.person1["age"]
print(a)
You can name the module file whatever you like, but it must have the file
extension .py
import mymodule as mx
a = mx.person1["age"]
print(a)
Built-in Modules
Module Use
import platform Platform module is used to retrieve as much possible information about
the platform on which the program is being currently executed.
import datetime Datetime module provides a module to work with dates as date objects
import math Math module facilitates the use of various mathematical functions
x = platform.system()
print(x)
datetime.now()
function has the
import datetime following attributes:
x = datetime.datetime.now() •Year
print(x) •month
•day
•hour
import math •minute
x = math.ceil(1.4) •second
y = math.floor(1.4) •microsecond
print("value of x:", x)
print("value of y:",y)
strftime() Method
The datetime object has a method for formatting date objects into readable strings.
The method is called strftime(), and takes one parameter, format, to specify the
format of the returned string
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
Built-in Math Functions
min() and max() functions can be used to find the lowest or
highest value in an iterable
The abs() function returns the absolute (positive) value of the
specified number.
import math
x=abs(-7.25)
print(x)
pow(x, y) function returns the value of x to the power of y (x y).
math.sqrt() method for example, returns the square root of a
number.
import math
x = math.sqrt(64)
print(x)
math.ceil() method rounds a number upwards to its nearest
integer, and the math.floor() method rounds a number
downwards to its nearest integer.
math.pi constant, returns the value of PI (3.14...)
Built-in Math Functions
Built-in Math Functions
Built-in Math Functions
Built-in Math Constants
Random module
In Python, random numbers are not generated
implicitly; it provides a random module in order to
generate random numbers explicitly.
Applications
Creating pseudo-random numbers on Lottery scratch cards
reCAPTCHA on login forms (numbers and images)
Picking a number, flipping a coin, and throwing of a dice
related games required random numbers
Shuffling deck of playing cards
A random module is imported using the command:
import random
Some of Built-in functions in Random module
(1) random() # Generate a random floating number between 0 and 1
Syntax:
random.random()
(2) randrange() # generate random numbers from a specified range
Syntax:
random.randrange(start(opt),stop,step(opt))
Raises ValueError if stop <= start and number is non- integral.
(3) randint() # Generate a random integer from a specified range
Syntax:
random.randint(start, end)
Returns a ValueError when floating point values are passed as parameters.
Returns a TypeError when anything other than numeric values are passed as parameters.
(4) seed() # generate pseudo-random numbers
Syntax:
random.seed(l) # l is a seed value used to produce a random number.
(5) choices() # Generate a random element from a sequence
Syntax:
random.choices(sequence, weights=None, k=1)
(6) shuffle() # Shuffling a list of objects
Syntax:
random.shuffle(sequence, function)
import random
#random() function
print(random.random())
print ("Random number from 0-100 is : ",end="")
#randrange() function
print (random.randrange(100))
#randint() function
r1 = random.randint(0, 10)
print("Random number between 0 and 10 is % s" % (r1))
#seed() function
random.seed(0)
print(random.randint(1, 1000))
#choices() function
mylist = ["geeks", "for", "python"]
print(random.choices(mylist, weights = [10, 1, 1], k = 5))
#shuffle() function
sample_list = ['A', 'B', 'C', 'D', 'E']
print("Original list : ")
print(sample_list)
random.shuffle(sample_list)
print("\nshuffled list : ")
print(sample_list)
Packages
A package is a collection of modules that are
organized in a hierarchical directory structure.
To use a module from a package, you first need
to import the package, followed by the module.
Creating Package
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.
Syntax Error
As the name suggests this error is caused by the wrong syntax in the code.
It leads to the termination of the program.
Example:
amount = 10000
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")
Exceptions
Exceptions are raised when the program is syntactically correct, but the code results in
an error.
This error does not stop the execution of the program, however, it changes the normal
flow of the program.
Example:
marks = 10000
a = marks / 0
print(a)
Different types of exceptions 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.
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.
Exception handling
Try and Except Statement – Catching Exceptions
Example
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
# Throws error since there are only 3 elements in array
print ("Fourth element = %d" %(a[3]))
except IndexError:
print (“array Out of Index (IndexError) error occurred")
Exception handling
Try with Else Clause
“else” clause can be used on the try-except block which must be present after all the
except clauses.
The code enters the else block only if the try clause does not raise an exception.
Example:
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
# function calls to test above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
Exception handling
Try with Else and finally Clause
The final block always executes after the normal termination of the try block or after
the try block terminates due to some exception.
try: Example:
k = 5//0 # raises divide by zero
exception.
print(k)
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
User defined exceptions
We can also define our own exceptions by sub classing the built-in
Exception class. Here's an example:
class MyError(Exception):
pass
def my_function(x):
if x < 0:
raise MyError("x must be non-negative")
return x**2
try:
result = my_function(-1)
except MyError as error:
print(error)
The MyError class is defined by sub classing Exception. The
my_function function raises a MyError exception if the input value x is
negative. The try statement catches the exception and prints the
error message.