GE3151 Problem Solving and Python Programming Lecture Notes 2
GE3151 Problem Solving and Python Programming Lecture Notes 2
com
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.
Examples:
1. Write an algorithm to find the area of circle.
Step1: Start
Step2: Read the value of radius as r
Step3: Calculate area = 3.14*r*r
Step4: Print the value of area.
Step5: Stop
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
Step7: Stop
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.
Ex:
Expression Statement
Assignment Statement
Print Statement
Import Statement
ii) Compound Statement:
Compound Statements consist of a group of statements. They control the execution of
other statements. It consists of one or more clauses.
Ex:
if – statement
while – statement
for – statement
try – statement
b) State
An algorithm is a deterministic automation for accomplishing a goal which given an
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.
Process 1 Start
Read radius r
Process 2 S=3.14*r*r
Print S
Process n
Stop
IF Condition THEN
Process A
…
…
…
Process
END IF
2) IF….THEN…ELSE
In this structure
o If the condition is true. It performs the process A.
o Else the condition is false. It executes process B.
The process execution is depending on the condition.
Pseudo code Flow Chart
IF Condition THEN
Process A
ELSE IF
Process B Conditio
Process A ns
Process B
END IF
Process 2
…
…
Process 1 Process 2 Process N
…
case Type-n:
Process n
END CASE
d) Functions
Functions are "self-contained" modules of code that accomplish a specific task. Functions
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
other functions. Functions "Encapsulate" a task (they combine many instructions into a single
line of code).
Ex:
>>>def add(num1,num2): #Function Definition
num3=num1+num2
print(“The sum is”,num3)
return num3
>>>a=10
>>>b=20
>>>c=add(a,b) #Function Call
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.
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
print(“The area of circle is”,rad)
>>>radius=9
>>>circle(radius) #Where ‘radius’ is the Actual Parameter
Ex:
READ num1, num2
result = num1 + num2
WRITE result.
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
INITIALIZE total=0,i=1
WHILE i<n
READ mark
total=total+mark
INCREMENT i
PRINT i
END
1.3.2. Flowchart
A flow chart is a diagrammatic representation that illustrates the sequence of operations
to be performed to arrive the solution.
Each step in the process is represented by a different symbol and has a short description
of the process steps.
The flow chart symbols are linked together with arrows showing flow directions.
(or)
Only one flow line should enter a decision symbol but two or three flow lines can leave.
Start Stop
Write within standard symbols briefly. You can also use annotation symbol to describe
the data more clearly.
– – – Calculation Part
If the flowchart becomes complex then it is better to use connector symbols to reduce the
number of flow lines.
Flow chart should have a start and stop.
Validity of a flow chart can be tested by passing through it with a simple test data.
Advantages of Flow Chart:
Flow Charts are better in communication.
A Problem can be analyzed in an effective way.
Program Flow Charts Serve as a good documentation.
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
Print area
Stop
Start
Read a,b
a>b
yes No
Start
Read N
Total=0
i=1
If
i<n
Stop Total=Total+Mark
Yes No
Design an algorithm
Prove Correctness
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:
o Instructions are executed one after another. Accordingly, algorithms designed to
be executed on such machines.
Parallel Algorithms:
o An algorithm which can be executed a piece at a time on many different
processing device and combine together at the end to get the correct result.
iii) Choosing between Exact and Approximate Problem Solving:
The next principal decision is to choose between solving the problem exactly (or) solving
it approximately.
An algorithm used to solve the problem exactly and produce correct result is called an
exact algorithm.
If the problem is so complex and not able to get exact solution, then we have to choose an
algorithm called an approximation algorithm. i.e., produces an approximate answer.
Ex: extracting square roots.
iv) Deciding an appropriate data structure:
In Object oriented programming, data structures is an important part for designing and
analyzes of an algorithm.
Data Structures can be defined as a particular scheme or structure to organize the data.
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++
>>>
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.
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
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
yes
ILLUSTRATIVE EXAMPLES
1.1. Find Minimum in a list:
Algorithm: Start
Step1:Start
Step2:Read total number of elements in the list
Read N
Step3:Read the first element as E
Step4:MIN=E
Read first Element as E
Step5:SET i=2
Step6:If i>n goto Step 11 ELSE goto Step 7
Step7:Read ith element as E Min= E I=2
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:
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
Algorithm: Start
Step 1: Start
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
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 i=0
Step 8: go to step 5
Step 9: READ Element to be insert as X
Step 10: SET i = N-1
Step 11: IF i>=0 AND X<List[i] THEN go i<N to step 12 ELSE go to step15
Step 12: List[i+1]=List[i]
Step 13: i=i-1
Pseudocode
Read Sorted List List[i]
READ Number of element in sorted list as N
SET i=0
WHILE i<N
READ Sorted list element as List[i] Read x
i=i+1 i=N-1
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
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
Step 9: PRINT “Guess is Too Low” AND go to step 5
Step 10: PRINT Count as Number of Guesses Took
R=random Number from 1 to N
Pseudocode:
SET Count =0
READ Range as N Read User guessesed Number G
R>G
An outline to
solve this
problem,
from the
starting pole,
to the goal
pole, using an intermediate pole:
1. Move a tower of height-1 to an intermediate pole, using the final pole.
2. Move the remaining disk to the final pole.
3. Move the tower of height-1 from the intermediate pole to the final pole using the
original pole.
we can use the three steps above recursively to solve the problem.
END Procedure
Flow Chart for Tower of Hanoi Algorithm
Begin Hanoi(disk,source,dest,aux)
IS
disk==1
Honai(disk-1,source,aux,dest)
Move disk from source to dest
Honai(disk-1,source,aux,dest)
Stop
WORKSHEETS
Flowchart:
Flowchart:
Pseudocode:
1. 2. Draw a Flowchart and write a pesudocode to find biggest between three numbers.
Flowchart:
Pseudocode:
Flowchart:
Pseudocode:
Flowchart:
Pseudocode:
Flowchart:
Pseudocode:
Flowchart:
Pseudocode:
Flowchart:
Pseudocode:
Pseudocode:
TWO MARKS
7. Write the pseudo code to calculate the sum and product displaying the answer on the
monitor screen.
BEGIN
INITIALIZE variables sum, product, number1, number2 of type real
READ number1, number2 sum = number1 +number2
PRINT “The sum is “, sum
COMPUTE product = number1 * number2
PRINT “The Product is “, product
END program
8. Give the rules for writing Pseudo codes.
o Write one statement per line.
o Capitalize initial keywords.
o Indent to show hierarchy.
o End multiline structure.
o Keep statements to be language independent
.
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 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.
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
Step 2:Read the total number of element in the list as N
Step3:Read first element as E
Step 4:MIN=E
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
Step 9:i=i+1
Step 10:goto step 6
Step 11:print MIN
Step12:Stop
22. Outline the logic to swap the contents of two identifiers without using the third variable
(University question)
Step1: Start
Step 2:Read A,B
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
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.
“A program is a sequence of instructions that specifies how to perform a computation” .The
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.
Output: Display data on the screen
Math: Perform the mathematical operations.
Conditional Execution: Check condition and execute certain code.
Repetition: Perform some action repeatedly.
2.1 INTRODUCTION
Python
Python is a high level programming language like C, C++ designed to be easy to read,
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
different platform with less or no modifications.
Features of Python:
Python is publicly available open source software.
Python is easy to learn.
Python is easy to read.
Python is easy to maintain.
Python provides automatic memory management.
Python is portable.
Python support database and GUI(Graphical User Interface)
2.2 PYTHON INTERPRETER AND INTERACTIVE MODE
Interpreter
Source Code (or) Source Code
Intermediate
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
execute a program if the syntax is correct otherwise the interpreter display an error
message.
Runtime Error:
The error that occurs during the program execution is called run time error.
Semantic Error:
The computer will not generate any error message but it will not do the right thing since
the meaning of the program is wrong.
2.2.5 Integrated Development Environment (IDE)
We can use any text editing software to write a Python script file. We just need to save it
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
development.
IDLE is a graphical user interface (GUI) that can be installed along with the Python
programming language.
Example:
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)
<class 'float'>
>>>type('Hello, World!')
<class 'str'>
In these results, the word ―class‖ is used in the sense of a category; a type is a category
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
strings.
>>>type('5')
<class 'str'>
>>>type('83.0')
<class 'str'>
2.3.2 Standard Datatypes
A datatype is a category for values and each value can be of different types. There are 7
data types mainly used in python interpreter.
a) Integer
b) Float
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
A Boolean variable can take only two values which are True or False. True and False
are simply set of integer values of 1 and 0.The type of this object is bool.
Example:
>>>bool(1)
True
>>>bool(0)
False
>>>a=True
>>>type(a) <type ‘bool’>
>>>b=false #Prints error
>>>c=’True’
>>>type(c) <type ‘str’>
The boolean type is a subclass of the int class so that arithmetic using a boolean works.
>>>True + 1
2
>>>False * 85
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
Output
Python Programming
P
g
tho
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
4. The String will be centred
along with the width specified str1.centre(20,+)
centre() centre(width,fullchar)
and the charecters will fill the ++++Hello++++
space
5. Converts all upper case into
lower() String.lower() str1.lower() hello
lower case
6. Converts all lower case into
upper() String.upper() str1.upper() HELLO
upper case
7. splits according to the
str1.split(“+”)
split() String.split(“Char”) character which is present
H+E+L+L+O
inside the function
8. It converts a string in to its
ord() ord(String) ord(‘a’) 96
corresponding value
9. It converts a number in to its
chr() chr(Number) chr(100)-->’d’
corresponding String
10. It removes all the spaces at the
rstrip() rstrip() rstrip(a) it returns -1
end
11. \n print(“String\n”) New Line Character print(“Hello\n”)
12. \t print(“String\t”) It provides Space print(“Hello\t”)
13. print(“Hello I\’m
\’ print(“String\’String”) Escape Character ( / ) is used
Fine”)
to print single quote or double
14. print(“Hello I\”m
\” print(“String\”String”) quote in a String
Fine”)
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
>>>print(list[1:3]) # Prints elements starting from 2nd till 3rd
>>>print list([2:]) # Prints elements starting from 3rd element
>>>print(smalllist * 2) # Prints list two times
>>>print(list + smalllist) # Prints concatenated lists
Output
['Hai', 123, 1.75, 'vinu', 100.25]
Hai
100.25
[123, 1.75]
[1.75, 'vinu', 100.25]
[251, 'vinu', 251, 'vinu']
['Hai', 123, 1.75, 'vinu', 100.25, 251, 'vinu']
f) Tuple
Tuple are sequence of values much like the list. The values stored in the tuple can be of
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
([ ]) and their elements and size can be changed while tuples are enclosed in parenthesis (( )) and
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
Example:
>>>dict1={}
>>>dict2={1:10,2:20,3:30}
>>>dict3={‘A’:’apple’,’B’:’200’}
>>>Dict={‘Name’:’john’,’SSN’:4576,’Designation’:’Manager’}
2.4 PYTHON KEYWORDS:
Keywords are reserved words that cannot be used as ordinary identifiers. All the
keywords except True, False and None are in lowercase .
False class finally is return None
continue for lambda try True def
from nonlocal while and del global
not with as elif if or
yield assert else import pass break
except in raise and print exec
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
Invalid Identifies: 1x x+y if
2.6 VARIABLES
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
>>>print(b)
2.7 PYTHON INDENTATION
Python uses indentation. Block of code starts with indentation and ends with the
unintended line. Four whitespace character is used for indentation ans is preferred over tabs.
Ex:
x=1
if x==1:
print(“x is 1”)
Result:
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
writing one after another, or with block constructs. Every expression can be used as a statement,
but most statements cannot be used as expressions
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.
Operator Meaning Syntax Description
+ Addition a+b It adds and gives the value 30
- Subtraction a-b It subtracts and gives the value -10
* Multiplication a*b It multiplies and gives the value 200
/ Division a/b It divides and gives the value 0.5
% Modulo a%b It divides and return the remainder 0
** Exponent a**b It performs the power and return 1020
// Floor a//b It divides and returns the least quotient
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
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.
*= 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.
%= a%=b a=a%b It divides the value of a and b and assign the
remainder to a.
**= 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 It divides the value of a and b and takes the least
quotient and assign it to a.
4. Logical Operator
Logical Operators are used to combine two or more condition and perform logical
operations using Logical AND, Logical OR, Logical Not.
Consider the values of a=10, b=20 for the following table.
Operator Example Description
AND if(a<b and a!=b) Both Conditions are true
OR if(a<b or a!=b) Anyone of the condition should be true
The condition returns true but not
NOT not (a<b)
operator returns false
5. Bitwise Operator
Bitwise Operator works on bits and performs bit by bit operation.
Consider the values of a=60, b=13 for the following table.
Operator Syntax Example Description
Binary AND It do the and operation
& a&b= 12
between two operations
Binary OR It do the or operation between
| a|b= 61
two operations
Binary Ones It do the not operation
~ ~a=61
Complement between two operations
<< Binary Left Shift <<a It do the left shift operation
>> Binary Right Shift >>a It do the right shift operation
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
Output:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is -61
Line 4 - Value of c is 240
Line 5 - Value of c is 15
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
7. Identity Operator
Identity Operators compare the memory locations of two objects.
Consider the values of a=10, b=20 for the following table.
Operator Syntax Example Description
If the variable 1 value is pointed
to the same object of variable 2
is variable 1 is variable 2 a is b returns False
value then it returns True, else
False
If the variable 1 value is not
variable 1 is not a is not b returns pointed to the same object of
is not
variable 2 False variable 2 value then it returns
True, else False
Example:
x1=7
y1=7
x2=’welcome’
y2=’Welcome’
print (x1 is y1)
print (x2 is y2)
print(x2 is not y2)
Output:
True
False
True
S. No Operators Description
1. () Parentheses
2. ** Exponent
3. +x, -x, ~x Unary plus, Unary minus, Bitwise NOT
4. *, /, //, % Multiplication, Division, Floor division, Modulus
5. +, - Addition, Subtraction
6. <<, >> Bitwise shift operators
7. & Bitwise AND
8. ^ Bitwise XOR
9. | Bitwise OR
is, is not, in, not in Comparison, Identity, Membership
10. ==, !=, >, >=, <, <=,
operators
11. not Logical NOT
12. and Logical AND
13. or Logical OR
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
23
10 * 7 // 3 is equivalent to (10 * 7)//3.
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)
i) type()
>>>type(25)
<class 'int'>
The name of the function is type(). The expression in parentheses is called the argument
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.
Python provides functions that convert values from one type to another. The int()
function takes any value and converts it to an integer, if it can, or it shows error otherwise:
ii) Casting:
>>>int('25')
25
>>>int('Python')
valueError: invalid literal for int(): Python
int() can convert floating-point values to integers, but it doesn’t round off; it chops off the
fraction part:
>>>int(9.999999)
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)
stop: Number of integers (whole numbers) to generate, starting from zero.
eg. range(3) == [0, 1, 2].
ii) range([start], stop[, step])
start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step: Difference between each number in the sequence.
Example:
>>>range(10)
[0,1,2,3,4,5,6,7,8,9]
>>>range(5,10)
[5,6,7,8,9]
>>>range[10,1,-2]
[10,8,6,4,2]
Example:
>>>def welcome(person_name):
"""This function welcome the person passed in as parameter"""
print(" Welcome " , person_name , " to learn Python")
function_name(parameter 1, parameter 2)
Example:
>>> welcome('Students')
Output:
Welcome Students to learn Python.
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
The order in which statements run is called the flow of execution. Execution always
begins at the first statement of the program. Statements are run one at a time, in order from top to
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
function, runs the statements there, and then comes back to pick up where it left off.
2.15.4 PARAMETERS AND ARGUMENTS
Inside the function, the arguments are assigned to variables called parameters. Here is a
definition for a function that takes an argument:
Function Arguments
Types of Formal arguments:
Required arguments
Default arguments
Keyword arguments
Variable-length arguments
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
>>>b=20
>>>add(a,b)
>>>add(a)
Output:
Sum of 10 and 20 is 30
Sum of 10 and 0 is 10
Keyword Arguments:
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.
Example:
>>>def add(a,b):
print ("Sum of ", a ,"and ", b, "is" ,a+b)
>>>a=10
>>>b=20
>>>add(b=a,a=b)
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')
Output:
Hello
Welcome
to
Learn Python
Example:
>>>double = lambda x: x * 2
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.
Example:
The Python code for a module add normally resides in a file named addition.py.
support.py
>>>def add(a,b):
result=a+b
return result
a) Importing Modules
We can invoke a module by two statements
i. import statement
ii. from…import statement
i) The import Statement
You can use any Python source file as a module by executing an import statement in
some other Python source file.
Syntax:
import module
Example:
import addition # Import module addition
addition.add(22,33) # Now we can call the function in that module as
Result:
Addition of two number is 55
ii) The from...import Statement
Python's from statement lets to import specific attributes from a module into the current
namespace. Multiple function can be imported by separating by their names with commas .
Syntax:
from module_name import function_name
Example:
addition.py
>>>def add(a,b):
result=a+b
return result
subt.py
>>>def sub(a,b):
result=a-b
return result
iii)Calender module:
This module is used to display calendar
>>>import calendar
>>>cal=calendar.month(2019,5)
>>>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
Output:
>>> Enter first side: 6
Enter second side: 8
Enter third side: 10
The area of the triangle is f 24.0
>>>
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))
>>>print(“The Values Shift three places in Anti Clockwise: ”circulate([1,2,3,4,5,6,7],-3))
Output:
The Values Shift two places in Clockwise: [3,4,5,6,7,1,2,]
The Values Shift three places in Anti Clockwise: [5, 6, 7, 1, 2, 3, 4]
WORKSHEETS
Note: - Always Get an Input from the User
Output:
2.2 Write a python program to convert Kilometers to Miles (Conversion factor = 0.621)
Formula: miles=kilometer*conversion_factor
Program:
Output:
Output:
Program:
Output:
Output:
2.6. Write a python program to o display your details like name, age, address in three
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
uppercase letters, but it is good to begin variable names with a lowercase letter.
3. Define keyword and enumerate some of the keywords in Python. (University question)
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.
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.
9. What is the order in which operations are evaluated? Give the order of precedence.
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
precedence followed by exponentiation. Multiplication and division have the next highest
precedence followed by addition and subtraction.
23. Write a program to accept two numbers multiply them and print them. (University
question)
A=10
B=2
multiplication=A*B
print (“Multiplication of two numbers :” ,multiplication)
BOOLEAN VALUES:
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.
Boolean Operations:
Control structures
if expression:
true statements
Flow Chart
Test False
Expres
sion
True
Body of if stmt
Example:
a=10
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
End of Code
Example:
a=10
if a==10:
print(“a is equal to 10”)
else:
print(“a is not equal to 10”)
Output:
a is equal to 10
3.elif else Statement(chained conditionals)
The elif statement or chained conditional allows you to check multiple expressions for true
and execute a block of code as soon as one of the conditions evaluates to true. The elif statement
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
Test
True Expressi False
Body of if on
of elif
True
Body of elif Body of else
End of Code
Example:
a=9
if a==10:
print(“a is equal to 10”)
elif a<10:
print(“a is lesser than 10”)
elif a>10:
print(“a is greater than 10”)
else
print(“a is not equal to 10”)
Output::
a is less than 10
if expression 1:
true statements
else:
if expression 2:
true statements
else:
false statement
Flow Chart
Test
True Conditio False
n1
Body of if
Test
True False
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:
a is lesser than 100
3.1.2 Iteration (or) Looping Statement
An Iterative statement allows us to execute a statement or group of statement multiple
times. Repeated execution of a set of statements is called iteration or looping.
Types of Iterative Statement
1. while loop
2. for loop
3. Nested loop
1. while loop
A while loop executes a block of statements again and again until the condition gets false.
The while keyword is followed by test expression and a colon. Following the header is an
indented body.
Syntax
while expression:
true statements
Flow Chart
Entering While
loop
Test
Expressi False
on
True
Body of while
Unit III Page 3.6
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
Example-2:
2. Write a python program to find factorial of n numbers.
n=int(input("Enter the number:"))
i=1
fact=1
while(i<=n):
fact=fact*i
i=i+1
print("The factorial is",fact)
Output:
Enter the number: 5
The factorial is 120
2. for loop
The for loop is used to iterate a sequence of elements (list, tuple, string) for a specified
number of times.
For loop in python starts with the keyword “for”followed by an arbitrary variable name,which
holds its value in the following sequence objects.
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
?
Body of for
Exit Loop
Example-1:
for letter in”python”:
print(“The current letter:”, letter)
Output:
The current letter: p
The current letter: y
The current letter: t
The current letter: h
The current letter: o
The current letter: n
Example-2:
>>>fruit=[‘apple’, ‘orange’, ‘mango’]
>>>for f in fruit:
print(“The current fruit”, f)
>>>print(“End of for”)
Output:
The current fruit: apple
The current fruit: orange
The current fruit: mango
End of for
3.Nested loop
Python Programming allows using one loop inside another loop. For example using a
while loop or a for loop inside of another while or for loop.
3.1.3.Unconditional Statement
In a situation the code need to exit a loop completely when an external condition is
triggered or need to skip a part of the loop. In such situation python provide unconditional
statements.
Types of Unconditional looping Statement
1. break statement
2. continue statement
3. pass statement
1.break statement
A break statement terminates the current loop and transfers the execution to statement
immediately following the loop. The break statement is used when some external condition is
triggered.
Syntax
break
Flow Chart
Condition Code
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
2. continue statement
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.
Syntax
continue
Flow Chart
Condition Code
If condition
is true
Conditio
conti
n
nue
If condition is False
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’:
pass
print(letter)
print(“bye”)
Output:
python
bye
len(variable) – which takes input as a string or a list and produce the length of string or a list as an
output.
range(start, stop, step) – which takes an integer as an input and return a list containing all the
numbers as the output.
Example-1:
Write a python program to find distance between two points:
import math
def distance(x1,y1,x2,y2): # Defining the Function Distance
dx=x2-x1
dy=y2-y1
print("The value of dx is", dx)
print("The value of dy is", dy)
d= (dx**2 + dy**2)
dist=math.sqrt(d)
return dist
x1 = float(input("Enter the first Number: ")) #Getting inputs from user
x2 = float(input("Enter the Second Number: "))
y1 = float(input("Enter the third number: "))
y2 = float(input("Enter the forth number: "))
print("The distance between two points are",distance(x1,x2,y1,y2))
def funct(param1,param2):
statements
return value
Once the function is defined,it can be called from main program or from another function.
Function call statement syntax
Result=function_name(param1,param2)
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
Cube of given number=8
3.3 Composition:
A Composition is calling one function from another function definition.
Example:
Write a python program to add three numbers by using function:
def addition(x,y,z): #function 1
add=x+y+z
return add
def get(): #function 2
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
c=int(input("Enter third number:"))
print("The addition is:",addition(a,b,c)) #Composition function calling
get() #function calling
Output:
Enter first number:5
Enter second number:10
Enter third number:15
The addition is: 30
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()
>>>print(‘a=’,a)
Output:
a=I am in TamilNadu
a=I am in India
a=I am in World
>>>a=”I am in world”
>>>outer_function()
>>>print(‘a=’,a)
Output:
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)
n=int(input("Enter a number:"))
print("The Factorial is", fact(n))
Output:
>>> Enter a number:5
The Factorial is 120
>>>
Explanation:
First Iteration - 5*fact(4)
Second Iteration - 5*4* fact(3)
Third Iteration - 5*4*3*fact(2)
Fourth Iteration - 5*4*3*2* fact(1)
Fifth Iteration - 5*4*3*2*1
Example-2:
Write a python program to find the sum of a ‘n’ natural number using Recursion:
def nat(n):
if(n<=1):
return n
else:
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
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.
This pattern of processing is called a traversal.
Example:
>>>index = 0
>>>str="Python"
>>>while index < len(str):
letter = str[index]
print(letter, end="")
index = index+1
Output:
Python
3.6.1 String Slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a character.
Syntax:
variable [start:stop]
<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
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
3. Program to find the exponential of a number
4. Program to find the sum of n numbers.
5. Program to find the maximum and minimum in a list
6. Program to perform the linear search
7. Program to perform Binary search
Output:
How many terms? 10
Fibonacci sequence upto 10 :
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 ,
>>>
Output:
>>>
[17, 15, 4]
[10, 12, 9]
[11, 13, 18]
>>>
for r in result:
print(r)
Output:
>>>
[12, 4, 3]
[7, 5, 8]
>>>
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:
>>> [114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
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:
Output:
3.2. Write a python program to find two numbers which are divisible by 13
Program:
Output:
Program:
Output:
Program:
Output:
3.5. Write a python program to accept the strings which contains all vowels
Input : ABeeIghiObhkUul Output : Accepted
Program:
Output:
Program:
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:
Output:
Program:
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.
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:
print 'x and y are equal'
elif is an abbreviation of “else if.” Again, exactly one branch will be executed. There is no
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):
while n > 0:
print n
n = n-1
print 'Blastoff!'
More formally, here is the flow of execution for a while statement:
1. Evaluate the condition, yielding True or False.
2. If the condition is false, exit the while statement and continue execution at the next
statement.
3. If the condition is true, execute the body and then go back to step 1
10. Explain ‘for loop’ with example.
The general form of a for statement is
Syntax:
for variable in sequence:
code block
Eg:
x=4
for i in range(0, x):
print i
11. What is a break statement?
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
print'Done!'
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)
4.1 LISTS
Define List
A list is an ordered set of values, where each value is identified by an index. The values in
a list are called its elements or items. The items can be of different types (int, float, string). To
create a new list, the simplest way is to enclose the elements in square bracket [ ]. Lists are
mutable which means the items in the list can be add or removed later.
Example:
>>>[ ] #empty list
>>>[1,2,3] #list of integers
>>>[‘physics’,’chemistry’,’python’] #list of strings
>>>[1,’hello’,3.4] #list with mixed datatypes
>>>list1=[‘a’,’b,’c’’d’]
>>>print(list1)
List can have another list as an item. This is called nested list.
Mylist=[‘mouse’,[8,6,5], 3.2]
List are mutable.
Lists are mutable which means the items in the list can be added or removed later.
>>>mark=[98,87,94]
>>>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:
list3=[‘Hello’,3.5,’abc’,4]
‘Hello’ in list3 → returns True
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
11. clear() listname.clear() This method is used to clear all a.clear() -->[]
the values in the list.
1. Write a python program to print the items in the list using while loop.
>>>a=[‘apple’,’mango’,’lime’,’orange’]
>>>i=0
>>>while len(a)>i:
print(“I like”,a[i])
i=i+1
Output:
The value of i makes the loop to goes on 4 times and print items one by one.
‘apple’
’mango’
‘lime’
’orange’
4.1.5 LIST ARE MUTABLE:
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[:]
print(b) [1,2,3]
4.1.8 LIST PARAMETER:
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:
>>> def mul(a_list): #a_list is a list passing as a parameter
for index,value in enumerate(a_list):
a_list[index]=2*value
print(a_list)
>>> a_list=[1,2,3,4,5]
>>> mul(a_list)
Output:
[2, 4, 6, 8, 10]
4.2 TUPLE
Tuples are sequence of values much like the list. The values stored in the tuple can be of
any type and they are indexed by integers.
The main difference between list and tuple is Tuple is immutable. Tuple is represented using ‘( )’
Syntax:
tuple_name=(items)
Ex:
>>> tuple1=(‘1’,’2’,’3’,’5’)
>>>tuple2=(‘a’,’b’,’c’)
>>>tuple3=’3’,’apple’,’100’
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
>>>print(rem) 1
Example-2:
def swap(a,b,c):
return(c,b,a)
a=100
b=200
c=300
>>>print(“Before Swapping”,a,b,c)
>>>print(“After Swapping”,swap(a,b,c))
Output:
Before Swapping 100,200,300
After Swapping 300,200,100
4.3 DICTIONARIES
Dictionaries is an unordered collection of items. Dictionaries are a kind of hash table. The
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}
>>>d[‘name’] ’xyz’ # since ’name’ is a String datatype, it should be represented within quotes
>>>d[name] shows error
By get()method
>>>d.get(‘name’) ‘xyz’
Update Values in Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an
existing entry.
Ex:
>>> d={‘name’:’xyz’,’age’:23}
>>>print(d) {‘ name’:’xyz’,’age’:23}
>>>d[‘age’=24] #modifying existing element
>>>print(d) {‘ name’:’xyz’,’age’:23}
By update method
>>>d1={‘place’:’abc’}
>>>d.update(d1)
print(d) {‘place’:’abc’,‘ name’:’xyz’,’age’:23}
Adding Values in Dictionary
>>>d[‘gender’]=’m’ #Adding new entry
>>> print(d) {‘gender’:’m’, ‘place’:’abc’,‘ name’:’xyz’,’age’:23}
Deleting or Removing Values in Dictionary
You can either remove individual dictionary elements or clear the entire contents of a
dictionary.
>>>del d[‘name’] {‘gender’:’m’, ‘place’:’abc’,’age’:23}
>>>d.clear() # remove all entries in dictionary
>>>del d #delete entire dictionary
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
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()
print("Largest element is:", list1[length-1])
print("Smallest element is:", list1[0])
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)
Output:
Largest element is: 45
Smallest element is: 2
Second Largest element is: 41
Second Smallest element is: 4
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
Program 2.3:
>>> subject= ['Physics', 'Chemistry', 'Computer']
>>> 'Chemistry' in subject
Output:
True
Program 2.4:
>>> subject= ['Physics', 'Chemistry', 'Computer']
>>> for s in subject:
print(s)
Output:
Physics
Chemistry
Computer
Program 2.5:
>>> for i in range(len(mark)):
mark[i] = mark[i] * 2
>>> print(mark)
Output:
[196, 174, 200]
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:
Output:
Output:
Program:
Output:
Program:
Output:
Program:
Output:
Program:
Output:
Program:
Output:
Program:
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.
3.Let list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]. Find a) list[1:3] b) t[:4] c) t[3:] .
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3] [’b’, ’c’]
>>> list[:4] [’a’, ’b’, ’c’, ’d’]
>>> list[3:] [’d’, ’e’, ’f’]
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]
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)
5.1.1 FILES
A File is a collection of data or information which has a name, called filename. All the
information is stored in the computer using a file. The file is a named location on disk to store
related information. It is used to store data in volatile memory. There are many different types of
files.
Data File
Text File
Program File
Directory File
Text File:
A text file is a sequence of characters stored on a permanent medium like a hard drive,
flash memory, or CD-ROM. Text files are identified with the .txt file extension.
Reading and Writing to Text Files
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
language,0s and 1s).
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.
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.
Syntax:
file_object=open(“filename”, “mode”)
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”)
f=open(“E:/Python/text.txt”, ‘r’)
f=open(“E:/Python/text.txt”, ‘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
1. rb Opens a file for reading only in binary format.
2. r+ Opens a file for both reading and writing.
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. w+ Opens a file for both writing and reading in binary format.
6. wb+ Opens a file for both writing and reading in binary format.
7. a+ Opens a file for both appending and reading.
1. read() Method
This method reads a string from an open file.
Syntax:
file_object.read()
Ex:
f=open("F:/Python/test.txt","r")
print(f.read())
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()
file_object.close()
Ex:
f=open("F:/Python/test.txt","r")
print(f.read())
f.close()
How to read a text file?
1. File Operation
2. Opening Modes
3. Read Functions
There are two functions to read a file line by line, then there are two methods
readline()
readlines()
1.readline()
Every time a user runs the method, it will return a string of characters that
contains a single line of information from the file.
Syntax:
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()
Ex:
Consider the same 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\n', 'This is the Second Line in the file\n', 'This is
the Third Line in the file']
file_object.tell()
Ex:
>>> f=open("F:/Python/test.txt","r")
>>>print(f.tell()) #0th poisition
>>>print(f.read())
>>>print(f.tell()) #Last Position
>>>f.close()
Output:
0
This is the First Line in the file
This is the Second Line in the file
73
ii) seek() method
This method is used to change the current file position.
Syntax:
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()
os.rename(current_filename, new_filename)
Ex:
>>>import os
>>>os.rename(“test.txt”,”new.txt ”)
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.
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.
Output:
>>>C:\Python30>python.exe command.py Hello World
command.py Hello World 11
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.
try:
#The operations here
Syntax:
except Exception 1:
#Handle Exception 1
except Exception 2:
#Handle Exception 2
iii) else block
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
try:
#The operations here
except Exception 1:
#Handle Exception 1
except Exception 2:
#Handle Exception 2
else:
#If no Exception, it will execute
finally:
#Always Execute
Ex:
5.4 Write a Python program to write a file with Exception Handling
try:
f=open(“test.txt”, ‘w+’)
f=write(“My First File”)
f.seek(0)
print(f.read())
except IOError:
print(“File not Found”)
else:
print(“File not Found”)
f.close()
finally:
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:
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:
#The operations here
except Exception Type, Argument:
#Handles Exception with Argument
else:
#If no Exception, it will execute
finally:
#Always Execute
Raising an Exception:
You can raise exceptions in several ways by using raise statement.
Syntax
Ex:
>>>def fun(level):
if level<10:
raise “Invalid Level”, level
>>>fun(5) #raise an Exception
>>>fun(11)
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)
Ex:
>>>def add(x):
assert(x<0)
return(x)
>>>add(10)
5.3 MODULES
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.
Ex
The Python code for a module support normally resides in a file named support.py.
support.py
>>>def print_func( par ):
print "Hello : ", par
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
Syntax:
5.4 PACKAGES
A package is a hierarchical file directory structure that defines a single Python
application environment that consists of modules and subpackages and sub-subpackages, and so
on.
Consider a file Pots.py available in Phone directory. This file has following line of source code −
>>>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
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')
f.write("hello world")
f.close()
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
error after the colon.
10. How do you handle the exception inside a program when you try to open a non-existent
file?
filename = raw_input('Enter a file name: ')
try:
f = open (filename, "r")
except IOError:
print 'There is no file named', filename
11. How does try and execute work?
The try statement executes the statements in the first block. If no exception occurs, then
except statement is ignored. If an exception of type IOError occurs, it executes the statements in
the except branch and then continues.
12. What is the function of raise statement? What are its two arguments?
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.
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
19. How do you delete a file in Python?
The remove() method is used to delete the files by supplying the name of the file to be
deleted as argument.
Syntax: os.remove(filename)
20. How do you use command line arguments to give input to the program?
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.