21cs15it Python
21cs15it Python
COURSE OBJECTIVES:
To be familiar with the basics of algorithmic problem solving.
To construct python programs with conditionals, loops and functions.
To use python data structures-Lists, Tuples and Dictionaries.
PREREQUISITE:
Basic Mathematics Skills and Computer Knowledge
COURSE OUTCOMES:
Blooms
CO. No. Course Outcomes level
At the end of the course students will be able to
C105. 1 Develop algorithmic solutions to simple computational K3
problems
C105. 2 Construct simple Python programs for solving problems. K3
C105. 3 Build Python programs with conditionals and loops. K3
C105. 4 Demonstrate a Python program into functions. K2
Show compound data using Python lists, tuples, and
C105. 5 dictionaries. K2
C105. 6 Read and write data from/to files in Python Programs. K3
COURSE OUTCOMES MAPPING WITH PROGRAM OUTCOMES AND PROGRAM SPECIFIC OUTCOMES
CO No. PO-1 PO-2 PO-3 PO-4 PO-5 PO-6 PO-7 PO-8 PO-9 PO-10 PO-11 PO-12 PSO-1 PSO-2
C105. 1 3 2 1 - - - - - - - - - 2 2
C105. 2 3 2 1 - - - - - - - - - 2 2
C105. 3 3 2 1 - - - - - - - - - 2 2
C105. 4 3 2 1 - - - - - - - - - 2 2
C105. 5 3 2 1 - - - - - - - - - 2 2
C105. 6 3 2 1 - - - - - - - - - 2 2
C105 3 2 1 - - - - - - - - - 2 2
Note: 1: Slight, 2: Moderate, 3: Substantial
1
SYLLABUS No. of Credits: 4
UNIT- I ALGORITHMIC PROBLEM SOLVING AND BASICS OF PYTHON 8
Algorithms-building blocks of algorithms (statements, state, control flow, functions), simple
Strategies for developing algorithms (iteration, recursion)-pseudo code- flow chart-programming
language. Introduction to Python-Features of Python-Python Interpreter: Interactive and script
mode- Values and types, variables, Keywords, Identifiers, operators, precedence of operators,
expression, Comments.
Lists- list operations, list methods, list loop, mutability, aliasing, cloning lists-Tuples-Tuple
assignment, Operations on Tuples, Tuple as return value- Dictionaries- operations and methods-
Sets-Operations on sets.
Total: 60 Periods
2
LEARNING RESOURCES:
TEXT BOOKS:
1. Reema Thareja, “Python Programming using Problem Solving Approach”, OXFORD
University Press, 2017.
2. Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition,
Updated for Python 3, Shroff/O‘Reilly Publishers, 2016.
REFERENCES:
1. Ashok Namdev Kamthane, Amit Ashok Kamthane, “Programming and Problem Solving with
Python”, Mc-Graw Hill Education, 2018.
2. Robert Sedgewick, Kevin Wayne, Robert Dondero, “Introduction to Programming in Python:
An Inter-disciplinary Approach, Pearson India Education Services Pvt. Ltd, 2016.
3. Kenneth A. Lambert, “Fundamentals of Python: First Programs”, CENGAGE Learning, 2012.
Required numbers
Sl. No. Description of Equipment (For batch of 30 students)
3
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
UNIT- I
ALGORITHMIC PROBLEM SOLVING AND BASICS OF PYTHON 8
ALGORITHM
Properties of Algorithms
Should be written in simple English
Each and every instruction should be precise and unambiguous.
Instructions in an algorithm should not be repeated infinitely.
Algorithm should conclude after a finite number of steps.
Should have an endpoint
Derived results should be obtained only after the algorithm terminates.
Qualities of a good algorithm
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.
Example:
Example
Write an algorithm to print “PSPP”
Step 1: Start
Step 2: Print “PSPP”
Step 3: Stop
Algorithmic problem solving is solving problem that require the formulation of an algorithm for the solution. Algorithmic
problem solving means solving the problem by means of algorithm.
Understanding the Problem
The problem given should be understood completely. Check if it is similar to some standard
problems & if a Known algorithm exists. Otherwise a new algorithm has to be developed It is
the process of finding the input of the problem that the algorithm solves.
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
1
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
2. State:
Transition from one process to another process under specified condition with in a
time is called state. State is the information that the program manipulates to accomplish
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
2
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
some task. It is data or information that gets changed or manipulated throughout the runtime
of a program. The state of an algorithm is defined as its condition regarding stored data.
Example: state refers to the set of variables and the values to which they refer.
3. Control flow:
The process of executing the individual statements in a given order is called control flow.
Control flow is the order that instructions are executed in a program .A control statement is a
statement that determines the control flow of a set of instructions
The control can be executed in three ways
1. sequence
2. selection
3. Iteration
Sequence:
All the instructions are executed one after another is called sequence execution.
Pseudo code Flowchart
BEGIN
statement
Statement Action1
END
Action2
Example:
Step 1: Start
Step 2: Get x,y
Step 3: Calculate sum=x+y
Step 4: Display sum
Step 5: Stop
Selection:
It is provided by a control statement that selectively executes instructions. The selection
structure allows the programs to make a choice between two alternate paths, whether it is true
or false. These statements are known as conditional or decision making or selection
statements or branching statements.
Iteration:
Iteration is a process of executing the set of instructions repeatedly till the condition in
iteration statement becomes false. The iteration statement includes the initialization,
comparison, execution of the statements inside the iteration statement and finally the updating
of the control variable. After the control variable is updated it is compared again, and the
process repeats itself, till the condition in iteration statement turns out to be false.
4. Functions:
Function is a sub program which consists of block of code(set of instructions) that
performs a particular task.
For complex problems, the problem is been divided into smaller and simpler
tasks during algorithm design.
Benefits of Using Functions
Reduction in line of code
code reuse
Better readability
Information hiding
Easy to debug and test
Improved maintainability
Example:
Function: piece of prewritten code that performs an operation
print function: displays output on the screen
Argument: data given to a function
Example: data that is printed to screen
Types of functions/categories of functions:
Pre-defined functions-built in functions provided by programming languages Example: print() in
python
User-defined functions-created by user. Example fact()
Pseudo code:
BEGIN BEGINPROCEDURE
CALLPROCEDURE statement1
END statement2
END PROCEDURE
SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS:
The following strategies are used for developing algorithms:
Iteration:
Iteration is a process of executing the set of instructions repeatedly till the condition in
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
4
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
iteration statement becomes false. The iteration statement includes the initialization,
comparison, execution of the statements inside the iteration statement and finally the
updating of the control variable. After the control variable is updated it is compared again,
and the process repeats itself, till the condition in iteration statement turns out to be false.
1. for loop
2. While loop
Advantages:
The iteration statement does not use a stack to store the variables. Hence, the execution
of the iteration statement is faster as compared to recursive function.
Even the iteration function does not have the overhead of repeated function calling which
also make its execution faster than recursive function.
Disadvantages:
The iteration is terminated when the control condition becomes false. The absence of
control condition in iteration statement may result in an infinite loop, or it may cause a
compilation error.
Example:
Problem: To find the factorial of a number (using While loop)
Description: factorial of a number n!=n*(n-1)! Where n is the number for which factorial
is to be calculated
Solution: The algorithm, pseudo code and flowchart are as follows:
Algorithm
step 1. Start
step 2. Read the number n step 3. Initialize i=1,
fact=1
step 4. Repeat step 4 through 6 until i<=n
step 5. fact =fact*i
step 6. i=i+1 step 7. Print fact step
8. Stop
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 been satisfied.
Recursion is a programming technique that comes from recurrence relation, where
the problem is divided further in sub problems smaller in size but same in nature.
This division stops when the problem cannot be divided further.
This point is called base case from where control moves back towards the original
problem by solving sub problems and assembling results in order to get the final
result.
Advantages: The main advantage recursion provides to programmers is that it takes less code
to write comparative to iterative version. The code written with help of recursion is more
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
5
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
There are some data structures you will see which are quite easy to code with help of recursion.
Tree traversals, quick, and merge sort are a few examples.
Disadvantages: Recursion provides no storage saving, nor time.
PSEUDO CODE
Pseudo code derived from ‘pseudo’ which means imitation and ‘code’ means instruction
is a generic way of describing an algorithm without using any specific programming language
related notations. Pseudo code is an artificial and informal language that helps programmers to
develop algorithms. Pseudo code can be defined as the narrative description of the flow and
logic of the intended program, written in plain language that expresses each step of the
algorithm. The pseudo code is also called as Program design language (PDL)
Characteristics/properties of Pseudo code:
statement 2
END‐IF
While: WHILE condition
statements
END‐WHILE
For: FOR condition
statements
ND‐WHILE
For: FOR condition
statements
END‐FOR
for subprogram BEGIN SUBPROGRAM, END
FLOW
CHART
SUBPROGRAM,BEGIN PROCEDURE,END PROCEDURE
Flow chart is defined as graphical representation of the logic for problem solving. The
purpose of flowchart is making the logic of the program clear in a visual
representation.
4. Only one flow line should enter a decision symbol. However, two or three
flow lines may leave the decision symbol.
Advantages of flowchart:
1. Communication: - Flowcharts are better way of communicating the logic of a
system to all concerned.
2. Effective analysis: - With the help of flowchart, problem can be analyzed in
more effective way.
3. Proper documentation: -Program flowcharts serve as a good
program documentation, which is needed for various purposes.
4. Efficient Coding: - The flowcharts act as a guide or blueprint during the
systems analysis and program development phase.
5. Proper Debugging: - The flowchart helps in debugging process.
6. Efficient Program Maintenance: - The maintenance of operating program
becomes easy with the help of flowchart. It helps the programmer to put efforts
more efficiently on that part.
Disadvantages of flow chart:
2. Complex logic: - Sometimes, the program logic is quite complicated. In that
case, flowchart becomes complex and clumsy.
3. Alterations and Modifications: - If alterations are required the flowchart may
require re-drawing completely.
4. Reproduction: - As the flowchart symbols cannot be typed, reproduction of
flowchart becomes a problem.
5. Cost: For large application the time and cost of flowchart drawing becomes
costly.
PROGRAMMING LANGUAGE
Compiler:
A compiler is a program which translates the source code written in a high level
language in to object code which is in machine language program. Compiler reads the
whole program written in high level language and translates it to machine language. If
any error is found it display error message on the screen.
Examples: C and C++ compilers.
INTRODUCTION TO PYTHON
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language.
It was created by Guido van Rossum during 1985- 1990.
Python got its name from “Monty Python’s flying circus”. Python was released in the year
2000.
Python is interpreted: Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it.
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
9
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
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.
PythonisaBeginner'sLanguage:Pythonisagreatlanguageforthebeginner-
level programmers and supports the development of a wide range of
applications.
1.1. 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++,Java script
,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.
1.2. Applications:
Bit Torrent file sharing
Google search engine, You tube
Intel, Cisco, HP,IBM
i–Robot
NASA
Face book, Drop box
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
Interpreter Takes Single instruction as
Compiler Takes Entire program as input
input
No Intermediate Object Code
Intermediate Object Code is Generated
is Generated
Conditional Control Statements are Conditional Control Statements are
Executes faster Executes slower
2.Script mode:
Script mode is where you write your code in a . py file and then run it with the python
command. This is the most common way that people use Python because it lets you write and
save your code so that you can use it again later.
2.1
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,
2.2 Sequence:
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
11
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
2.2.2 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 data types.
2.2.4 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.
Tuple can be used as keys in dictionaries, while lists can't.
Mapping
-This data type is unordered and mutable.
-Dictionaries fall under Mappings.
2.3.1 Dictionaries:
Lists are ordered sets of objects, whereas dictionaries are unordered sets.
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
12
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
Value:
Value can be any letter ,number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different data types.)
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:
3.3 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 (_).
3.6 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 anhour
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.
3.7 DOCSTRING:
Doc string 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 doc string.
Triple quotes are used while writing doc strings.
Syntax:
function name__ doc.__
Python has a very powerful tuple assignment feature that allows a tuple of variables
on the left of an assignment to be assigned values from a tuple on the right of the
assignment.
The left side is a tuple of variables; the right side is a tuple of values.
Each value is assigned to its respective variable.
All the expressions on the right side are evaluated before any of the assignments. This
feature makes tuple assignment quite versatile.
Naturally, the number of variables on the left and the number of values on the right
have to be the same.
>>>(a, b, c, d) = (1, 2, 3)
Value error: need more than 3 values to unpack
-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:
-The right side can be any kind of sequence (string, list, tuple)
Example:
-To split an email address in to user name and a domain
>>>maili d='[email protected]'
>>>name, domain=mail id. split('@')
>>>print name
god
>>> print (domain) abc.org
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
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
15
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
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
% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder
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) a%b=0
print("a/b=",a/b) a//b=2
print("a%b=",a%b) a**b= 100000
print("a//b=",a//b)
print("a**b=",a**b)
!= If values of two operands are not equal, then condition becomes (a!=b) is
true. true
> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.
< If the value of left operand is less than the value of right operand, (a < b) is
then condition becomes true. true.
>= If the value of left operand is greater than or equal to the value (a >= b) is
of right operand, then condition becomes true. not true.
<= If the value of left operand is less than or equal to the value of (a <= b) is
right operand, then condition becomes true. true.
Example
a=10 Output:
b=5 print("a>b=>",a>b) a>b=> True
print("a>b=>",a<b) a>b=> False
print("a==b=>",a==b) a==b=> False
print("a!=b=>",a!=b) a!=b=> True
print("a>=b=>",a<=b) a>=b=> False
print("a>=b=>",a>=b) a>=b=> True
+= Add AND It adds right operand to the left operand and assign the c += a is
result to left operand equivalent
to c = c + a
-= Subtract It subtracts right operand from the left operand and assign c -= a is
AND the result to left operand equivalent
to c = c -a
/= Divide It divides left operand with the right operand and assign c /= a is
AND the result 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 c %= a is
AND to left operand equivalent
to c = c % a
//= Floor It performs floor division on operators and assign value to c //= a is
Division the left 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
c=0 Line 3 - Value of c is 1092
c=a+b Line 4 - Value of c is 52.0
print("Line 1 - Value of c is ",c) Line 5 - Value of c is2
c += a Line 6 - Value of c is 2097152
print("Line 2 - Value of c is ", c) Line 7 - Value of c is99864
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)
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)
Example Output
a=60 # 60 = 00111100 Line 1 - Value of c is 12
b =13 # 13 = 00001101 Line 2 - Value of c is 61
c=0 Line 3 - Value of c is 49
c = a& b; # 12 = 00001100 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
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
Evaluates to find a value or a variable is in the specified sequence of string, list, tuple,
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
20
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
dictionary or not.
Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in operators are
used.
Example:
x=[5,3,6,4,1]
>>>5 in x
True
>>>5 not in x
False
Example
x =5 Output
y =5 False
x2 = 'Hello' True
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
OPERATOR PRECEDENCE
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description
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 m=-43||8&&0||-2
a=9-4+6-1 A=6+4-1+6 m=-43||0||-2
a=5+6-1 A=10-1+6 m=1||-2
a=11-1 a=10 A=9+6 m=1
A=15
a=2,b=12,c=1 a=2*3+4%5-3//2+6
d=a<b>c a=2,b=12,c=1 a=6+4-1+6
d=2<12>1 d=a<b>c-1 a=10-1+6
d=1>1 d=2<12>1-1 a=15
d=0 d=2<12>0
d=1>0
d=1
PROGRAM
a=532
b=42.5
c=True
d=10+5j
e="Hello"
f=[1,2,3,4,5]
g=(1,2,3,4,5)
h={1,2,3,4,5}
i={"Eng":45,"Mat":52,"Sci":53}
print("a:",a ,type(a))
print("b:",b ,type(b))
print("c:",c ,type(c))
print("d:",d ,type(d))
print("e:",e ,type(e))
print("f:",f ,type(f))
print("g:",g ,type(g))
print("h:",h ,type(h))
print("i:",i ,type(i))
OUTPUT
UNIT II
1) Conditional Statements
we have to control the flow of execution of our program and we want to execute some
set of statements only if the given condition is satisfied, and a different set of
statements when it’s not satisfied.Conditional statements are also known as decision-
making statements. We need to use these conditional statements to execute the specific
block of code if the given condition is true or false.
• 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:
if(condition 1):
statement 1
Flowchart:
EXAMPLE:
1
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
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:
if(condition 1):
statement 1
else:
statement 2
Flowchart:
Examples:
1. odd or even number
2. positive or negative number
2
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
print("leap year")
else:
print("not leap year")
3. leap year or not
The elif is short for else if. This is used to check more than one condition. 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:
if(condition 1):
statement 1
elif(condition 2):
statement 2
elif(condition 3):
statement 3
else:
default statement
Flowchart:
Example:
1. student mark system
2. traffic light system
3
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
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
if(condition ):
if (condition 1):
statement 1
else:
statement 2
else:
statement 3
Flowchart:
4
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
Example:
1. greatest of three numbers
2. positive negative or zero
greatest of three numbers output
5
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
state
while
for
break
continue
pass
State:
Transition from one process to another process under specified condition with in a time is called
state.
while:
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:
initial value
while (condition):
body of while loop
increment
flowchart:
Examples:
program to find sum of n numbers:
program to find factorial of a number
program to find sum of digits of a number:
Program to Reverse the given number:
Program to find number is Armstrong number or not
Program to check the number is palindrome or not
program to find sum of n numbers output
n=eval(input("enter n")) enter n
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
6
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
i=1 10
sum=0 55
while(i<=n):
sum=sum+i
i=i+1
print(sum)
program to find factorial of a number output
n=eval(input("enter n")) enter n
i=1 5
fact=1 120
while(i<=n):
fact=fact*i
i=i+1
print(fact)
program to find sum of digits of a number output
n=eval(input("enter a number")) enter a number
sum=0 123
while(n>0): 6
a=n%10
sum=sum+a
n=n//10
print(sum)
Program to Reverse the given number output
n=eval(input("enter a number")) enter a number
sum=0 123
while(n>0): 321
a=n%10
sum=sum*10+a
n=n//10
print(sum)
Program to find number is Armstrong number or not output
7
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
sum=sum*10+a
n=n//10
if(sum==org):
print("The given no is palindrome")
else:
print("The given no is not palindrome")
For loop:
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.
for i in sequence:
print (i)
Sequence can be a list, strings or tuples
8
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
R
1. For loop in string for i in "Ramu": print(i)
A
M
U
2
2. For loop in list for i in [2,3,5,6,9]: print(i)
3
5
6
9
Examples:
Fibonacci Series:
01
9
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
for i in range(2,n):
if(n%i==0):
break
else:
output:
enter a no:7
BREAK
Flowchart
10
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
Example:
for i in "welcome":
if(i=="c"):
break
print(i)
output:
CONTINUE
It terminates the current iteration and transfer the control to the next iteration in the loop.
Syntax:
Continue
Flowchart
11
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
Example:
for i in "welcome":if(i=="c"):
continueprint(i)
Output
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.
Syntax:
Pass
Break
EXAMPLE
for i in “welcome”:
if(i==“c”):
pass
print(i)
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
12
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
OUTPUT:
w
E
L
C
O
M
E
Difference between break and continue
It terminates the current loop It terminates the current iteration
and executes the remaining and transfer the control to the
statement outside the loop. next iteration in the loop.
Syntax Syntax
break continue
for i in welcome": for i in "welcome":
if(i=="c"): if(i=="c"):
break continue
print(i) print(i)
w we
e lo
l m
e
If else statement is used in for loop, the else statement is executed when the loop has reached
the limit. The statements inside for loop and statements inside else will also execute.
Example
For i in range(1,6):
Print (i)
Else:
Output
1
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
13
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
If else statement is used within while loop , the else part will be executed when the condition
become false. The statements inside for loop and statements inside else will also execute.
Example:
i=1
while(i<=5):
print(i)
i=i+1
else:
5
the number greater than 5
14
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
FUNCTION:
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.
When the program is too complex and large they are divided into parts. Each part is
separatelycoded and combined into single program. Each subprogram is called as function.
Debugging, Testing and maintenance becomes easy when the program is divided into
subprograms.
Functions are used to avoid rewriting same code again and again in a program.
Types of function:
Built in functions are the functions that are already created and stored in python.
These built in functions are always available for usage and accessed by a programmer. It
cannot be modified.
15
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
User defined functions are the functions that programmers create for their requirement and
use.
These functions can then be combined to form module which can be used in other programs
byimporting them.
Advantages of user defined functions:
Programmers working on large project can divide the workload by making different
functions.
If repeated code occurs in a program, function can be used to include those codes and execute
when needed by calling that function.
16
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
EXAMPLE:
def my_add(a,b):
c=a+b
return c
Function Calling: (Main Function)
Once we have defined a function, we can call it from another function, program or
even the Pythonprompt.
To call a function we simply type the function name with appropriate arguments.
Example:
x=5 y=4
my_add(x,y)
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:
17
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
Parameters:
Parameters are the value(s) provided in the parenthesis when we write function
header.
These are the values required by function to work.
If there is more than one value required, all of them will be listed in parameter list
separated by
comma.
Example: defmy_add(a,b):
Arguments :
18
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
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]
Example:
ARGUMENT TYPES:
Required Arguments
Keyword Arguments
Default Arguments
Variable length Arguments
Required Arguments :
The number of arguments in the function call should match exactly with the function
definition.
defmy_details( name, age ):
print("Name: ", name)
print("Age ", age)
return my_details("george",56)
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.
Output:
Name: georgeAge56
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
19
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
Default Arguments:
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
def my_details(*name ):
print(*name)
my_details("rajan","rahul","micheal", ärjun")
Output:
rajanrahulmichealärjun
Fruitful Function:
Fruitful Function:
Void function
Return values
Parameters
Local and global scope
Function composition
Recursion
Fruitful Function:
A function that returns a value is called fruitful function.
Example:
Root=sqrt (25)
Example:
def add():
a=10
b=20
c=a+b
return c
c=add()
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
20
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
print(c)
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
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:
a=50
Local Scope
A variable with local scope can be used only within the function .
EXAMPLE:
def add():
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
21
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
b=20
c=a+b
print©
def sub():
b=30
c=a-b
print©
print(a)
print(b)
OUTPUT:
70
20
error
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.
EXAMPLE:
find sum and average using function output composition
def sum(a,b):
sum=a+b return sum
def avg(sum):
avg=sum/2 return avg
a=eval(input("enter a:"))
b=eval(input("enter b:"))
sum=sum(a,b) avg=avg(sum)
print("the avg is",avg)
OUTPUT:
enter a:4
enter b:8
the avg is 6.0
Recursion
A function calling itself till it reaches the base value - stop point of function call.
Example: factorial of a given number using recursion.
EXAMPLE:
FACTORIAL PROGRAM
def fact(n):
if(n==1):
return 1
else:
return n*fact(n-1)
n=eval(input("enter no. to find fact:"))
fact=fact(n)
print("Fact is",fact)
OUTPUT:
enter no. to find fact:5
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
22
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
Fact is 120.
EXPLANATION:
LAMBDA FUNCTIONS
A function is said to be anonymous function when it is defined without a name and def
keyword A lambda function evaluates an expression for a given argument. You give the
function a value
(argument) and then provide the operation (expression). The keyword lambda must come
first. A fullcolon (:) separates the argument and the expression.
#Normal python
function def a_name(x):
return x+x
Example 1: #Lambda
function lambda x: x+x
Example 2:
a=lambda b: b*2+b print(a(3))
Advantages:
Good for simple logical operations that are easy to understand. This makes the code more
readable too.
Good when you want a function that you will use just one time.
Disadvantages:
They can only perform one expression. It’s not possible to have multiple independent
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
23
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
Bad because you can’t write a doc-string to explain all the inputs, operations, and
outputs as you would in a normal def function.
Scalar values
This is when you execute a lambda function on a single value. (lambda x: x*2)(12)
###Results 24
Filter(). This is a Python inbuilt library that returns only those values that fit certain criteria.
The syntax is filter(function, iterable).
list_1 = [1,2,3,4,5,6,7,8,9]
list(filter(lambda x: x%2==0, list_1))
###Results[2, 4, 6, 8]
Map( ). This is another inbuilt python library with the syntax map(function, iterable). This
returns a modified list where every value in the original list has been changed based on a
function.
list_1 = [1,2,3,4,5,6,7,8,9]
cubed = map(lambda x: pow(x,3),list_1)
list(cubed) ###Results
[1, 8, 27, 64, 125, 216, 343, 512, 729]
Program:
a=int(input ("Enter the number:"))
if a%2==0:
print("The given number is even")
else:
print("The given number is odd")
Output:
24
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
Programs:
a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
c=int(input("Enter the value of c:"))
if(a>b):
if(a>c):
print("The greatest number is",a)
else:
print("The greatest number is",c)
else:
if(b>c):
print("The greatest number is",b)
else:
print("The greatest number is",c)
Output:
25
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
sum=0
while(n>0):
a=n%10
sum=sum+a*a*a
n=n//10
if(sum==org):
print("The given number is Armstrong ")
else:
print("The given number is not Armstrong")
Output:
Program:
a=0
b=1
n=int(input("Enter the number of terms"))
print("fibonacci series")
print(a,b)
for i in range(1,n,1):
c=a+b
print(c)
a=b
b=c
Output:
write a python program using Function to generate the Factorial of given number.
Program:
def fact(n):
if(n==1):
return 1
else:
return n*fact(n-1)
n=int(input("Enter the number to find Factorial"))
Fact=fact(n)
print("Factorial value is ", Fact)
Output:
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
26
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
Programs:
defgcd(a,b):
if(b==0):
return a
else:
return b
a=int(input("Enter first number:"))
b=int(input("Enter second number: "))
GCD=gcd(a,b)
print("The GCD of a and b is ",GCD )
Output:
Output:
27
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
UNIT-III
MODULES,PACKAGES,STRINGS
Topics:
Modules- Packages- Strings- String Operations, String
Functions And Methods.
MODULES
A module allows to logically organize Python code.
Grouping related code into a module makes the code easier to understand
and use.
A module is a Python object with arbitrarily named attributes that can
bind and reference.
Simply, a module is a file consisting of Python code.
A module can define functions, classes and variables.
A module can also include runnable code.
EXAMPLE:
The Python code for a module named aname normally resides in
a file named aname.py.
Example of a simple module, support.py
defprint_func( parameter ):
print"Hello : ", parameter
return
1
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
Example,
To import the module sample.py, need to put the following command at the top
of the script
#!/usr/bin/python
For example, to import the function factorial from the module fact, use the
following statement –
from fact import factorial
This statement does not import the entire module fact into the current
namespace; it just introduces the item factorial from the module fact into the
global symbol table of the importing module.
from...import * Statement
It is also possible to import all names from a module into the current namespace
by using the following import statement –
2
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.
Locating Modules
To import a module, the Python interpreter searches for the module in the
following sequences −
The current directory.
If the module isn't found, Python then searches each directory in the shell
variable PYTHONPATH.
If all else fails, Python checks the default path. On UNIX, this default
path is normally /usr/local/lib/python/.
The module search path is stored in the system module sys as
the sys.path variable.
The sys.path variable contains the current directory, PYTHONPATH, and
the installation-dependent default.
The PYTHONPATH Variable
The PYTHONPATH is an environment variable, consisting of a list of
directories. The syntax of PYTHONPATH is the same as that of the shell
variable PATH.
PYTHONPATH from a Windows system –
set PYTHONPATH = c:\python20\lib;
Namespaces and Scoping:
Variables are names (identifiers) that map to objects. A namespace is a
dictionary of variable names (keys) and their corresponding objects
(values).
Access variables in a local namespace and in the global namespace. If a
local and a global variable have the same name, the local variable
shadows the global variable.
Each function has its own local namespace. Class methods follow the
same scoping rule as ordinary functions.
Python makes educated guesses on whether variables are local or global.
It assumes that any variable assigned a value in a function is local.
Therefore, in order to assign a value to a global variable within a
function, you must first use the global statement.
The statement global VarName tells Python that VarName is a global
variable. Python stops searching the local namespace for the variable.
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
3
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
number=2000
defAddnumber():
# Uncomment the following line to fix the code:
# globalnumber
Number =number+1
Print number
Addnumber()
Print number
4
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
defdots():
print"I'm dots Phone"
Similar way, another two files having different functions with the same name
as above −
Phone/Isdn.py file having function Isdn()
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
5
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
Phone.dots()
Phone.Isdn()
Phone.G3()
OUTPUT:
I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone
6
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
String in Python
A string is a sequence of characters.
A character is simply a symbol. For example, the English language has 26
characters.
Computers do not deal with characters, they deal with numbers (binary).
Even though characters on user screen, internally it is stored and
manipulated as a combination of 0s and 1s.
This conversion of character to a number is called encoding, and the
reverse prSocess is decoding. ASCII and Unicode are some of the popular
encodings used.
In Python, a string is a sequence of Unicode characters. Unicode was
introduced to include every character in all languages and bring
uniformity in encoding.
How to create a string in Python?
Strings can be created by enclosing characters inside a single quote or
double-quotes.
Even triple quotes can be used in Python but generally used to represent
multiline strings and docstrings.
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
# triple quotes string can extend multiple lines
my_string = """Hello, welcome to
the world of Python"""
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
7
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
print(my_string)
output
Hello
Hello
Hello
Hello, welcome to
the world of Python
The index of -1 refers to the last item, -2 to the second last item and so on.
Access a range of items in a string by using the slicing operator :(colon).
String Function
#Accessing string characters in Python
str = 'programiz'
print('str = ', str)
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
8
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
output:
str = programiz
str[0] = p
str[-1] = z
str[1:5] = rogr
str[5:-2] = am
To access an index out of the range or use numbers other than an integer,
will get errors.
# index must be in range
my_string[15] ...
IndexError: string index out of range
# index must be an integer
my_string[1.5]
...
TypeError: string indices must be integers
To access a range, the index that will slice the portion from the string.
9
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
cannot delete or remove characters from a string. But deleting the string
entirely is possible using the del keyword.
del my_string[1]
...
TypeError: 'str' object doesn't support item deletion
del my_string
my_string
...
NameError: name 'my_string' is not defined
Python String Operations
There are many operations that can be performed with strings which makes it
one of the most used data types in Python.
The ‘+ ‘operator does this in Python. Simply writing two string literals
together also concatenates them.
The * operator can be used to repeat the string for a given number of
times.
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
10
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)
output:
str1 + str2 = HelloWorld!
str1 * 3 = HelloHelloHello
Iterate through a string using a for loop. here is an example to count the number
of 'l's in a string.
STRING LAB EXERCISE
count = 0
if(letter == 'l'):
count += 1
print(count,'letters found')
output:
3 letters found
11
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
test if a substring exists within a string or not, using the keyword in.
Various built-in functions that work with sequence work with strings as
well.
Some of the commonly used ones are enumerate() and len().
The enumerate() function returns an enumerate object.
It contains the index and value of all the items in the string as pairs.
This can be useful for iteration.
Similarly, len() returns the length (number of characters) of the string.
str = 'cold'
# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)
#character count
print('len(str) = ', len(str))
output:
list(enumerate(str) = [(0, 'c'), (1, 'o'), (2, 'l'), (3, 'd')]
len(str) = 4
12
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
Escape Sequence
13
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
\\ Backslash
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
14
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
print("C:\\Python32\\Lib")
C:\Python32\Lib
15
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
print(keyword_order)
output:
--- Default Order ---
Raj,cash and paid
--- Positional Order ---
# formatting floats
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
16
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
# round off
# string alignment
"|{:<10}|{:^10}|{:>10}|".format('butter','bread','ham')
17
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
18
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
19
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
20
UNIT IV
COMPOUND DATA: LISTS, TUPLES, DICTIONARIES
Lists, list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples, tuple assignment, tuple as return value; Dictionaries: operations and
methods; advanced list processing - list comprehension, Illustrative programs: selection
sort, insertion sort, merge sort, Histogram.
Lists
List is a 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 data types.
Eg: a=[10, 20, 30, 40]; b=[10, 20, “abc”, 4.5]
Operations on list:
1. Indexing - accessing the list elements
2. Slicing - accessing the list elements
3. Concatenation -main Operations
4. Repetition - main Operations
5. Updating -updating the list
6. Membership -other operations
7. Comparison -other operations
>>> print(a[0:3])
Slicing [2, 3, 4]
>>> print(a[0:]) Printing a part of the list.
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> print(a[2])
4 Updating the list using
Updating >>> a[2]=100 Index value .
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
>>> a=[2,3,4,5,6,7,8,9,10]
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in list. Otherwise
False returns false.
>>> 2 not in a
False
List slices:
List slicing is an operation that extracts a subset of elements from an list and packages
them as another list.
Syntax:
Listname[start:stop]
Listname[start:stop:steps]
default start value is 0
default stop value is n-1
[:] this will print the entire list
[2:2] this will create a empty slice
slices Example Description
>>> a=[9,8,7,6,5,4]
a[0:3] >>> a[0:3] Printing a part of a list from
[9, 8, 7] 0 to 2.
a[:4] >>> a[:4] Default start value is 0. So
[9, 8, 7, 6] prints from 0 to 3
a[1:] >>> a[1:] Default stop value will be
[8, 7, 6, 5, 4] n-1. so prints from 1 to 5
List methods:
Methods used in lists are used to manipulate the data quickly.
These methods work only on lists.
They do not work on the other sequence types that are not mutable, that is, the values
they contain cannot be changed, added, or deleted.
syntax:
list name.method name( element/index/list)
>>> a.clear()
12 Clear(): list.clear() >>> print(a) Removes all items
[] from the list.
List loops:
1. For loop
2. While loop
Infinite Loop
A loop becomes infinite loop if the condition given never becomes false. It keeps on
running. Such loops are called infinite loop.
Example Output:
a=1 Enter the number 10
while (a==1): you entered:10
n=int(input("enter the number")) Enter the number 12
print("you entered:" , n) you entered:12
Enter the number 16
you entered:16
Program:
size=int(input("Enter the number of elements:"))
lst=[]
print("Enter the elements:")
for i in range(0,size):
lst.append(int(input()))
print("The elements of the list are",lst)
max=lst[0]
for i in range(0,size):
iflst[i]>max:
max=lst[i]
print("The Maximum element is",max)
Output:
Mutability:
Lists are mutable. (can be changed)
Mutability is the ability for certain types of data to be changed without entirely
recreating it.
An item can be changed in a list by accessing it directly as part of the assignment
statement.
Using the indexing operator (square brackets[ ]) on the left side of an assignment, one
of the list items can be updated.
Example description
Example Output:
a= [1, 2, 3 ,4 ,5]
b=a
print (b) [1, 2, 3, 4, 5]
print (a is b) True
a[0]=100
print(a) [100,2,3,4,5]
print(b) [100,2,3,4,5]
In this a single list object is created and modified using the subscript operator.
When the first element of the list named “a” is replaced, the first element of the list
named “b” is also replaced.
This type of change is what is known as a side effect. This happens because after the
assignment b=a, the variables a and b refer to the exact same list object.
They are aliases for the same object. This phenomenon is known as aliasing.
To prevent aliasing, a new object can be created and the contents of the original can be
copied which is called cloning.
Cloning:
To avoid the disadvantages of copying we are using cloning. creating a copy of a same
list of elements with two different memory locations is called cloning.
Changes in one list will not affect locations of another list.
Cloning is a process of making a copy of the list without modifying the original list.
Example:
>>>a=[1,2,3,4,5]
>>>b=a[:] or a.copy()
>>>print(b)
[1,2,3,4,5]
>>>a is b
False
Example Output:
a= [1, 2, 3 ,4 ,5]
b=a.copy()
print (b) [1, 2, 3, 4, 5]
print (a is b) False
a[0]=100
print(a) [100,2,3,4,5]
print(b) [1,2,3,4,5]
List as parameters:
In python, arguments are passed by reference.
If any changes are done in the parameter which refers within the function, then the
changes also reflects back in the calling function.
When a list to a function is passed, the function gets a reference to the list.
Passing a list as an argument actually passes a reference to the list, not a copy of the
list.
Since lists are mutable, changes made to the elements referenced by the parameter
change the same list that the argument is referencing.
Example 2: Output
def inside(a): inside [11, 12, 13, 14, 15]
for i in range(0,len(a),1): outside [11, 12, 13, 14, 15]
a[i]=a[i]+10
print(“inside”,a)
a=[1,2,3,4,5]
inside(a)
print(“outside”,a)
Example 3 Output
def insert(a): [30, 1, 2, 3, 4, 5]
a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)
Tuple:
A tuple is a set of elements separated by commas and enclosed in parentheses.
A tuple is an immutable list. i.e. once a tuple has been created, we can't add elements to
a tuple or remove elements from the tuple.
But tuple can be converted into list and list can be converted in to tuple.
A tuple can also be created without using parentheses.
Methods Example description
list( ) >>> a=(1,2,3,4,5) it converts the given sequence
>>> a=list(a) into list.
>>> print(a)
[1, 2, 3, 4, 5]
it convert the given sequence
tuple( ) >>> a=[1,2,3,4,5] into tuple.
>>> a=tuple(a)
>>> print(a)
(1, 2, 3, 4, 5)
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.
Operations on Tuples:
1. Indexing -accessing tuple elements
2. Slicing -accessing tuple elements
3. Concatenation -main operations
4. Repetition -main operations
5. Membership -other operations
6. Comparison -other operations
Operations examples description
Creating the tuple with
Creating a tuple >>>a=(20,40,60,”apple”,”ball”) elements of different data
types.
>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in tuple. Otherwise
False returns false.
>>> 2 not in a
False
>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4) Returns True if all elements
Comparison
>>> a==b in both elements are same.
False Otherwise returns false
>>> a!=b
True
Tuple methods:
Tuple Assignment:
Tuple assignment allows, variables on the left of an assignment operator and values of
tuple on the right of the assignment operator.
Multiple assignment works by creating a tuple of expressions from the right hand side,
and a tuple of targets from the left, and then matching each expression to a target.
Because multiple assignments use tuples to work, it is often termed tuple assignment.
Multiple assignments:
Example2: Output:
def min_max(a): smallest: 1
small=min(a) biggest: 6
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small)
print("biggest:",big)
Tuple as argument:
The parameter name that begins with * gathers argument into a tuple.
Example: Output:
def printall(*args): (2, 3, 'a')
print(args)
printall(2,3,'a')
tuple_1 =( 2, 4, 5, 6, 2, 3, 4, 4, 7)
print(tuple_1)
count = tuple_1.count(4)
print(count)
Output:
Dictionaries:
Dictionary is a collection of elements. An element in dictionary has a key: value pair.
All elements in dictionary are placed inside the curly braces i.e. { }
Elements in Dictionaries are accessed via keys and not by their position.
The values of a dictionary can be any data type.
Keys must be immutable data type (numbers, strings, tuple)
Operations on dictionary:
1. Accessing an element
2. Update
3. Add element
4. Membership
Operations Example Description
membership a={1: 'ONE', 2: 'two', 3: 'three'} Returns True if the key is present in
>>> 1 in a dictionary. Otherwise returns false.
True
>>> 3 not in a
False
Methods in dictionary:
Copy()
Items()
Keys()
Values()
Pop()
Setdefault()
Update()
Fromkeys()
clear()
get()
popitem()
Syntax Example Description
Can contain duplicate Can contain duplicate elements. Cant contain duplicate
Elements Faster compared to lists keys, but can contain
duplicate values
Slicing can be done Slicing can be done Slicing can't be done
Usage: Usage: Usage:
List is used if a Tuple can be used when data Dictionary is used
collection of data that cannot be changed. when a logical
doesnt need random A tuple is used in combination association between
access. with a dictionary i.e.a tuple might key:value pair.
List is used when represent a key. When in need of fast
data can be modified lookup for data, based
frequently on a custom key.
Dictionary is used
when data is being
constantly modified.
Integrated lab Program
Python program to print a dictionary where the keys are numbers between 1 and 10 and the
valuesare square of keys.
Program:
d=dict()
for x in range(1,11):
d[x]=x**2
print(d)
Output:
Sets in Python:
A set is an unordered collection of items. Every set element is unique (no duplicates) and must be
immutable (cannot be changed).
However, a set itself is mutable. We can add or remove items from it.
Sets can also be used to perform mathematical set operations like union, intersection, symmetric
difference, etc.
Creating Python Sets:
A set is created by placing all the items (elements) inside curly braces {}, separated by comma, or
by using the built-in set() function.
It can have any number of items and they may be of different types (integer, float, tuple, string etc.).
But a set cannot have mutable elements like lists, sets or dictionaries as its elements.
Program 1:
# Different types of sets in Python
# set of integers
my_set = {1, 2, 3}
print(my_set)
# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)
Output:
{1, 2, 3}
{1.0, (1, 2, 3), 'Hello'}
Program 2:
Output:
{1, 2, 3, 4}
{1, 2, 3}
Traceback (most recent call last):
File "<string>", line 15, in <module>
my_set = {1, 2, [3, 4]}
TypeError: unhashable type: 'list'
# initialize a with {}
a = {}
Output:
<class 'dict'>
<class 'set'>
Program 4:
# initialize my_set
my_set = {1, 3}
print(my_set)
#my_set[0]
# if you uncomment the above line
# you will get an error
# TypeError: 'set' object does not support indexing
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
Output:
{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# not present in my_set
# you will get an error.
# Output: KeyError
my_set.remove(2)
Output:
{1, 3, 4, 5, 6}
{1, 3, 5, 6}
{1, 3, 5}
{1, 3, 5}
Traceback (most recent call last):
File "<string>", line 28, in <module>
KeyError: 2
Similarly, we can remove and return an item using the pop() method.
Since set is an unordered data type, there is no way of determining which item will be popped. It is
completely arbitrary.
Program 6:
We can also remove all the items from a set using the clear() method.
# initialize my_set
# Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)
# pop an element
# Output: random element
print(my_set.pop())
# pop another element
my_set.pop()
print(my_set)
# clear my_set
# Output: set()
my_set.clear()
print(my_set)
Output:
Sets can be used to carry out mathematical set operations like union, intersection, difference and
symmetric difference. We can do this with operators or methods.
Let us consider the following two sets for the following operations.
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
Set Union:
Program 7:
Output:
{1, 2, 3, 4, 5, 6, 7, 8}
Set Intersection:
Program 8 :
# Intersection of sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use & operator
# Output: {4, 5}
print(A & B)
Output:
{4, 5}
Set Difference:
Program 9:
# Difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on A
# Output: {1, 2, 3}
print(A - B)
Run Code
Output:
{1, 2, 3}
Program 10:
# Symmetric difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
Run Code
Output:
{1, 2, 3, 6, 7, 8}
There are many set methods, some of which we have already used above. Here is a list of all the
methods that are available with the set objects:
Method Description
Output:
True
False
Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are
commonly used with sets to perform different tasks.
Function Description
all() Returns True if all elements of the set
are true (or if the set is empty).
any() Returns True if any element of the set
is true. If the set is empty, returns
False.
Returns an enumerate object. It
enumerate() contains the index and value for all the
items of the set as a pair.
len() Returns the length (the number of
items) in the set.
max() Returns the largest item in the set.
min() Returns the smallest item in the set.
Returns a new sorted list from
sorted() elements in the set(does not sort the set
itself).
Returns the sum of all elements in the
sum()
set.
Python Frozenset:
Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once
assigned. While tuples are immutable lists, frozensets are immutable sets.
Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand,
frozensets are hashable and can be used as keys to a dictionary.
Frozensets can be created using the frozenset() function.
This data type supports methods
like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference()
and union(). Being immutable, it does not have methods that add or remove elements.
# Frozensets
# initialize A and B
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
Integrated Lab Program
Python program to perform set operation(Union, Intersection, Difference, Symmetric
Difference)
Program:
A={0,2,4,6.8}
B={1,2,3,4,5}
print("Union:",A|B)
print("Intersection:",A&B)
print("Difference:",A-B)
print("Symmetric difference:",A^B)
output:
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
UNIT V
FILES, MODULES, PACKAGES
File Type
1. Text file
2. Binary file
File Operation:
Open a file
Reading a file
Writing a file
Closing a file
1. Open ( ) function:
Syntax:
file_object=open(“file_name” , ”mode”)
Example:
fp=open(“a.txt”,”r”)
2. Read ( ) function
Read functions contains different methods
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
Output
3. Write ( ) function
This method is used to add information or content to existing file.
Syntax:
file_name.write( )
Example:
fp=open(“a.txt”,”w”)
fp.write(“this file is a.txt”)
fp.write(“to add more lines”)
fp.close()
Output: a.txt
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()
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 = 0for 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
107
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
Format Operator
The argument of write has to be a string, so if we want to put other values in afile,
we have to convert them to strings. The easiest way to do that is with str:
>>> f5=open('stringsample.txt','w')
>>>f5.write(5)
TypeError: expected a string or other character buffer object
>>>f5.write(str(5))
An alternative is to use the format operator, %. When applied to integers, %
is the modulus operator. But when the first operand is a string, % is the format operator.
The first operand is the format string, which contains one or more format sequences, whichspecify how
the second operand is formatted. The result is a string.
For example, the format sequence '%d' means that decimal value is converted to string.
Conversion Meaning
d Signed integer decimal.
i Signed integer decimal.
o Unsigned octal.
u Unsigned decimal.
x Unsigned hexadecimal (lowercase).
X Unsigned hexadecimal (uppercase).
e Floating point exponential format (lowercase).
E Floating point exponential format (uppercase).
f Floating point decimal format.
F Floating point decimal format.
g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise.
G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise.
c Single character (accepts integer or single character string).
r String (converts any python object using repr()).
s String (converts any python object using str()).
% No argument is converted, results in a "%" character in the result.
The result is the string '8', which is not to be confused with the integer value8.Some other format strings are.
A format sequence can appear anywhere in the string, so you can embed avalue
in a sentence:
>>> 'India need %d runs'%3
'India need 3 runs'
If there is more than one format sequence in the string, the second argument
has to be a tuple. Each format sequence is matched with an element of the tuple, in order.
>>> 'India need %d runs in %d balls'%(3,5)
'India need 3 runs in 5 balls'
The following example uses '%d' to format an integer, '%g' to format a
floating-point number, and '%s' to format a string:
>>> '%d %s price is %g rupees'%(5,'apple',180.50)'5
apple price is 180.500000 rupees'
The number of elements in the tuple has to match the number of format
108
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
sequences in the string. Also, the types of the elements have to match the format sequences:
>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'apple'
TypeError: %d format: a number is required, not str
In the first example, there aren‘t enough elements; in the second, the element
is the wrong type.
os.path provides other functions for working with filenames and paths. For
example, os.path.exists checks whether a file or directory exists:
>>>os.path.exists('memo.txt')
True
If it exists, os.path.isdir checks whether it‘s a directory:
>>>os.path.isdir('memo.txt')
False
>>>os.path.isdir ('C:\\Python27')
True
Similarly, os.path.isfile checks whether it‘s a file.
os.listdir returns a list of the files (and other directories) in the given directory:
>>>cwd=os.getcwd()
>>>os.listdir(cwd)
['DLLs', 'Doc', 'include', 'infinitLoop.py', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'parameter.py',
'python.exe', 'pythonw.exe', 'README.txt', 'sample.txt', 'sample2.txt', 'Scripts', 'stringsample.txt',
'swapwith third.py', 'tcl', 'Tools', 'w9xpopen.exe', 'wc.py', 'wc.pyc']
To demonstrate these functions, the following example ―walks‖ through a
109
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
directory, prints the names of all the files, and calls itself recursively on all the directories.
>>>def walk(dirname):
for name in os.listdir(dirname):
path = os.path.join(dirname, name)
ifos.path.isfile(path):
print(path)
else:
walk(path)
>>>cwd=os.getcwd()
>>>walk(cwd)
Output:
C:\Python27\DLLs\tcl85.dll
C:\Python27\include\abstract.h
C:\Python27\include\asdl.h
C:\Python27\include\ast.h
os.path.join takes a directory and a file name and joins them into a complete
path.
>>>os.path.join(cwd,'stringsample.txt')'C:\\Python27\\stringsample.txt'
It is possible to pass some values from the command line to your python programs
when they are executed. These values are called command line arguments and many times they are
important for your program especially when you want to control your program from outside instead of
hard coding those values inside the code.
The command line arguments are handled using sys module. We can access
command-line arguments via the sys.argv. This serves two purposes −
Example 1
Consider the following script command_line.py
import sys
print 'There are %d arguments'%len(sys.argv)
print 'Argument are', str(sys.argv)
print 'File Name is: ', sys.argv[0]
110
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
111
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
Example 2
This is a Python Program to copy the contents of one file into another. Source
and destination file names are given through command line argument while running the
program.
1) Open file name with command line argument one as read mode (input file).
2) Open file name with command line argument two as write mode (output file).
3) Read each line from the input file and write it into the output file until the
input filedata getsover.
4) Exit.
Program
import sys source=open(sys.argv[1],'r')
destination=open(sys.argv[2],'w')
while(True):
new_line=source.readline()
ifnew_line=='':
break
destination.write(new_line)
source.close()
destination.close()
Program:
OUTPUT:
Enter file name:abc.txt
Number of lines in the input file: abc.txt is: 5
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
OverflowError Raised when a calculation exceeds maximum limit for a numeric type.
FloatingPointError Raised when a floating point calculation fails.
ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types.
AssertionError Raised in case of failure of the Assert statement.
AttributeError Raised in case of failure of attribute reference or assignment.
Exception Handling Mechanism
1. try –except
2. try –multiple except
3. try –except-else
4. raise exception
5. try –except-finally
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
statements
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
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
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
2. Importwith renaming:
The import a module by renaming it as follows,
>>>import math as a
>>>print(“The value of pi is “,a.pi)
The value of pi is 3.14159265
Writing modules:
Any python source code file can be imported as a module into another python source
file. For example, consider the following code named as support.py, which is python
source file defining two function add(), display().
Support.py:
def add(a,b):
print(“The result is “,a+b)
return
def display(p):
print(“welcome “,p)
return
The support.py file can be imported as a module into another python source file and
its functions can be called from the new files as shown in the following code:
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
The OS module in python provide function for interacting with operating
system
To access the OS module have to import the OS module in our program
import os
method example description
name Osname ‘nt’ This function gives the name
of the operating system
getcwd() Os,getcwd() Return the current working
,C;\\Python34’ directory(CWD)of the file
used to execute the code
mkdir(folder) Os.mkdir(“python”) Create a directory(folder)
with the given name
rename(oldname,newname) Os.rename(“python”,”pspp”) Rename the directory or
folder
6. Sys Module
Sys module provides information about constant, function and methods
It provides access to some variables used or maintained by the interpreter
import sys
methods example description
sys.argv sys.argv Provides the list of
command line arguments
passed to a python script
sys.argv(0) Provides to access the file
name
sys.argv(1) Provides to access the first
input
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
Step2: write module for calculator directory add save the module in calculator directory
Here four module have create for calculator directory
Output :
>>> 15
5
50
2
Two marks:
Read Write
A "Read" operation occurs when a computer A "Write" operation occurs when a computer
program reads information from a computer program adds new information, or changes
file/table (e.g. to be displayed on a screen). existing information in a computer file/table.
The "read" operation gets
information out of a file.
After a "read", the information from the After a "write", the information from the
file/table is available to the computer program file/table is available to the computer program
but none of the information that was read but the information that was read from the
from the file/table is changed in file/table can be changed in any
any way. way.
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