Problem Solving and Python Programming Notes (All Unit) PDF
Problem Solving and Python Programming Notes (All Unit) PDF
in/
Problem Solving and Python Programming
UNIT I
1.1 - ALGORITHMS
An Algorithm is defined as step by step procedure for solving a problem. An Algorithm
is a well-defined computational procedure consists of a set of instructions that takes some values
as an input, then manipulate them by following prescribed texts in order to produce some values
as output.
/
in
INPUT ALGORITHM OUTPUT
n.
aa
1.1.1 –Two Phases of Algorithmic Problem Solving
Derivation of an algorithm that solves the problem
o riy
Conversion of an algorithm into code (or) program
program. The Programming languages provide simple data type such as Integers, real numbers
and characters.
s:
tp
/
in
1.1.5 – Representation of an Algorithm:
n.
An algorithm can be represented in a number of ways which include
aa
Natural Language usually verbose and ambiguous.
Flow Chart pictorial representation of an algorithm
Pseudo Code
Programming Language
riy
resembles common elements of an language and no particular format
Algorithms are the basis of programs. Expressed in High level
o
language.
.p
w
Examples:
w
Step5: Stop
ht
3. Write an algorithm for calculating total marks of specified number of subjects given as
66, 99, 98, 87, 89.
Step1: Start
Step2: Read Numbers as N
Step3: Initialize the value of Total as 0 and as 1
Step4: Repeat step 5 to step7 until i is less than n
Step5: Read the marks
Step6: Add mark to the total
Step7: Increment the value of i
/
Step6: Print the value of total
in
Step7: Stop
n.
1.2 – Building Blocks of an Algorithm
aa
There are four building blocks of algorithm which are
a) Instructions / Statement
i. Simple Statement
o riy
ii. Compound Statement
.p
b) State
w
c) Control Flow
w
d) Functions
tp
a) Instructions / Statement
In Computer programming, a statement is a smallest standalone element which expresses
ht
some action to be covered. It is an instruction written in a high level language that commands the
computer to perform a specified action. A program written in such language is formed by
sequence of one or more statements.
Ex:
sumnum1+num2
Step-5: Display sum
Step-6: Stop
There are two types of statements they are
i. Simple Statement
ii. Compound Statement
i) Simple Statement:
/
Simple Statement consists of a single logical line.
in
Ex:
n.
Expression Statement
aa
Assignment Statement
Print Statement
Import Statement
ii) Compound Statement:
o riy
Compound Statements consist of a group of statements. They control the execution of
.p
other statements. It consists of one or more clauses.
w
Ex:
w
if – statement
while – statement
//w
for – statement
try – statement
s:
b) State
tp
initial state, will terminate in a defined end state and internal state for performing an algorithm.
Initial State starts by keyword “START” or “BEGIN”.
Internal State starts from data, which is read as an input, written to an output and stored
for processing. The stored data is regarded as a part of Internal State.
End State is nothing but the keyword “END”
c) Control Flow
Control Flow or Flow of Control is the order function calls, instructions and statement are
executed or evaluated when a program is running. Program Control structures are defined as the
program statements that specifies the order in which statements are executed. There are three
types of control structures. They are.
/
one process after another.
in
The logic is from top to bottom approach.
n.
Process 1 Start
aa
Process 2
o riy Read radius r
S=3.14*r*r
.p
w
Print S
w
Process n
//w
Stop
Selection Control Structure or Decision Control Structure allows the program to make a
tp
1) IF….THEN
2) IF….THEN…ELSE
1) IF….THEN
This choice makes between two processes.
o If the condition is true. It performs the process.
o If the condition is false. It skips over the process.
IF Condition THEN
Process A
…
…
…
Process
END IF
/
in
2) IF….THEN…ELSE
n.
In this structure
o If the condition is true. It performs the process A.
aa
o Else the condition is false. It executes process B.
Pseudo code
o riy
The process execution is depending on the condition.
Flow Chart
IF Condition THEN
.p
Process A
w
ELSE IF
Conditio
w
Process B
Process A ns
Process B
END IF
//w
This is a multi-way selection structures that is used to choose one option from many
tp
options. If the value is equal to type 1 then it executes process-1, If the value is equal to
ht
type 2 then it executes process-2 and so on. END CASE is used to indicate the end of the
CASE Structure.
Process 2
…
…
Process 1 Process 2 Process N
…
case Type-n:
Process n
END CASE
/
in
d) Functions
n.
Functions are "self-contained" modules of code that accomplish a specific task. Functions
aa
usually "take in" data as INPUT, process it, and "return" a result as OUTPUT. Once a function is
written, it can be used over and over and over again. Functions can be "called" from the inside of
line of code).
o riy
other functions. Functions "Encapsulate" a task (they combine many instructions into a single
Ex:
.p
>>>def add(num1,num2): #Function Definition
w
num3=num1+num2
print(“The sum is”,num3)
w
return num3
//w
>>>a=10
>>>b=20
s:
Flow of a Function:
When a function is "called" the program "leaves" the current section of code and begins
to execute the first line inside the function. Thus the function "flow of control" is:
The program comes to a line of code containing a "function call".
The program enters the function (starts at the first line in the function code).
All instructions inside of the function are executed from top to bottom.
The program leaves the function and goes back to where it started from.
Any data computed and RETURNED by the function is used in place of the function in
the original line of code.
Functions allow us to create sub-steps. (Each sub-step can be its own function and a
group of Instructions)
They allow us to reuse code instead of rewriting it.
Functions allow us to keep our variable namespace without any confusion.
Functions allow us to test small parts of our program in isolation from the rest.
/
Understand the purpose of the function.
in
Define the data that comes into the function (in the form of parameters).
n.
Define what data variables are needed inside the function to accomplish its goal.
Decide the data produces as output to accomplish this goal.
aa
to work.
//w
output variables.
tp
Function Workspace
Every function has its own Workspace which means that every variable inside the
ht
function is only usable during the execution of the function. After that we cannot use the
variable. The variables can be created inside the function or passed as an argument.
Function Workspace
Every function has its own Workspace which means that every variable inside the
function is only usable during the execution of the function. After that we cannot use the
variable. The variables can be created inside the function or passed as an argument.
The parameter "r" is called a Formal parameter, this just means a place holder name for
radius.
The variable ‘radius’ is the Actual parameter, this means "what is actually used" for this call to
the function
Example:
Write a Python Program to find area of a circle:
>>>def circle(r): #Where ‘r’ is the Formal Parameter
/
rad=3.14*r*r
in
print(“The area of circle is”,rad)
n.
>>>radius=9
>>>circle(radius) #Where ‘radius’ is the Actual Parameter
aa
1.3 NOTATIONS (CLASSIFICATIONS OF AN ALGORITHM):
i. Pseudo code
o riy
The Notations of an algorithm is classified into three
Pseudo cannot be compiled nor executed, and there are no real format or syntax rules
The benefits of pseudo code is it enables the programmer to concentrate on the algorithm
tp
Ex:
READ num1, num2
result = num1 + num2
WRITE result.
/
in
ELSE
print b
n.
End multi line Structures
Each structure must be ended properly to provide more clarity
aa
Ex: END IF
Keep statements language Independent.
riy
The statement should be Independent to the language we are using. The
language features should be used properly.
o
.p
Advantages of Pseudo Code.
Can be done easily on a word processor.
w
Easily modified.
Implements structured concepts well.
w
It is not visual.
There is no standard format.
tp
Examples:
1. Write a pseudocode to find the area of circle.
BEGIN
READ radius r
INITIALIZE pi=3.14
COMPUTE Area=pi*r*r
PRINT r
2. Write a pseudocode to find the biggest of two numbers
BEGIN
READ A, B
IF A>B
PRINT “B is big”
ELSE
PRINT “A is big”
3. Write a pseudocode for calculating total marks of specified number of subjects given as
66, 99, 98, 87, 89
/
BEGIN
in
INITIALIZE total=0,i=1
n.
WHILE i<n
READ mark
aa
total=total+mark
PRINT i
END
INCREMENT i o riy
.p
w
1.3.2. Flowchart
A flow chart is a diagrammatic representation that illustrates the sequence of operations
w
to be performed to arrive the solution.
//w
Each step in the process is represented by a different symbol and has a short description
of the process steps.
s:
The flow chart symbols are linked together with arrows showing flow directions.
tp
ht
/
in
and directions of flow
Represent a circle and a letter or
n.
6. Connectors digit inside the circle. Used to
aa
connect two flow charts
Which maps out the process in terms of who is doing the steps.
tp
Which shows various participants and the flow of steps among those participants.
(or)
Only one flow line should enter a decision symbol but two or three flow lines can leave.
/
in
Only one flow line is used in conjunction with terminal symbol
n.
aa
Start Stop
the data more clearly.
o riy
Write within standard symbols briefly. You can also use annotation symbol to describe
– – – Calculation Part
.p
If the flowchart becomes complex then it is better to use connector symbols to reduce the
w
Validity of a flow chart can be tested by passing through it with a simple test data.
Advantages of Flow Chart:
s:
Flow Charts acts as a blue print during system analysis and program development phase.
The maintenance of operating program becomes easy with the help of flow chart.
Disadvantages of Flow Chart:
Sometimes the program logic is quite complicated, In that case flowchart becomes
complex and clumsy.
If alterations are required the flowchart may require re-drawing completely.
As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem.
Example:
1. Draw a flowchart to find the area of circle.
Start
Read r
area=3.14*r*r
/
in
n.
Print area
aa
Stop
o riy
.p
w
w
//w
s:
Start
tp
ht
Read a,b
a>b
yes No
/
in
n.
aa
o riy
Start
.p
Read N
w
w
//w
Total=0
i=1
s:
tp
ht
If
i<n
Stop Total=Total+Mark
Yes No
/
in
n.
aa
o riy
.p
w
w
//w
s:
tp
ht
/
Each Computer has its own machine language.
in
The Machine Language encodes the instructions for the computer.
n.
Ex:
aa
01010010101
An assembler is used to convert the assembly language into an executable machine code.
w
Start
//w
add x,y
sub x,y
s:
…
…
tp
End
ht
/
Ex for High Level Programming Language:
in
main()
n.
{
aa
if(x<y)
{
print(“x is greater”)
}
o riy
else
.p
{
w
print(“y is greater”)
}
w
}
//w
1. Fortan
tp
2. C
ht
3. C++
4. Java
5. Pearl
Define Compiler:
A Compiler is a computer software that transforms computer code written in High Level
Programming Language into Machine Language (0,1) as well as vice versa.
Define Interpreter:
An Interpreter translates a High Level Programming Language into an immediate form of
Machine Level Language. It executes instructions directly without compiling.
Define Assembler:
/
A sequence of steps involved in designing and analyzing an algorithm is shown in the
in
figure below.
n.
Understand the Problem
aa
o riy
Decide on Computational Means,
exact vs approximate solving
.p
algorithmic design technique
w
w
Design an algorithm
//w
Prove Correctness
s:
tp
An Input to an algorithm specifies an instance of the problem and range of the input to
handle the problem.
ii) Decision making
The Decision making is done on the following:
a) Ascertaining the Capabilities of the Computational Device
After understanding the problem one need to ascertain the capabilities of the
computational device the algorithm is intended for.
/
Sequential Algorithms:
in
o Instructions are executed one after another. Accordingly, algorithms designed to
n.
be executed on such machines.
aa
Parallel Algorithms:
o An algorithm which can be executed a piece at a time on many different
riy
processing device and combine together at the end to get the correct result.
iii) Choosing between Exact and Approximate Problem Solving:
o
The next principal decision is to choose between solving the problem exactly (or) solving
.p
it approximately.
w
An algorithm used to solve the problem exactly and produce correct result is called an
w
exact algorithm.
If the problem is so complex and not able to get exact solution, then we have to choose an
//w
algorithm called an approximation algorithm. i.e., produces an approximate answer.
Ex: extracting square roots.
s:
In Object oriented programming, data structures is an important part for designing and
ht
analyzes of an algorithm.
Data Structures can be defined as a particular scheme or structure to organize the data.
/
action.
in
vii) Proving an algorithm’s correctness:
n.
Once an algorithm has been specified, it has to be proved for its correctness.
aa
An algorithm has to prove with the input to yield a required output with respective of
time. A Common technique is mathematical induction.
viii) Analyze the algorithm:
riy
For an algorithm the most important is efficiency. In fact, there are two kinds of
o
algorithm efficiency. They are:
.p
space efficiency.
Some factors to analyze an algorithm are:
s:
o Generality of an algorithm
ix) Coding of an algorithm:
The coding / implementation of an algorithm is done by a suitable programming language
like C, C++, JAVA, PYTHON.
The transition from an algorithm to a program can be done correctly and it should be
checked by testing.
After testing, the programs are executed and this solves our problem.
An Iterative function is one that repeats some parts of the codes again and again until one
condition gets false.
Ex:
Write a Python program to print 10 values:
>>>i=0
>>>while i<=10:
print(“The Value of i is”,i)
/
i++
in
>>>
n.
Recursion:
aa
A Recursive function is the one which calls itself again and again to repeat the code. The
Recursion terminates when a base case Iteration terminates when loop continuation test
2.
is recognized. becomes false.
s:
occupied.
Examples:
Algorithm, Pesudocode, Flowchart for finding Factorial using Recursion
1. Algorithm to find the factorial of given number using recursion
Step1: Start
Step2: Read the value of n
Step3: Call factorial(n) and store the result in f
/
in
2. Write the pseudocode for finding the factorial using recursion
n.
BEGIN factorial
READ n
aa
f=factorial(n)
PRINT f
subprogram
Begin Factorial (n)
o riy
.p
IF n==0 THEN return 1
w
Factorial(n)
Start
Read n Return
if
3. Draw the flowchart for finding the factorial using recursion n*factorial(n-1)
n==
0
f =factorial(n)
Return 1
No
Print f
Unit I Page 1.23
https://www.poriyaan.in/ https://eee.poriyaan.in/
yes
/
in
n.
ILLUSTRATIVE EXAMPLES
aa
1.1. Find Minimum in a list:
Algorithm: Start
Step1:Start
Step2:Read total number of elements in the list
Step3:Read the first element as E
o riy
Read N
.p
Step4:MIN=E
Read first Element as E
Step5:SET i=2
w
IS
Step10:goto Step 6
I<N
Step11:Print MIN
tp
Step12:stop
ht
Read I th Element as E
Pseudocode
BEGIN
READ total number of elements in the list Is
READ the first element as E E<
SET MIN=E N
SET i=2
MIN=E
WHILE I <= n
Read ith element as E
if E < MIN then set MIN=E I=I+1
i=i+1
Print MIN
END
Flow chart:
/
in
n.
N
aa
Y
o riy
.p
N
w
Y
w
//w
s:
tp
ht
Position 0 1 2 3 4 5
Original list 4 6 9 10 11
7>11 4 6 9 10 11
7>10 4 6 9 10 11
7>9 4 6 9 10 11
7>6 4 6 7 9 10 11
Start
/
Algorithm:
in
Step 1: Start
n.
Step 2: Declare variables N, List[], i, and X.
Step 3: READ Number of element Read in sorted list as N
no of element as E
aa
Step 4: SET i=0
Step 5: IF i<N THEN go to step 6 ELSE go to step 9
Step 6: READ Sorted list element as List[i]
Step 7: i=i+1
Step 8: go to step 5
o riy
i=0
Pseudocode
Read Sorted List List[i]
READ Number of element in sorted list as N
SET i=0
s:
WHILE i<N
READ Sorted list element as List[i] Read x
tp
i=i+1 i=N-1
ht
ENDWHILE
READ Element to be insert as X
SET i = N-1
WHILE i >=0 and X < List[i]
List[i+1] =List[i] i>=0
i=i–1 &&
END WHILE X<List[i
List[i+1] = X ]
Flow Chart
List[i+1]=List[i]
i=i+1
List[i+1]=X
Unit I Page 1.26
https://www.poriyaan.in/ https://eee.poriyaan.in/
/
in
n.
aa
o riy
.p
N
w
w
Y
//w
s:
tp
ht
Step 1: Start
Step 2: SET Count =0
Step 3: READ Range as N
Step 4: SELECT an RANDOMNUMBER from 1 to N as R
Start
Step 5: READ User Guessed Number as G
Step 6: Count = Count +1 Count=0
Step 7: IF R==G THEN go to step 10 ELSE go to step 8
/
Step 8: IF R< G THEN PRINT “Guess is Too
Read range N High” AND go to step 5 ELSE go to step9
in
Step 9: PRINT “Guess is Too Low” AND go to step 5
n.
Step 10: PRINT Count as Number of Guesses Took
R=random Number from 1 to N
aa
Pseudocode:
SET Count =0
READ Range as N
SELECT an RANDOM NUMBER from 1 to N as R
o riy
Read User guessesed Number G
WHILE TRUE
.p
Count=Count+1
READ User guessed Number as G
w
Count =Count +1
w
IF R== G THEN
IS
//w
BREAK R==
ELSEIF R<G THEN G
DISPLAY “Guess is Too High”
s:
ELSE
tp
IS
DISPLAY “Guess is Too Low” R>G
ht
ENDIF
ENDWHILE
DISPLAY Count as Number of guesses Took
IS Print “Grade is high”
R>G
/
in
Y
n.
N
aa
o
Y
riy N
.p
w
w
//w
Y
s:
tp
ht
/
in
n.
aa
o riy An outline to
solve this
problem,
.p
from the
w
starting pole,
to the goal
w
3. Move the tower of height-1 from the intermediate pole to the final pole using the
tp
original pole.
ht
we can use the three steps above recursively to solve the problem.
/
in
Output:
moving disk from A to B
n.
moving disk from A to C
aa
moving disk from B to C
moving disk from A to B
moving disk from C to A
moving disk from C to B
moving disk from A to B
o riy
.p
A recursive Step based algorithm for Tower of Hanoi
w
END Procedure
Flow Chart for Tower of Hanoi Algorithm
Begin Hanoi(disk,source,dest,aux)
IS
disk==1
/
in
n.
aa
Honai(disk-1,source,aux,dest)
Move disk from source to dest
Honai(disk-1,source,aux,dest)
w
//w
s:
tp
Stop
ht
WORKSHEETS
Flowchart:
/
in
n.
aa
o riy
.p
w
w
Flowchart:
//w
s:
tp
Pseudocode:
ht
1. 2. Draw a Flowchart and write a pesudocode to find biggest between three numbers.
/
in
n.
aa
o riy
.p
w
w
Flowchart:
//w
Pseudocode:
s:
tp
ht
/
in
n.
aa
o riy
.p
w
w
Flowchart:
//w
Pseudocode:
s:
tp
ht
/
in
n.
aa
o riy
.p
w
w
Flowchart:
//w
Pseudocode:
s:
tp
ht
/
in
n.
aa
riy
o
.p
w
w
Flowchart:
//w
Pseudocode:
s:
tp
ht
/
in
n.
aa
o riy
.p
w
w
Flowchart:
//w
Pseudocode:
s:
tp
ht
/
in
n.
aa
o riy
.p
w
w
Flowchart:
//w
s:
Pseudocode:
tp
ht
/
in
n.
aa
riy
o
.p
w
w
//w
s:
Pseudocode:
tp
ht
TWO MARKS
/
ALGORITHM : Find Minimum of 3 numbers in a list
in
Step 1: Start
n.
Step 2: Read the three numbers A, B, C
Step 3: Compare A and B.
aa
If A is minimum, go to step 4 else go to step 5 Step 4: Compare A and C.
o riy
If A is minimum, output “A is minimum” else output “C is minimum”. Go to step 6.
Step 5: Compare B and C.
If B is minimum, output “B is minimum” else output “C is minimum”.
.p
Step 6: Stop
w
Statements
//w
Sequence
Selection or Conditional
s:
Functions
ht
/
in
7. Write the pseudo code to calculate the sum and product displaying the answer on the
n.
monitor screen.
BEGIN
aa
INITIALIZE variables sum, product, number1, number2 of type real
READ number1, number2 sum = number1 +number2
PRINT “The sum is “, sum
COMPUTE product = number1 * number2
o riy
.p
PRINT “The Product is “, product
w
END program
8. Give the rules for writing Pseudo codes.
w
.
9. Give the difference between flowchart and pseudo code.
Flowchart is a graphical representation of the algorithm.
Pseudo code is a readable, formally English like language representation.
10. Define a flowchart.
A flowchart is a diagrammatic representation of the logic for solving a task. A flowchart
is drawn using boxes of different shapes with lines connecting them to show the flow of control.
The purpose of drawing a flowchart is to make the logic of the program clearer in a visual form.
/
A flowchart should have a start and end,
in
The direction of flow in a flowchart must be from top to bottom and left to right
n.
The relevant symbols must be used while drawing a flowchart.
aa
13. Mention the characteristics of an algorithm.
Algorithm should be precise and unambiguous.
o riy
Instruction in an algorithm should not be repeated infinitely.
Ensure that the algorithm will ultimately terminate.
.p
Algorithm should be written in sequence.
w
//w
The normal mode is the mode where the scripted and finished .py files are run in the Python
tp
interpreter. Interactive mode is a command line shell which gives immediate feedback for each
statement, while running previously fed statements in active memory
ht
/
17.Give the differences between recursion and iteration
in
Recursion Iteration
n.
Function calls itself until the base condition is Repetition of process until the condition fails.
reached.
aa
Only base condition (terminating condition) is It involves four steps: initialization, condition,
specified. execution and updation.
It keeps our code short and simple.
It is slower than iteration due to overhead of
maintaining stack.
o riy
Iterative approach makes our code longer.
Iteration is faster.
.p
It takes more memory than iteration due to Iteration takes less memory.
overhead of maintaining stack.
w
w
Advantages Disadvantages
Recursive functions make the code look clean Sometimes the logic behind recursion is hard to
and elegant. follow through.
s:
tp
A complex task can be broken down into Recursive calls are expensive (inefficient) as
simpler sub-problems using recursion. they take up a lot of memory and time.
ht
Sequence generation is easier with recursion Recursive functions are hard to debug.
than using some nested iteration.
20. Write an algorithm to accept two number. compute the sum and print the result.
(University question)
Step 1: Start
Step 2: READ the value of two numbers
Step 3:Compute sum of two numbers
Step 4 :Print the sum
Step 5:Stop
21. Write an algorithm to find the minimum number in a given list of numbers. (University
question)
/
Step 1: Start
in
Step 2:Read the total number of element in the list as N
n.
Step3:Read first element as E
Step 4:MIN=E
aa
Step 5:Set i=2
Step6:IF i>n goto Step 11 ELSE goto Step 7
Step 7:Read i th element as E
Step 8:IF E<MIN then set MIN=e
o riy
.p
Step 9:i=i+1
w
Step12:Stop
//w
22. Outline the logic to swap the contents of two identifiers without using the third variable
s:
(University question)
tp
Step1: Start
Step 2:Read A,B
ht
Step 3 :A=A+B
Step 4:B=A-B
Step5:A=A-B
Step 6:Print A ,B
Step 7:Stop
PROGRAM
The most important skill for a computer Engineer is problem solving. Problem solving
/
in
means the ability to formulate problem, think creatively about solution clearly and accurately.
The process of learning to program is an excellent opportunity to practice Problem solving skills.
n.
“A program is a sequence of instructions that specifies how to perform a computation” .The
aa
computation might be mathematical i e Solving equations, Finding the roots of polynomial,
symbolic computation such as searching and replacing text in a document.
Basic Instruction in Language
Input: Get data from Keyboard.
o riy
.p
Output: Display data on the screen
Math: Perform the mathematical operations.
w
2.1 INTRODUCTION
Python
s:
Python is a high level programming language like C, C++ designed to be easy to read,
tp
and less time to write. It is an open source and it is an interpreter which directly executes the
program without creating any executable file. Python is portable which means python can run on
ht
Interpreter
Source Code (or) Source Code
Intermediate
/
operating python can also be found in the start menu. All Programs Python 3.6 Python 3.6
in
(Shell) and Python IDLE.
n.
2.2.2 Python Interactive mode
aa
Interactive mode is a command line which gives immediate feedback for each statement.
Python interactive mode can be start by two methods - Python 3.6 (Shell) and Python
IDLE.
riy
Python 3.6 (Shell), A prompt will appear and it usually have 3 greater than signs (>>>).
o
Each Statements can be enter after this (>>>) symbol. For continuous lines three dots (…)
.p
will represent the multiple lines.
w
Python IDLE (Integrated Development for Learning Environment) which provides a user
w
friendly console to the python users. Different colors are used to represent different
keywords.
//w
IDLE starts by python version, after a line (>>>) three greater than symbols will be
displayed. The statements will be executed in that line.
s:
Example:
tp
>>> 1+1
ht
2
>>>5+10
15
2.2.3 In Script mode
In script mode, type python program in a file and store the file with .py extension and use
the interpreter to execute the content of the file which is called a script.
Working in script mode is convenient for testing small piece of code because you can
type and execute them immediately, But for more than few line we can use script since
we can modify and execute in future.
2.2.4 Debugging
Programming is error –prone, programming errors are called bugs and process of tracking
them is called debugging.
Three kinds of error can occur in a program:
o Syntax Error
o Runtime Error
o Semantic error.
Syntax error:
/
Syntax refers to the structure of a program and rules about the structure. Python can only
in
execute a program if the syntax is correct otherwise the interpreter display an error
n.
message.
aa
Runtime Error:
The error that occurs during the program execution is called run time error.
Semantic Error:
riy
The computer will not generate any error message but it will not do the right thing since
o
the meaning of the program is wrong.
.p
2.2.5 Integrated Development Environment (IDE)
w
We can use any text editing software to write a Python script file. We just need to save it
w
with the .py extension. IDE is a piece of software that provides useful features like code hinting,
syntax highlighting and checking, file explorers etc. to the programmer for application
//w
development.
IDLE is a graphical user interface (GUI) that can be installed along with the Python
s:
programming language.
tp
Example:
ht
Type the following code in any text editor or an IDE and save it as helloWorld.py
print("Hello world!")
To run the script, type python helloWorld.py in the command window and the output as
follows:
Hello world!
2.3.1Values
A value is one of the fundamental things; a program works with like a word or number.
Some example values are 5, 83.0, and 'Hello, World!'. These values belong to different types:
5 is an integer, 83.0 is a floating-point number, and 'Hello, World!' is a string. If you are not
sure what type a value has, the interpreter can tell you:
>>>type(5)
<class 'int'>
/
>>>type(83.0)
in
<class 'float'>
n.
>>>type('Hello, World!')
aa
<class 'str'>
In these results, the word ―class‖ is used in the sense of a category; a type is a category
riy
of values. Integers belong to the type int, strings belong to str and floating-point numbers belong
to float. The values like '5' and '83.0' look like numbers, but they are in quotation marks like
o
strings.
.p
>>>type('5')
w
<class 'str'>
>>>type('83.0')
w
<class 'str'>
//w
a) Integer
b) Float
ht
c) Boolean
d) String
e) List
f) Tuple
g) Dictionary
a) Integer
Let Integer be positive values, negative values and zero.
Example:
>>>2+2
4
>>>a=-20
print() 20
>>> type(a) <type ‘int’>
b) Float
A floating point value indicates number with decimal point.
Example:
>>> a=20.14
>>>type(a) <type ‘float’>
/
c) Boolean
in
A Boolean variable can take only two values which are True or False. True and False
n.
are simply set of integer values of 1 and 0.The type of this object is bool.
Example:
aa
>>>bool(1)
True
>>>bool(0)
False
o riy
.p
>>>a=True
w
>>>c=’True’
//w
>>>True + 1
tp
2
>>>False * 85
ht
0
# A Boolean variable should use Capital T in true & F in False and shouldn’t be enclosed within
the quotes.
>>>d=10>45 #Which returns False
Boolean Operators
Boolean Operations are performed by ‘AND’, ‘OR’, ‘NOT’.
Example:
True and True True
True and False False
True or True True
/
>>>type(a)
in
<type ‘str’>
n.
Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0 in
the beginning of the string and working their way from -1 at the end. The plus (+) sign is the
aa
string concatenation operator and the asterisk (*) is the repetition operator.
Example:
>>>str = 'Python Programming'
>>>print(str)
o riy
# Prints complete string
>>>print(str[0]) # Prints first character of the string
.p
Output
s:
Python Programming
P
tp
g
tho
ht
thon Programming
Python ProgrammingPython Programming
Python Programming Course
String Functions:
For the following string functions the value of str1 and str2 are as follows:
>>>str1=”Hello”
>>>str2=”World”
S.No Method Syntax Description Example
1. print(str1+str2)
+ String1 + String2 It Concatenates two Strings
HelloWorld
2. str1*3
* String*3 It multiples the string
HelloHelloHello
/
3. len() len(String) Returns the length of the String len(str1) 5
in
4. The String will be centred
along with the width specified str1.centre(20,+)
n.
centre() centre(width,fullchar)
and the charecters will fill the ++++Hello++++
aa
space
5. Converts all upper case into
lower() String.lower() str1.lower() hello
lower case
6.
upper() String.upper() riy
Converts all lower case into
upper case
o str1.upper() HELLO
corresponding value
9. It converts a number in to its
//w
e) List
A list is an ordered set of values, where each value is identified by an index. The values
that make up a list are called its elements. A list contains items separated by commas and
enclosed within square brackets ([]). Lists are mutable which means the items in the list can be
add or removed later.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+)
sign is the list concatenation operator, and the asterisk (*) is the repetition operator.
Example:
>>>list = [ 'Hai', 123 , 1.75, 'vinu', 100.25 ]
>>>smalllist = [251, 'vinu']
>>>print(list) # Prints complete list
>>>print(list[0]) # Prints first element of the list
>>>print(list[-1]) # Prints last element of the list
/
in
>>>print(list[1:3]) # Prints elements starting from 2nd till 3rd
>>>print list([2:]) # Prints elements starting from 3rd element
n.
>>>print(smalllist * 2) # Prints list two times
>>>print(list + smalllist) # Prints concatenated lists
aa
Output
['Hai', 123, 1.75, 'vinu', 100.25]
Hai
100.25
o riy
[123, 1.75]
.p
[1.75, 'vinu', 100.25]
w
f) Tuple
Tuple are sequence of values much like the list. The values stored in the tuple can be of
s:
any type and they are indexed by integers. A tuple consists of a sequence of elements separated
by commas. The main difference between list and tuples are:” List is enclosed in square bracket
tp
([ ]) and their elements and size can be changed while tuples are enclosed in parenthesis (( )) and
ht
cannot be updated.
Syntax:
tuple_name=(items)
Example:
>>> tuple1=(‘1’,’2’,’3’,’5’)
>>>tuple2=(‘a’,’b’,’c’)
>>>tuple3=’3’,’apple’,’100’
>>>print(tuple2) #print tuple2 elements
>>>print(tuple2[0]) #print the first element of tuple2
/
g) Dictionary
in
Dictionaries are an unordered collection of items. Dictionaries are enclosed by curly
n.
braces ‘{ }’ .The element in dictionary is a comma separated list of keys: value pairs where keys
are usually numbers and strings and values can be any arbitrary python data types. The value of a
aa
dictionary can be accessed by a key. and values can be accessed using square braces ‘[ ]’
Syntax:
Example:
>>>dict1={}
w
>>>dict2={1:10,2:20,3:30}
//w
>>>dict3={‘A’:’apple’,’B’:’200’}
>>>Dict={‘Name’:’john’,’SSN’:4576,’Designation’:’Manager’}
s:
Keywords are reserved words that cannot be used as ordinary identifiers. All the
ht
Identifiers can be composed of uppercase, lowercase letters, underscore and digits bur
should start only with an alphabet or an underscore.
Identifiers can be a combination of lowercase letters (a to z) or uppercase letters (A to Z)
or digits or an underscore.
Identifiers cannot start with digit
Keywords cannot be used as identifiers.
Only ( _ ) underscore special symbol can be used.
/
Valid Identifiers: sum total _ab_ add_1
in
Invalid Identifies: 1x x+y if
n.
2.6 VARIABLES
aa
A variable is nothing but a reserved memory location to store values. A variable in a
program gives data to the computer.
Ex:
>>>b=20
o riy
>>>print(b)
.p
2.7 PYTHON INDENTATION
w
Python uses indentation. Block of code starts with indentation and ends with the
w
unintended line. Four whitespace character is used for indentation ans is preferred over tabs.
Ex:
//w
x=1
if x==1:
s:
print(“x is 1”)
tp
Result:
ht
x is 1
2.8 EXPRESSIONS
An Expression is a combination of values, variables and operators.
Ex:
>>>10+20
12
2.9 STATEMENTS
A Statement is an instruction that a python interpreter can execute.IN python enf of a
statement is marked by a newline character.
c=a+b
Multiline statement can be used in single line using semicolon(;)
>>a=1;b=10;c=a +b
Ex:
>>>b=20
>>>print(b)
>>>print(“\”Hello\””)
A statement is a complete line of code that performs some action, while an expression is
any section of the code that evaluates to a value. Expressions can be combined ―horizontally
/
into larger expressions using operators, while statements can only be combined vertically by
in
writing one after another, or with block constructs. Every expression can be used as a statement,
n.
but most statements cannot be used as expressions
aa
2.10 TUPLE ASSIGNMENTS
Ex:
o riy
Tuple Assignment means assigning a tuple value into another tuple.
t=(‘Hello’,’hi’)
.p
>>>m,n=t
w
>>>print(m) Hello
w
>>>print(n) hi
>>>print(t) Hello,hi
//w
In order to interchange the values of the two tuples the following method is used.
>>>a=(‘1’,’4’)
s:
>>>b=(‘10’,’15’)
tp
>>>a,b=b,a
ht
>>>print(a,b)
((‘10’,’15’), (‘1’,’4’))
2.11 COMMENTS
Comments are non-executable statements which explain what program does. There are
two ways to represent a comment.
2.11.1 Single Line Comment
Begins with # hash symbol
Ex:
>>>print(“Hello world”) # prints the string
/
Eg: 4+5=9
in
Where 4, 5, 9 are operand
n.
+ is Addition Operator
aa
= is Assignment Operator
Types of Operator:
1.
2.
3.
Arithmetic Operator
riy
Comparison Operator (or) Relational Operator
Assignment Operator
o
.p
4. Logical Operator
5. Bitwise Operator
w
6. Membership Operator
7. Identity Operator
w
//w
1. Arithmetic Operator
It provides some Arithmetic operators which perform some arithmetic operations
Consider the values of a=10, b=20 for the following table.
s:
Example Program:
1.Write a Python Program with all arithmetic operators
>>>num1 = int(input('Enter First number: '))
>>>num2 = int(input('Enter Second number '))
>>>add = num1 + num2
/
in
>>>print('Modulus of ',num1 ,'and' ,num2 ,'is :',modulus)
>>>print('Exponent of ',num1 ,'and' ,num2 ,'is :',power)
n.
>>>print('Floor Division of ',num1 ,'and' ,num2 ,'is :',floor_div)
Output:
aa
>>>
Enter First number: 10
Enter Second number 20
Sum of 10 and 20 is : 30
o riy
Difference of 10 and 20 is : -10
.p
Product of 10 and 20 is : 200
Division of 10 and 20 is : 0.5
w
Modulus of 10 and 20 is : 10
w
>>>
s:
condition. Consider the values of a=10, b=20 for the following table.
ht
3. Assignment Operator
Assignment operators are used to hold a value of an evaluated expression and used for
assigning the value of right operand to the left operand.
Consider the values of a=10, b=20 for the following table.
Operator Syntax Meaning Description
= a=b a=b It assigns the value of b to a.
+= a+=b a=a+b It adds the value of a and b and assign it to a.
-= a-=b a=a-b It subtract the value of a and b and assign it to a.
/
in
*= a*=b a=a*b It multiplies the value of a and b and assign it to a.
/= a/=b a=a/b It divides the value of a and b and assign it to a.
n.
%= a%=b a=a%b It divides the value of a and b and assign the
remainder to a.
aa
**= a**=b a=a**b It takes ‘a’ as base value and ‘b’ as its power and
assign the answer to a.
//= a//=b a=a//b o riy
It divides the value of a and b and takes the least
quotient and assign it to a.
4. Logical Operator
.p
Logical Operators are used to combine two or more condition and perform logical
w
A B A&B A|B ~A
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0
/
1. Write a Python Program with all Bitwise Operator
in
a = 10 # 10 = 0000 1010
n.
b = 20 # 20 = 0001 0100
c=0
aa
c = a & b; # 0 = 0000 0000
print ("Line 1 - Value of c is ", c)
c = a | b; # 30 = 0001 1110
print ("Line 2 - Value of c is ", c)
c = ~a;
print ("Line 3 - Value of c is ", c)
o riy # -11 = 0000 1011
Output:
//w
Line 1 - Value of c is 12
Line 2 - Value of c is 61
s:
6. Membership Operator
Membership Operator test for membership in a sequence such as strings, lists or tuples.
Consider the values of a=10, b=[10,20,30,40,50] for the following table.
Operator Syntax Example Description
value in String or If the value is ‘in’ the list then
in a in b returns True
List or Tuple it returns True, else False
value not in String If the value is ‘not in’ the list
not in a not in b returns False
or List or Tuple then it returns True, else False
Example:
x=’python programming’
print(‘program’ not in x)
print(‘program‘ in x)
print(‘ Program‘ in x)
Output:
False
True
False
/
in
7. Identity Operator
n.
Identity Operators compare the memory locations of two objects.
aa
Consider the values of a=10, b=20 for the following table.
Operator Syntax Example Description
is variable 1 is variable 2
riy
a is b returns False
o If the variable 1 value is pointed
to the same object of variable 2
value then it returns True, else
False
.p
Example:
s:
x1=7
y1=7
tp
x2=’welcome’
ht
y2=’Welcome’
print (x1 is y1)
print (x2 is y2)
print(x2 is not y2)
Output:
True
False
True
/
in
>>> 20 – 5*3
5
n.
But we can change this order using Parentheses () as it has higher precedence.
>>> (20 - 5) *3
aa
45
The operator precedence in Python are listed in the following table.
1. () Parentheses
w
2. ** Exponent
3. +x, -x, ~x Unary plus, Unary minus, Bitwise NOT
w
5. +, - Addition, Subtraction
6. <<, >> Bitwise shift operators
s:
9. | Bitwise OR
ht
If more than one operator exists in the same group. These operators have the same
precedence. When two operators have the same precedence, associativity helps to determine
which the order of operations. Associativity is the order in which an expression is evaluated that
has multiple operator of the same precedence. Almost all the operators have left-to-right
associativity. For example, multiplication and floor division have the same precedence. Hence, if
both of them are present in an expression, left one evaluates first.
Example:
>>> 10 * 7 // 3
23
>>> 10 * (7//3)
20
/
>>> (10 * 7)//3
in
23
n.
10 * 7 // 3 is equivalent to (10 * 7)//3.
aa
Exponent operator ** has right-to-left associativity in Python.
>>> 5 ** 2 ** 3
390625
>>> (5** 2) **3
o riy
.p
15625
w
2 ** 3 ** 2 is equivalent to 2 ** (3 ** 2).
//w
2.15 FUNCTIONS
A function is a named sequence of statements that performs a specific task. Functions
help programmers to break complex program into smaller manageable units. It avoids repetition
and makes code reusable.
Types of Functions
Functions can be classified into
BUILT-IN FUNCTIONS
USER DEFINED FUNCTIONS
2.15.1 BUILT-IN FUNCTIONS
The Python interpreter has a number of functions that are always available for use. These
functions are called built-in functions. The syntax is
function_name(parameter 1, parameter 2)
/
in
i) type()
n.
>>>type(25)
<class 'int'>
aa
The name of the function is type(). The expression in parentheses is called the argument
riy
of the function. The result, for this function, is the type of the argument. Function takes an
argument and returns a result. The result is also called the return value.
o
Python provides functions that convert values from one type to another. The int()
.p
function takes any value and converts it to an integer, if it can, or it shows error otherwise:
w
ii) Casting:
>>>int('25')
w
25
//w
>>>int('Python')
valueError: invalid literal for int(): Python
s:
int() can convert floating-point values to integers, but it doesn’t round off; it chops off the
tp
fraction part:
>>>int(9.999999)
ht
9
>>>int(-2.3)
-2
float() converts integers and strings to floating-point numbers:
>>>float(25)
25.0
>>>float('3.14159')
3.14159
Finally, str() converts its argument to a string:
>>>str(25)
'25'
iii) range()
The range() constructor returns an immutable sequence object of integers between the
given start integer to the stop integer.
Python's range() Parameters
The range() function has two sets of parameters, as follows:
/
i) range(stop)
in
stop: Number of integers (whole numbers) to generate, starting from zero.
n.
eg. range(3) == [0, 1, 2].
ii) range([start], stop[, step])
aa
start: Starting number of the sequence.
[0,1,2,3,4,5,6,7,8,9]
>>>range(5,10)
w
[5,6,7,8,9]
//w
>>>range[10,1,-2]
[10,8,6,4,2]
s:
tp
expressions, and it will separate the results with single blanks by default.
Example:
>>> x=10
>>> y=7
>>>print(‘The sum of’,x, ‘plus’, y, ‘is’, x+y)
Output:
The sum of 10 plus 7 is 17
print statement can pass zero or more expressions separated by commas.
/
The input([prompt]) function print the string which is in the prompt and the cursor point
in
will wait for an input.
n.
>>>str = input("Enter your input: ");
Enter your input: 10
aa
>>> print(“The input is : ", str)
10
Syntax:
w
A function definition is a heart of the function where we will write main operation of that
//w
function.
Syntax:
s:
Example:
>>>def welcome(person_name):
"""This function welcome the person passed in as parameter"""
print(" Welcome " , person_name , " to learn Python")
/
Using Function or Function Call
in
Once we have defined a function, we can call it from another function, program or even
n.
the Python prompt. To call a function we simply type the function name with appropriate
parameters.
aa
Syntax:
function_name(parameter 1, parameter 2)
Example:
o riy
.p
>>> welcome('Students')
w
Output:
Welcome Students to learn Python.
w
//w
called.
tp
Syntax:
ht
return variable_name
This statement can contain expression which gets evaluated and the value is returned. If
there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object.
Example:
>>>def absolute_value(num):
"""This function returns the absolute value of the entered number"""
if num >= 0:
return num
else:
return -num
>>>print(absolute_value(5))
>>>print(absolute_value(-7))
Output:
5
7
/
2.15.3 FLOW OF EXECUTION
in
The order in which statements run is called the flow of execution. Execution always
n.
begins at the first statement of the program. Statements are run one at a time, in order from top to
aa
bottom. Function definitions do not alter the flow of execution of the program, but when the
function is called Instead of going to the next statement, the flow jumps to the body of the
Inside the function, the arguments are assigned to variables called parameters. Here is a
.p
definition for a function that takes an argument:
w
Function Arguments
Types of Formal arguments:
w
Required arguments
//w
Default arguments
Keyword arguments
s:
Variable-length arguments
tp
ht
Required Arguments
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the function
definition.
Example:
>>>def add(a,b): # add() needs two arguments, if not it shows error
return a+b
>>>a=10
>>>b=20
>>>print("Sum of ", a ,"and ", b, "is" , add(a,b))
Output:
Sum of 10 and 20 is 30
Default Arguments:
A default argument is an argument that assumes a default value if a value is not provided
in the function call for that argument.
Example:
>>>def add(a,b=0):
print ("Sum of ", a ,"and ", b, "is" ,a+b)
/
>>>a=10
in
>>>b=20
n.
>>>add(a,b)
>>>add(a)
aa
Output:
Sum of 10 and 20 is 30
Sum of 10 and 0 is 10
o riy
.p
Keyword Arguments:
w
Keyword arguments are related to the function calls. When you use keyword arguments
in a function call, the caller identifies the arguments by the parameter name.
w
Example:
//w
>>>def add(a,b):
print ("Sum of ", a ,"and ", b, "is" ,a+b)
s:
>>>a=10
tp
>>>b=20
>>>add(b=a,a=b)
ht
Output:
Sum of 20 and 10 is 30
Variable-Length Arguments:
The special syntax *args in function definitions in python is used to pass a variable
number of arguments to a function. It is used to pass a non-keyworded, variable-length argument
list.
The syntax is to use the symbol * to take in a variable number of arguments; by
convention, it is often used with the word args.
What *args allows you to do is take in more arguments than the number of formal
arguments that you previously defined. With *args, any number of extra arguments can
be tacked on to your current formal parameters
Example:
>>>def myFun(*argv):
for arg in argv:
print (arg)
/
>>>myFun('Hello', 'Welcome', 'to', 'Learn Python')
in
Output:
n.
Hello
Welcome
aa
to
Learn Python
normal functions are defined using the def keyword, in Python anonymous functions are defined
using the lambda keyword. Hence, anonymous functions are also called lambda functions.
w
Syntax:
//w
Example:
tp
>>>double = lambda x: x * 2
ht
print(double(5))
Output:
10
In the above program, lambda x: x * 2 is the lambda function. Here x is the argument and
x * 2 is the expression that gets evaluated and returned.
The same Anonymous function can be written in normal function as
>>>def double(x):
return x * 2
>>>double(5)
2.16 MODULES
Modules
a) Importing Modules
b) Built-in Modules
Define Module
A module allows you to logically organize the python code. Grouping related code into a
module makes the code easy to use. A module is a file consisting python code. A module can
/
define functions, classes and variables. A module can also include runnable code.
in
Example:
n.
The Python code for a module add normally resides in a file named addition.py.
aa
support.py
>>>def add(a,b):
result=a+b
return result
o riy
.p
a) Importing Modules
We can invoke a module by two statements
w
i. import statement
w
You can use any Python source file as a module by executing an import statement in
some other Python source file.
s:
Syntax:
tp
import module
Example:
ht
addition.py
>>>def add(a,b):
result=a+b
return result
subt.py
>>>def sub(a,b):
result=a-b
return result
/
>>>from example import add,sub
in
>>> print(addition.add(9,2))
n.
11
aa
>>>print(subt.sub(5,2))
3
b) Built-in Modules
riy
Python have many built-in modules such as random, math, os, date, time, URLlib21.
o
i) random module:
.p
This module is used to generate random numbers by using randint function.
w
Ex:
w
import random
print(random.randint(0,5))
//w
print(random.random())
print( random.random()*10)
s:
my_data=[156,85,”john’,4.82,True]
tp
print(random.choice(my_data))
ht
Output:
1
0.675788
5.2069
4.82
ii) math module:
This math module provides access to mathematical constants and functions.
Ex:
>>>import math
>>>math.pi #Pi, 3.14
/
iii) date & time module
in
It is useful for web development. This is module is use to display date and time
n.
Ex:
>>>import datetime
aa
>>> x = datetime.datetime.now()
>>>print(x)
Output:
o riy
.p
w
w
//w
iii)Calender module:
s:
>>>import calendar
>>>cal=calendar.month(2019,5)
ht
>>>print(cal)
Output:
Calendar is displayed
ILLUSTRATIVE EXAMPLES
Note- Always get an Input from the USER.
1. Write a python Program to find the area of a triangle
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: ')) # calculate the semi-perimeter
s = (a + b + c) / 2 # calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print(“The area of the triangle is f”,area) # displays the area
/
in
Output:
>>> Enter first side: 6
n.
Enter second side: 8
Enter third side: 10
aa
The area of the triangle is f 24.0
>>>
d = (b**2) - (4*a*c)
sol1 = (-b-cmath.sqrt(d))/(2*a) # find two solutions
w
sol2 = (-b+cmath.sqrt(d))/(2*a)
//w
print(“The solution are {0} and {1}”.format(sol1,sol2)) # displays the quadratic equation
Output:
>>> Enter a: 1
Enter b: 5
s:
Enter c: 6
tp
/
x1 = float(input("Enter the first Number: ")) #Getting inputs from the user
in
x2 = float(input("Enter the Second Number: "))
y1 = float(input("Enter the third number: "))
n.
y2 = float(input("Enter the forth number: "))
print("The distance between two points are",distance(x1,x2,y1,y2))
aa
#Calling the function distance
Output:
>>> Enter the first Number: 2
Enter the Second Number: 4
Enter the third number: 6
Enter the forth number: 12
o riy
The value of dx is 4.0
.p
The value of dy is 8.0
The distance between two points are 8.94427190999916
w
def circulate(list,n):
return list[n:]+list[:n]
>>>print(“The Values Shift two places in Clockwise: ”circulate([1,2,3,4,5,6,7],2))
s:
Output:
ht
WORKSHEETS
Note: - Always Get an Input from the User
/
in
n.
Output:
aa
Formula: miles=kilometer*conversion_factor
o riy
2.2 Write a python program to convert Kilometers to Miles (Conversion factor = 0.621)
.p
Program:
w
w
//w
s:
Output:
tp
ht
Output:
Program:
/
Output:
in
n.
aa
2.5. Write a python program to find Compound Interest
Formula: Compound Interest = P(1+ R/100)Time
Program:
o riy
.p
w
w
//w
Output:
s:
tp
2.6. Write a python program to o display your details like name, age, address in three
ht
different lines.
Program:
Output:
TWO MARKS
1. What is a value? What are the different types of values? (University question)
A value is one of the fundamental things – like a letter or a number – that a program
manipulates. Its types are: integer, float, , strings , lists and Dicitionary.
2. Define a variable and write down the rules for naming a variable.
A name that refers to a value is a variable. Variable names can be arbitrarily long. They
can contain both letters and numbers, but they have to begin with a letter. It is legal to use
/
in
uppercase letters, but it is good to begin variable names with a lowercase letter.
n.
3. Define keyword and enumerate some of the keywords in Python. (University question)
aa
A keyword is a reserved word that is used by the compiler to parse a program. Keywords
cannot be used as variable names. Some of the keywords used in python are: and, del, from, not,
while, is, continue.
o riy
.p
4. Define statement and what are its types?
A statement is an instruction that the Python interpreter can execute. There are two types
w
Eg 1: Message = “hello”
tp
Eg 2: n = 17
ht
8. What do you mean by an operand and an operator? Illustrate your answer with relevant
example.
An operator is a symbol that specifies an operation to be performed on the operands. The
data items that an operator acts upon are called operands. The operators +, -, *, / and ** perform
addition, subtraction, multiplication, division and exponentiation.
Example: 20+32
In this example, 20 and 32 are operands and + is an operator.
/
in
9. What is the order in which operations are evaluated? Give the order of precedence.
n.
The set of rules that govern the order in which expressions involving multiple operators
and operands are evaluated is known as rule of precedence. Parentheses have the highest
aa
precedence followed by exponentiation. Multiplication and division have the next highest
precedence followed by addition and subtraction.
o riy
10. Illustrate the use of * and + operators in string with example.
.p
The * operator performs repetition on strings and the + operator performs concatenation
w
on strings.
Example:
w
>>> ‘Hello*3’
//w
Output: HelloHelloHello
>>>’Hello+World’
s:
Output: HelloWorld
tp
/
in
14. What is a local variable?
n.
A variable defined inside a function. A local variable can only be used inside its function.
aa
15. What is the output of the following?
a. float(32)
b. float("3.14159")
Output:
o riy
.p
a. 32.0 The float function converts integers to floating-point numbers.
w
In order to ensure that a function is defined before its first use, we have to know the order
in which statements are executed, which is called the flow of execution. Execution always begins
s:
at the first statement of the program. Statements are executed one at a time, in order from top to
tp
bottom.
17. Write down the output for the following program.
ht
first = 'throat'
second = 'warbler' print first + second
Output:
throatwarbler
18. Give the syntax of function definition.
def NAME( LIST OF PARAMETERS ):
STATEMENTS
/
float.
in
Eg:
n.
>>> minute = 59
>>> minute / 60.0
aa
0.983333333333
A list of the functions that tells us what program file the error occurred in, and what line,
//w
and what functions were executing at the time. It also shows the line of code that caused the
error.
s:
tp
23. Write a program to accept two numbers multiply them and print them. (University
question)
ht
A=10
B=2
multiplication=A*B
print (“Multiplication of two numbers :” ,multiplication)
BOOLEAN VALUES:
/
in
Boolean values can be tested for truth value, and used for IF and WHILE condition. There
are two values True and False. 0 is considered as False and all other values considered as True.
n.
Boolean Operations:
aa
Consider x=True, y= False
Operator Example Description
and
or
not
x and y- returns false
x or y- returns true
not x returns false
o riy Both operand should be true
Anyone of the operand should be true
Not carries single operand
.p
Control structures
//w
s:
/
in
if expression:
true statements
n.
aa
Flow Chart
o riy
.p
Test False
Expres
sion
w
w
True
//w
Body of if stmt
s:
tp
Example:
a=10
ht
if a==10:
print(“a is equal to 10”)
Output:
a is equal to 10
2. if else statement
The second form of if statement is “alternative execution” in which there are two possibilities and
the condition determines which block of statement executes.
Syntax
if test_expression:
true statements
else:
false statements
If the testexpression evaluates to true then truestatements are executed else falsestatements are
executed.
Flow Chart
True False
Test
Expres
sion
/
in
Body of if Body of else
n.
aa
End of Code
Example:
o riy
.p
a=10
if a==10:
w
Output:
a is equal to 10
s:
and execute a block of code as soon as one of the conditions evaluates to true. The elif statement
ht
has more than one statements and there is only one if condition.
Syntax
if expression 1:
true statements
elif expression 2:
true statements
elif expression 3:
true statements
else:
false statement
Flow Chart
Test
Expressi False
on
of if
/
in
Test
True False
n.
Expressi
Body of if on
of elif
aa
True
Body of elif
o riy
Body of else
.p
w
End of Code
w
//w
Example:
a=9
if a==10:
s:
elif a<10:
print(“a is lesser than 10”)
elif a>10:
ht
if expression 1:
true statements
else:
/
if expression 2:
in
true statements
n.
else:
false statement
aa
o riy
.p
Flow Chart
w
w
Test
True Conditio False
//w
n1
s:
tp
Body of if
Test
True False
ht
Conditio
n2
End of Code
Example:
a=10
if a==100:
print(“a is equal to 10”)
else:
if a>100:
print(“a is greater than 100”)
else
print(“a is lesser than 100”)
/
Output:
in
a is lesser than 100
n.
3.1.2 Iteration (or) Looping Statement
An Iterative statement allows us to execute a statement or group of statement multiple
aa
times. Repeated execution of a set of statements is called iteration or looping.
Types of Iterative Statement
1. while loop
2. for loop
o riy
.p
3. Nested loop
1. while loop
w
A while loop executes a block of statements again and again until the condition gets false.
w
The while keyword is followed by test expression and a colon. Following the header is an
//w
indented body.
s:
Syntax
tp
while expression:
true statements
ht
Flow Chart
Entering While
loop
Test
Expressi False
on
True
Body of while
Unit III Page 3.6
https://www.poriyaan.in/ GE3151 - Problem Solving And Python Programming https://eee.poriyaan.in/
Exit Loop
Example-1:
1.Write a python program to print the first 100 natural numbers
i=1
while (i<=100):
print(i)
i=i+1
Output:
/
Print numbers from 1 to 100
in
Example-2:
n.
2. Write a python program to find factorial of n numbers.
aa
n=int(input("Enter the number:"))
i=1
fact=1
while(i<=n):
fact=fact*i
o riy
i=i+1
.p
Output:
Enter the number: 5
w
2. for loop
The for loop is used to iterate a sequence of elements (list, tuple, string) for a specified
s:
number of times.
tp
For loop in python starts with the keyword “for”followed by an arbitrary variable name,which
ht
Syntax
for iterating_variable in sequence:
statements
A sequence represents a list or a tuple or a string. The iterating variable takes the first item
in the sequence. Next, the statement block is executed. Each item in the list is assigned to the
iterating variable and the statements will get executed until the last item in the sequence get
assigned.
Flow Chart
Entering for each item in
for loop sequence
Is Last
Item
Reached No Yes
?
/
in
n.
aa
Body of for
Exit Loop
Example-1:
o riy
for letter in”python”:
.p
print(“The current letter:”, letter)
Output:
w
3.1.3.Unconditional Statement
/
In a situation the code need to exit a loop completely when an external condition is
in
triggered or need to skip a part of the loop. In such situation python provide unconditional
n.
statements.
aa
Types of Unconditional looping Statement
1. break statement
2. continue statement
3. pass statement
o riy
1.break statement
.p
A break statement terminates the current loop and transfers the execution to statement
w
immediately following the loop. The break statement is used when some external condition is
triggered.
w
Syntax
//w
break
s:
Flow Chart
tp
Condition Code
ht
If condition
is true brea
Conditio
k
n
If condition is False
Example:
for letter in”python”:
if letter==’h’:
break
print(letter)
print(“bye”)
Output:
pyt
/
bye
in
2. continue statement
n.
A continue statement returns the control to the beginning of the loop statement. The
continue statement rejects all remaining statement and moves back to the top of the loop.
aa
Syntax
continue
Flow Chart
o riy
.p
Condition Code
w
If condition
w
is true
//w
Conditio
conti
n
nue
s:
tp
If condition is False
ht
Example:
for letter in”python”:
if letter==’h’:
continue
print(letter)
print(“bye”)
Output:
pyton
bye
3. pass statement
A pass statement is a null operation, and nothing happens when it executed.
Syntax
pass
Example:
for letter in”python”:
if letter==’h’:
/
in
pass
print(letter)
n.
print(“bye”)
aa
Output:
python
bye
by an expression which is evaluated, its result is returned to the caller as the “fruit” of calling this
w
function.
w
len(variable) – which takes input as a string or a list and produce the length of string or a list as an
output.
s:
range(start, stop, step) – which takes an integer as an input and return a list containing all the
tp
/
Function Name – ‘distance()’
in
Function Definition – def distance(x1, y1, x2, y2)
Formal Parameters - x1, y1, x2, y2
n.
Actual Parameter – dx, dy
aa
Return Keyword – return the output value ‘dist’
Function Calling – distance(x1, y1, x2, y2)
Parameter in fruitful function
A function in python
Take input data, called parameter
o riy
Perform computation
.p
Return result
w
def funct(param1,param2):
w
statements
return value
//w
Once the function is defined,it can be called from main program or from another function.
Function call statement syntax
s:
tp
Result=function_name(param1,param2)
ht
Parameter is the input data that is sent from one function to another. The parameters are of two
types
1. Formal parameter
The parameter defined as part of the function definition.
The actual parameter is received by the formal parameter.
2. Actual parameter
The parameter is defined in the function call
Example-1:
def cube(x):
return x*x*x #x is the formal parameter
a=input(“Enter the number=”)
b=cube(a) #a is the actual parameter
print”cube of given number=”,b
Output:
Enter the number=2
/
in
Cube of given number=8
n.
3.3 Composition:
aa
A Composition is calling one function from another function definition.
Example:
def addition(x,y,z):
o riy
Write a python program to add three numbers by using function:
#function 1
.p
add=x+y+z
return add
w
Output:
Enter first number:5
tp
Scope is the portion of the program from where a namespace can be accessed directly
without any prefix. When a reference is made inside a function, the name is searched in the local
namespace, then in the global namespace and finally in the built-in namespace.
>>>a=”I am in world”
/
>>>outer_function()
in
>>>print(‘a=’,a)
n.
Output:
a=I am in TamilNadu
aa
a=I am in India
a=I am in World
def inner_function():
a=” I am in TamilNadu”
w
print(“a=”a)
iner_function()
//w
print(‘a=”,a)
s:
>>>a=”I am in world”
>>>outer_function()
tp
>>>print(‘a=’,a)
Output:
ht
a=I am in TamilNadu
a=I am in TamilNadu
a=I am in TamilNadu
3.5 Recursion:
A Recursive function is the one which calls itself again and again to repeat the code. The
recursive function does not check any condition. It executes like normal function definition and
the particular function is called again and again
Syntax:
def function(parameter):
#Body of function
Example-1:
Write a python program to find factorial of a number using Recursion:
def fact(n):
if(n<=1):
return n
else:
/
return n*fact(n-1)
in
n=int(input("Enter a number:"))
n.
print("The Factorial is", fact(n))
aa
Output:
>>> Enter a number:5
>>>
The Factorial is 120
Explanation:
o riy
First Iteration - 5*fact(4)
.p
Second Iteration - 5*4* fact(3)
Third Iteration - 5*4*3*fact(2)
w
Example-2:
Write a python program to find the sum of a ‘n’ natural number using Recursion:
def nat(n):
s:
if(n<=1):
tp
return n
else:
ht
return n+nat(n-1)
>>>n=int(input("Enter a number:"))
>>>print("The Sum is", nat(n))
Output:
>>> Enter a number: 5
The Sum is 15
>>>
Explanation:
First Iteration – 5+nat(4)
Second Iteration – 5+4+nat(3)
Third Iteration – 5+4+3+nat(2)
Fourth Iteration – 5+4+3+2+nat(1)
Fifth Iteration – 5+4+3+2+1
3.6 String:
A string is a combination of characters. A string can be created by enclosing the characters
within single quotes or double quotes. The character can be accessed with the bracket operator.
Example:
var1=’Hello’
var2=”Python Programming”
print(var1) # Prints Hello
print(var2) # Prints Python Programming
Traversal with a for Loop
/
in
A lot of computations involve in processing a string, one character at a time. Often they
start at the beginning, select each character in turn, do something to it, and continue until the end.
n.
This pattern of processing is called a traversal.
aa
Example:
>>>index = 0
>>>str="Python"
>>>while index < len(str):
o riy
letter = str[index]
.p
print(letter, end="")
w
index = index+1
w
Output:
//w
Python
3.6.1 String Slices:
s:
variable [start:stop]
ht
<String_name> [start:stop]
Example
Char a= “B A N A N A”
Index from Left 0 1 2 3 4 5
Index from Right -6 -5 -4 -3 -2 -1
>>>print(a[0]) prints B #Prints B Alone 0th Position
>>>print(a[5]) prints A #Prints A Alone Last Position
>>>print(a[-4]) print N #Print From Backwards -4th Position
>>>a[:] 'BANANA' #Prints All
>>>print(a[1:4]) print ANA #Print from 1st Position to 4th Position
>>> print(a[1:-2]) ANA #Prints from 1st position to -3th Position
/
S.No Method Syntax Description Example
in
1. len() len(String) Returns the length of the String len(a) 5
n.
The String will be centered
String.center(width,fill along with the width specified a.center(20,+)
2. center()
aa
char) and the characters will fill the ++++Hello++++
space
3.
4.
lower()
upper()
String.lower()
String.upper()
o riy
Converts all upper case into
lower case
Converts all lower case into
b.lower() hello
a.upper() HELLO
upper case
.p
It converts the first letter into
5. capitalize() String.capitalize() b.capitalize() Hello
capital
w
/
c.isdecimal() returns
in
16. isdecimal() String.isdecimal() contains decimal value or false
1
otherwise
n.
Returns title cased, all the d=”hello how h u”
17. title() String.title() characters begin with upper d.title() ”Hello How
aa
case R U”
a.find(“e”,0,4)
String.find(“text”, If the string is found it returns
18. find()
start,end)
riy
index position or it returns -1
o
The string will check for
returns 1 (index
position)
23. rindex()
beg, end) from right to left returns 3
String.rjust(width, It will justify the character into a.rjust(10,’-‘)
24. rjust()
fillchar) right and fill with the character -----Hello
String.ljust(width, It will justify the character into a.ljust(10,a,’+‘)
25. ljust()
fillchar) left and fill with the character Hello+++++
It removes all the spaces at the
26. rstrip() rstrip() rstrip(a) it returns -1
end
startswith(text, beg, It checks whether the character a.stratswith(H,0)
27. startswith()
end) starts with the specified one returns true
/
in
print("split", "=>", string.split(text))
n.
print("join", "=>", string.join(string.split(text), "+"))
print("replace", "=>", string.replace(text, "Python", "Java"))
aa
print("find", "=>", string.find(text, "Python"), string.find(text, "Java"))
print("count", "=>", string.count(text, "n"))
Output:
upper => MONTY PYTHON'S FLYING CIRCUS
o riy
lower => monty python's flying circus
.p
find => 6 -1
//w
count => 3
The word in is a boolean operator that takes two strings and returns True if the first appears as a
tp
>>>‘t’ in 'python'
True
>>> 'jan' in 'python'
False
3.9 List as Array
To store such data, in Python uses the data structure called list (in most programming
languages the different term is used — “array”).
Arrays are sequence types and like lists, except that the type of objects stored in them is
constrained. A list (array) is a set of objects. Individual objects can be accessed using ordered
indexes that represent the position of each object within the list (array).
The list can be set manually by enumerating of the elements the list in square brackets, like here:
Unit III Page 3.19
https://www.poriyaan.in/ GE3151 - Problem Solving And Python Programming https://eee.poriyaan.in/
ILLUSTRATIVE EXAMPLES
Note- Always get an Input from the USER.
1. Program to find the square root using Newton Method.
/
2. Program to find the GCD of two numbers
in
3. Program to find the exponential of a number
n.
4. Program to find the sum of n numbers.
aa
5. Program to find the maximum and minimum in a list
6. Program to perform the linear search
7. Program to perform Binary search
o riy
.p
1. Write a python Program to Check if a Number is Positive, Negative or 0
Using if...elif...else
w
if num > 0:
print("Positive number")
//w
elif num == 0:
print("Zero")
else:
s:
print("Negative number")
Output:
tp
Positive number
3.2 Using Nested if
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Output:
>>> Enter a number: 5
Positive number
/
print("{0} is not a leap year".format(year))
in
Output:
>>>
n.
Enter a year: 2000
2000 is a leap year
aa
>>>
Enter a year: 1991
1991 is not a leap year
count = 0
# check if the number of terms is valid
w
if nterms <= 0:
//w
print(n1)
else:
tp
print(n1,end=' , ')
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1 # Ending of While loop
Output:
How many terms? 10
Fibonacci sequence upto 10 :
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 ,
>>>
/
print(num,"is not an Armstrong number")
in
Output:
n.
>>> Enter a number: 121
121 is not an Armstrong number
>>>
aa
3.6 Write a Python Program to Find LCM of two numbers
def lcm(x, y):
if x > y:
greater = x
o riy
.p
else:
greater = y
w
while(True):
if((greater % x == 0) and (greater % y == 0)):
w
lcm = greater
break
//w
greater += 1
return lcm
num1 = int(input("Enter first number: "))
s:
Output:
ht
Output:
>>>
[17, 15, 4]
/
[10, 12, 9]
in
[11, 13, 18]
n.
>>>
aa
X = [[12,7],
[4 ,5],
[3 ,8]]
result = [[0,0,0],
[0,0,0]]
o riy
# iterate through rows
for i in range(len(X)):
.p
# iterate through columns
for j in range(len(X[0])):
w
result[j][i] = X[i][j]
w
for r in result:
//w
print(r)
Output:
s:
>>>
[12, 4, 3]
tp
[7, 5, 8]
>>>
ht
for i in range(len(X)):
# iterate through column Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
Output:
/
in
>>> [114, 160, 60, 27]
[74, 97, 73, 14]
n.
[119, 157, 112, 23]
aa
3.10 Write a Python Program to Check Whether a String is Palindrome or Not
my_str = 'madame'
my_str = my_str.casefold()
rev_str = reversed(my_str)
o riy # it suitable for case less comparison
# reverse the string
.p
if list(my_str) == list(rev_str): # check the string is equal to its reverse
print("It is palindrome")
w
else:
w
Output:
>>>
s:
It is not palindrome
tp
3.11 Write a Python Program to count the number of each vowel in a string.
vowels = 'aeiou' # string of vowels
ht
ip_str = 'Hello, have you tried our turorial section yet?' # change this value
ip_str = input("Enter a string: ")
ip_str = ip_str.casefold() # make it suitable for caseless comparisions
count = {}.fromkeys(vowels,0) # make a dictionary with each vowel a key and value 0
for char in ip_str: # count the vowels
if char in count:
count[char] += 1
print(count)
Output:
>>>{'o': 5, 'i': 3, 'a': 2, 'e': 5, 'u': 3}
Unit III Page 3.24
https://www.poriyaan.in/ GE3151 - Problem Solving And Python Programming https://eee.poriyaan.in/
WORKSHEETS
NOTE: Always get an Input from the User
3.1. Write a python program for Sum of squares of first n natural numbers
12+22+32+………+n2
Program:
/
in
n.
aa
Output:
o riy
.p
w
w
3.2. Write a python program to find two numbers which are divisible by 13
//w
Program:
s:
tp
ht
Output:
Program:
/
in
n.
aa
Output:
o riy
.p
w
Program:
s:
tp
ht
Output:
3.5. Write a python program to accept the strings which contains all vowels
Input : ABeeIghiObhkUul Output : Accepted
Program:
/
in
n.
aa
Output:
o riy
.p
w
Input : s = "qwertyu" , d = 2
//w
Program:
s:
tp
ht
Output:
3.7. Write a python program Find words which are greater than given length k
Input : str = "string is easy in python" , k=3
Output : string easy python
Program:
/
in
n.
aa
Output: o riy
.p
w
Output : Python-is-Easy
Program:
s:
tp
ht
Output:
TWO MARKS
1. Define Boolean expression with example.
A boolean expression is an expression that is either true or false. The values true and false
are called Boolean values.
Eg :
>>> 5 == 6
>>> False
/
True and False are special values that belongs to the type bool; they are not strings.
in
n.
2. What are the different types of operators?
aa
Arithmetic Operator (+, -, *, /, %, **, // )
Relational operator ( == , !=, <>, < , > , <=, >=)
Logical Operator (AND, OR, NOT)
o riy
Assignment Operator ( =, += , *= , - =, /=, %= ,**= )
Identity(is, is not)
//w
divided by the second. In Python, the modulus operator is a percent sign (%). The syntax is the
tp
Eg:
>>> remainder = 7 % 3
>>> print remainder 1
So 7 divided by 3 is 2 with 1 left over.
/
in
6. What is conditional execution?
n.
The ability to check the condition and change the behavior of the program accordingly is
aa
called conditional execution. Example:
If statement:
The simplest form of if statement is:
Syntax:
o riy
.p
if statement:
Eg:
w
if x > 0:
w
The boolean expression after ‘if’ is called the condition. If it is true, then the indented
statement gets executed. If not, nothing happens.
s:
tp
Sometimes there are more than two possibilities and we need more than two branches. One
way to express a computation like that is a chained conditional:
Eg:
if x < y:
print 'x is less than y'
elif x > y:
print 'x is greater than y'
else:
/
in
print 'x and y are equal'
n.
elif is an abbreviation of “else if.” Again, exactly one branch will be executed. There is no
aa
limit on the number of elif statements. If there is an else clause, it has to be at the end, but there
doesn’t have to be one.
9. Explain while loop with example. Eg:
def countdown(n):
o riy
.p
while n > 0:
print n
w
n = n-1
w
print 'Blastoff!'
//w
2. If the condition is false, exit the while statement and continue execution at the next
tp
statement.
3. If the condition is true, execute the body and then go back to step 1
ht
When a break statement is encountered inside a loop, the loop is immediately terminated
and the program control resumes at the next statement following the loop.
Eg:
while True:
line = raw_input('>')
if line == 'done':
break
print line
/
in
print'Done!'
n.
12. What is a continue statement?
aa
The continue statement works somewhat like a break statement. Instead of forcing
termination, it forces the next iteration of the loop to take place, skipping any code in between.
Eg:
for num in range(2,10):
o riy
.p
if num%2==0;
print “Found an even number”, num
w
continue
w
Return gives back or replies to the caller of the function. The return statement causes our
tp
def area(radius):
temp = math.pi * radius**2 return temp
Composition:
Calling one function from another is called composition.
Eg:
def circle_area(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp) result = area(radius)
return result
14.What is recursion?
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function.
Eg:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
/
in
15. Explain global and local scope.
n.
The scope of a variable refers to the places that we can see or access a variable. If we
aa
define a variable on the top of the script or module, the variable is called global variable. The
variables that are defined inside a class or function is called local variable.
Eg:
def my_local():
o riy
.p
a=10
print(“This is local variable”)
w
Eg:
w
a=10
//w
def my_global():
print(“This is global variable”)
s:
String Slices :
A segment of a string is called string slice, selecting a slice is similar to selecting a
character. Eg: >>> s ='Monty Python'
>>> print s[0:5] Monty
>>> print s[6:12] Python
17. Define string immutability.
Python strings are immutable. ‘a’ is not a string. It is a variable with string value. We can’t
mutate the string but can change what value of the variable to a new string.
/
in
uppercase letters. Instead of the function syntax upper(word), it uses the method syntax
word.upper().
n.
>>> word = 'banana'
aa
>>> new_word = word.upper()
>>> print new_word
BANANA
o riy
.p
20. Explain about string module.
The string module contains number of useful constants and classes, as well as some
w
Eg:
def bar():
pass
If the function bar() is called, it does absolutely nothing.
4.1 LISTS
Define List
/
A list is an ordered set of values, where each value is identified by an index. The values in
in
a list are called its elements or items. The items can be of different types (int, float, string). To
n.
create a new list, the simplest way is to enclose the elements in square bracket [ ]. Lists are
aa
mutable which means the items in the list can be add or removed later.
Example:
>>>[ ]
>>>[1,2,3]
#empty list
riy
#list of integers
o
>>>[‘physics’,’chemistry’,’python’] #list of strings
.p
>>>list1=[‘a’,’b,’c’’d’]
w
>>>print(list1)
//w
List can have another list as an item. This is called nested list.
Mylist=[‘mouse’,[8,6,5], 3.2]
List are mutable.
s:
Lists are mutable which means the items in the list can be added or removed later.
tp
>>>mark=[98,87,94]
ht
>>>mark[2]=100
>>>print(mark) #Prints [98,87,100]
To access the elements in a list
The syntax for accessing an element is same as string. The square brackets are used to
access the elements. The index value within the square brackets should be given.
>>>list1=[] #Empty list
>>>list2=[1,2,3,4,5,6,7,8]
>>>list3=[‘Hello’,3.5,’abc’,4]
print(list3[1]) → 3.5
List Length:
The function len returns the length of a list, which is equal to the number of elements.
len(list2) → 8
len(list3) → 4
List Membership:
The memberrship operator “in” and “not in” can also be used in a list to check whether
the element is present in the list or not.
/
Ex:
in
list3=[‘Hello’,3.5,’abc’,4]
n.
‘Hello’ in list3 → returns True
aa
4.1.1 LIST OPERATIONS:
1. + Operator which concatenates two lists.
>>>list2=[1,2,3,4,5,6,7,8]
>>>list3=[‘Hello’,3.5,’abc’,4]
o riy
.p
>>>print(list2+list3)
Output
w
1,2,3,4,5,6,7,8, ‘Hello’,3.5,’abc’,4
w
>>>list2=[1,2,3,4,5,6,7,8]
>>>list2*2
s:
Output
tp
1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8
4.1.2 LIST SLICE
ht
A subsequence of a sequence is called a slice and the operation that extracts a subsequence
is called slicing. For slicing we use square brackets [ ]. Two integer values splitted by ( : ).
Syntax:
List_Name[Starting_Value : Ending_Value]
Ex:
>>>a=[‘a’,’b’,’c’,’d’,’e’]
List a= ‘a’ ‘b’ ‘c’ ‘d’ ‘e’
Index from Left 0 1 2 3 4
Index from Right -5 -4 -3 -2 -1
/
Consider the values of list a and list b be
in
>>>a=[‘apple’,’mango’,’lime’]
n.
>>>b=[‘grape’]
aa
S.No Name Syntax Description Example
2. insert()
riy
the item to the end of a list
o
listname.insert(index,it This method inserts an item at a a.insert(1,’banana’)
.p
em) particular place and two
arguments (index,item)
w
w
argument. a.extend(b)
s:
/
in
11. clear() listname.clear() This method is used to clear all a.clear() -->[]
n.
the values in the list.
aa
4.1.4 LIST LOOP:
A loop is to access all the elements in a list.
>>>a=[‘apple’,’mango’,’lime’,’orange’]
o riy
>>>print(a) → [‘apple’,’mango’,’lime’,’orange’] # displays all at a time
.p
>>>print(a[0]) → ‘apple’
w
i) for var in a:
w
Output:
The loop goes on 4 times and print all values
‘apple’,’mango’,’lime’,’orange’
s:
‘apple’,’mango’,’lime’,’orange’
tp
‘apple’,’mango’,’lime’,’orange’
ht
‘apple’,’mango’,’lime’,’orange’
ii) for var in a:
print(var) #displays a item at a time
Output:
The loop goes on 4 times and print items one by one.
‘apple’
’mango’
‘lime’
’orange’
iii) >>>i=0
/
‘lime’
in
’orange’
n.
1. Write a python program to print the items in the list using while loop.
aa
>>>a=[‘apple’,’mango’,’lime’,’orange’]
>>>i=0
>>>while len(a)>i:
print(“I like”,a[i])
o riy
.p
i=i+1
w
Output:
The value of i makes the loop to goes on 4 times and print items one by one.
w
‘apple’
//w
’mango’
‘lime’
s:
’orange’
tp
Unlike String, List is mutable (changeable) which means we can change the elements at
any point.
Ex:
>>>a=[‘apple’,’mango’,’lime’,’orange’]
>>>a[0]=’grape’
>>>print(a) → ’grape’, ’mango’,’lime’,’orange’
4.1.6 LIST ALIASING:
Since variables refer to objects, if we assign one variable to another, both variables refer to
same objects.(One or more variable can refer the same object)
>>>a=[1,2,3]
>>>b=a
>>>a is b # Displays True
4.1.7 LIST CLONING:
If we want to modify a list and also keep copy of the original we can use cloning to copy
the list and make that as a reference.
Ex:
a=[1,2,3]
/
b=a[:]
in
print(b) [1,2,3]
n.
4.1.8 LIST PARAMETER:
aa
Passing a list as an argument actually passes a reference to the list, not the copy of the list.
We can also pass a list as an argument to the function.
Ex:
riy
>>> def mul(a_list): #a_list is a list passing as a parameter
o
for index,value in enumerate(a_list):
.p
a_list[index]=2*value
w
print(a_list)
w
>>> a_list=[1,2,3,4,5]
>>> mul(a_list)
//w
Output:
[2, 4, 6, 8, 10]
s:
4.2 TUPLE
tp
Tuples are sequence of values much like the list. The values stored in the tuple can be of
ht
tuple_name=(items)
Ex:
>>> tuple1=(‘1’,’2’,’3’,’5’)
>>>tuple2=(‘a’,’b’,’c’)
>>>tuple3=’3’,’apple’,’100’
/
t1=(‘a’,’b’)
in
t1=(‘A’,)+t1[1:] t1=(‘A’,’b)
n.
The disadvantage in this method is we can only add the items from the beginning.
4.2.1 TUPLE ASSIGNMENT
aa
Tuple Assignment means assigning a tuple value into another tuple.
Ex:
t=(‘Hello’,’hi’)
o riy
>>>m,n=t
.p
>>>print(m) Hello
w
>>>print(n) hi
>>>print(t) Hello,hi
w
In order to interchange the values of the two tuples The following method is used.
//w
>>>a=(‘1’,’4’)
>>>b=(‘10’,’15’)
s:
>>>a,b=b,a
tp
>>>print(a,b)
ht
((‘10’,’15’), (‘1’,’4’))
COMPARING TUPLES
The comparison operator works with tuple and other sequence. It will check the elements
of one tuple to another tuple. If they are equal it return true. If they are not equal it returns false.
>>>t1=(‘1’,’2’,’3’,’4’,’5’)
>>>t2=(‘a’,’b’,’c’)
>>>t1<t2 #It returns false
4.2.2 TUPLE AS RETURN VALUE
In a function a tuple can return multiple values where a normal function can return single
value at a time.
Example-1:
Using a built-in function divmod which return quotient and remainder at the same time.
>>>t=divmod(7,3)
>>>print(t) (2,1)
>>>quot,rem=divmod(7,3)
/
>>>print(quot) 2
in
>>>print(rem) 1
n.
Example-2:
def swap(a,b,c):
aa
return(c,b,a)
a=100
b=200
c=300
o riy
.p
>>>print(“Before Swapping”,a,b,c)
w
>>>print(“After Swapping”,swap(a,b,c))
Output:
w
4.3 DICTIONARIES
tp
Dictionaries is an unordered collection of items. Dictionaries are a kind of hash table. The
ht
value of a dictionary can be accessed by a key. Dictionaries are enclosed by curly braces ‘{ }’ and
values can be accessed using square braces ‘[ ]’
Syntax:
A Key can be any Immutable type like String, Number, Tuple. A value can be any
datatype. The values can be repeated and the keys should not be repeated.
Ex:
>>>dict1={}
>>>dict2={1:10,2:20,3:30}
>>>dict3={‘A’:’apple’,’B’:’200’}
>>>dict4={(1,2,3):’A’,(4,5):’B’}
>>>dict5={[1,2,3]:’A’,[4,5]:’B’} #Error, Only Immutable types can be assigned in Keys
4.3.1ACCESS, UPDATE, ADD, DELETE ELEMENTS IN DICTIONARY:
Accessing Values in Dictionary
To access dictionary elements, you can use the familiar square brackets along with the key
to obtain its value.
Ex:
/
>>>d={‘name’:’xyz’,’age’:23}
in
>>>d[‘name’] ’xyz’ # since ’name’ is a String datatype, it should be represented within quotes
n.
>>>d[name] shows error
aa
By get()method
>>>d.get(‘name’) ‘xyz’
Update Values in Dictionary
riy
You can update a dictionary by adding a new entry or a key-value pair, modifying an
o
existing entry.
.p
Ex:
w
>>> d={‘name’:’xyz’,’age’:23}
>>>print(d) {‘ name’:’xyz’,’age’:23}
w
>>>print(d) {‘ name’:’xyz’,’age’:23}
By update method
s:
>>>d1={‘place’:’abc’}
tp
>>>d.update(d1)
ht
/
2. keys() dictionary.keys() Return the dictionary's >>> d.keys()
in
keys. ['a', 'c', 'b', 'd']
n.
3. values() dictionary.values() Return the dictionary's >>> d.values()
Values [1, 3, 2, 4]
aa
4. items() dictionary.items() Return the dictionary's >>> d.items()
Keys and Values [('a', 1), ('c', 3), ('b',
6. key not in key not in dict Returns True if the Key is >>> 'e' not in d
dict not in Dictionary, else True
w
returns false.
//w
/
in
often the qualities of sets. It consists of brackets containing an expression followed by a for clause,
n.
then zero or more for or if clauses.
Ex-1:
aa
>>>x = [i for i in range(10)]
>>>print x
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Ex-2:
o riy
.p
>>>squares = []
>>>for x in range(10):
w
squares.append(x**2)
w
print (squares)
>>>squares = [x**2 for x in range(10)] # List comprehensions to get the same result:
//w
>>>print (squares)
Output:
s:
ILLUSTRATIVE EXAMPLES
Note- Always get an Input from the USER.
1.Write a Python Program to find Largest, Smallest, Second Largest, Second Smallest in a
List without using min() & max() function.
>>>def find_len(list1):
length = len(list1)
/
list1.sort()
in
print("Largest element is:", list1[length-1])
n.
print("Smallest element is:", list1[0])
aa
print("Second Largest element is:", list1[length-2])
print("Second Smallest element is:", list1[1])
>>>list1=[12, 45, 2, 41, 31, 10, 8, 6, 4]
>>>Largest = find_len(list1)
o riy
Output:
.p
Largest element is: 45
w
Program 2.1:
tp
>>>empty=[]
>>> print(subject, mark, empty)
Output:
['Physics', 'Chemistry', 'Computer'], [98, 87, 94], []
Program 2.2:
>>>mark=[98,87,94]
>>> mark[2]=100
>>> print(mark)
Output:
[98, 87, 100]
Unit IV Rohini College of Engineering and technology Page
4.12
https://www.poriyaan.in/ GE3151 - Problem Solving And Python Programming https://eee.poriyaan.in/
Program 2.3:
>>> subject= ['Physics', 'Chemistry', 'Computer']
>>> 'Chemistry' in subject
Output:
True
Program 2.4:
>>> subject= ['Physics', 'Chemistry', 'Computer']
/
>>> for s in subject:
in
print(s)
Output:
n.
Physics
aa
Chemistry
Computer
Program 2.5:
>>> for i in range(len(mark)):
o riy
.p
mark[i] = mark[i] * 2
>>> print(mark)
w
Output:
w
WORKSHEETS
NOTE: Always get an Input from the User
4.1. Write a python program to interchange first and last elements in a list
Input : [1, 2, 3] Output : [3, 2, 1]
Program:
/
in
n.
aa
o riy
.p
Output:
w
w
//w
Program:
ht
Output:
Program:
/
in
n.
aa
Output:
o riy
.p
w
Program:
s:
tp
ht
Output:
Program:
/
in
n.
aa
Output:
o riy
.p
w
w
Program:
s:
tp
ht
Output:
Program:
/
in
n.
aa
Output:
o riy
.p
w
w
//w
Program:
s:
tp
ht
Output:
TWO MARKS
1. What is a list?
A list is an ordered set of values, where each value is identified by an index. The values
that make up a list are called its elements. Lists are similar to strings, which are ordered sets of
characters, except that the elements of a list can have any type.
/
in
2. Solve a)[0] * 4 and b) [1, 2, 3] * 3.
n.
>>> [0] * 4 [0, 0, 0, 0]
aa
>>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]
List is a mutable type meaning that it can be modified whereas dictionary is immutable and
ht
is a key value store. Dictionary is not ordered and it requires that the keys are hashable whereas
list can store a sequence of objects in a certain order.
/
>>> b=a
in
>>> b is a True
n.
8. Define cloning in list.
aa
In order to modify a list and also keep a copy of the original, it is required to make a copy
word “copy”.
o riy
of the list itself, not just the reference. This process is called cloning, to avoid the ambiguity of the
.p
9. Explain List parameters with an example.
w
Passing a list as an argument actually passes a reference to the list, not a copy of the list.
For example, the function head takes a list as an argument and returns the first element:
w
def head(list):
//w
return list[0]
output:
s:
>>> head(numbers)
ht
11. Write a program in Python returns a list that contains all but the first element of the
given list.
def tail(list): return list[1:]
Here’s how tail is used:
>>> numbers = [1, 2, 3]
>>> rest = tail(numbers)
/
>>> print rest [2, 3]
in
n.
12. What is the benefit of using tuple assignment in Python?
It is often useful to swap the values of two variables. With conventional assignments a
aa
temporary variable would be used. For example, to swap a and b:
>>>
>>>
>>>
temp = a
a=b
b = temp
o riy
.p
>>> a, b = b, a
w
index and a value separated by a colon. In a dictionary, the indices are called keys, so the elements
are called key-value pairs.
s:
tp
associated (or mapped) to a value. The values of a dictionary can be any Python data type. So
dictionaries are unordered key-value-pairs.
Example:
>>> eng2sp = {} # empty dictionary
>>> eng2sp[’one’] = ’uno’
>>> eng2sp[’two’] = ’dos’
15. How to return tuples as values?
A function can only return one value, but if the value is a tuple, the effect is the same as
returning multiple values. For example, if we want to divide two integers and compute the
quotient and remainder, it is inefficient to compute x/y and then x%y. It is better to compute them
both at the same time.
>>> t = divmod(7, 3)
>>> print t (2, 1)
/
Len - returns the number of key-value pairs
in
n.
17.Define dictionary methods with an example.
A method is similar to a function—it takes arguments and returns a value— but the syntax
aa
is different. For example, the keys method takes a dictionary and returns a list of the keys that
x=5
tp
y = 10
temp = x
ht
x=y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
5.1.1 FILES
/
A File is a collection of data or information which has a name, called filename. All the
in
information is stored in the computer using a file. The file is a named location on disk to store
n.
related information. It is used to store data in volatile memory. There are many different types of
aa
files.
Data File
Text File
Program File
Directory File
o riy
.p
Text File:
A text file is a sequence of characters stored on a permanent medium like a hard drive,
w
flash memory, or CD-ROM. Text files are identified with the .txt file extension.
w
Python provides inbuilt functions for creating, writing and reading files. There are two
types of files that can be handled in python, normal text files and binary files (written in binary
s:
Text files: In this type of file, each line of text is terminated with a special character called
EOL (End of Line), which is the new line character (“\n”) in python by default.
ht
Binary files: In this type of file, there is no terminator for a line and the data is stored after
converting it into machine understandable binary language.
In order to perform some operations on files we have to follow below steps
Opening
Reading or writing
Closing
When the user want to do some operations in the file there is a sequence of steps that
should be followed.
i. Open the File
ii. Read or Write data in the file
iii. Close the File
i .Open the File
Python has a built-in function open() to open a file. This function returns a file object and
has two arguments which are file name & opening mode. The opening modes are reading,
/
writing or appending.
in
Syntax:
n.
file_object=open(“filename”, “mode”)
aa
where file_object is the variable to add the object and the mode tells the interpreter which
way the file will be used.
Ex:
f=open(“text.txt”)
o riy
f=open(“E:/Python/text.txt”, ‘r’)
.p
f=open(“E:/Python/text.txt”, ‘w’)
w
w
f=open("F:/Python/test.txt","w+")
f.write("Python Programming is Interesting")
f.seek(0)
print(f.read())
f.close()
There are several opening modes apart from the main opening modes.
/
S.No Modes Description
in
1. rb Opens a file for reading only in binary format.
n.
2. r+ Opens a file for both reading and writing.
aa
3. rb+ Opens a file for both reading and writing in binary format.
4. wb Opens a file for writing only in binary format.
5.
6.
w+
wb+
riy
Opens a file for both writing and reading in binary format.
Opens a file for both writing and reading in binary format.
o
7. a+ Opens a file for both appending and reading.
.p
w
1. read() Method
w
Syntax:
file_object.read()
s:
Ex:
tp
f=open("F:/Python/test.txt","r")
print(f.read())
ht
print(f.read(2))
f.close()
2.write() Method
This method writes a string from an open file.
Syntax:
file_object.write(“String”)
Ex:
f=open("F:/Python/test.txt","w+")
print(f.write(“This is my first file”))
f.seek(0)
print(f.read())
f.close()
/
in
Syntax:
n.
file_object.close()
aa
Ex:
f=open("F:/Python/test.txt","r")
print(f.read())
f.close()
How to read a text file?
o riy
1. File Operation
.p
2. Opening Modes
3. Read Functions
w
There are two functions to read a file line by line, then there are two methods
w
readline()
readlines()
//w
1.readline()
Every time a user runs the method, it will return a string of characters that
s:
Syntax:
ht
file_object.readline()
Ex:
Consider the file test.txt contain these three lines
This is the First Line in the file
This is the Second Line in the file
This is the Third Line in the file
Now the Python source code is
f=open("F:/Python/test.txt","r")
print(f.readline())
f.close()
Output:
This is the First Line in the file #Returns the first line
2.readlines()
This method is used to return a list containing all the lines separated by the special
character ( \n ).
Syntax:
/
file_object.readlines()
in
n.
Ex:
Consider the same file
aa
Now the Python source code is
f=open("F:/Python/test.txt","r")
print(f.readline())
f.close()
o riy
.p
Output:
['This is the First Line in the file\n', 'This is the Second Line in the file\n', 'This is
w
>>> f=open("test.txt","r")
tp
>>>for line in f:
print(line)
ht
>>>f.close()
5.3. Write a python program to access a file using with statement.
Syntax:
/
1. tell()
in
2.seek()
n.
i) tell() method
aa
This method is used to tell the current position within a file. It starts from the
beginning of the file and this method followed by read() and write() method.
Syntax:
file_object.tell()
o riy
Ex:
.p
>>> f=open("F:/Python/test.txt","r")
>>>print(f.tell()) #0th poisition
w
>>>print(f.read())
w
Output:
0
s:
73
ht
file_object.seek(offset, from)
seek() method set the file’s current position at the offset. The default argument of offset is 0. The
offset represents the number of the bytes to be moved.
The from argument represents three values.
0 represents the beginning of the file
1 represents the current position as reference
2 represents the end of the file
Ex:
>>> f=open("F:/Python/test.txt","r")
>>>print(f.tell()) #0th poisition
>>>print(f.read())
>>>f.seek(0,0)
>>>f.seek(0,1)
>>>f.seek(0,2)
>>>f.close()
/
2. Renaming and Delete a File
in
Two file processing operations are there, they are
n.
i. rename() method
aa
ii. remove() method
i) rename() method
Syntax:
o riy
The rename() method takes two argument, the current filename and new filename.
.p
os.rename(current_filename, new_filename)
w
Ex:
w
>>>import os
>>>os.rename(“test.txt”,”new.txt ”)
//w
The remove() method is used to delete the file. The argument contains file name.
tp
Syntax:
ht
os.remove(filename)
Ex:
>>>import os
>>>os.rename(“new.txt ”)
3. Directories in Python
All files are contained within various directories. The os module has several methods to
create, remove and change directories.
/
in
5.1.5 FORMAT OPERATOR
n.
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:
aa
>>> f=open('stringsample.txt','w')
>>> f.write(5)
>>> f.write(str(5))
#TypeError o riy
An alternative is to use the format operator, %. The first operand is the format string,
.p
which contains one or more format sequences, which specify how the second operand is
w
>>>var=8
//w
The Value is : 8
tp
Sl No Conversion Meaning
1 d Signed integer decimal.
2 i Signed integer decimal
3 o Unsigned octal.
4 u Unsigned decimal.
5 x Unsigned hexadecimal (lowercase).
6 X Unsigned hexadecimal (uppercase).
7 e Floating point exponential format (lowercase).
8 E Floating point exponential format (uppercase).
9 f Floating point decimal format.
10 F Floating point decimal format.
/
in
Here sys.argv[0] is the program name.
Example 1
n.
Consider the following script command.py
aa
>>>import sys
>>>program_name = sys.argv[0]
>>>arguments = sys.argv[1:]
>>>count = len(arguments)
o riy
.p
>>>print(program_name)
>>>print(arguments)
w
>>>print(count)
w
//w
Output:
>>>C:\Python30>python.exe command.py Hello World
s:
/
i) Syntax Error
in
Python will find these kinds of errors when it tries to parse your program, and exit with
n.
an error message without running anything. Syntax errors are mistakes in the use of the Python
aa
Language, and are analogous to spelling or grammar mistakes in a language like English.
Common Python Syntax Errors include:
Leaving out a Keyword
Putting a keyword in a wrong place
o riy
Misspelling a Keyword
.p
Incorrect Indent
w
Unnecessary Spaces
Empty Spaces
w
Ex:
//w
>>>my function(x,y):
return x+y
s:
>>>else:
print(“Hello”)
tp
>>>if mark>=50
print(“Passed”)
ht
>>>else mark:
print(“Not Passed”)
/
iii) Logical Error
in
Logical Errors are the most difficult one to fix. They occur when the program runs
n.
without crashing but it produces an incorrect result. The error is occurred by a mistake in
aa
program logic.
Common Python Logical Errors include:
Using the wrong variable name
Indenting a block to the wrong level
o riy
Using Integer division instead of float division
.p
Define Exception
How to handle Exception?
Types of Exception
s:
o Built-in Exception
o User Defined Exception
tp
Assertion
ht
Exception
An Exception is an event which occurs during the execution of a program that disrupts
the normal flow of the program’s instructions. If a python script encounters a situation it cannot
cope up, it raises an exception.
/
One can defend their program from a run time error by placing the codes inside the try block.
in
Syntax:
n.
try:
aa
#The operations here
Syntax:
w
//w
except Exception 1:
#Handle Exception 1
s:
except Exception 2:
#Handle Exception 2
tp
If there is no exception in the program the else block will get executed.
Syntax:
else:
#If no Exception, it will execute
finally:
#Always Execute
Unit V Rohini College of Engineering and Technology Page 5.12
https://www.poriyaan.in/ GE3151 - Problem Solving And Python Programming https://eee.poriyaan.in/
try:
#The operations here
except Exception 1:
#Handle Exception 1
except Exception 2:
/
in
#Handle Exception 2
else:
n.
#If no Exception, it will execute
aa
finally:
#Always Execute
Ex:
o riy
5.4 Write a Python program to write a file with Exception Handling
.p
try:
f=open(“test.txt”, ‘w+’)
w
f.seek(0)
print(f.read())
//w
except IOError:
print(“File not Found”)
else:
s:
f.close()
finally:
ht
print(“Close a file”)
Ex:
5.5 Write a python program to read a file which raises an exception.
Assume test.txt is not created in the computer and the following program is executed
which raises an Exception.
try:
f=open(“test.txt”, ‘w+’)
f=write(“My First File”)
f.seek(0)
print(f.read())
except IOError:
print(“File not Found”)
else:
/
in
try:
#The operations here
n.
except:
#Handles Exception
aa
else:
#If no Exception, it will execute
finally:
#Always Execute
o riy
.p
Except clause with multiple Exception
An except statement can have multiple exceptions. We call it by exception name.
w
Syntax
w
try:
//w
else:
tp
#Always Execute
Ex:
5.6 Write a python program to read a file with multiple exceptions.
try:
f=open(“test.txt”, ‘w+’)
f=write(“My First File”)
print(f.read())
except (IOError, ValueError, ZeroDivisionError):
print(“File not Found”)
else:
print(“File not Found”)
f.close()
finally:
print(“Close a file”)
Argument of an Exception
An Exception can have an argument which is a value that gives additional information
the problem. The content of an argument will vary by the exception.
Syntax
try:
/
in
#The operations here
except Exception Type, Argument:
n.
#Handles Exception with Argument
else:
aa
#If no Exception, it will execute
finally:
#Always Execute
o riy
Raising an Exception:
.p
Syntax
w
Ex:
s:
>>>def fun(level):
if level<10:
tp
>>>fun(11)
/
and it has invalid values.
in
7. RuntimeError Raised when a generated error does not fall into any category.
Raised when the user interrupts program execution by pressing
n.
8. KeyboardInterrupt
Ctrl+C
aa
9. FloatingPointError Raised when floating calculation Fails.
10. AssertionError Raised in case of failure of assert statement.
Raised when a calculation exceeds maximum limit for a numeric
11. OverFlowError
12. StandardError
types.
riy
Base class for all built-in exception except ‘StopIteration and
o
SystemExit’
.p
13. StopIteration Raised when next() method of an iteration does not exist
14. SystemExit Raised by the sys.exit() function
w
Step-1
ht
5.2.4 ASSERTION
An assertion is a sanity check which can turn on (or) turn off when the program is in
testing mode.
The assertion can be used by assert keyword. It will check whether the input is valid and
after the operation it will check for valid output.
Syntax:
assert(Expression)
/
in
Ex:
n.
>>>def add(x):
assert(x<0)
aa
return(x)
>>>add(10) o riy
.p
5.3 MODULES
w
A module allows you to logically organize the python code. Grouping related code into a
module makes the code easy to use. A module is a file consisting python code. A module can
w
define functions, classes and variables. A module can also include runnable code.
//w
Ex
The Python code for a module support normally resides in a file named support.py.
s:
support.py
>>>def print_func( par ):
tp
return
import module
Ex
import support # Import module support
support.print_func("xyz") # Now we can call the function in that module as
Output:
Hello : Zara
/
Python's from statement lets you import specific attributes from a module into the current
in
namespace.
n.
Syntax:
aa
from module_name import function_name
5.4 PACKAGES
//w
on.
tp
Consider a file Pots.py available in Phone directory. This file has following line of source code −
ht
>>>def Pots():
print "I'm Pots Phone"
Similar way, we have another two files having different functions with the same name as above
Phone/Isdn.py file having function Isdn()
Phone/G3.py file having function G3()
We can import by
>>>import Phone
>>>Phone.Pots()
>>>Phone.Isdn()
>>>Phone.G3()
Output:
I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone
/
in
n.
aa
o riy
.p
w
w
//w
s:
tp
ht
TWO MARKS
1. What is a text file?
A text file is a file that contains printable characters and whitespace, organized in to lines
separated by newline characters.
2. Write a python program that writes “Hello world” into a file.
f =open("ex88.txt",'w')
/
in
f.write("hello world")
f.close()
n.
aa
3. Write a python program that counts the number of words in a file.
f=open("test.txt","r")
content =f.readline(20)
words =content.split()
o riy
print(words)
.p
w
The open function takes two arguments : name of the file and the mode of operation.
//w
Example: f = open("test.dat","w")
5. What is a file object?
s:
A file object allows us to use, access and manipulate all the user accessible files. It
maintains the state about the file it has opened.
tp
ht
8. What are the error messages that are displayed for the following exceptions?
a. Accessing a non-existent list item IndexError: list index out of range
b. Accessing a key that isn’t in the dictionary KeyError: what
c. Trying to open a non-existent file IOError: [Errno 2] No such file or directory:
'filename'
9. What are the two parts in an error message?
/
The error message has two parts: the type of error before the colon, and specific about the
in
error after the colon.
n.
10. How do you handle the exception inside a program when you try to open a non-existent
file?
aa
filename = raw_input('Enter a file name: ')
try:
f = open (filename, "r")
except IOError:
o riy
.p
print 'There is no file named', filename
w
except statement is ignored. If an exception of type IOError occurs, it executes the statements in
//w
12. What is the function of raise statement? What are its two arguments?
tp
The raise statement is used to raise an exception when the program detects an error. It
takes two arguments: the exception type and specific information about the error.
ht
/
A module is simply a file that defines one or more related functions grouped together. To
in
reuse the functions of a given module, we need to import the module. Syntax: import
n.
<modulename>
aa
17. What is a package?
18. What is the special file that each package in Python must contain?
Each package in Python must contain a special file called _init__.py
w
The remove() method is used to delete the files by supplying the name of the file to be
deleted as argument.
s:
Syntax: os.remove(filename)
tp
20. How do you use command line arguments to give input to the program?
ht
Python sys module provides access to any command-line arguments via sys.argv.
sys.argv is the list of command-line arguments. len(sys.argv) is the number of command-line
arguments.
https://www.poriyaan.in/