Python For Problem Solving Notes - All Units (2) - 240221 - 093412
Python For Problem Solving Notes - All Units (2) - 240221 - 093412
SYLLABUS: Algorithms, building blocks of algorithms (statements, state, control flow, functions),
notation (pseudo code, flow chart, programming language), algorithmic problem solving, simple
strategies for developing algorithms (iteration, recursion). Illustrative problems: find minimum in a
list, insert a card in a list of sorted cards, Guess an integer number in a range.
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 Techniques:
Problem solving can be expressed in the form of
1. Algorithms.
2. Flowcharts.
3. Pseudo codes.
4. Programs
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.
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 end point
Derived results should be obtained only after the algorithm terminates.
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
Write an algorithm to print „Good Morning”
Step 1: Start
Step 2: Print “Good Morning”
Step 3: Stop
Statements:
Statement is a single action in a computer.
In a computer statements might include some of the following actions
input data-information given to the program
process data-perform operation on a given input
output data-processed result
State:
Transition from one process to another process under specified condition with in a time is called
state.
Control flow:
The process of executing the individual statements in a given order is called control flow.
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.
PYTHON FOR PROBLEM SOLVING UNIT - I
Example:
Add two numbers:
Step 1: Start
Step 2: get a,b
Step 3: calculate c=a+b
Step 4: Display c
Step 5: Stop
Selection:
A selection statement causes the program control to be transferred to a specific part of the program
based upon the condition.
If the conditional test is true, one part of the program will be executed, otherwise it will execute the
other part of the program.
Example
Write an algorithm to check whether he is eligible to vote?
Step 1: Start
PYTHON FOR PROBLEM SOLVING UNIT - I
Iteration:
In some programs, certain set of statements are executed again and again based upon conditional
test. i.e. executed more than one time. This type of execution is called looping or iteration.
Example
Write an algorithm to print all natural numbers up to n
Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 7
Step 5: Print i value and increment i value by 1
PYTHON FOR PROBLEM SOLVING UNIT - I
Step 6: go to step 4
Step 7: Stop
Functions:
Example:
Algorithm for addition of two numbers using function
Main function()
Step 1: Start
Step 2: Call the function add()
Step 3: Stop
sub function add()
Step 1: Function start
Step 2: Get a, b Values
Step 3: add c=a+b
Step 4: Print c
Step 5: Return
PYTHON FOR PROBLEM SOLVING UNIT - I
NOTATIONS
FLOW CHART
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.
PYTHON FOR PROBLEM SOLVING UNIT - I
4. Only one flow line should enter a decision symbol. However, two or three flow lines may leave the
decision symbol.
PYTHON FOR PROBLEM SOLVING UNIT - I
Advantages of flowchart:
Communication: - Flowcharts are better way of communicating the logic of a system to all
concerned.
Effective analysis: - With the help of flowchart, problem can be analyzed in more effective
way.
Proper documentation: - Program flowcharts serve as a good program documentation,
which is needed for various purposes.
Efficient Coding: - The flowcharts act as a guide or blueprint during the systems analysis
and program development phase.
Proper Debugging: - The flowchart helps in debugging process.
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.
Complex logic: - Sometimes, the program logic is quite complicated. In that case, flowchart
becomes complex and clumsy.
Alterations and Modifications: - If alterations are required the flowchart may require re-
drawing completely.
Reproduction: - As the flowchart symbols cannot be typed, reproduction of flowchart
becomes a problem.
Cost: For large application the time and cost of flowchart drawing becomes costly.
PSEUDO CODE:
Pseudo code consists of short, readable and formally styled English languages used for explain
an algorithm.
It does not include details like variable declaration, subroutines.
It is easier to understand for the programmer or non programmer to understand the general
working of the program, because it is not based on any programming language.
It gives us the sketch of the program before actual coding.
It is not a machine readable
PYTHON FOR PROBLEM SOLVING UNIT - I
IF (a>b) THEN
DISPLAY a is greater
ELSE
DISPLAY b is greater
END IF
END
Advantages:
Pseudo is independent of any language; it can be used by most programmers.
Disadvantages:
Example:
Addition of two numbers:
BEGIN
GET a,b
ADD c=a+b
PRINT c
END
PYTHON FOR PROBLEM SOLVING UNIT - I
PROGRAMMING LANGUAGE
A programming language is a set of symbols and rules for instructing a computer to perform
specific tasks. The programmers have to follow all the specified rules before writing program using
programming language. The user has to communicate with the computer using language which it
can understand.
Types of programming language
1. Machine language
2. Assembly language
3. High level language
Machine language:
The computer can understand only machine language which uses 0’s and 1’s. In machine language
the different instructions are formed by taking different combinations of 0’s and 1’s.
Advantages:
Translation free:
Machine language is the only language which the computer understands. For executing any
program written in any programming language, the conversion to machine language is necessary.
PYTHON FOR PROBLEM SOLVING UNIT - I
The program written in machine language can be executed directly on computer. In this case any
conversion process is not required.
High speed
The machine language program is translation free. Since the conversion time is saved, the execution
of machine language program is extremely fast.
Disadvantage:
It is hard to find errors in a program written in the machine language.
Writhing program in machine language is a time consuming process.
Machine dependent: According to architecture used, the computer differs from each other. So
machine language differs from computer to computer. So a program developed for a particular type
of computer may not run on other type of computer.
Assembly language:
To overcome the issues in programming language and make the programming process easier, an
assembly language is developed which is logically equivalent to machine language but it is easier for
people to read, write and understand.
Assembly language is symbolic representation of machine language. Assembly languages are
symbolic programming language that uses symbolic notation to represent machine language
instructions. They are called low level language because they are so closely related to the machines.
Assembler
Assembler is the program which translates assembly language instruction in to a machine language.
Easy to understand and use.
It is easy to locate and correct errors.
Disadvantage
Machine dependent
The assembly language program which can be executed on the machine depends on the
architecture of that computer.
Hard to learn
It is machine dependent, so the programmer should have the hardware knowledge to create
applications using assembly language.
PYTHON FOR PROBLEM SOLVING UNIT - I
Less efficient
Execution time of assembly language program is more than machine language program.
Because assembler is needed to convert from assembly language to machine language.
Machine independent
High level language program have the advantage of being portable between machines.
Easy debugging
Easy to find and correct error in high level language
Disadvantages
Less efficient
The translation process increases the execution time of the program. Programs in high level
language require more memory and take more execution time to execute.
PYTHON FOR PROBLEM SOLVING UNIT - I
Scripting language:
Scripting language are programming languages that control an application. Scripts can execute
independent of any other application. They are mostly embedded in the application that they
control and are used to automate frequently executed tasks like communicating with external
program.
Examples:
Apple script
VB script
Markup languages:
A markup language is an artificial language that uses annotations to text that define hoe the text is
to be displayed.
Examples:
HTML
XML
Object oriented programming is a programming paradigm based on the concept of objects which
may contain data in the form of procedures often known as methods.
Examples:
Lava
Moto
If the instructions are executed one after another, it is called sequential algorithm.
If the instructions are executed concurrently, it is called parallel algorithm.
The next principal decision is to choose between solving the problem exactly or
solving it approximately.
Based on this, the algorithms are classified as
exact algorithm and approximation algorithm.
Data structure plays a vital role in designing and analysis the algorithms.
Some of the algorithm design techniques also depend on the structuring data
specifying a problem’s instance
Algorithm+ Data structure=programs.
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.
A common technique for proving correctness is to use mathematical induction
because an algorithm’s iterations provide a natural sequence of steps needed for
such proofs.
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.
Analysing an Algorithm
1. Efficiency.
Time efficiency, indicating how fast the algorithm runs,
Space efficiency, indicating how much extra memory it uses.
2. simplicity.
Coding an Algorithm
1. iterations
2. Recursions
1. Iterations:
A sequence of statements is executed until a specified condition is true is called iterations.
1. for loop
2. While loop
END
Recursions:
Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop
More examples:
BEGIN
READ l,b
CALCULATE A=l*b
DISPLAY A
END
PYTHON FOR PROBLEM SOLVING UNIT - I
BEGIN
READ r
CALCULATE A and C
A=3.14*r*r
C=2*3.14*r
DISPLAY A
DISPLAY C
END
BEGIN
READ P, n, r
CALCULATE S
SI=(p*n*r)/100
DISPLAY SI
END
PYTHON FOR PROBLEM SOLVING UNIT - I
BEGIN
READ P,C,M
CALCULATE
Cutoff= (P/4+C/4+M/2)
DISPLAY Cutoff
END
BEGIN
READ a,b
IF (a>b) THEN
DISPLAY a is greater
ELSE
DISPLAY b is greater
END IF
END
PYTHON FOR PROBLEM SOLVING UNIT - I
BEGIN
READ y
IF (y%4==0) THEN
DISPLAY leap year
ELSE
DISPLAY not leap year
END IF
END
BEGIN
READ num
IF (num%2==0) THEN
DISPLAY num is even
ELSE
DISPLAY num is odd
END IF
END
BEGIN
READ a, b, c
IF (a>b) THEN
IF(a>c) THEN
DISPLAY a is greater
ELSE
PYTHON FOR PROBLEM SOLVING UNIT - I
DISPLAY c is greater
END IF
ELSE
IF(b>c) THEN
DISPLAY b is greater
ELSE
DISPLAY c is greater
END IF
END IF
END
BEGIN
GET n
IF(n==0) THEN
DISPLAY “ n is zero”
ELSE
IF(n>0) THEN
DISPLAY “n is positive”
ELSE
DISPLAY “n is positive”
END IF
END IF
END
PYTHON FOR PROBLEM SOLVING UNIT - I
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
PYTHON FOR PROBLEM SOLVING UNIT - I
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+2
ENDWHILE
END
BEGIN
GET n
INITIALIZE i=2
WHILE(i<=n) DO
PRINT i
i=i+2
ENDWHILE
END
PYTHON FOR PROBLEM SOLVING UNIT - I
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i*i
i=i+2
ENDWHILE
END
PYTHON FOR PROBLEM SOLVING UNIT - I
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i*i*i
i=i+2
ENDWHILE
END
PYTHON FOR PROBLEM SOLVING UNIT - I
BEGIN
GET n
INITIALIZE i=1,sum=0
WHILE(i<=n) DO
sum=sum+i
i=i+1
ENDWHILE
PRINT sum
END
PYTHON FOR PROBLEM SOLVING UNIT - I
BEGIN
GET n
INITIALIZE i=1,fact=1
WHILE(i<=n) DO
fact=fact*i
i=i+1
ENDWHILE
PRINT fact
END
PYTHON FOR PROBLEM SOLVING UNIT - I
ILLUSTRATIVE PROBLEM
Algorithm:
Step1: Start
Step 2: Declare hidden, guess,range=1 to 100
Step 3: Compute hidden= Choose a random value in a range
Step 4: Read guess
Step 5: If guess=hidden, then Print
Guess is hit
Else
Print Guess not hit
Print hidden
Step 6: Stop
Pseudocode:
BEGIN
COMPUTE hidden=random value in a range
READ guess
IF guess=hidden, then PRINT
Guess is hit
ELSE
PRINT Guess not hit
PRINT hidden
END IF-ELSE
END
PYTHON FOR PROBLEM SOLVING UNIT - I
Flowchart:
PYTHON FOR PROBLEM SOLVING UNIT - I
Algorithm: Step 1:
Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5
Pseudocode:
BEGIN
READ n
min=a[i] INCREMENT i
ELSE
INCREMENT i
END IF-ELSE
END FOR
PRINT min
END
PYTHON FOR PROBLEM SOLVING UNIT - I
Flowchart:
PYTHON FOR PROBLEM SOLVING UNIT - I
Algorithm:
Step 1: Start
Step 2: Read n
Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5
Step 7: If i>=0 and item<a[i], then go to step 7.1, 7.2 else goto step 8
Step 10: If i<n, then goto step 10.1, 10.2 else goto step 11
Pseudocode:
BEGIN
READ n
a[i] INCREMENT
END FOR
READ item
CALCULATE a[i+1]=a[i]
DECREMENT i
a[i+1]=a[i] COMPUTE
PRINT a[i]
INCREMENT i
END FOR
END
PYTHON FOR PROBLEM SOLVING UNIT - I
Flowchart:
PYTHON FOR PROBLEM SOLVING UNIT - II
UNIT II
SYLLABUS - 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 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.
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.
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.
PYTHON FOR PROBLEM SOLVING UNIT - II
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.
Python Interpreter is a program that reads and executes Python code. It uses 2 modes of Execution.
1. Interactive mode
2. Script mode
1. Interactive mode:
Interactive Mode, as the name suggests, allows us to interact with OS.
Advantages:
Python, in interactive mode, is good enough to learn, experiment or explore.
Working in interactive mode is convenient for beginners and for testing small pieces of code.
Drawback:
We cannot save the statements and have to retype all the statements once again to re-run them.
In interactive mode, you type Python programs and the interpreter displays the result:
>>> 1+1
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you to enter code. If
you type 1 + 1, the interpreter replies 2.
>>> print ('Hello, World!')
Hello, World!
This is an example of a print statement. It displays a result on the screen. In this case, the result is the
words.
PYTHON FOR PROBLEM SOLVING UNIT - II
2. 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.
PYTHON FOR PROBLEM SOLVING UNIT - II
It is bundled with the default implementation of the python language and also comes with optional
part of the Python packaging.
Features of IDLE:
Multi-window text editor with syntax highlighting.
Auto completion with smart indentation.
Value:
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.
1. Numbers:
Sequence:
1. Strings
2. Lists
3. Tuples
1. Strings
Strings are immutable i.e. the contents of the string cannot be changed after it is created.
Indexing:
Operations on string:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Member ship
PYTHON FOR PROBLEM SOLVING UNIT - II
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.
PYTHON FOR PROBLEM SOLVING UNIT - II
Operations on list:
Indexing
Slicing
Concatenation
Repetitions
Updation, Insertion, Deletion
PYTHON FOR PROBLEM SOLVING UNIT - II
3. 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:
Altering the tuple data type leads to error. Following error occurs when user tries to do.
>>> t[0]="a"
Set
Set is an unordered collection of unique items. Set is defined by values separated by comma
inside braces { }. Items in a set are not ordered.
We can perform set operations like union, intersection on two sets. Set have unique values. They
eliminate duplicates.
Example
>>> a = {1,2,2,3,3,3}
>>> a
{1, 2, 3}
Mapping
Dictionaries:
Lists are ordered sets of objects, whereas dictionaries are unordered sets.
Dictionary is created by using curly brackets. i,e. {}
Dictionaries are accessed via keys and not via their position.
PYTHON FOR PROBLEM SOLVING UNIT - II
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
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["car"]
KeyError: 'car'
PYTHON FOR PROBLEM SOLVING UNIT - II
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.
Value should be given on the right side of assignment operator(=) and variable on left side.
>>>counter =45
print(counter)
Assigning a single value to several variables simultaneously:
>>> a=b=c=100
Assigning multiple values to multiple variables:
>>> a,b,c=2,4,"ram"
KEYWORDS:
We cannot use a keyword as variable name, function name or any other identifier.
They are used to define the syntax and structure of the Python language.
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 (_).
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
Statements:
-Instructions that a Python interpreter can executes are called statements.
-A statement is a unit of code like creating a variable or displaying a value.
>>> n = 17
>>> print(n)
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:
PYTHON FOR PROBLEM SOLVING UNIT - II
>>> 42
42
>>> a=2
>>> a+3+2
7
>>> z=("hi"+"friend")
>>> print(z)
Hifriend
COMMENTS:
A hash sign (#) is the beginning of a comment.
Anything written after # in a line is ignored by interpreter.
Example:
# This is a comment.
# This is a comment, too.
# I said that already.
Most of the programming languages like C, C++, Java use braces { } to define a block of
code. But, python uses indentation.
Blocks of code are denoted by line indentation.
It is a space given to the block of codes for class and function definitions or flow control.
Example:
a=3
b=1
if a>b:
print("a is greater")
else:
print("b is greater")
QUOTATION IN PYTHON:
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals.
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
Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction, multiplication
etc. Assume, a=10 and b=5
Examples
PYTHON FOR PROBLEM SOLVING UNIT - II
a=10
b=5
print("a+b=",a+b)
print("a-b=",a-b)
print("a*b=",a*b)
print("a/b=",a/b)
print("a%b=",a%b)
print("a//b=",a//b)
print("a**b=",a**b)
Output:
a+b= 15
a-b= 5
a*b= 50
a/b= 2.0
a%b= 0
a//b= 2
a**b= 100000
Example
a=10
b=5
print("a>b=>",a>b)
print("a>b=>",a<b)
print("a==b=>",a==b)
print("a!=b=>",a!=b)
print("a>=b=>",a<=b)
print("a>=b=>",a>=b)
Output:
a>b=> True
PYTHON FOR PROBLEM SOLVING UNIT - II
a>b=> False
a==b=> False
a!=b=> True
a>=b=> False
a>=b=> True
Assignment Operators:
Example
PYTHON FOR PROBLEM SOLVING UNIT - II
a = 21
b = 10
c=0
c=a+b
print("Line 1 - Value of c is ", c)
c += a
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)
Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
Logical Operators:
Example
a = True
b = False
print('a and b is',a and b)
print('a or b is',a or b)
print('not a is',not a)
Output
x and y is False
x or y is True
not x is False
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)
PYTHON FOR PROBLEM SOLVING UNIT - II
Example
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a & b; # 12 = 0000 1100
print "Line 1 - Value of c is ", c
c = a | b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
c = ~a; # -61 = 1100 0011
print "Line 4 - Value of c is ", c
c = a << 2; # 240 = 1111 0000
print "Line 5 - Value of c is ", c
c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c
Output
Line 1 - Value of c is 12
Line 2 - Value of c is 61
PYTHON FOR PROBLEM SOLVING UNIT - II
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
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 are used.
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 part of the memory.
PYTHON FOR PROBLEM SOLVING UNIT - II
Example
x=5
y=5
x2 = 'Hello'
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
Output
False
True
PYTHON FOR PROBLEM SOLVING UNIT - II
OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation depends on the
order of operations.
Parentheses have the highest precedence and can be used to force an expression to evaluate
in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1)is 4, and
(1+1)**(5-2) is 8.
Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2 *3**2 is 18,
not 36.
Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-
1 is 5, not 4, and 6+4/2 is 8, not 5.
Operators with the same precedence are evaluated from left to right (except exponentiation).
Example:
a=9-12/3+3*2-1
a=?
a=9-4+3*2-1
a=9-4+6-1
a=5+6-1
a=11-1
a=10
A=2*3+4%5-3/2+6
A=6+4%5-3/2+6
A=6+4-3/2+6
PYTHON FOR PROBLEM SOLVING UNIT - II
A=6+4-1+6
A=10-1+6
A=9+6
A=15
find m=?
m=-43||8&&0||-2
m=-43||0||-2
m=1||-2
m=1
a=2,b=12,c=1
d=a<b>c
d=2<12>1
d=1>1
d=0
a=2,b=12,c=1
d=a<b>c-1
d=2<12>1-1
d=2<12>0
d=1>0
d=1
a=2*3+4%5-3//2+6
a=6+4-1+6
a=10-1+6
a=15
PYTHON FOR PROBLEM SOLVING UNIT - II
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:
i) Built in functions
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.
PYTHON FOR PROBLEM SOLVING UNIT - II
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 by importing them.
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
Once we have defined a function, we can call it from another function, program or even the
Python prompt.
To call a function we simply type the function name with appropriate arguments.
Example:
x=5
y=4
my_add(x,y)
PYTHON FOR PROBLEM SOLVING UNIT - II
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.
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:
i. Function without arguments and without return type
ii. Function with arguments and without return type
iii. Function without arguments and with return type
iv. Function with arguments and with return type
In this type no argument is passed through the function call and no output is return to
main function
The sub function will read the input values perform the operation and print the result in
the same block
PYTHON FOR PROBLEM SOLVING UNIT - II
Example
def add( ):
a=int(input("enter a"))
b=int(input("enter b"))
c=a+b
print(c)
add()
OUTPUT:
enter a 5
enter b 10
15
o Arguments are passed through the function call but output is not return to the main function
Example
def add(a,b):
c=a+b
print(c)
a=int(input("enter a"))
b=int(input("enter b"))
add(a,b)
OUTPUT:
enter a 5
enter b 10
15
PYTHON FOR PROBLEM SOLVING UNIT - II
o In this type no argument is passed through the function call but output is return to the main
function.
Example
def add():
a=int(input("enter a"))
b=int(input("enter b"))
c=a+b
return c
c=add()
print(c)
OUTPUT:
enter a 5
enter b 10
15
In this type arguments are passed through the function call and output is return to the main
function
Example
def add(a,b):
c=a+b
PYTHON FOR PROBLEM SOLVING UNIT - II
return c
a=int(input("enter a"))
b=int(input("enter b"))
c=add(a,b)
print(c)
OUTPUT:
enter a 5
enter b 10
15
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: def my_add(a,b):
Arguments :
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:
def my_add(a,b):
c=a+b
return c
x=5
y=4
print(my_add(x,y))
Output:
9
ARGUMENTS TYPES:
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments
PYTHON FOR PROBLEM SOLVING UNIT - II
1. Required Arguments:
The number of arguments in the function call should match exactly with the function
definition.
def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details("george",56)
Output:
Name: george
Age 56
2. 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.
def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details(age=56,name="george")
Output:
Name: george
Age 56
3. Default Arguments:
Assumes a default value if a value is not provided in the function call for that argument.
def my_details( name, age=40 ):
print("Name: ", name)
print("Age ", age)
PYTHON FOR PROBLEM SOLVING UNIT - II
return
my_details(name="george")
Output:
Name: george
Age 40
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:
rajan rahul micheal ärjun
MODULES:
Once we import a module, we can reference or use to any of its functions or variables in
our code.
Syntax:
import module_name
module_name.function_name(variable)
Arithmetic operators:
They are used to perform mathematical operations like addition,
subtraction, multiplication etc. Assume, a=10 and b=5
Examples
a=10
b=5
print("a+b=",a+b)
print("a-b=",a-b)
print("a*b=",a*b)
print("a/b=",a/b)
print("a%b=",a%b)
print("a//b=",a//b)
print("a**b=",a**b)
Output:
a+b= 15
a-b= 5
a*b= 50
a/b= 2.0
a%b= 0
a//b= 2
a**b= 100000
Assignment Operators:
Assignment operators are used in Python to assign values to variables.
Example
a = 21
b = 10
c=0
c=a+b
print("Line 1 - Value of c is ", c)
c += a
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)
Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
Logical Operators:
Logical operators are the and, or, not operators.
Example
a = True
b = False
print('a and b is',a and b)
print('a or b is',a or b)
print('not a is',not a)
BitwiseOperators:
Let x=10(0000 1010in binary)and y= 4(00000100inbinary)
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 are used.
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 part
of the memory.
Example
x=5
y=5
x2 = 'Hello'
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
Output
False
True
CONDITIONALS
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. Program to provide flat rs 500, if the purchase amount is greater than
2000.
2. Program to provide bonus mark if the category is sports.
#Program to provide flat rs 500, if the purchase amount is greater than 2000.
purchase=eval(input(“enter your purchase amount”))
if(purchase>=2000):
purchase=purchase-500
print(“amount to pay”,purchase)
output
enter your purchase
amount
2500
amount to pay
2000
output
enter ur mark out of 100
85
enter ur categery G/S
S
mark is 90
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
4. greatest of two numbers
5. eligibility for voting
Output
enter a number4
even number
Output
enter a number8
positive number
Output
enter a yaer2000
leap year
Output
enter a value:4
enter b value:7
greatest: 7
Output
enter ur age:78
you are eligible for vote
Chained conditionals(if-elif-else)
· 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:
Flowchart:
Example:
1. student mark system
2. traffic light system
3. compare two numbers
4. roots of quadratic equation
#student mark system
mark=eval(input("enter ur mark:"))
if(mark>=90):
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
Output
enter ur mark:78
grade:B
Output
enter colour of light:green
GO
#compare two numbers
x=eval(input("enter x value:"))
y=eval(input("enter y value:"))
if(x == y):
print("x and y are equal")
elif(x < y):
print("x is less than y")
else:
print("x is greater than y")
Output
enter x value:5
enter y value:7
x is less than y
output
enter a value:1
enter b value:0
enter c value:0
same and real roots
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:
Flowchart:
Example:
1. greatest of three numbers
2. positive negative or zero
output
enter the value of n:-9
the number is negative
ITERATION/CONTROL STATEMENTS:
· 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 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 starts with indentation and the first
unindented line marks the end.
Syntax:
Flowchart
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:
n=eval(input("enter n"))
i=1
sum=0
while(i<=n):
sum=sum+i
i=i+1
print(sum)
output
enter n
10
55
#Factorial of a numbers:
n=eval(input("enter n"))
i=1
fact=1
while(i<=n):
fact=fact*i
i=i+1
print(fact)
output
enter n
5
120
output
enter a number
123
6
output
enter a number
123
321
#Armstrong number or not
n=eval(input("enter a number"))
org=n
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 number")
else:
print("The given number is not
Armstrong number")
output
enter a number153
The given number is Armstrong number
Palindrome or not
n=eval(input("enter a number"))
org=n
sum=0
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
if(sum==org):
print("The given no is palindrome")
else:
print("The given no is not palindrome")
output
enter a number121
The given no is palindrome
For loop:
for in range:
v
We can generate a sequence of numbers using range() function.
range(10) will generate numbers from 0 to 9 (10 numbers).
v
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.
Sequence can be a list, strings or tuples
Examples:
1. print nos divisible by 5 not by 10:
2. Program to print fibonacci series.
3. Program to find factors of a given number
4. check the given number is perfect number or not
5. check the no is prime or not
6. Print first n prime numbers
7. Program to print prime numbers in range
print nos divisible by 5 not by 10
n=eval(input("enter a"))
for i in range(1,n,1):
if(i%5==0 and i%10!=0):
print(i)
output
enter a:30
5
15
25
Fibonacci series
a=0
b=1
n=eval(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
Enter the number of terms: 6
Fibonacci Series:
01
1
2
3
5
8
#find factors of a number
n=eval(input("enter a number:"))
for i in range(1,n+1,1):
if(n%i==0):
print(i)
Output
enter a number:10
1
2
5
10
Output
enter a number:6
the number is perfect number
output:
enter a lower range50
enter a upper range100
53
59
61
67
71
73
79
83
89
97
Loop Control Structures
BREAK
v
Break statements can alter the flow of a loop.
v
It terminates the current
v
loop and executes the remaining statement outside the loop.
v
If the loop has else statement, that will also gets terminated and come out of
the loop completely.
Syntax:
Break
Flowchart
example
for i in "welcome":
if(i=="c"):
break
print(i)
Output
w
e
l
CONTINUE
It terminates the current iteration and transfer the control to the next iteration in
the loop.
Syntax:
Continue
Flowchart
Example:
for i in "welcome":
if(i=="c"):
continue
print(i)
Output
w
e
l
o
m
e
PASS
Syntax:
pass
break
Example
for i in “welcome”:
if (i == “c”):
pass
print(i)
Output
w
e
l
c
o
m
e
Difference between break and continue
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()
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,c– return 3 variables
return a+b– return expression
return 8– return value
PARAMETERS / ARGUMENTS:
Keyword parameter:
When we call a function with some values, these values get assigned to the
parameter according to their position. When we call functions in keyword
parameter, the order of the arguments can be changed.
Example
def student(name,roll,mark):
print(name,roll,mark)
student(90,102,"bala")
Output:
90 102 bala
Default parameter:
Python allows function parameter to have default values; if the function is
called without the argument, the argument gets its default value in function
definition.
Example
def student( name, age=17):
print (name, age)
student( “kumar”):
student( “ajay”):
Output:
Kumar 17
Ajay 17
Local Scope A variable with local scope can be used only within the function .
Function Composition:
v Function Composition is the ability to call one function from within
another function
v It is a way of combining functions such that the result of each function is
passed as the argument of the next function.
v In other words the output of one function is given as the input of another
function is known as function composition.
Example:
math.sqrt(math.log(10))
def add(a,b):
c=a+b
return c
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)
Output:
900
Recursion
A function calling itself till it reaches the base value - stop point of function
call. Example: factorial of a given number using recursion
Factorial of n
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
Fact is 120
Explanation
Strings:
v
Strings
v
String slices
v
Immutability
v
String functions and methods
v
String module
Strings:
v
String is defined as sequence of characters represented in quotation
marks (either single quotes ( ‘ ) or double quotes ( “ ).
v
An individual character in a string is accessed using a index.
v
The index should always be an integer (positive or negative).
v
A index starts from 0 to n-1.
v
Strings are immutable i.e. the contents of the string cannot be changed after
it is created.
v
Python will get the input at run time by default as a string.
v
Python does not support character data type. A string of size 1 can be treated
as characters.
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.
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.
string built in functions and methods:
A method is a function that “belongs to” an object.
Syntax to access the method
Stringname.method()
a=”happy birthday”
here, a is the string name.
String modules:
v
A module is a file containing Python definitions, functions, statements.
v
Standard library of Python is extended as modules.
v
To use these modules in a program, programmer needs to import the
module.
v
Once we import a module, we can reference or use to any of its functions or
variables in our code.
v
There is large number of standard modules also available in python.
v
Standard modules can be imported the same way as we import our user-
defined modules.
Syntax:
import module_name
Example
import string
print(string.punctuation)
print(string.digits)
print(string.printable)
print(string.capwords("happ
y birthday"))
print(string.hexdigits)
print(string.octdigits)
output
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
0123456789
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
./:;<=>?@[\]^_`{|}~
Happy Birthday
0123456789abcdefABCDEF
01234567
Escape sequences in string
PYTHON FOR PROBLEM SOLVING
UNIT III
LIST, TUPLES
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.
Operations on list:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison
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
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)
1. List using For Loop:
The for loop in Python is used to iterate over a sequence (list, tuple,
string) or other iterable objects.
Iterating over a sequence is called traversal.
Loop continues until we reach the last item in the sequence.
The body of for loop is separated from the rest of the code using
indentation.
Syntax:
for val in sequence:
Syntax:
while (condition):
body of while
Sum of elements in list
a=[1,2,3,4,5]
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)
Output:
15
3. 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
a=1
while (a==1):
n=int(input("enter the number"))
print("you entered:" , n)
Output:
Enter the number 10
you entered:10
Enter the number 12
you entered:12
Enter the number 16
you entered:16
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.
But tuple can be converted into list and list can be converted in to 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.
Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison
Tuple methods:
Tuple is immutable so changes cannot be done on the elements of a tuple
once it is assigned.
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
tupleassignment.
Example:
Swapping using temporary variable:
a=20
b=50
temp = a
a=b
b = temp
print("value after swapping is",a,b)
Tuple as argument:
The parameter name that begins with * gathers argument into a tuple.
Example:
def printall(*args):
print(args)
printall(2,3,'a')
Output:
(2, 3, 'a')
Different between List and Tuples
PYTHON FOR PROBLEM SOLVING UNIT – V
SYLLABUS : Files and exception: text files, reading and writing files, format operator -
command line arguments - errors and exceptions - handling exceptions – modules –
packages - Illustrative programs: word count, copy file.
FILES
File is a named location on disk to store related information. It is used to permanently store data
in a non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when computer is turned
off, we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When we are done, it needs
to be closed, so that resources that are tied with the file are freed. Hence, in Python, a file
operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file
Opening a file
Python has a built-in function open() to open a file. This function returns a file object, also called
a handle, as it is used to read or modify the file accordingly.
>>> f = open("test.txt") # open file in current directory
>>> f = open("C:/Python33/README.txt") # specifying full path
We can specify the mode while opening a file. In mode, we specify whether we want to read 'r',
write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode or
binary mode.
The default is reading in text mode. In this mode, we get strings when reading from the file. On
the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-
text files like image or exe files.
PYTHON FOR PROBLEM SOLVING UNIT – V
Hence, when working with files in text mode, it is highly recommended to specify the encoding
type.
f = open("test.txt",mode = 'r',encoding = 'utf-8')
Closing a File
When we are done with operations to the file, we need to properly close it.
Closing a file will free up the resources that were tied with the file and is done using the close()
method.
Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to
close the file.
f = open("test.txt",encoding = 'utf-8')
# perform file operations
f.close()
PYTHON FOR PROBLEM SOLVING UNIT – V
This method is not entirely safe. If an exception occurs when we are performing some operation
with the file, the code exits without closing the file. A safer way is to use a try...finally block.
try:
f= open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
This way, we are guaranteed that the file is properly closed even if an exception is raised,
causing program flow to stop.
The best way to do this is using the with statement. This ensures that the file is closed when the
block inside with is exited.
We don't need to explicitly call the close() method. It is done internally.
with open("test.txt",encoding = 'utf-8') as f:
# perform file operations
A text file is a sequence of characters stored on a permanent medium like a hard drive, flash
memory, or CD-ROM.
To write a file, you have to open it with mode 'w' as a second parameter:
>>> fout = open('output.txt', 'w')
>>> print fout
<open file 'output.txt', mode 'w' at 0xb7eb2410>
If the file already exists, opening it in write mode clears out the old data and starts fresh, so be
careful! If the file doesn’t exist, a new one is created.
The write method puts data into the file.
>>> line1 = "This here's the wattle,\n"
>>>fout.write(line1)
PYTHON FOR PROBLEM SOLVING UNIT – V
Again, the file object keeps track of where it is, so if you call write again, it adds the new data to
the end.
>>> line2 = "the emblem of our land.\n"
>>> fout.write(line2)
When you are done writing, you have to close the file.
>>> fout.close()
F1=open(“abc.txt”,”x”)
out=open("abc.dat","w")
str= input("Enter string : ")
out.write(str)
out.close()
out=open("abc.dat","r")
str=out.read()
print("File contains")
print(str)
out.close()
Output
Enter string : Welcome to Python file handling
File contains
Welcome to Python file handling
Format operator
The argument of write has to be a string, so if we want to put other values in a file, we have to
convert them to strings. The easiest way to do that is with str:
>>> x = 52
>>> fout.write(str(x))
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.
PYTHON FOR PROBLEM SOLVING UNIT – V
The first operand is the format string, which contains one or more format sequences, which
specify how the second operand is formatted. The result is a string.
For example, the format sequence '%d' means that the second operand should be formatted as an
integer (d stands for “decimal”):
>>> camels = 42
>>> '%d' % camels
'42'
The result is the string '42', which is not to be confused with the integer value 42. A format
sequence can appear anywhere in the string, so you can embed a value in a sentence:
>>> camels = 42
>>> 'I have spotted %d camels.' % camels
'I have spotted 42 camels.'
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.
The following example uses '%d' to format an integer, '%g' to format a floating-point number and
'%s' to format a string:
>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')
'In 3 years I have spotted 0.1 camels.'
The number of elements in the tuple has to match the number of format 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' % 'dollars'
TypeError: illegal argument type for built-in operation
PYTHON FOR PROBLEM SOLVING UNIT – V
Files are organized into directories (also called “folders”). Every running program has a “current
directory,” which is the default directory for most operations. For example, when you open a file
for reading, Python looks for it in the current directory.
The os module provides functions for working with files and directories (“os” stands for
“operating system”). os.getcwd returns the name of the current directory:
>>> import os
>>> cwd = os.getcwd()
>>> print cwd /home/dinsdale
cwd stands for “current working directory.” The result in this example is /home/dinsdale, which
is the home directory of a user named dinsdale.
A string like cwd that identifies a file is called a path. A relative path starts from the current
directory; an absolute path starts from the topmost directory in the file system.
The paths we have seen so far are simple filenames, so they are relative to the current directory.
To find the absolute path to a file, you can use os.path.abspath:
>>> os.path.abspath('memo.txt')
'/home/dinsdale/memo.txt'
To demonstrate these functions, the following example “walks” through a 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)
if os.path.isfile(path):
print path
else:
walk(path)
os.path.join takes a directory and a file name and joins them into a complete path.
Input can be directly sent as an argument. When the program is running under command
prompt then inputs can be passed directly in the command and can be fetched using
"sys" module.
Example program:
import sys
noargs=len(sys.argv)
print ("Number of arguments :%d" %noargs)
arguments= str(sys.argv)
print ("Arguments are : %s" %arguments)
Output
PYTHON FOR PROBLEM SOLVING UNIT – V
EXCEPTION
•Syntax errors
– python interpreter find the syntax error when it executes the coding. Once find
the error, it displays the error by stopping the execution.
– if a program is free of syntax errors then it runs by the interpreter and the
errors occurs during the run time of the program due to logical mistake is called runtime errors.
Examples:
•When the program raises an exception, then python must handle the exception otherwise it
terminates and quits
•try block – suspicious code (code that makes exception) placed here
•except block – code that handles the exception placed here and gets executed during exception
•else block – code that is to be executed if no exception is placed here for normal execution
try:
except exception1:
except exception2:
Example program:
try:
n=int(input(“enter a value”))
expert:
print(“you didn’t enter the integer input”)
else:
print(“value entered correctly and stored”)
output:
enter a value:5
value entered correctly and stored
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!",sys.exc_info()[0],"occured.")
print("Next entry.")
print()
print("The reciprocal of",entry,"is",r)
Output
The entry is a
PYTHON FOR PROBLEM SOLVING UNIT – V
The entry is 0
Oops! <class 'ZeroDivisionError' > occured.
Next entry.
The entry is 2
The reciprocal of 2 is 0.5
In this program, we loop until the user enters an integer that has a valid reciprocal. The portion
that can cause exception is placed inside try block.
If no exception occurs, except block is skipped and normal flow continues. But if any exception
occurs, it is caught by the except block.
Here, we print the name of the exception using ex_info() function inside sys module and ask the
user to try again. We can see that the values 'a' and '1.3' causes ValueError and '0' causes
ZeroDivisionError.
MODULES
Any file that contains Python code can be imported as a module. For example, suppose you have
a file named wc.py with the following code:
def linecount(filename):
count = 0
for line in open(filename):
count += 1
return count
print linecount('wc.py')
If you run this program, it reads itself and prints the number of lines in the file, which is 7.
You can also import it like this:
PYTHON FOR PROBLEM SOLVING UNIT – V
>>> import wc
7
yy= 2017
mm = 8
PACKAGES:
Packages are namespaces which contain multiple packages and modules themselves. They are
simply directories, but with a twist.
Each package in Python is a directory which must contain a special file called _ _init_
_.py To be a package the folder must contain a file called __init__.py
Packages can be nested to any depth i.e. it contains many sub packages and modules in it.
Accessing Packages:
Step 1: Create a folder name “MyPackage” in the folder where the python files are storing.
Step 2: Create a subfolder name “Add” in the folder “MyPackage”.
Step 3: Type a python program containing the function to add two numbers with function name
“add” and save the file inside the folder
Example Program:
PYTHON FOR PROBLEM SOLVING UNIT – V
Illustrative programs:
Word Count of a file:
import sys
fname=sys.argv[1]
n=0
with open(fname,'r') as f:
for line in f:
words=line.split()
n+=len(words)
print("Number of words:",n)
Copy file:
f1=open(“sourcefile.txt”,”r”)
f2=open(“destinationfile.txt”,”w”)
for line in f1:
f2.write(“\n”+line)
f1.close( )
f2.close( )
print(“Content of Source file:”)
f1=open(“sourcefile.txt”,”r”)
print(f1.read( ))
print(“Content of Copied file:”)
f2=open(“destinationfile.txt”,”r”)
print(f2.read( ))