GE3151 Problem Solving and Python Programming Lecture Notes 3
GE3151 Problem Solving and Python Programming Lecture Notes 3
com
NOTES OF LESSON
GE3151- PROBLEM SOLVING AND
PYTHON PROGRAMMING
INTRODUCTION
PROBLEM SOLVING
Problem solving is the systematic approach to define the problem and creating number of
solutions.
The problem solving process starts with the problem specifications and ends with a
correct program.
PROBLEM SOLVING TECHNIQUES
Problem solving technique is a set of techniques that helps in providing logic for solving a
problem.
Problem solving can be expressed in the form of
1. Algorithms.
2. Flowcharts.
3. Pseudo codes.
4. Programs
1.ALGORITHM
It is defined as a sequence of instructions that describe a method for solving a problem.
In other words it is a step by step procedure for solving a problem
The following are the primary factors that are often used to judge the quality of the
algorithms.
Time – To execute a program, the computer system takes some amount of time. The lesser
is the time required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory space.
The lesser is the memory required, the better is the algorithm.
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given
problem, some of these may provide more accurate results than others, and such algorithms may be
suitable
States
An algorithm is deterministic automation for accomplishing a goal which, given an initial
state, will terminate in a defined end-state.
An algorithm will definitely have start state and end state.
Control Flow
Control flow which is also stated as flow of control, determines what section of code is to
run in program at a given time. There are three types of flows, they are
1. Sequential control flow
2. Selection or Conditional control flow
3. Looping or repetition control flow
4.1. Print i
5. Stop
Function
A function is a block of organized, reusable code that is used to perform a single, related
action. Function is also named as methods, sub-routines.
Elements of functions:
1. Name for declaration of function
2. Body consisting local declaration and statements
3. Formal parameter
4. Optional result type.
Basic Syntax
function_name(parameters)
function statements
end function
2.NOTATIONS OF AN ALGORITHM
Algorithm can be expressed in many different notations, including Natural Language,
Pseudo code, flowcharts and programming languages. Natural language tends to be verbose
and ambiguous. Pseudocode and flowcharts are represented through structured human language.
A notation is a system of characters, expressions, graphics or symbols designs used among
each others in problem solving to represent technical facts, created to facilitate the best result for a
program
Pseudocode
Pseudocode is an informal high-level description of the operating principle of a
computer program or algorithm. It uses the basic structure of a normal programming language,
but is intended for human reading rather than machine reading.
It is text based detail design tool. Pseudo means false and code refers to instructions
written in programming language.
Pseudocode cannot be compiled nor executed, and there are no real formatting or syntax
rules. The pseudocode is written in normal English language which cannot be understood by the
computer.
Example:
Pseudocode: To find sum of two numbers
READ num1,num2
sum=num1+num2
PRINT sum
Basic rules to write pseudocode:
1. Only one statement per line.
Statements represents single action is written on same line. For example to read the
input, all the inputs must be read using single statement.
2. Capitalized initial keywords
The keywords should be written in capital letters. Eg: READ, WRITE, IF, ELSE,
ENDIF, WHILE, REPEAT, UNTIL
Example:
Pseudocode: Find the total and average of three subjects
RAED name, department, mark1, mark2, mark3
Total=mark1+mark2+mark3
Average=Total/3
WRITE name, department,mark1, mark2, mark3
3. Indent to show hierarchy
Indentation is a process of showing the boundaries of the structure.
4. End multi-line structures
Each structure must be ended properly, which provides more clarity.
Example:
Advantages of Pseudocode
• Can be done easily on a word processor
• Easily modified
• Implements structured concepts well
• It can be written easily
• It can be read and understood easily
• Converting pseudocode to programming language is easy as compared with
flowchart
Disadvantages of Pseudocode
• It is not visual
• There is no standardized style or format
Flowchart
A graphical representation of an algorithm. Flowcharts is a diagram made up of boxes,
diamonds, and other shapes, connected by arrows.
Each shape represents a step in process and arrows show the order in which they occur.
Table 1: Flowchart Symbols
S.No Name of Symbol Type Description
symbol
1. Terminal Oval Represent the start and
Symbol stop of the program.
4. Only one flow line should enter a decision symbol, but two or three flow lines, one for
each possible answer, cap leave the decision symbol.
Advantages of Flowchart
Communication:
Flowcharts are better way of communicating the logic of the system.
Effective Analysis
With the help of flowchart, a problem can be analyzed in more effective way.
Proper Documentation
Flowcharts are used for good program documentation, which is needed for various
purposes.
Efficient Coding
Disadvantages of Flowchart
Complex Logic: Sometimes, the program logic is quite complicated. In that case flowchart
becomes complex and difficult to use.
Alteration and Modification: If alterations are required the flowchart may require re-
drawing completely.
Reproduction: As the flowchart symbols cannot be typed, reproduction becomes
problematic.
Control Structures using flowcharts and Pseudocode
Sequence Structure
Pseudocode Flow Chart
General Structure
Process 1
…. Process 1
Process 2
…
Process 2
Process 3
Process 3
Example
READ a
Start
READ b
Result c=a+b
PRINT c a=10,b=20
c=a+b
print c
Stop
Conditional Structure
• Conditional structure is used to check the condition. It will be having two outputs only (True or False)
• IF and IF…ELSE are the conditional structures used in Python language.
• CASE is the structure used to select multi way selection control. It is not supported in Python.
Process 1 No
Process 2
Example
READ a
READ b Start
IF a>b THEN
PRINT a is greater a=10,b=20
Yes if (a>b)
Print a is greater No
Stop
IF… ELSE
IF…THEN…ELSE is the structure used to specify, if the condition is true, then execute Process1,
else, that is condition is false then execute Process2
Process 2
Example
READ a Start
READ b
IF a>b THEN
a=10,b=20
PRINT a is greater
Yes if (a>b)
Print a is greater
No
Print b is greater
Stop
Yes
Body of the loop
Example
• DO…WHILE is exit checked loop, so the loop will be executed at least once.
Yes
Stop
Print a
a=a+1
Programming Language
• A programming language is a vocabulary and set of grammatical rules for instructing a computer
or computing device to perform specific tasks. In other word it is set of instructions for the
computer to solve the problem.
• Programming Language is a formal language with set of instruction, to the computer to solve a
problem. The program will accept the data to perform computation.
Program= Algorithm +Data
Need for Programming Languages
• Programming languages are also used to organize the computation
• Using Programming language we can solve different problems
• To improve the efficiency of the programs.
Types of Programming Language
In general Programming languages are classified into three types. They are
• Low – level or Machine Language
• Intermediate or Assembly Language
• High – level Programming language
Machine Language:
Machine language is the lowest-level programming language (except for computers that utilize
programmable microcode). Machine languages are the only languages understood by computers. It is also
called as low level language.
Example code:100110011
111001100
Assembly Language:
An assembly language contains the same instructions as a machine language, but the instructions
and variables have names instead of being just numbers. An assembler language consists of mnemonics,
mnemonics that corresponds unique machine instruction.
Example code: start
addx,y
subx,y
Figure : Interpreter
Compiled Programming Languages
Compile is to transform a program written in a high-level programming language from source
code into object code. This can be done by using a tool called compiler.
A compiler reads the whole source code and translates it into a complete machine code program to
perform the required tasks which is output as a new file.
Figure: Compiler
If the instructions are executed one after another, it is called sequential algorithm
• Programming language can be fed into an electronic computer directly. Instead, it needs to be
converted into a computer program written in a particular computer language. We can look at such
a program as yet another way of specifying the algorithm, although it is preferable to consider it as
the algorithm’s implementation.
• Once an algorithm has been specified, you have to prove its correctness. That is, you have to
prove that the algorithm yields a required result for every legitimate input in a finite amount of
time.
• It might be worth mentioning that although tracing the algorithm’s performance for a few specific
inputs can be a very worthwhile activity, it cannot prove the algorithm’s correctness conclusively.
But in order to show that an algorithm is incorrect, you need just one instance of its input for
which the algorithm fails.
Analyzing an Algorithm
1. Efficiency.
Time efficiency: indicating how fast the algorithm runs,
Space efficiency: indicating how much extra memory it uses
2. simplicity.
An algorithm should be precisely defined and investigated with mathematical
expressions.
Simpler algorithms are easier to understand and easier to program.
Simple algorithms usually contain fewer bugs.
Coding an Algorithm
Most algorithms are destined to be ultimately implemented as computer programs.
Programming an algorithm presents both a peril and an opportunity.
A working program provides an additional opportunity in allowing an empirical analysis
of the underlying algorithm. Such an analysis is based on timing the program on several
inputs and then analyzing the results obtained.
Recursions:
A function that calls itself is known as recursion.
Recursion is a process by which a function calls itself repeatedly until some specified condition has
beensatisfied.
Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop
FLOW CHART
Main function:
BEGIN
GET n
CALL
factorial(n)
PRINT fact
BIN
IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)
Pseudocode:
BEGIN
COMPUTE guess=input
READ guess,
IF guess>n
PRINT Guess is high
ELSE
IF guess<n
PRINT Guess is low
ELSE
IF guess=n
PRINT Good job
ELSE
Nope
END
Flowchart:
Start
Read n
Read
Guess number
Guess=input
If Guess>n
If Guess<n
Good job
Stop
Pseudocode:
BEGIN
READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
COMPUTE min=a[0]
FOR i=1 to n, then
IF a[i]<min, then
CALCULATE min=a[i]
INCREMENT i
ELSE
INCREMENT i
END IF-ELSE
END FOR
PRINT min
END
20
Flowchart:
21
Pseudocode:
BEGIN
READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
READ item
FOR i=n-1 to 0 and item<a[i], then
CALCULATE a[i+1]=a[i]
DECREMENT i
END FOR
COMPUTE a[i+1]=a[i]
COMPUTE n=n+1
FOR i=0 to n, then
PRINT a[i]
INCREMENT i
END FOR
END
22
Flowchart:
23
4.Tower of Hanoi
Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and more
than one rings.
Tower of Hanoi is one of the best example for recursive problem solving.
Pre-condition:
These rings are of different sizes and stacked upon in an ascending order, i.e. the smaller
one sits over the larger one. There are other variations of the puzzle where the number of disks
increase, but the tower count remains the same.
Post-condition:
All the disk should be moved to the last pole and placed only in ascending order as shown
below.
Rules
The mission is to move all the disks to some another tower without violating the sequence
of arrangement. A few rules to be followed for Tower of Hanoi are
• Only one disk can be moved among the towers at any given time.
• Only the "top" disk can be removed.
• No large disk can sit over a small disk.
Tower of Hanoi puzzle with n disks can be solved in minimum 2n−1 steps. This presentation
shows that a puzzle with 3 disks has taken 23 - 1 = 7 steps.
Algorithm
To write an algorithm for Tower of Hanoi, first we need to learn how to solve this problem with
lesser amount of disks, say → 1 or 2. We mark three towers with name, source, aux (only to help
moving the disks) and destination.
Input: one disk
If we have only one disk, then it can easily be moved from source to destination peg.
Input: two disks
If we have 2 disks −
• First, we move the smaller (top) disk to aux peg.
• Then, we move the larger (bottom) disk to destination peg.
• And finally, we move the smaller disk from aux to destination peg.
Input: more than two disks
• So now, we are in a position to design an algorithm for Tower of Hanoi with more than
two disks. We divide the stack of disks in two parts. The largest disk (n th disk) is in one
part and all other (n-1) disks are in the second part.
24
25
Stop
If disk==1?
Return
26
27
1. What is an algorithm?
An algorithm is a finite number of clearly described, unambiguous do able steps that
can be systematically followed to produce a desired results for given input in the given amount
of time. In other word, an algorithm is a step by step procedure to solve a problem with finite
number of steps.
Algorithm Program
1. Systematic logical approach which is a It is exact code written for
well-defined, step-by-step procedure that problem following all the rules of the
allows a computer to solve a problem. programming language.
2. An algorithm is a finite number of clearly The program will accept the data to
described, unambiguous do able steps that perform computation.
can be systematically followed to produce
a desired results for given input in the Program=Algorithm + Data
given amount of time.
6. Write an algorithm to accept two numbers, compute the sum and print the result.
Step 1: Start
Step 2: Declare variables num1,num2 and sum,
Step 3: Read values num 1 and num2.
Step 4: Add and assign the result to sum.
Sum←num1+num2
Step 5: Display sum
28
29
11.Draw a flow chart to find whether the given number is leap year or not.
Start
Read year
If
(year%4==0)
Stop
30
Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables,
expressions, statements, tuple assignment, precedence of operators, comments; Modules and functions,
function definition and use, flow of execution, parameters and arguments; Illustrative programs: exchange
the values of two variables, circulate the values of n variables, distance between two points.
1. INTRODUCTION TO PYTHON:
• Python is interpreted: Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it.
• Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
• Python is Object-Oriented: Python supports Object-Oriented style or technique of programming
that encapsulates code within objects.
• Python is a Beginner's Language: Python is a great language for the beginner-
Level programmers and supports the development of a wide range of applications.
Python Features:
• Easy-to-learn: Python is clearly defined and easily readable. The structure of the program is very
simple. It uses few keywords.
• Easy-to-maintain: Python's source code is fairly easy-to-maintain.
• Portable: Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
• Interpreted: Python is processed at runtime by the interpreter. So, there is no need to compile a
program before executing it. You can simply run the program.
• Extensible: Programmers can embed python within their C,C++,JavaScript
, ActiveX, etc.
• Free and Open Source: Anyone can freely distribute it, read the source code, and edit it.
• High Level Language: When writing programs, programmers concentrate on solutions of the
current problem, no need to worry about the low level details.
• Scalable: Python provides a better structure and support for large programs than shell scripting.
Applications:
Bit Torrent file sharing
Google search engine, YouTube
Intel, Cisco, HP,IBM
i–Robot
NASA
Face book, Drop box
Downloaded from
31 EnggTree.com
EnggTree.com
Python interpreter:
Interpreter: To execute a program in a high-level language by translating it one line ata time.
Compiler: To translate a program written in a high-level language into a low-level language all at once, in
preparation for later execution.
Compiler Interpreter
Compiler Takes Entire program as input Interpreter Takes Single instruction as input
Downloaded from
32 EnggTree.com
EnggTree.com
This is an example of a print statement. It displays a result on the screen. In this case, the result is the words.
Script mode:
In script mode, we type python program in a file and then use interpreter to execute the content of the
file.
Scripts can be saved to disk for future use. Python scripts have the
extension .py, meaning that the filename ends with.py
Save the code with filename.py and run the interpreter in script mode to execute the script.
Can’t save and edit the code Can save and edit the code
If we want to experiment with the code, If we are very clear about the code, we can
we can use interactive mode. use script mode.
we cannot save the statements for further use and we we can save the statements for further use and we no
have to retype all the statements to re-run them. need to retype all the statements to re-run them.
We can see the results immediately. We can’t see the code immediately.
Downloaded from
33 EnggTree.com
EnggTree.com
Auto completion with smart indentation.
Python shell to display output with syntax highlighting.
Value:
Value can be any letter, number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different datatypes.)
Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values.
Python has four standard data types:
Numbers:
Number data type stores Numerical Values.
This data type is immutable [i.e. values/items cannot be changed].
Python supports integers, floating point numbers and complex numbers. They are defined as,
Sequence:
A sequence is an ordered collection of items, indexed by positive integers.
It is a combination of mutable (value can be changed) and immutable (values cannot be changed)
datatypes.
Downloaded from
34 EnggTree.com
EnggTree.com
There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples
Strings:
A String in Python consists of a series or sequence of characters - letters, numbers, and special
characters.
Strings are marked by quotes:
• Single quotes(' ') E.g., 'This a string in single quotes'
• double quotes(" ") E.g., "'This a string in double quotes'"
• triple quotes(""" """)E.g., """This is a paragraph. It is made up of multiple
lines and sentences."""
Individual character in a string is accessed using a subscript(index).
Characters can be accessed using indexing and slicing operations .Strings are
Immutable i.e the contents of the string cannot be changed after it is created.
Indexing:
Downloaded from
35 EnggTree.com
EnggTree.com
st
Slice operator is used >>>print(s[:4]) - Displaying items from 1
to extract part of a Good
position till 3rd.
data
type
Lists
List is an ordered sequence of items. Values in the list are called elements /items.
It can be written as a list of comma-separated items (values) between square brackets[].
Items in the lists can be of different datatypes.
Operations on list:
Indexing
Slicing
Concatenation
Repetitions
Updation, Insertion, Deletion
Downloaded from
36 EnggTree.com
EnggTree.com
6.78, 9]
Repetition >>>list2*3 Creates new strings, concatenating
['god', 6.78, 9, 'god', 6.78, 9, 'god', multiple
6.78, 9] copies of the same string
Updating the list >>>list1[2]=45 Updating the list using index value
>>>print( list1)
[‘python’, 7.79, 45, ‘hello’]
Inserting an element >>>list1.insert(2,"program") Inserting an element in 2ndposition
>>> print(list1)
['python', 7.79, 'program', 45,
'hello']
Removing an element >>>list1.remove(45) Removing an element by
>>> print(list1) giving the element directly
['python', 7.79, 'program', 'hello']
Tuple:
A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of square brackets.
A tuple is an immutable list.i.e. once a tuple has been created, you can't add elements to a tuple or
remove elements from the tuple.
Benefit of Tuple:
Tuples are faster than lists.
If the user wants to protect the data from accidental changes, tuple can be used.
Tuples can be used as keys in dictionaries, while lists can't.
Basic Operations:
Creating a tuple >>>t=("python", 7.79, 101, Creating the tuple with elements
"hello”) of different data types.
Indexing >>>print(t[0]) python Accessing the item in the
>>>t[2] position0
101 Accessing the item in the
position2
Altering the tuple data type leads to error. Following error occurs when user tries to do.
Downloaded from
37 EnggTree.com
EnggTree.com
>>>t[0]="a"
Trace back (most recent call last):
File "<stdin>", line 1, in <module>
Type Error: 'tuple' object does not support item assignment
Mapping
-This data type is unordered and mutable.
-Dictionaries fall under Mappings.
Dictionaries:
Lists are ordered sets of objects, whereas dictionaries are unorderedsets.
Dictionary is created by using curly brackets. i,e.{}
Dictionaries are accessed via keys and not via their position.
A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated
(or mapped) to a value.
The values of a dictionary can be any Python data type. So dictionaries are unordered key-value-
pairs(The association of a key and a value is called a key- value pair)
Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and lists.
If you try to access a key which doesn't exist, you will get an error message:
>>>words = {"house" : "Haus", "cat":"Katze"}
>>>words["car"]
Traceback (most recent call last): File
"<stdin>", line 1, in <module>KeyError: 'car'
Downloaded from
38 EnggTree.com
EnggTree.com
VARIABLES:
A variable allows us to store a value by assigning it to a name, which can be used later.
Named memory locations to store values.
Programmers generally choose names for their variables that are meaningful.
It can be of any length. No space is allowed.
We don't need to declare a variable before using it. In Python, we simply assign a value to a variable
and it will exist.
>>> a=b=c=100
Assigning multiple values to multiple variables:
>>>a,b,c=2,4,"ram"
KEYWORDS:
Keywords are the reserved words in Python.
We cannot use a keyword as name, function name or any other identifier.
They are used to define the syntax and structure of the Python language.
Keywords are case sensitive.
IDENTIFIERS:
Identifier is the name given to entities like class, functions, variables etc. in Python.
Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to
Z) or digits (0 to 9) or an underscore (_).
Downloaded from
39 EnggTree.com
EnggTree.com
all are valid example.
An identifier cannot start with a digit.
Keywords cannot be used as identifiers.
Cannot use special symbols like!, @, #, $, % etc. in our identifier.
Identifier can be of any length.
Example:
Names like myClass, var_1, and this_is_a_long_variable
Here, The first line is an assignment statement that gives a value to n. The second line is
a print statement that displays the value of n.
Expressions:
-An expression is a combination of values, variables, and operators.
- A value all by itself is considered an expression, and also a variable.
- So the following are all legal expressions:
>>> 42
42
>>> a=2
>>>a+3+2 7
>>> z=("hi"+"friend")
>>>print(z) hifriend
INPUT: Input is data entered by user (end user) in the program. In python, input
() function is available for input.
Syntax for input() is:
variable = input (“data”)
Downloaded from
40 EnggTree.com
EnggTree.com
Example:
>>> x=input("enter the name:")
enter the name: george
>>>y=int(input("enter the number"))
enter the number 3
#python accepts string as default data type. Conversion is required for type.
COMMENTS:
A hash sign (#) is the beginning of a comment.
Anything written after # in a line is ignored by interpreter.
Eg: percentage = (minute * 100)/60 # calculating percentage of an hour
Python does not have multiple-line commenting feature. You have to comment each line
individually as follows:
Example:
# This is a comment.
# This is a comment, too.
# I said that already.
DOCSTRING:
Docstring is short for documentation string.
It is a string that occurs as the first statement in a module, function, class, or method definition. We
must write what a function/class does in the docstring.
Triple quotes are used while writing docstrings.
Syntax:
functionname__doc.__ Example:
def double(num):
"""Function to double thevalue"""
return2*num
>>>print (double.__doc__)
Function to double the value
Downloaded from
41 EnggTree.com
EnggTree.com
Example:
a=3
b=1
if a>b:
print("a is greater")
else:
print("b is greater")
QUOTATION INPYTHON:
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals. Anything that is
represented using quotations are considered as string.
TUPLE ASSIGNMENT
Example:
-It is useful to swap the values of two variables. With conventional assignment statements, we have to use a
temporary variable. For example, to swap a and b:
Downloaded from
42 EnggTree.com
EnggTree.com
-Tuple assignment solves this problem neatly:
(a, b) = (b, a)
-In tuple unpacking, the values in a tuple on the right are ‘unpacked ‘into the variables/names on the
right:
4.OPERATORS:
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator
Types of Operators:
-Python language supports the following types of operators
• Arithmetic Operators
• Comparison (Relational)Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Downloaded from
43 EnggTree.com
EnggTree.com
Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction, multiplication etc.
Assume, a=10 and b=5
% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder
// Floor Division - The division of operands where the result is the 5//2=2
quotient in which the digits after the decimal point are removed
Examples Output:
a=10 a+b=15
b=5 a-b= 5
print("a+b=",a+b) a*b= 50
print("a-b=",a-b)
a/b= 2.0
print("a*b=",a*b)
print("a/b=",a/b) a%b=0
print("a%b=",a%b) a//b=2
print("a//b=",a//b) a**b= 100000
print("a**b=",a**b)
Comparison (Relational)Operators:
• Comparison operators are used to compare values.
• It either returns True or False according to the condition. Assume, a=10 and b=5
Downloaded from
44 EnggTree.com
EnggTree.com
!= If values of two operands are not equal, then condition becomes true. (a!=b) is
true
> If the value of left operand is greater than the value of right operand, then (a > b) is not
condition becomes true. true.
< If the value of left operand is less than the value of right operand, then (a < b) is true.
condition becomes true.
>= If the value of left operand is greater than or equal to the value of right (a >= b) is not
operand, then condition becomes true. true.
<= If the value of left operand is less than or equal to the value of right (a <= b) is
operand, then condition becomes true. true.
Example
Output: a>b=>
a=10 True a>b=>
b=5 False a==b=>
print("a>b=>",a>b) False a!=b=>
print("a>b=>",a<b) True a>=b=>
print("a==b=>",a==b) False a>=b=>
print("a!=b=>",a!=b) True
print("a>=b=>",a<=b)
print("a>=b=>",a>=b)
Assignment Operators:
-Assignment operators are used in Python to assign values to variables.
Operator Description Example
= Assigns values from right side operands to left side operand c=a+b
assigns value
of a + b into c
+= Add AND It adds right operand to the left operand and assign the result to c += a is
leftoperand equivalent to c
=c+a
-= Subtract It subtracts right operand from the left operand and assign the result c -= a is
AND to left operand equivalent to c
= c -a
Downloaded from
45 EnggTree.com
EnggTree.com
*= Multiply It multiplies right operand with the left operand and assign the c *= a is
AND result to left operand equivalent to c
= c *a
/= Divide It divides left operand with the right operand and assign the result c /= a is
AND to left operand equivalent to c
= c /ac
/= a is
equivalent to c
= c /a
%= Modulus It takes modulus using two operands and assign the result to left c %= a is
AND operand equivalent to c
=c%a
//= Floor It performs floor division on operators and assign value to the left c //= a is
Division operand equivalent to c
= c // a
Example Output
a =21 Line 1 - Value of c is 31
b =10 Line 2 - Value of c is 52
Line 3 - Value of c is 1092
c=0
Line 4 - Value of c is 52.0
c=a+b Line 5 - Value of c is2
print("Line 1 - Value of c is ",c) Line 6 - Value of c is 2097152
c += a Line 7 - Value of c is99864
print("Line 2 - Value of c is ", c)
c *= a
print("Line 3 - Value of c is ",c)
c /= a
print("Line 4 - Value of c is ", c)
c=2
c %=a
print("Line 5 - Value of c is ",c)
c **= a
print("Line 6 - Value of c is ",c)
c //= a
print ("Line 7 - Value of c is ", c)
Downloaded from
46 EnggTree.com
EnggTree.com
Logical Operators:
-Logical operators are the and, or, not operators.
Example Output
a = True x and y is False
b = False x or y is True
print('a and b is', a and b) not x is False
print('a or b is' ,a or b)
print('not a is', not a)
Bitwise Operators:
• A bitwise operation operates on one or more bit patterns at the level of individual bits
Example: Let x = 10 (0000 1010 in binary)and
y = 4 (0000 0100 in binary)
Example Output
a = 60 # 60 = 0011 1100 Line 1 - Value of c is 12
b = 13 # 13 = 0000 1101 Line 2 - Value of c is 61
c=0 Line 3 - Value of c is 49
c = a & b; # 12 = 0000 1100 Line 4 - Value of c is-61
print "Line 1 - Value of c is ", c Line 5 - Value of c is 240
c = a|b; # 61 = 00111101 Line 6 - Value of c is 15
print "Line 2 - Value of c is ", c
c = a^b; # 49 = 00110001
print "Line 3 - Value of c is ", c
c =~a; # -61 = 11000011
Downloaded from
47 EnggTree.com
EnggTree.com
print "Line 4 - Value of c is ", c
c = a<<2; # 240 = 11110000
print "Line 5 - Value of c is ", c
c = a>>2; # 15 = 00001111
print "Line 6 - Value of c is ", c
Membership Operators:
Evaluates to find a value or a variable is in the specified sequence of string, list, tuple, dictionary or
not.
Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in operators areused.
Example:
x=[5,3,6,4,1]
>>>5 in x
True
>>>5 not in x
False
Identity Operators:
• They are used to check if two values (or variables) are located on the same partof the
memory.
Example
Output
x =5
False
y =5 True
x2 = 'Hello'
y2= 'Hello'
print(x1 is not y1)
print(x2 is y2)
Downloaded from
48 EnggTree.com
EnggTree.com
5.OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description
~+- Complement, unary plus and minus (method names for the
last two are +@ and -@)
Downloaded from
49 EnggTree.com
EnggTree.com
Examples:
a=9-12/3+3*2-1 A=2*3+4%5-3/2+6
a=? A=6+4%5-3/2+6 find m=?
a=9-4+3*2-1 A=6+4-3/2+6 A=6+4- m=-43||8&&0||-2 m=-
a=9-4+6-1 1+6 43||0||-2 m=1||-2
a=5+6-1 a=11- A=10-1+6 m=1
1 a=10 A=9+6 A=15
6.Functions, Function Definition And Use, Function call, Flow Of Execution, Function Prototypes,
Parameters And Arguments, Return statement, Arguments types, Modules
FUNCTIONS:
Function is a sub program which consists of set of instructions used to perform a specific task.
A large program is divided into basic building blocks called function.
Types of function:
Functions can be classified into two categories:
i) user defined function
ii) Built in function
i) Built in functions
• Built in functions are the functions that are already created and stored inpython.
• These built in functions are always available for usage and accessed by a programmer. It cannot be
modified.
Downloaded from
50 EnggTree.com
EnggTree.com
Built in function Description
Downloaded from
51 EnggTree.com
EnggTree.com
Syntax:
def fun_name(Parameter1,Parameter2…Parameter n): statement1
statement2…
statement n return[expression]
Example:
def my_add(a,b):
c=a+b
return c
Flow of Execution:
• The order in which statements are executed is called the flow of execution
• Execution always begins at the first statement of the program.
• Statements are executed one at a time, in order, from top to bottom.
• Function definitions do not alter the flow of execution of the program, but remember that statements
inside the function are not executed until the function is called.
• Function calls are like a bypass in the flow of execution. Instead of going to the next statement, the
flow jumps to the first line of the called function, executes all the statements there, and then comes
back to pick up where it left off.
Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of execution. This
means that you will read the def statements as you are scanning from top to bottom, but you should skip the
statements of the function definition until you reach a point where that function is called.
Function Prototypes:
Downloaded from
52 EnggTree.com
EnggTree.com
OUTPUT: OUTPUT:
enter a5 enter a5
enter b 10 enter b 10
15 15
OUTPUT: OUTPUT:
enter a5 enter a5
enter b 10 enter b 10
15 15
Downloaded from
53 EnggTree.com
EnggTree.com
Example:
def my_add(a,b):
c=a+b
return c
x=5
y=4
print(my_add(x,y))
Output:
9
ARGUMENT TYPES:
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments
Required Arguments :The number of arguments in the function call should match exactly with
the function definition.
Downloaded from
54 EnggTree.com
EnggTree.com
Output:
Name:
georgeAge56
Keyword Arguments:
Python interpreter is able to use the keywords provided to match the values with parameters even though
if they are arranged in out of order.
DefaultArguments:
Assumes a default value if a value is not provided in the function call for that argument.
defmy_details( name, age=40 ):
print("Name: ", name)
print("Age ", age) return
my_details(name="george")
Output:
Name:
georgeAge40
Variable lengthArguments
If we want to specify more arguments than specified while defining the function, variable length
arguments are used. It is denoted by * symbol before parameter.
def my_details(*name ):
print(*name)
my_details("rajan","rahul","micheal", ärjun")
Output:
rajanrahulmichealärjun
7.MODULES:
A module is a file containing Python definitions ,functions, statements and instructions.
Standard library of Python is extended as modules.
To use these modules in a program, programmer needs to import the module.
Downloaded from
55 EnggTree.com
EnggTree.com
Once we import a module, we can reference or use to any of its functions or variables in our code.
• There is large number of standard modules also available in python.
• Standard modules can be imported the same way as we import our user- defined
modules.
• Every module contains many functions.
• To access one of the function , you have to specify the name of the module and the name
of the function separated by dot .This format is called dot notation.
Syntax:
import
module_namemodule_name.function_name(variable)
Importing Builtin Module: Importing User Defined Module:
import math x=math.sqrt(25) import calx=cal.add(5,4)
print(x) print(x)
Downloaded from
56 EnggTree.com
EnggTree.com
than or equal to x
math. floor(x) - Return the floor of x, the largest integer less than or equal to x.
math. factorial(x)-Return x factorial.
math.gcd(x,y)-Return the greatest common divisor of the integers a and b
math.sqrt(x)- Return the square root of x
math.pi - The mathematical constant π = 3.141592
math.e – returns The mathematical constant e = 2.718281
8.ILLUSTRATIVE PROGRAMS
Downloaded from
57 EnggTree.com
EnggTree.com
2marks:
1. What is Python?
Python is a general-purpose interpreted, interactive, object-oriented, and high-
level programming language.
Downloaded from
58 EnggTree.com
EnggTree.com
6. What is a tuple?
A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of square brackets.
A tuple is an immutable list.i.e. once a tuple has been created, you can't add elements to a tuple or
remove elements from the tuple.
7. Outline the logic to swap the contents of two identifiers without using third variable.
Swap two numbers Output:
a=2;b=3
print(a,b) (2, 3)
a = a+b (3, 2)
b= a-b >>>
a= a-b
print(a,b)
Example Output
Downloaded from
59 EnggTree.com
EnggTree.com
10. What is return statement?
The return statement is used to exit a function and go back to the place from
where it was called. If the return statement has no arguments, then it will not return any
values. But exits from function.
Syntax:
return[expression]
• Required Arguments
• Keyword Arguments
• Default Arguments
• Variable length Arguments
Downloaded from
60 EnggTree.com
EnggTree.com
61
1) Conditional Statements
•
Conditional if
•
Alternative if… else
•
Chained if…elif…else
• Nested if….else
Conditional (if):
conditional (if) is used to test a condition, if the condition is true the statements inside if will be
executed.
syntax:
Flowchart:
Downloaded from
61 EnggTree.com
EnggTree.com
Alternative (if-else):
In the alternative the condition must be true or false. In this else statement can be combined with if
statement. The else statement contains the block of code that executes when the condition is false. If the
condition is true statements inside the if get executed otherwise else part gets executed. The alternatives are
called branches, because they are branches in the flow of execution.
syntax:
Flowchart:
Examples:
1. odd or even number
2. positive or negative number
3. leap year or not
Downloaded from
62 EnggTree.com
EnggTree.com
• If the condition1 is False, it checks the condition2 of the elif block. If all the conditions are
False, then the else part is executed.
• Among the several if...elif...else part, only one part is executed according to the condition.
The if block can have only one else block. But it can have multiple elif blocks.
The way to express a computation like that is a chained conditional.
syntax:
Flowchart:
Downloaded from
63 EnggTree.com
Example: EnggTree.com
1. student mark system
2. traffic light system
Nested conditionals
One conditional can also be nested within another. Any number of condition can be nested inside
one another. In this, if the condition is true it checks another if condition1. If both the conditions are true
statement1 get executed otherwise statement2 get execute. if the condition is false statement3 gets
executed
Syntax
Downloaded from
64 EnggTree.com
EnggTree.com
Flowchart:
Example:
1. greatest of three numbers
2. positive negative or zero
greatest of three numbers output
a=eval(input(“enter the value of a”)) enter the value of a 9
b=eval(input(“enter the value of b”)) enter the value of a 1
c=eval(input(“enter the value of c”)) enter the value of a 8
if(a>b): the greatest no is 9
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
else:
if(b>c):
else:
print(“the greatest no is”,c)
State:
Transition from one process to another process under specified condition with in a time is called
state.
While loop:
While loop statement in Python is used to repeatedly executes set of statement as long as a given
condition is true.
In while loop, test expression is checked first. The body of the loop is entered only if the test
expression is True. After one iteration, the test expression is checked again. This process continues
until the test expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
The statements inside the while start with indentation and the first unintended line marks the end.
Syntax:
Flow chart:
Downloaded from
66 EnggTree.com
EnggTree.com
Examples:
1. program to find sum of n numbers:
2. program to find factorial of a number
3. program to find sum of digits of a number:
4. Program to Reverse the given number:
5. Program to find number is Armstrong number or not
6. Program to check the number is palindrome or not
Sum of n numbers: output
n=eval(input("enter n")) enter n
i=1 10
sum=0 55
while(i<=n):
sum=sum+i
i=i+1
print(sum)
Downloaded from
67 EnggTree.com
EnggTree.com
Downloaded from
68 EnggTree.com
EnggTree.com
For loop:
for in range:
We can generate a sequence of numbers using range() function. range(10) will
generate numbers from 0 to 9 (10 numbers).
In range function have to define the start, stop and step size
as range(start,stop,step size). step size defaults to 1 if not provided.
syntax
Flowchart:
For in sequence
• The for loop in Python is used to iterate over a sequence (list, tuple, string). Iterating over a
sequence is called traversal. Loop continues until we reach the last element in the sequence.
•
The body of for loop is separated from the rest of the code using indentation.
Downloaded from
69 EnggTree.com
EnggTree.com
2
2. For loop in list for i in [2,3,5,6,9]: 3
print(i) 5
6
9
for i in (2,3,1): 2
3. For loop in tuple print(i) 3
1
Examples:
1. Program to print Fibonacci series.
2. check the no is prime or not
Fibonacci series output
a=0 Enter the number of terms: 6
b=1 Fibonacci Series:
n=eval(input("Enter the number of terms: ")) 01
print("Fibonacci Series: ") 1
print(a,b) 2
for i in range(1,n,1): 3
c=a+b 5
print(c) 8
a=b
b=c
Downloaded from
70 EnggTree.com
EnggTree.com
3.Loop Control Structures
BREAK
•
Break statements can alter the flow of a loop.
•
It terminates the current
•
loop and executes the remaining statement outside the loop.
•
If the loop has else statement, that will also gets terminated and come out of the loop completely.
Syntax:
break
Flowchart
example Output
for i in "welcome": w
if(i=="c"): e
break l
print(i)
Downloaded from
71 EnggTree.com
EnggTree.com
CONTINUE
It terminates the current iteration and transfer the control to the next iteration in the loop.
Syntax: Continue
Flowchart
Example: Output
for i in "welcome": w
if(i=="c"): e
continue l
print(i) o
m
e
PASS
•
It is used when a statement is required syntactically but you don’t want any code to execute.
•
It is a null statement, nothing happens when it is executed.
Downloaded from
72 EnggTree.com
EnggTree.com
Syntax:
pass
break
Example Output
for i in “welcome”: w
if (i == “c”): e
pass l
print(i) c
o
m
e
break continue
It terminates the current loop and It terminates the current iteration and
executes the remaining statement outside transfer the control to the next iteration in
the loop. the loop.
syntax: syntax:
break continue
w w
e e
l l
o
m
e
Downloaded from
73 EnggTree.com
EnggTree.com
example output
for i in range(1,6): 1
print(i) 2
else: 3
print("the number greater than 6") 4
5 the number greater than 6
4) Fruitful Function
•
Fruitful function
•
Void function
•
Return values
•
Parameters
•
Local and global scope
•
Function composition
• Recursion
Downloaded from
74 EnggTree.com
EnggTree.com
Void Function
A function that perform action but don’t return any value.
Example:
print(“Hello”)
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()
Return values:
return keywords are used to return the values from the function.
example:
return a – return 1 variable
return a,b– return 2 variables
return a+b– return expression
return 8– return value
PARAMETERS / ARGUMENTS(refer 2nd unit)
Global Scope
•
The scope of a variable refers to the places that you can see or access a variable.
•
A variable with global scope can be used anywhere in the program.
•
It can be created by defining a variable outside the function.
Example output
a=50
def add():
Global Variable
b=20 70
c=a+b
print© Local Variable
def sub():
b=30
c=a-b 20
print©
print(a) 50
Downloaded from
75 EnggTree.com
EnggTree.com
Local Scope A variable with local scope can be used only within the function .
Example output
def add():
b=20
c=a+b 70
Local Variable
print©
def sub():
b=30 20
c=a-b
Local Variable
print©
print(a) error
print(b) error
Function Composition:
Function Composition is the ability to call one function from within another function
It is a way of combining functions such that the result of each function is passed as the argument of
the next function.
In other words the output of one function is given as the input of another function is known as
function composition.
Recursion
A function calling itself till it reaches the base value - stop point of function call. Example:
factorial of a given number using recursion
Downloaded from
76 EnggTree.com
EnggTree.com
Factorial of n Output
def fact(n): enter no. to find fact:5
if(n==1): Fact is 120
return 1
else:
return n*fact(n-1)
Examples:
1. sum of n numbers using recursion
2. exponential of a number using recursion
Sum of n numbers Output
def sum(n): enter no. to find sum:10
if(n==1): Fact is 55
return 1
else:
return n*sum(n-1)
sum=sum(n)
print("Fact is",sum)
Downloaded from
77 EnggTree.com
EnggTree.com
Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship
String slices:
•
A part of a string is called string slices.
• The process of extracting a sub string from a string is called slicing.
Print[0:4] – HELL The Slice[n : m] operator extracts sub
Slicing:
Print[ :3] – HEL string from the strings.
a=”HELLO” Print[0: ]- HELLO A segment of a string is called a slice.
Immutability:
Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.
operations Example output
element assignment a="PYTHON" TypeError: 'str' object does
a[0]='x' not support element
assignment
Downloaded from
79 EnggTree.com
EnggTree.com
string built in functions and methods:
A method is a function that “belongs to” an object.
Stringname.method()
a=”happy birthday”
here, a is the string name.
syntax example description
1 a.capitalize() >>> a.capitalize() capitalize only the first letter
' Happy birthday’ in a string
2 a.upper() >>> a.upper() change string to upper case
'HAPPY BIRTHDAY’
3 a.lower() >>> a.lower() change string to lower case
' happy birthday’
4 a.title() >>> a.title() change string to title case i.e.
' Happy Birthday ' first characters of all the
words are capitalized.
5 a.swapcase() >>> a.swapcase() change lowercase characters
'HAPPY BIRTHDAY' to uppercase and vice versa
6 a.split() >>> a.split() returns a list of words
['happy', 'birthday'] separated by space
7 a.center(width,”fillchar >>>a.center(19,”*”) pads the string with the
”) '***happy birthday***' specified “fillchar” till the
length is equal to “width”
8 a.count(substring) >>> a.count('happy') returns the number of
1 occurences of substring
9 a.replace(old,new) >>>a.replace('happy', replace all old substrings
'wishyou happy') with new substrings
'wishyou happy
birthday'
10 a.join(b) >>> b="happy" returns a string concatenated
>>> a="-" with the elements of an
>>> a.join(b) iterable. (Here “a” is the
'h-a-p-p-y' iterable)
11 a.isupper() >>> a.isupper() checks whether all the case-
False based characters (letters) of
the string are uppercase.
12 a.islower() >>> a.islower() checks whether all the case-
True based characters (letters) of
the string are lowercase.
13 a.isalpha() >>> a.isalpha() checks whether the string
False consists of alphabetic
characters only.
Downloaded from
80 EnggTree.com
EnggTree.com
String modules:
•
A module is a file containing Python definitions, functions, statements.
•
Standard library of Python is extended as modules.
•
To use these modules in a program, programmer needs to import the module.
•
Once we import a module, we can reference or use to any of its functions or variables in our code.
•
There is large number of standard modules also available in python.
•
Standard modules can be imported the same way as we import our user-defined modules.
Syntax:
import module_name
Example output
import string
print(string.punctuation) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.digits) 0123456789
print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
print(string.capwords("happ KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
y birthday")) ./:;<=>?@[\]^_`{|}~
print(string.hexdigits) Happy Birthday
print(string.octdigits) 0123456789abcdefABCDEF
01234567
Downloaded from
81 EnggTree.com
EnggTree.com
6) Array:
Array is a collection of similar elements. Elements in the array can be accessed by index. Index
starts with 0. Array can be handled in python by module named array.
To create array have to import array module in the program.
Syntax :
import array
Syntax to create array:
Array_name = module_name.function_name(‘datatype’,[elements])
example:
a=array.array(‘i’,[1,2,3,4])
a- array name
array- module name
i- integer datatype
Example
Program to find sum of Output
array elements
import array 10
sum=0
a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)
Syntax:
arrayname.fromlist(list_name)
Example
program to convert list Output
into array
import array 35
sum=0
l=[6,7,8,9,5]
a=array.array('i',[])
a.fromlist(l)
for i in a:
sum=sum+i
print(sum)
Downloaded from
82 EnggTree.com
EnggTree.com
Methods of an array
a=[2,3,4,5]
Downloaded from
83 EnggTree.com
EnggTree.com
7.ILLUSTRATIVE PROGRAMS:
Downloaded from
84 EnggTree.com
EnggTree.com
Binary search
output
a=[20, 30, 40, 50, 60, 70, 89] [20, 30, 40, 50, 60, 70, 89]
print(a) enter a element to search:30
search=eval(input("enter a element to search:")) element found at 2
start=0
stop=len(a)-1
while(start<=stop):
mid=(start+stop)//2
if(search==a[mid]):
print("element found at",mid+1)
break
elif(search<a[mid]):
stop=mid-1
else:
start=mid+1
else:
print("not found")
Downloaded from
85 EnggTree.com
EnggTree.com
Two marks:
1. What is a Boolean value?
•
Boolean data type have two values. They are 0 and 1.
•
0 represents False
•
1 represents True
•
True and False are keyword.
Example:
>>> 3==5
False
>>> 6==6
True
>>> True+True
2
>>> False+True
1
>>> False*True
0
break continue
It terminates the current loop and It terminates the current iteration and
executes the remaining statement outside transfer the control to the next iteration in
the loop. the loop.
syntax: syntax:
break continue
w w
e e
l l
o
m
e
Downloaded from
86 EnggTree.com
EnggTree.com
3. Write a Python program to accept two numbers, multiply them and print the result.
4. Write a Python program to accept two numbers, find the greatest and print the result.
number1 = int(input("Enter first number: "))
number2 = int(input("Enter second number: "))
if(number1>number2):
print('number1 is greater',number1)
else:
print('number2 is greater',number2)
Example:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
Downloaded from
87 EnggTree.com
EnggTree.com
Syntax:
pass
break
Example Output
for i in “welcome”: w
if (i == “c”): e
pass l
print(i) c
o
m
e
Downloaded from
88 EnggTree.com
EnggTree.com
UNIT IV LISTS, TUPLES, DICTIONARIES
1. Insertion sort
Insertion sort is an elementary sorting algorithm that sorts one element at a time. Most
humans, when sorting a deck of cards, will use a strategy similar to insertion sort. The algorithm
takes an element from the list and places it in the correct location in the list. This process is repeated
until there are no more unsorted items in the list.
Example:
Program:
a=list()
n=int(input("Enter size of list"))
for i in range(n):
a.append(int(input("Enter list elements")))
print("Before sorting",a)
for i in range(1,n):
key=a[i]
j=i-1
while j>=0 and key<a[j]:
a[j+1]=a[j]
j-=1
a[j+1]=key
print("After sorting(using insertion sort)",a)
Output
Enter size of list6
Enter listelements4
Enter listelements33
Enter list elements6
Enter listelements22
Enter list elements6
Enter list elements-9
Before sorting [4, 33, 6, 22, 6, -9]
After sorting(using insertion sort) [-9, 4, 6, 6, 22, 33]
89
2. Selection Sort
The selection sort algorithm starts by finding the minimum value in the array and moving it to
the first position. This step is then repeated for the second lowest value, then the third, and so on until
the array is sorted.
Example
Program
a=list()
n=int(input("Enter size of list"))
for i in range(n):
a.append(int(input("Enter list elements")))
print("List before sorting",a)
for i in range(0,n):
j=i+1
for j in range(j, n):
if a[i]> a[j]:
temp=a[i]
a[i]=a[j]
a[j]=temp
print("Sorted list(using Selection Sort)=",a)
Output:
Enter size of list5
Enter list elements12
Enter list elements-5
Enter list elements4
Enter listelements48
Enter listelements98
List before sorting [12, -5, 4, 48, 98]
Sorted list(using Selection Sort)= [-5, 4, 12, 48, 98]
90
3. Quadratic Equation:
Formula :
ax2+bx+c = -b±√b2 – 4ac
Program 2a
import cmath
a = int(input("Enter the coefficients a:"))
b=int(input("Enter the coefficients b: "))
c = int(input("Enter the coefficients c: "))
d = b**2-4*a*c # discriminant
x1 = (-b+cmath.sqrt((b**2)-(4*(a*c))))/(2*a)
x2 = (-b-cmath.sqrt((b**2)-(4*(a*c))))/(2*a)
print ("This equation has two solutions: ", x1, " or", x2)
Output
Enter the coefficients a: 5
Enter the coefficients b: 1
Enter the coefficients c: 2
This equation has two solutions: (-0.1+0.6244997998398398j) or (-0.1-0.6244997998398398j)
4. Merge sort
Merge sort works as follows:
a. Divide the unsorted list into n sub lists, each containing 1 element (a list of 1 element is
considered sorted).
b. Repeatedly merge sub lists to produce new sorted sub lists until there is only 1 sub list
remaining. This will be the sorted list.
Example
91
Program:
Output
Enter size of list5
Enter list elements21
Enter list elements1
Enter list elements-8
Enter list elements14
Enter list elements18
Unsorted list is [21, 1, -8, 14, 18]
Sorted list using merge sort is [-8, 1, 14, 18, 21]
92
5. LIST
o List is a sequence of values, which can be of different types. The values in list are called
"elements" or ''items''
o Each elements in list is assigned a number called "position" or "index"
o A list that contains no elements is called an empty list. They are created with empty
brackets[]
o A list within another list is nested list
Creating a list :
The simplest way to create a new list is to enclose the elements in square brackets ([])
[10,20,30,40]
[100, "python" , 8.02]
1. LIST OPERATIONS:
1. Concatenation of list
2. Repetition of list
93
a= [5,10,50,100]
b=a
b[0] = 80
print ("original list", a) = [5,10,50,100]
print ("Aliasing list", b) = [80,5,10,50,100]
• Here both a & b refers to the same list. Thus, any change made with one object will affect other,
since they are mutable objects.
• in general, it is safer to avoid aliasing when we are working with mutable objects
5. Cloning:
• Cloning creates a new list with same values under another name. Taking any slice of list create
new list.
• Any change made with one object will not affect others. the easiest way to clone a new list is to
use "slice operators"
a = [5,10,50,100]
b= a[ : ]
b[0] = 80
Print (" original list", a) = [5,10,50,100]
Print (" cloning list", b) = [5,10,50,100]
List parameter:
• List can be passed as arguments to functions the list arguments are always passed by reference
only.
• Hence, if the functions modifies the list the caller also changes.
Eq: def head ():
del t[ 0 ]
>>> letters = ['a','b','c']
>>> head (letters)
>>> letters
['b','c']
In above,
The parameters 't' and the variable 'letters' or aliases for the same objects
An alternative way to write a function that creates and return a new list
Eq: def tail (t):
return t [1:]
>>> letters = ['a','b','c']
>>> result = tail (letters)
>>> result
['b','c']
In above,
The function leaves the original list unmodified and return all element in list except first element
94
6. TUPLES:
A tuple is a sequence of value which can be of any type and they are indexed by integers.
Values in tuple are enclosed in parentheses and separated by comma. The elements in the tuple cannot
be modified as in list (i.e) tuple are immutable objects
Creating tuple:
Tuple can be created by enclosing the element in parentheses separated by comma
t = ('a','b','c','d')
To create a tuple with a single element we have to include a final comma
>>> t = 'a',
>>> type (t)
< class 'tuple'>
Alternative way to create a tuple is the built-in function tuple which mean, it creates an empty tuple
>>> t = tuple ()
>>> t
>>> ( )
Accessing element in tuple:
If the argument in sequence, the result is a tuple with the elements of sequence.
>>>t= tuple('python')
>>> t
('p','y','t','h','o','n')
t = ('a','b',100,8.02)
print (t[0]) = 'a'
print (t[1:3]) = ('b', 100 , 8.02)
95
7. Histogram
histogram([2, 3, 6, 5])
96
2. What is dictionary?
A dictionary is an unordered set of key: value pair. In a list, the indices have to be integers; in a
dictionary they can be any type. A dictionary contains a collection of indices, which are called keys, and
a collection of values. Each key is associated with a single value. The association of a key and a value is
called a key-value pair. Dictionary is created by enclosing with curly braces {}.
Eg:
>>>
dictionary={"RollNo":101,2:(1,2,3),"Name":"Ramesh",20:20.50,Loc":['Chennai']}
>>> dictionary
{'Name':'Ramesh', 'Loc':['Chennai'], 2:(1,2.3), 20: 20.0, 'RollNo': 101}
97
4. What is data structure? List out the data structures used in Python
A data structure is a particular way of organizing and storing data in a computer so that it can be
accessed and modified efficiently.
Python data structures:-
1. List
2. Tuples
3. Dictionary
append() extend()
>>>a=[10,20,30] >>>a=[10,20,30]
>>>b=[40,50] >>>b=[40,50]
>>>a.append(b) >>>a.extend(b)
>>>print(a) >>>print(a)
[10,20,30,[40,50]] [10,20,30,40,50]
98
99
100
UNIT V
FILES, MODULES, PACKAGES
File Operation:
Open a file
Reading a file
Writing a file
Closing a file
101
1. Open ( ) function:
• Pythons built in open function to get a file object.
• The open function opens a file.
• It returns a something called a file object.
• File objects can turn methods and attributes that can be used to collect
Syntax:
file_object=open(“file_name” , ”mode”)
Example:
fp=open(“a.txt”,”r”)
Create a text file
fp=open (“text.txt”,”w”)
2. Read ( ) function
Read functions contains different methods
• read() – return one big string
• readline() – return one line at a time
• readlines() – return a list of lines
Syntax:
file_name.read ()
Example:
fp=open(“a.txt”,”w”)
print(fp.read())
print(fp.read(6))
print (fp.readline())
print (fp.readline(3))
print (fp.readlines())
a.txt
102
4. Close ( ) function
It is used to close the file.
Syntax:
File name.close()
Example:
fp=open(“a.txt”,”w”)
fp.write(“this file is a.txt”)
fp.write(“to add more lines”)
fp.close()
103
2. Write a program for one file content copy into another file:
source=open(“a.txt”,”r”)
destination=open(“b.txt”,”w”)
for line in source:
destination.write(line)
source. close()
destination.close()
Output:
Input a.txt Output b.txt
A file stores related data, information, A file stores related data, information,
settings or commands in secondary storage settings or commands in secondary storage
device like magnetic disk, magnetic tape, device like magnetic disk, magnetic tape,
optical disk, flash memory optical disk, flash memory
3. Write a program to count number of lines, words and characters in a text file:
fp = open(“a.txt”,”r”)
line =0
word = 0
character = 0
for line in fp:
words = line . split ( )
line = line + 1
word = word + len(words)
character = character +len(line)
print(“Number of line”, line)
print(“Number of words”, word)
print(“Number of character”, character)
Output:
Number of line=5
Number of words=15
Number of character=47
104
4. ERRORS,EXCEPTION HANDLING
Errors
• Error is a mistake in python also referred as bugs .they are almost always the fault of
the programmer.
• The process of finding and eliminating errors is called debugging
Types of errors
o Syntax error or compile time error
o Run time error
o Logical error
Syntax errors
• Syntax errors are the errors which are displayed when the programmer do mistakes
when writing a program, when a program has syntax errors it will not get executed
Leaving out a keyword
Leaving out a symbol, such as colon, comma, brackets
Misspelling a keyword
Incorrect indentation
Runtime errors
• If a program is syntactically correct-that is ,free of syntax errors-it will be run by
the python interpreter
• However, the program may exit unexpectedly during execution if it encounters a
runtime error.
• When a program has runtime error it will get executed but it will not produce output
Division by zero
Performing an operation on incompatible types
Using an identifier which has not been defined
Trying to access a file which doesn’t exit
Logical errors
• Logical errors are the most difficult to fix
• They occur when the program runs without crashing but produces incorrect result
Using the wrong variable name
Indenting a blocks to the wrong level
Using integer division instead of floating point division
Getting operator precedence wrong
Exception handling
Exceptions
• An exception is an error that happens during execution of a program. When that Error
occurs
Errors in python
• IO Error-If the file cannot be opened.
• Import Error -If python cannot find the module
• Value Error -Raised when a built-in operation or function receives an argument that
has the right type but an inappropriate value
• Keyboard Interrupt -Raised when the user hits the interrupt
• EOF Error -Raised when one of the built-in functions (input() or raw_input()) hits an
end-of-file condition (EOF) without reading any data
105
Example:
X=int(input(“Enter the value of X”))
Y=int(input(“Enter the value of Y”))
try:
result = X / ( X – Y )
print(“result=”.result)
except ZeroDivisionError:
print(“Division by Zero”)
Output:1 Output : 2
Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 10
Result = 2 Division by Zero
106
Example
X=int(input(“Enter the value of X”))
Y=int(input(“Enter the value of y”))
try:
sum = X + Y
divide = X / Y
print (“ Sum of %d and %d = %d”, %(X,Y,sum))
print (“ Division of %d and %d = %d”, %(X,Y,divide))
except NameError:
print(“ The input must be number”)
except ZeroDivisionError:
print(“Division by Zero”)
3. Try –Except-Else
o The else part will be executed only if the try block does not raise the exception.
o Python will try to process all the statements inside try block. If value error occur,
the flow of control will immediately pass to the except block and remaining
statements in try block will be skipped.
Syntax:
try:
statements
except:
statements
else:
statements
Example
X=int(input(“Enter the value of X”))
Y=int(input(“Enter the value of Y”))
try:
result = X / ( X – Y )
except ZeroDivisionError:
print(“Division by Zero”)
else:
print(“result=”.result)
Output:1 Output : 2
Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 10
Result = 2 Division by Zero
107
4. Raise statement
• The raise statement allows the programmer to force a specified exception to occur.
Example:
>>> raise NameError('HiThere')
Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere
If you need to determine whether an exception was raised but don’t intend to handle
it, a simpler form of the raise statement allows you to re-raise the exception:
Example
try:
... raise NameError('HiThere')
... except NameError:
... print('An exception flew by!')
... raise
Output:
An exception flew by! Traceback
(most recent call last):
File "<stdin>", line 2, in <module>
NameError: HiThere
5. Try –Except-Finally
A finally clause is always executed before leaving the try statement, whether an
exception has occurred or not.
The finally clause is also executed “on the way out” when any other clause of the
try statement is left via a break, continue or return statement.
Syntax
try:
statements
except:
statements
finally:
statements
Example
X=int(input(“Enter the value of X”))
Y=int(input(“Enter the value of Y”))
try:
result = X / ( X – Y )
except Zero DivisionError:
print(“Division by Zero”)
else:
print(“result=”.result)
finally:
print (“executing finally clause”)
Output:1 Output : 2
Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 10
Result = 2 Division by Zero
executing finally clause executing finally clause
108
5. MODULES IN PYTHON
• A python module is a file that consists of python definition and statements. A module
can define functions, classes and variables.
• It allows us to logically arrange related code and makes the code easier to understand
and use.
1. Import statement:
• An import statement is used to import python module in some python source file.
Syntax: import module1 [, module2 […module]]
Example:
>>>import math
>>>print (math.pi)
3.14159265
109
Output:
The result is 7
The result is 8.2
The result is ab
The result is yonaalex
Welcome, fleming
4. from……import statement:
5. OS Module
110
6. Sys Module
111
6. PACKAGES IN PYTHON
A package is a collection of python module. Module is a single python file containing
function definitions
A package is a directory(folder)of python module containing an additional init py
file, to differentiate a package from a directory
Packages can be nested to any depth, provided that the corresponding directories
contain their own init py file.
init py file is a directory indicates to the python interpreter that the directory
should be treated like a python package init py is used to initialize the python
package
Steps to Create a Package
Step1: create the package directory
Create the directory (folder)and give it your packages name
Here the package name is calculator
Name Data modified Type
1. pycache 05-12-2017 File folder
2.calculater 08-12-2017 File folder
3. DLLs 10-12-2017 File folder
Step2: write module for calculator directory add save the module in calculator directory
Here four module have create for calculator directory
112
Output :
>>> 15
5
50
2
113
114
7. Write a program to add some content to existing file without effecting the existing content.
file=open(“newfile.txt”,’a)
file.write(“hello”)
newfile.txt newfile.txt(after updating)
Hello!!World!!! Hello!!!World!!!hello
8. What is package?
• A package is a collection of python module. Module is a single python file containing function
definitions
• A package is a directory(folder)of python module containing an additional init py file, to
differentiate a package from a directory
• Packages can be nested to anydepth, provided that the corresponding directories contain their
own __init py file
9. What is module?
A python module is a file that consists of python definition and statements. A module can
define functions, classes and variables.
makes the code easier to understand and use.
Output:
C:\\Users\\Mano\\Desktop
115
116