0% found this document useful (0 votes)
33 views68 pages

Unit 3,4,&5 Material

python

Uploaded by

mithunsriram.v
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views68 pages

Unit 3,4,&5 Material

python

Uploaded by

mithunsriram.v
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

UNIT III CONTROL FLOW, FUNCTIONS, STRINGS

Conditionals: Boolean values and Operators, Conditional (if), Alternative (if-else), chained
conditional (if-elif-else); Iteration: state, while, for, break, continue, pass; Fruitful functions: return values,
parameters, local and global scope, function composition, recursion; Strings: string slices, immutability,
string functions and methods, string module; Lists as arrays. Illustrative programs: square root, gcd,
exponentiation, sum an array of numbers, linear search, binary search.

BOOLEAN VALUES
 The Boolean data type is a data type that has one of two possible values.
o True
o False

 The following values are considered false:


o None
o False
o zero of any numeric type, for example, 0, 0L, 0.0, 0j.
o any empty sequence, for example, '', (), [].
o any empty mapping, for example, {}.

 All other values are considered true — so objects of many types are always true.

 We can also check the data type of True or False with the help of ‘type’ function.
>>> type(True)
<class ‘bool’>
>>> type(False)
<class ‘bool’>

 The Relational Operators always results, Boolean value True(1) or False(0).


Ex >>> 3==3
True
>>>3==5
False

The other relational operators are:

x != y # x is not equal to y
x>y # x is greater than y
x<y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y

1
OPERATORS IN PYTHON WITH SUITABLE EXAMPLES [Dec/Jan 2018]

 Operators are a special symbol that specifies an operation to be performed on the operands.
Operators in programming languages are taken from mathematics.
 An operator may have one or two operands.
 An operand is one of the inputs (arguments) of an operator.
 Those operators that work with only one operand are called unary operators.
 Those who work with two operands are called binary operators.
 Ex. a+b,
 Here a and b are operands,+ operator.

Types of operators:
1. Arithmetic Operators ( + ,-,*,/,%,//,**)
2. Comparison (Relational) Operators (>,<,==,!=,>=,<=)
3. Logical Operators (and,or,not)
4. Assignment Operators (=,+=,-=,*=,/=,%=,**=)
5. Bitwise Operators (&, |, ^, ~)
6. Membership Operators (in ,not in)
7. Identity Operators (is, is not)

1. Arithmetic Operators
• Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication etc. ( + ,-,*,/, %, //(floor division), **(exponentiation)).

Operator Description Syntax


+ Addition: adds two operands x+y
– Subtraction: subtracts two operands x–y
* Multiplication: multiplies two operands x*y
/ Division (float): divides the first operand by the second x/y
// Division (floor): divides the first operand by the second x // y
Modulus: returns the remainder when the first operand is divided
% x%y
by the second
** Power: Returns first raised to power second x ** y

Example:
x = 15 OUTPUT:
y=4 x + y = 19
print(“ x + y = “, x+y) x - y = 11
print(“ x - y = “, x-y) x * y = 60
print(“ x * y = “, x*y) x / y = 3.75
print(“ x / y = “, x/y) x%y = 3
print(“ x % y = “, x%y) x // y = 3
print(“ x // y = “, x//y) x ** y = 50625
print(“ x ** y = “, x**y)

2
2. Comparison operators
• Comparison operators are used to compare two or more operands. These are also known as
Relational Operators.
• Relational operators are used in decision making process.
• It either returns True or False according to the condition.
• The comparison operators are >,<,==,!=,>=,<=.

Operator Description Syntax


Greater than: True if the left operand is greater than the
> x>y
right
< Less than: True if the left operand is less than the right x<y
== Equal to: True if both operands are equal x == y
!= Not equal to – True if operands are not equal x != y
Greater than or equal to True if the left operand is greater
>= x >= y
than or equal to the right
Less than or equal to True if the left operand is less than or
<= x <= y
equal to the right
is x is the same as y x is y
is not x is not the same as y x is not y

For example,
x = 10
OUTPUT:
y = 12
print(“x > y is”,x>y) x > y is False
print(“x < y is”,x<y) x < y is True
print(“x == y is”,x==y) x == y is False
print(“x != y is”,x!=y) x != y is True
x >= y is False
print(“x >= y is”,x>=y)
x <= y is True
print(“x <= y is”,x<=y)

3. Logical operators:
 Logical operators are used to combine the results of two or more conditions.
 Logical operators are and, or, not operators.
 Python's logical operators mostly use boolean operands to produce boolean results.

Operator Description Syntax


and Logical AND: True if both the operands are true x and y
or Logical OR: True if either of the operands is true x or y
not Logical NOT: True if the operand is false not x

3
Truth Table:

Example:
x = True
Output:
y = False
print(“x and y is”, x and y) x and y is False
print(“x or y is”, x or y) x or y is True
print(“not x is”, not x) not x is False

4. Assignment operators
 Assignment operators are used in python to assign values to variables.
(=,+=,-=,*=,/=,%=,**=,>>=,<<=,&=,|=,^=)

Syntax:
Variable=expression (or) value

Ex.1
a = 21
b = 10 Output:
c=0 Line 1 - Value of c is 21
c += a Line 2 - Value of c is
print( "Line 1 - Value of c is ", c)
5842587018385982521381124421
c **= a
print( "Line 2 - Value of c is ", c)

Ex2: value to multiple variables Output:


a=b=c=4
print (a, b, c ) 4 4 4

5. Bitwise operator
 It works on bits and performs bit by bit operation. It operates on integers only.
 Decimal numbers are natural to humans. Binary numbers are native to computers. Binary, octal,
decimal or hexadecimal symbols are only notations of the same number.
 Bitwise operators work with bits of a binary number. We have binary logical operators and shift
operators.
 Bitwise operators are seldom used in higher level languages like Python.

4
Operator Description Syntax
& Bitwise AND x&y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>>
<< Bitwise left shift x<<

Example:
a = 60
b = 13
c=0
c=a&b
print ("Line 1 - Value of c is ", c)
c=a|b
Output:
print ("Line 2 - Value of c is ", c)
c=a^b Line 1 - Value of c is 12
print ("Line 3 - Value of c is ", c) Line 2 - Value of c is 61
c = ~a Line 3 - Value of c is 49
print ("Line 4 - Value of c is ", c) Line 4 - Value of c is -61
c = a << 2 Line 5 - Value of c is 240
print ("Line 5 - Value of c is ", c) Line 6 - Value of c is 15
c = a >> 2
print ("Line 6 - Value of c is ", c)

6. Membership operators:

 in and not in are the membership operators in Python.


 They are used to test whether a value or variable is found in a sequence

Operator Description Example


Evaluates to true if it finds a variable in the x in y, here in results in a 1 if x is a
in
specified sequence and false otherwise. member of sequence y.
Evaluates to true if it does not finds a variable x not in y, here not in results in a 1
not in
in the specified sequence and false otherwise. if x is not a member of sequence y.

Ex. Output:
x = “Hello world” True
y = {1:'a', 2:'b'} True
print('H' in x) True
print('hello' not in x)
print(1 in y)

5
7. Identity Operators:

 Identity operators compare the memory locations of two objects.(is ,is not)

Operator Description Example


Evaluates to true if the variables on either x is y, here is results in 1
Is side of the operator point to the same if id(x) equals id(y).
object and false otherwise.
Evaluates to false if the variables on x is not y, here is not
is not either side of the operator point to the results in 1 if id(x) is not
same object and true otherwise. equal to id(y).

For ex.
OUTPUT:
a = 20
b = 20 Line 1 - a and b have same identity
if ( a is b ):
print( "Line 1 - a and b have same identity“)
else:
print ("Line 1 - a and b do not have same identity")

Operator Precedence
The precedence of the operators is essential to find out since it enables us to know which
operator should be evaluated first. The precedence table of the operators in Python is given below.
Operator Description
The exponent operator is given priority over all
**
the others used in the expression.
~+- The negation, unary plus, and minus.
The multiplication, divide, modules, reminder,
* / % //
and floor division.
+- Binary plus, and minus
>> << Left shift. and right shift
& Binary and.
^| Binary xor, and or
Comparison operators (less than, less than
<= < > >=
equal to, greater than, greater then equal to).
<> == != Equality operators.
= %= /= //= -= +=
Assignment operators
*= **=
is is not Identity operators
in not in Membership operators
not or and Logical operators

6
CONDITIONAL OR DECISION MAKING STATEMENTS [Dec/Nov 2018]
 Conditional Statements decides the order in which statements or blocks of code are executed at
runtime based on a condition.
 Conditional Statements are also called as Selection Structure, Decision Making Statements and
Control Flow.
 In a program all the instructions are executed sequentially by default, when no repetitions of some
calculations are necessary in some situation we may have to change the execution order of
statements based on condition or to repeat a set of statements until certain conditions are met.

Conditional Statements:

o A statement that controls the flow of execution depending on some condition.


o In python the keywords if , elif , and if-elif-else are used for conditional statements.
o The conditional statements are

a) if statement(conditionals)
b) if –else statement(alternative)
c) if –elif –else(chained conditional)

a) if statement(conditionals)
 The if statement is a decision making statement. It is used to control the flow of execution of
the statements and also used to test logically whether the condition is true or false.
 The program evaluates the test condition and executes the statements only if the test condition
is True.
 If the test condition is False, the statements are not executed.
Properties of an if statement:
i. if the condition is true, then the simple or compound condition statements are executed.
ii. If the condition is false, it does not do anything.
iii. The condition is given in parenthesis and must be evaluated as true (non-zero value) or
false (zero value).
Syntax: Flow Chart:
if (expression):
True Statements
.
.
.

For ex, program to find given number is positive.

x=int(input("enter number"))
if ( x>0):
print ("x is positive")

7
b) if –else statement
 It evaluates test condition and executes the True statement block only when the test
condition is true.
 If the condition is False, false statements block is executed.
 Indentation is used to separate the blocks.
Syntax: Flow charts:

if(condition):
True Statements
else:
False Statments

Ex. program to find the given number is odd or even

n = int( input("Enter a No: "))


if (n % 2 == 0):
print (n," is even")
else:
print (n," is odd")

c) if –elif –else(chained conditional) or nested if…else statement:


 The elif is short form for else if.
 It is used to check multiple conditions.
 If the condition1 is false, it will check the condition 2 of the next elif block and so on.
 If all the conditions are false, then the else statement is executed.
Syntax: Flow chart:

if condition 1:
True statement block for cond 1
elif condition 2:
True statement block for cond 2
else:
False statement Block

Ex. Given number is positive, negative or zero.


n=int(input(“Enter the value of n:”))
if(n>0):
print(“The number is positive”)
elif (n<0):
OUTPUT:
print(“The number is negative”) Enter the value of n: -9
elif (n==0): The number is negative
print(“the number is equal to zero”)
else:
print(“invalid”)

8
LOOPING OR ITERATING STATEMENTS: [DEC/NOV 2018]

 The loop is defined as the block of statements which are repeatedly executed for certain number
of times.
 The loop consists of 2 parts.
1.body of the loop
2.control statement.
 Any looping statement would include the following steps:
1. Initialization of a condition variable.
2. Test the control statements
3. Executing the body of the loop depending on the condition
4. Updating the condition variable.

The following are the loop structures available in python:


1.while loop
2.for loop

1. while loop
• It is a repetitive control structure, used to execute the statements within the body, until the
condition becomes false.
• The while loop is an entry controlled loop statement, which means the condition is evaluated
first and if it is true, then the body of the loop is executed.
• After executing the body of the loop, the condition is once again evaluated, if it is true, the loop
continues until the condition finally becomes false and the control is transferred out of the loop.

Syntax: Flow chart:

while (expression):
statement(s)

Ex.1 Addition of numbers upto 10 by using the while loop.


i=0
sum=0
while(i<=10):
sum=sum+i
i=i+1
print(“sum of numbers upto 10 is”,sum)
output:
sum of numbers upto 10 is 55

Ex 2:program to print 1-10 numbers


i=1
while(i<=10):
print(“i=”,i)
i=i+1

9
2. for loop:
 The for loop is another repetitive control structure, and is used to execute a set of instructions
repeatedly, until the condition becomes false.
 In Python, the for loop is used to iterate over a sequence such as a list, string, tuple, other iterable
objects such as range.
 The Initializing Counter Variable, Increment or Decrement and Condition checking is done in for
statement itself, where as other control structures are not offered all these features in one statement.

Syntax: Flow chart:


for iterating_var in sequence:
statements(s)

Ex 1. Addition of numbers upto 10 by using the for loop

sum=0
for i in range(11): output:
sum=sum+i sum of numbers upto 10 is: 55
print(“sum of numbers upto 10 is :”,sum)

Ex.2 printing characters in a word using for loop Output:


for word in “Python”: char in word: P
char in word: y
print(“char in word:”,word)
char in word: t
char in word: h
char in word: o
char in word: n

OUTPUT:
Ex3. print the pyramid of numbers. 0 1
for i in range(5): 1 10
print(“{0:3} {1:16}”.format(i, 10**i)) 2 100
3 1000
4 10000

10
LOOP CONTROL STATEMENTS IN DETAIL? (UNCONDITIONAL STATEMENTS)
[Dec/Nov 2018]
 Loop control statements change execution from its normal sequence.
 When execution leaves a scope, all automatic objects that were created in that scope are
destroyed.
 Python supports the following control statements.
1.break statement
2.continue statement
3.pass statement

Control
Description
statement
Terminates the loop statement and transfers execution to the statement
break
immediately following the loop.
Causes the loop to skip the reminder of its body and immediately
continue
retest its condition prior to reiterating.
The pass statement in python is used when a statement is required
pass
syntactically but you do not want any command or code to execute.

1.break statement:
 The break statement is used to terminate the loop.
 When the keyword break is used inside any python loop, control is automatically transferred to
the first statement after the loop. A break is usually associated with an if statement.
 The break statement can be used in both while and for loops.

Syntax: Flow chart:


break

Ex.

for letter in “Python”:


if letter == 'h':
break
print (“Current Letter :”, letter)

output:
Current Letter : P
Current Letter : y
Current Letter : t

11
2.continue:
 In some situations, we want to take the control to the beginning of the loop, by passing the
statements inside the loop which have not yet been executed, for this purpose the continue is used.
 When the statement continue is encountered inside any python loop control automatically passes
to the beginning of the loop.
 The continue statement can be used in both while and for loops.

Syntax: Flow chart:


continue

Example:
for letter in 'Python':
if letter == 'h':
continue
print(“Current Letter :”, letter)
OUTPUT:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n

3. pass statement:
 It is used when a statement is required syntactically but you do not want any command or code to
execute.
 The pass statement is a null operation; nothing happens when it executes. We generally use it as
a placeholder.

Syntax: pass

 Suppose we have a loop or a function that is not implemented yet, but we want to implement it in
the future.
 They cannot have an empty body. The interpreter would complain. So, we use the pass statement
to construct a body that does nothing.

For ex. OUTPUT:


for letter in 'Python':
Current Letter: P
if letter == 'h': Current Letter: y
pass Current Letter: t
print ('This is pass block' ) This is pass block
print( 'Current Letter :', letter) Current Letter: h
Current Letter: o
Current Letter: n

12
FRUITFUL FUNCTIONS
 A function that returns a value is called fruitful functions.
 The return statement is followed by an expression which is evaluated.
 Its result is returned to the caller as the “fruit” of calling function.

RETURN VALUE:
 Return value means the result of a function.
 Return takes zero, values or an expression. Default value is none.
 If a function is called using an expression, the return value is the value of the expression.
 The value can be returned from a function using the keyword return.

Syntax:
return[expression _list]

For example,
#Area of Circle
def Area_Circle(r):
return 3.14*r*r

r=int(input("enter r"))
print("ans=",Area_Circle(r)) function calling

 Sometimes it is useful to have multiple return statements, one in each branch of a conditional:
def big(a,b):
if(a>b):
return a
else:
return b

print(big(5,8))

 In the above ex, since these return statements are in an alternative conditional, only one will be
executed. As soon as one is executed, the function terminates without executing any subsequent
statements.
 Code that appears after a return statement, or any other place the flow of execution can never
reach, is called dead code.

PARAMETERS:
 Input values (parameters) are passed from function calling line to function definition block, these
inputs are called as arguments or parameters.
 Here is an example of a user-defined function that takes an argument:
def print_twice(bruce):
print (bruce)
print (bruce)
 This function assigns the argument to a parameter named bruce. When the function is called, it
prints the value of the parameter (whatever it is) twice.
 This function works with any value that can be printed.

13
Ex 1 >>> print_twice('Spam') #String
Spam
Spam
Ex 2 >>> print_twice(17) #Integer
17
17
Ex 3 >>> print_twice(math.pi) #Pre-defined value of ‘pi’
3.14159265359
3.14159265359
Ex 4 >>> print_twice('Spam '*4) #String 4 times
Spam Spam Spam Spam
Spam Spam Spam Spam
Ex 5 Use a variable as an argument: #Variable value
>>> michael = 'Eric, the half a bee’
>>> print_twice(michael)
Eric, the half a bee.
Eric, the half a bee.
The name of the variable we pass as an argument (michael) has nothing to do with the name of the
parameter (bruce). It doesn’t matter what the value was called back home (in the caller)
Here in print_twice, we call everybody bruce.

LOCAL AND GLOBAL SCOPE (or) SCOPE OF VARIABLES


 All variables in a program may not be accessible at all locations in that program. This depends on
where you have declared a variable.
 The scope of a variable determines the portion of the program where you can access a particular
identifier.
 There are two basic scopes of variables in Python −
 Global variables
 Local variables

1. global variables:
Variables that are defined outside a function have a global scope.

2. local variables:

Variables that are defined inside a function body have a local scope.

Example

a=5 #global variable


def fun():
Output:
x=3 #local variable
value of x is 3
print (“value of x is:”, x)
value of a is 5
print (“value of a is:”, a)
fun()

14
CALL-BY-VALUE vs. CALL-BY-REFERENCE
Call by Value: In this parameter passing method, values of actual parameters are copied to
function’s formal parameters and the two types of parameters are stored in different memory locations.
So any changes made inside functions are not reflected in actual parameters of caller.
Call by Reference: Both the actual and formal parameters refer to same locations, so any changes
made inside the function are actually reflected in actual parameters of caller.

Ex. for call by value:


def changeme(mylist):
mylist.append([1,2,3,4]);
print("Values inside the function: ", mylist)
return OUTPUT:
mylist = [10,20,30]; Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
changeme(mylist); Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
print ("Values outside the function: ", mylist)

Ex. for call by reference:


def changeme(mylist):
mylist = [1,2,3,4];
print("Values inside the function: ", mylist)
return
OUTPUT:
mylist = [10,20,30]; Values inside the function: [1, 2, 3, 4]
changeme(mylist); Values outside the function: [10, 20, 30]
print ("Values outside the function: ", mylist)

FUNCTION COMPOSITION
Function composition is a way of combining functions such that the result of each function is
passed as the argument of the next function.
 For example, the composition of two functions f and g is denoted f(g(x)). x is the argument of g,
the result of g is passed as the argument of f and the result of the composition is the result of f.
Example:
def add(a,b):
return a+b
def mul(c,num):
return c*num
def mainfun(x,y):
z=add(x,y)
result=mul(z,10)
return result

Output:
mainfun(8,8)
160

15
RECURSION
 Recursion is a way of programming or coding a problem, in which a function calls itself one or
more times in its body.
 Usually, it is returning the return value of this function call. If a function definition fulfils the
condition of recursion, we call this function a recursive function.
Syntax:
Function1():
Function1()
the function1() is called themselves continuously, so the function is in recursion manner.
Advantages:
1. The code look clean and elegant.
2. Large problems broken down into small problems
Disadvantages:
1. Logic is hard to follow.
2. It takes more memory.
3. It is hard to debug.
Example 1: Factorial of a number
def fact(n):
if (n == 1):
return 1 Output:
else: Enter a number 3
return n * fact(n-1) Factorial is 6

x=int(input("Enter a number")) function call


print("Facorial is",fact(x))

Example 2: Fibonacci series using recursion


def fibo(n): OUTPUT:
if(n <= 1): Enter number of terms:5
return n Fibonacci sequence:
else: 0
return(fibo(n-1) + fibo(n-2)) 1
1
n = int(input("Enter number of terms:")) 2
print("Fibonacci sequence:") 3
for i in range(n):
print(fibo(i))

Example 3 Tower of Hanoi


def hanoi(disk,source,dest,aux): OUTPUT:
if disk>0: how many disks:3
hanoi(disk-1, source, aux, dest) move disk from A to C
print('move disk from', source, ‘to', dest) move disk from A to B
hanoi(disk-1, aux, dest, source) move disk from C to B
move disk from A to C
source = 'A'
aux = 'B' move disk from B to A
dest = 'C' move disk from B to C
disks=int(input('how many disks:')) move disk from A to C
hanoi(disk,source, dest, aux)

16
STRINGS
 A string is a sequence of characters, enclosed within single-quotes (‘ ’) or double quotes(“ ”).
Strings are immutable, which means you can’t change an existing string.
 For ex.
>>>fruit=”banana”
>>>print(fruit)
banana
 String index: The expression in brackets is called an index.
 The index indicates which character in the sequence to be displayed. The index starts at 0.
Example
>>>fruit=”banana”
>>>print(fruit[1])
a

>>>fruit=’banana’
>>>print(fruit[4])
n
 As an index, we can use an expression that contains variables and operators.
>>>fruit=’banana’
>>>i=1
>>>fruit[i]
a
>>>fruit[i+1]
n
 The value of the index has to be an integer.
>>>letter[1.5]
Type error: string indices must be integers

Reading strings from keyboard:


 The input() function reads a line entered on a console by an input device such as a
keyboard and convert it into a string and returns it. You can use this input string in
your python code.
Ex. str=input(“Enter a string:”)

String slices:
A segment of a string is called a slice. This can be represented using slicing operator ‘:’.

Example 1.
Output:
s= “Monty Python!” Monty
print (s[0:5]) Python
print(s[6:12]

 The operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth”
character, including the first but excluding the last.
o print (s[0:5]) #Monty

 If you omit the first index (before the colon), the slice starts at the beginning of the string.
o print (s[:5]) #Monty

17
 If you omit the second index, the slice goes to the end of the string.
o print (s[6:]) #Python

 If the first index is greater than or equal to the second the result is an empty string, represented
by two quotation marks.
o print (s[7:5]) #

 An empty string contains no characters and has length 0, but other than that, it is the same as
any other string.

Accessing strings:
 Python does not support a character type; these are treated as strings of length one, thus also
considered a substring.
 To access substrings, use the square brackets for slicing along with the index or indices to
obtain your substring.
 For example −
var1 = 'Hello World!'
var2 = "Python Programming"
print("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])

OUTPUT:
var1[0] : H
var2[1:5]: ytho

len( ):
 len() is a built-in(pre-defined) function that returns number of characters in a string.
>>>fruit=’banana’
>>>len(fruit)
6
 To get the last letter of a string, you might be tempted to try something like this:
>>> length = len(fruit)
>>> last = fruit[length-1]
 Since we started counting at zero, the six letters are numbered 0 to 5.
>>> print last
a
 Alternatively, you can use negative indices, which count backward from the end of the string. The
expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on.

 Ex.
>>>fruit=’banana’
>>>print(fruit[-1]
a
>>>print(fruit[-6]
b

18
Traversal with a for loop
 A lot of computations involve 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.
 Ex1: One way to write a traversal is with a while loop:
index = 0 OUTPUT:
fruit=”banana” b
while( index < len(fruit)): a
letter = fruit[index] n
print( letter ) a
index = index + 1 n
a

 This loop traverses the string and displays each letter on a line by itself

 Ex2: Another way to write a traversal is with a for loop


fruit=”banana”
for char in fruit:
print char

Immutability:

 Strings are immutable, that is we cannot change the existing strings.


Ex.
>>> msg=”Good Morning”
>>> msg[0]=’g’

Type error: ‘str’ object does not support item assignment

 The reason for the error is that strings are immutable, which means you can’t change an existing
string. The best you can do is create a new string that is a variation on the original:
>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> print (new_greeting Jello, world!)
 This example concatenates a new first letter onto a slice of greeting. It has no effect on the original
string.

String functions & methods:


 A method is similar to a function—it takes arguments and returns a value.

 Python has several built-in functions associated with the string data type.

 These functions helps us to easily modify and manipulate strings.

19
str.isalnum() - String consists of only alphanumeric characters (no symbols)
str.isalpha() - String consists of only alphabetic characters (no symbols)
str.islower() - String‘s alphabetic characters are all lower case
str.isnumeric()- String consists of only numeric characters
str.isspace() - String consists of only whitespace characters

Ex.
Book1 = "PYTHON PROGRAMMING"
book2 = "Python Program Book"
poem = "problem solving python"
print(book1.islower( )) OUTPUT:
False
print(book1.isupper( )) True
print(book2.istitle( )) True
print(book2.isupper( )) False
print(poem.istitle( )) False
print(poem.islower( )) True

join(), split(), and replace() methods

join( ) method:
 The str.join() method will concatenate two strings, but in a way that passes one string
through another.
 Syntax:
str.join(Sequence)
Ex.
s = "-";
seq = ("a", "b", "c");
print s.join( seq )

output:
a-b-c

split( ) method:

 The method split() returns a list of all the words in the string

Ex.
words = "This is random text"
words2 = words . split(" ")
print(words2)
output:
['This', 'is', 'random', 'text']

20
replace( ) method:

 The replace() method returns a copy of the string where all occurrences of a substring is
replaced with another substring.
Example:
song = 'cold, cold heart'
print (song . replace('cold', 'hurt'))

output:
hurt, hurt heart

STRING MODULES

 The string module provides additional tool to manipulate strings.


 This module contains a number of functions to process standard python strings.
 In recent version, string build in function are available as string module functions.

# String module
import string as str
text="Monty Python's Flying Circus"
OUTPUT:
print("upper", "=>",str.upper(text))
print( "lower", "=>",str.lower(text)) upper => MONTY PYTHON'S FLYING CIRCUS
print("split", "=>",str.split(text)) lower => monty python's flying circus
print("join", "=>", str.join(str.split(text),"+")) split => ['Monty', "Python's", 'Flying', 'Circus']
join => Monty+Python's+Flying+Circus
print("replace", "=>",str.replace(text,"Python", "Java"))
replace => Monty Java's Flying Circus
print("find", "=>",str.find(text, "Python")), find => 6
print("count", "=>",str.count(text, "n")) count => 3

21
ILLUSTRATIVE PROGRAMS:
1. Square root of a number
def newtonsqrt(n):
approx=0.5*n
better=0.5*(approx+n/approx)
while(better!=approx):
approx=better
better=0.5*(approx+n/approx)
return approx Output:
n=int(input("Enter the number:")) Enter the number:81
result=newtonsqrt(n) The square root for the given number is: 9.0
print("The square root for the given number is:",result)

2. gcd of a number
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)

a=int(input("Enter first number:")) Output:


Enter the first number:15
b=int(input("Enter second number:"))
Enter the second number:5
print (“The GCD of the two numbers is:”, gcd(a,b)) The GCD of the two numbers is 5

3. Exponentiation
import math Output:
x=int(input("Enter X:")) Enter X:3
y=int(input("Enter Y:")) EnterY:2
print("Power:",math.pow(x,y)) Power :9

4. linear search
n=int(input("Enter the limit:"))
list=[ ]
print("Enter the element one by one:") Output:
for i in range(0,n): Enter the limit:5
x=int(input()) Enter the element one by one:
list.append(x)
34
key=int(input("Which element to search:"))
12
count=0
for i in range(0,n): 45
if(key==list[i]): 67
count=count+1 32
if(count>0): Which element to search:45
print("Element found") Element found
else:
print("Element not found")

22
5. Binary search

n=int(input("Enter the limit"))


list=[ ]
print("Enter list elements one by one")
for i in range(0,n):
x=int(input())
list.append(x)
print("The list elements are")
print(list) Output:
key=int(input(“Which element to search”)) Enter the limit 4
locn=-1 Enter list elements one by one
first=0 10
last=n 20
while(first<=last): 30
mid=(first+last)//2 40
if(list[mid]>key): The list elements are
last=mid-1 [10, 20, 30, 40]
elif(list[mid]<key): Which element to search
first=mid+1 40
else: Element not found
first=last+1 40 Found at position 3
if(list[mid]==key):
locn=mid
if(locn<0):
print("Element not found")
else:
print(key, "Found at postion", locn)

6.Sum of array of numbers

sum=0
i=0
a=[10,20,30,40]
for i in range(4):
sum=sum+a[i]
print(sum)

23
Additional Programs:
1.Write a python program to find factorial of a number without recursion and without recursion
[Dec /Jan 2018]

without recursion:

n=int(input("Enter number:"))
i=1
fact=1
while(i<=n):
fact=fact*i
i=i+1
print("Factorial of the number is: ")
print(fact)

with recursion:
def fact(n):
if (n == 1):
return 1
else:
return n * fact(n-1)

x=int(input("enter a number:"))
print("Facorial is:",fact(x))

Output:
enter a number : 3
Factorial is: 6

2.Write a python program to generate first ‘N’ Numbers.(0,1,1,2,3,5,8,13,……)


[Dec/Jan 2018]

def fibo(n):
if(n <= 1): Output:
return n Enter number of terms: 6
else: Fibonacci sequence:
return(fibo(n-1) + fibo(n-2)) 0
1
1
n = int(input("Enter number of terms:")) 2
print("Fibonacci sequence:") 3
for i in range(n): 5
print(fibo(i))

24
UNIT IV LISTS, TUPLES, DICTIONARIES
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and methods; advanced
list processing - list comprehension; Illustrative programs: simple sorting, histogram, Students marks
statement, Retail bill preparation.

LISTS
Like a string, a list is a sequence of values. In a string, the values are characters; In a list, they can be
of any type. The values in a list are called elements or sometimes items.
A list need not be homogenous. The elements of a list don’t have to be the same type. A list can contain
different data type items such as string, integer, float, real and another list. Each and every item has its unique
index.

There are several ways to create a new list; the simplest is to enclose the elements in square brackets ([ ]):
>>>L1=[10, 20, 30, 40] #List of four Integers
>>>L2=[‘Apple’, ‘Banana’, ‘Orange’] #List of three Strings
>>>L3=[‘spam’, 2.0, 5, [10, 20]] #list with string, a float, an integer, and another list
>>>L4=[] #A list that contains no elements is called an empty list;

Mutability in Lists
To access the elements of a list the bracket operator is used. The expression inside the brackets specifies
the index. The indices starts at 0.
Any integer expression can be used as an index. If an index has a negative value, it counts backward
from the end of the list.
>>> L2=[‘Apple’, ‘Banana’, ‘Orange’]
>>> L2[0]
‘Apple’
Unlike strings, lists are mutable. We can delete or replace the items or elements in the list.
>>> L2[1]= ‘Grapes’ #replaces ‘Banana’
>>> L2
[‘Apple’, ‘Grapes’, ‘Orange’]

The in operator also works on lists:


>>> L2=[‘Apple’, ‘Banana’, ‘Orange’]
>>>’Apple’ in L2
True
>>>’Banana’ in L2
False
Traversing a List:
The most common way to traverse the elements of a list is with for loop. For loop in python is an
iterator that works on any sequence like list, tuple and string.

Example 1: Program to list contents


Output:
mylist = ['one', 'two', 'three']
number one
for x in mylist: number two
number three
print('number' ,x)

Accessing Values in Lists:


To access values in lists, use the square brackets for slicing along with the index or indices to obtain
value available at that index.

Example: Program to access the values in lists.


list1 = ['computer', 'maths', 'physics', 'chemistry']
list2 = [1,2,3,4,5] Output:
list3 = ['x', 'y', 'x'] computer
print(list1[0]) [3,4,5]
print(list2[2:5]) [‘x’, ‘y’, ‘x’]
print(list3)

Updating list
Single or multiple elements can be updated in a list by giving the slice on the lefthand side of the
assignment operator and also can add the elements in a list with the append() method.
Example.py
s=['Red','green','Blue','yellow','Purple']
print("value at index 2:",s[2])
Output:
s[2]='Lavender'
print(s) value at index 2: Blue
s.append('Orange') ['Red', 'green', 'Lavender', 'yellow', 'Purple']
print(s) ['Red', 'green', 'Lavender', 'yellow', 'Purple', 'Orange']

Deleting elements in a List


 When index of element is known then, ‘del’ keyword is used to delete.
 When element to delete is known,then remove() method is used.

Example.py
s=['Red','green','Blue','yellow','Purple']
print(s) Output:
del s[2] ['Red', 'green', 'Blue', 'yellow', 'Purple']
print(s)
['Red', 'green', 'yellow', 'Purple']
s.remove('yellow')
print(s) ['Red', 'green', 'Purple']
LIST OPERATIONS

List Operations:
List respond to the + and * operators much like strings; they mean concatenation and repetition here
too, expect that the result is a new list, not a string.

Python Expression Result Description


len ([1,2,3,4]) 4 Length
[1,2,3,4] + [5,6,7,8] [1,2,3,4,5,6] Concatenation
[‘Hi!’] * 2 [‘Hi!’, ‘Hi’] Repetition
2 in [1,2,3] True Membership
for x in [1,2,3,4,5]:
12345 Iteration
print(x)

The + is a concatenation operator, that concatenates lists:


>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
[1, 2, 3, 4, 5, 6]
The * is a Repetition operator, that repeats the list for a given number of times:
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
The first ex, repeats [0] four times. The second ex, repeats the list [1, 2, 3] three times.
len() is used to find the number of elements in a sequence.
>>>list1=[1,2,3,4]
>>>print(len(list1))
4
max () & min(): max(s) returns the largest value in a sequence s and min(s) returns the smallest
value in a sequence s
>>>list1=[1,2,3,4]
>>>print(max(list1))
4
>>>print(min(list1))
1
List index:
The index operator[ ] is used to access an item in a list. Index starts from 0. So, a list having 5 elements
will have index from 0 to 4.Trying to access an element other that this will raise an IndexError. The index
must be an integer. We can’t use float or other types, this will result into TypeError. Nested list are accessed
using nested indexing.
Example: Program to access list elements using index.
my_list = [‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’] Output:
print(my_list[4]) o
n_list = [“happy”, [2,0,1,5]] [‘happy’, [2,0,1,5]]
print(n_list) a
print(n_list[0][1]) 5
print(n_list[1][3])
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the
second last item and so on.
Example : Program to use negative index in lists.
my_list = [‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’] Output:
print(my_list[-1]) n
print(my_list[-3]) h
print(my_list[-5]) y

LIST SLICES
We can access a range of items in a list by using the slicing operator(colon :)

The slice operator also works on lists:


>>> t = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
>>> t =[1:3]
[‘b’, ‘c’]
>>> t[ :4]
[‘a’, ‘b’, ‘c’, ‘d’]
>>> t[3:]
[‘d’, ‘e’, ‘f’]

If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes to the
end. So if you omit both, the slice is a copy of the whole list:
>>> t[:]
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]

Since lists are mutable, it is often useful to make a copy before performing operations that modify lists.

Example: Program to use slice operator in the list


my_list = [‘K’, ‘E’, ‘C’, ‘ ’, ‘P’, ‘u’, ‘b’, ‘l’, ‘i’, ‘s’, ‘h’, ‘e’, ‘r’, ‘s’]
print(my_list[0:3]) Output:
print(my_list[:-5]) [‘K’, ‘E’, ‘C’]
print(my_list[4:]) [‘K’, ‘E’, ‘C’, ‘ ’, ‘P’, ‘U’, ‘B’, ‘L’, ‘I’]
[‘P’, ‘U’, ‘B’, ‘L’, ‘I’, ‘S’, ‘H’, ‘E’, ‘R’, ‘S’]
print(my_list[:]) [‘K’, ‘E’, ‘C’, ‘ ’, ‘P’, ‘U’, ‘B’, ‘L’, ‘I’, ‘S’, ‘H’, ‘E’, ‘R’, ‘S’]

Slicing can be bets visualized by considering the index to be between the elements as shown below. So if we
want to access a range, we need two index that will slice that portion from the list.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 Index
K E C P U B L I s h e r s
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Negative Index
LIST METHODS
List method is a method to list all the elements in the set. Python provides methods that operates on
lists. They are accessed as list.method( ).

 List methods are,


1. list.append(elem) – adds a single elements to the end of the list.
2. list.insert(index,elem) – inserts the element at the given index.
3. list.extend(list2) – adds the elements in list2 to the end of the list.
4. List.index(elem) – search for the given element from the start of the list and returns its index.
5. list.remove(elem) – search for the first instance of the given element and removes it.
6. list.sort( ) – sorts the list in place
7. list.reverse( ) – reverses the list in place
8. list.pop(index) – removes and returns the elements at the given index.
9. list.clear( ) – removes all elements from the list
10. list.count( ) – returns the count of number of items passed as an argument.
11. list.copy( ) – returns a shallow copy of the list

Example for list methods:


list = [‘apple’ , ‘orange’ , ‘grapes’]
list.append(‘banana’) #append element at end
list.insert(0, ‘gova’) #insert element at index 0
list.extend([‘chikoo’ , ‘jackfruit’]) #add elements at end
print list #[‘gova’ , ‘apple’ , ‘orange’ , ‘grapes’ , ‘banana’ , ‘chikoo’ , ‘jackfruit’]
print list.index(‘orange’) #2
list.remove(‘orange’) #search and remove the element
list.pop(1) #removes and returns ‘apple’
print list #[‘gova’ , ‘grapes’ , ‘banana’ , ‘chikoo’ , ‘jackfruit’]

Output:
[‘guava’ , ‘apple’ , ‘orange’ , ‘grapes’ , ‘banana’ , ‘chikoo’ , ‘jackfruit’]
2
[‘guava’ , ‘grapes’ , ‘banana’ , ‘chikoo’ , ‘jackfruit’]
append(): reverse():
This method appends / adds the pass object (v) to This method reverses the element in the list.
the existing list.
list1=[1,2,3,4] list1=[5,2,10,4]
list1.append(99) list1.reverse()
print(list1) print(list1)
Output: Output:
[1, 2, 3, 4, 99] [4, 10, 2, 5]

insert(): count():
This method insert the given element at the This method returns count of how many times
specified position. elements occur in the list.
list1=[1,2,3,4] list1=[5,2,10,4,3,5]
list1.insert(1,100) print(list1.count(5))
print(list1) Output:
Output: 2
[1, 100, 2, 3, 4]
index():
remove(): This method returns the index value of an element.
Removes the element from the list. If there is no
element then it displays error. list1=[5,2,10,4,3]
list1=[1,2,3,4] print(list1.index(10))
list1.remove(4) Output:
print(list1) 2
Output:
[1, 2, 3] pop():
This method removes the element from the list at
extend(): the specified index. If the index value is not
This method appends the contents of the list. specified it removes the last element from the list.
list1=[5,2,10,4,3]
list1=[1,2,3,4] print(list1.pop(4))
list1.extend([10,20,30]) print(list1.pop(7))
print(list1) Output:
Output: 3
[1, 2, 3, 4, 10, 20, 30] Traceback (most recent call last):
File "python", line 3, in <module>
sort(): IndexError: pop index out of range
This method sorts the element either alphabetically
or numerically. del():
list1=[5,2,10,4] Element to be deleted is mentioned using list name
list1.sort() and index.
print(list1)
Output: list1=[5,2,10,4,3]
[2, 4, 5, 10] del list1[3]
print(list1)
Output:
[5, 2, 10, 3]
LIST LOOP
Creating list using range( )
The range( ) functions returns an immutable sequence object of integers between the given start integer
to the stop integer.
It generates a list of numbers, which is generally used to iterate over with loops.
Syntax:
range(stop)
range(start, stop[, step])
where,
start – starting number of the sequence
stop – generate numbers up to, but not including this number.
step – integer value which determines the increment between each integer in the sequence

Iterate or Loop a List using ‘for’:


Example 1: To print numbers using range( ) function
for i in range(5):
Output:
print(i, end= “ ”)
01234
Example 2:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)

Iterate or Loop a List using ‘while’:


We can loop through the list items by using a while loop.
The len() function is used to determine the length of the list, then start at 0 and loop through the list
items by referring to their indexes.
After each iteration, the index must be incremented by one.

Example: Loop a list using while loop


mylist = range(5) Output:
i=0
while(i<len(mylist)): 01234
print(i,end= “ ”)
i+=1

Looping Using List Comprehension


List Comprehension offers the shortest syntax for looping through lists:

Example
A short hand for loop that will print all items in a list:

thislist = ["apple", "banana", "cherry"]


[print(x) for x in thislist]
ALIASING
An object with more than one references has more than one name, such object is called alias.
Example: a = [1, 2, 3]
b=a
b is a

rogram of List Aliasing OUTPUT


a=[1,2,3,4]
b=a b: [1,2,3,4]
print ’b:’,b
b.append(5) a after change in b:[1,2,3,4,5]
print ‘a after change in b:’,a

CLONING LISTS:
Cloning is different from aliasing. Aliasing just creates another name for the same list. Cloning creates
a new list with same values under another name. Taking any slice of a list creates a new list.
Example:
fruits=[“apples”,”pear”,”grapes”,”orange”,”mango”]
fruit_list=fruits
clonefruit=fruit_list[:]
clonefruit.append(“banana”) OUTPUT:
fruit_list[1]=”Lemon”
Original List: [“apples”, “Lemon”, “grapes”, “orange”, “mango”]
print “Original List:”,fruits
print “Alias List:”,fruit_list Alias List: [“apples”, “Lemon”, “grapes”, “orange”, “mango”]
print “clone List:”,clonefruit
clone List: [“apples”, “pear”, “grapes”, “orange”,
“mango”, “banana”]
LIST PARAMETERS
When you pass a list to a function ,the function gets a reference to the list.If the function modifies the
list,the caller sees the change.

For ex: delete _head removes the first element from a list:

def delete_head(t):
del t[0]
>>> letters=[‘a’,b’,’c’]
>>>delete_head(letters)
>>>letters
[‘b’,’c’]
The parameter‘t’ and the variable letters are aliases from the same object.
TUPLE
A tuple is a sequence of values. The values can be any type. They are immutable (i.e)objects whose
value is unchangeable once they are created.

Example: t = ('a', 'b', 'c',’d’, 'e')

CREATING AND ACCESSING TUPLE:

Tuple can be created by putting different values separated by comma;the parantheses are optional.

Example:

a=() #Empty tuple

b=(1,2,3) #Integer tuple

c=(1,”hello”,3.4) # Mixed tuple

Simple example for tuples:

No’s_Tuple=(1,2,3)
print No’s_tuple
Nested _tuple=(“string”,[‘list’,’in’,’tuple’],(‘tuple’,’in’,tuple’)) OUTPUT:
print Nested _tuple[0] (1, 2, 3)
print (Nested_tuple[1] string
print Nested _tuple[2] ['list', 'in', 'tuple']
Mixed_tuple=3,”kg”,”apples” ('tuple', 'in', 'tuple')
print(Mixed_tuple) (3, 'kg', 'apples')
Nos,measure,what=Mixed_tuple 3
print(Nos) kg
print(measure) apples
print(what)

OPERATIONS IN TUPLE

Two operators + and * is allowed in tuples. ‘+’ concatenates the tuples and ‘*’ repeates the tuple
elements a given number of times.

Ex:

t1= (1,2,3,4,7,8,9)
t2=(‘a’,)*5 OUTPUT:
t3=t1+t2
print “Add operation:”,t3 Add operation: (1, 2, 3, 4, 7, 8, 9, 'a', 'a', 'a', 'a', 'a')
print “Repeat operation:”,t2
Repeat operation: ('a', 'a', 'a', 'a', 'a')
SLICING AND INDEXING OF TUPLES:

Slicing of tuples is similar to list.


Ex:

a=(‘physics’,’chemistry’,1997,2000)
b=(1,2,3,4,5) OUTPUT:
c=(“x”,”y”,(10,4,5))
a[0]: physics
print “a[0]: ”,a[0]
c[2]: (10, 4, 5)
print ”c[2]: ”,c[2]
b[-2]: 4
print “b[-2]: ”,b[-2]
b[1:3]: (2, 3)
print “b[1:3]: ”,b[1:3]

DELETING AND UPDATING TUPLES:

Tuples are immutable; the elements cannot be changed. In lists the elements can be deleted.In
tuples elements cannot be deleted. However the entire tuple can be deleted using del.Similarly the elements
cannot be modified in a tuple.

In tuple we can replace one tuple with another, but can’t modify the elements.

Ex : >>>t = ('a', 'b', 'c', 'd', 'e')


>>>t =(‘A’,)+t[1:]
<<<t
(‘A’, ’b’ , ’c’, ’d’, ’e’)

TUPLE ASSIGNMENT
Python has a very powerful tuple assignment feature that allows a tuple of variables on the left of an
assignment to be assigned values from a tuple on the right of the assignment.
Example: a,b,c=1,2,3
The left side is a tuple of variable; the right side is a tuple of values. Each value is assigned to its
respective variable. The number of variables on the left and the right of the assignment operator must be same.
All the expression on the right side are evaluated before any of the assignment. This features make
tuple assignment quite versatile.

For Example:
>>> (a, b, c)=(1, 2, 3)

# Program to swap a and b (without using third variable)


a=2; b=3
print(a, b) OUTPUT:
a,b=b,a
print(a, b) (2, 3)
(3, 2)
 One way to think of tuple assignment is as tuple packing/unpacking:
In tuple packing, the value on the left are ‘packed’ together in a tuple:
>>> b= (“George”,25,”20000”) #tuple packing
>>> (name, age, salary) = b #tuple unpacking
>>> name
‘George’
>>> age
25

TUPLE AS RETURN VALUE


Functions can only return 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.

The built-in-function divmod takes two arguments and return a tuple of two values: the quotient and
remainder. You can store the result as a tuple:

>>> def divmod(x,y):


Return(x/y,x%y)

>>> t=divmod(7,3)
>>>t
>>>(2,3)

Or use tuple assignment to store the elements separately:


>>>quot,rem=divmod(7,3)
>>>quot
2
>>>rem
1

Here is an example of a function that returns a tuple:

def min_max(t)
return min(t),max(t)

max and min are build-in-functions that find the largest and smallest elements of a sequence.min_max
computes both and returns a tuple of two values.
DICTIONARIES
DICTIONARY

A dictionary is set of pairs of value with each pair containing a key and an item and is enclosed in curly
brackets. It is one of the compound data type like string, list and tuple.
 In dictionary the index can be immutable data type.
 It is a set of zero or more ordered pairs of key and value.
 The value can be any type.
 Each key may occur only once in the dictionary
 No key may be mutable. A key may not be a list or tuple or dictionary and so on.

Example:
dict={} #empty dictionary
d1={1:'fruit ', 2:'ve getables', 3:'cereals'}

Creation and Accessing dictionary


There are two ways to create dictionaries.
1) It is created by specifying the key and value separated by a colon(:) and the
elements separated by commas and entire set of elements must be enclosed by curly braces.
2) dict() constructor that uses a sequence to create dictionary.

Example:
d1={1:'fruit',2:'vegetables',3:'cereals'}
d2=dict({'name':'aa','age':40})
print(d1[1])
print(d2)
Output:
fruit
{'name': 'aa', 'age': 40}

Deletion of elements
The elements in the dictionary can be deleted by using del statements.
The entire dictionary can be deleted by specifying the dictionary variable name.

Example:
del d1[1]#remove entry with key '1'
print(d1)
d1.clear()#remove all entries in dict
print(d1)
Output:
{2: 'vegetables', 3: 'cereals'}
{}
Updating elements
In dictionary the keys are always immutable.
The values are mutable that can be modified. New-key value pair can be inserted or deleted from the
dictionary.

Example:
d3={'name':'abc','dept':'ece'}
d3['name']='xxxx'
print(d3)
Output:
{'name': 'xxxx', 'dept': 'ece'}

Length:
The len function works on dictionaries; it returns the number of key-value pairs:
>>> dict1 = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> len(dict1)
3

In Operator:
The in operator works on dictionaries; it tells you whether something appears as a key in the
dictionary (appearing as a value is not good enough).
>>> dict1= {'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> 'one' in eng2sp
True
>>> 'uno' in dict1
False

To see whether something appears as a value in a dictionary, we can use the method values, which
returns the values as a list, and then use the in operator:
>>> vals = eng2sp.values()
>>> 'uno' in vals
True

Delete Dictionary Elements


 We can either remove individual dictionary elements or clear the entire contents of a dictionary.
 To explicitly remove an entire dictionary, just use the del statement.
Following is a simple example −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # remove entry with key 'Name'
dict.clear() # remove all entries in dict
del dict # delete entire dictionary
print ( "dict ['Age']: " , dict ['Age'] )
print ("dict ['School']: " , dict ['School'])
Properties of Dictionary Keys:
Here are two important points to remember about dictionary keys −

1) More than one entry per key is not allowed. This means no duplicate key is allowed. When duplicate
keys are encountered during assignment, the last assignment wins.
For example −
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Mani'}
print ("dict['Name']: ", dict['Name'])
Output:
dict['Name']: Mani
2) Keys must be immutable. This means you can use strings, numbers or tuples as dictionary keys but
something like ['key'] is not allowed.
Following is a simple example −
dict = {['Name']: 'Zara', 'Age': 7}
print ("dict['Name']: ", dict['Name'])

When the above code is executed, it produces the following result


Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7}
TypeError: list objects are unhashable

Looping and dictionaries:

If you use a dictionary in a for statement, it traverses the keys of the dictionary.

For example,
def histogram(s):
d=dict()
for c in s: Output:
if c not in d: >>> h = histogram('parrot')
d[c]=1 >>> print_hist(h)
else: a1
d[c]+=1 p1
return d r2
t1
print_hist prints each key and the corresponding value: o1
def print_hist(h):
for c in h:
print c, h[c]

Again, the keys are in no particular order.


OPERATIONS IN DICTIONARY
1. cmp(dict1, dict2)
 Compares elements of both dict.
 This method returns 0 if both dictionaries are equal, -1 if dict1 < dict2 and 1 if dict1 > dic2.
For ex.
dict1 = {'Name': 'Zara', 'Age': 7}; OUTPUT:
dict2 = {'Name': 'Mahnaz', 'Age': 27};
dict3 = {'Name': 'Abid', 'Age': 27}; Return Value : -1
Return Value : 1
dict4 = {'Name': 'Zara', 'Age': 7};
Return Value : 0
print ("Return Value :",cmp(dict1, dict2))
print ("Return Value :",cmp(dict2, dict3))
print ("Return Value :",cmp(dict1, dict4))
2. len(dict)
Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
For ex. OUTPUT:
dict = {'Name': 'Zara', 'Age': 7};
print ("Length : ", len (dict)) Length : 2

3. str(dict)
Produces a printable string representation of a dictionary
For ex.
dict = {'Name': 'Zara', 'Age': 7} OUTPUT:
print ("Equivalent String :",str (dict))
Equivalent String : {'Age': 7, 'Name': 'Zara'}
4. type(variable)
 Returns the type of the passed variable. If passed variable is dictionary, then it would return a
dictionary type.
For ex.
dict = {'Name': 'Zara', 'Age': 7};
print ("Variable Type :", type (dict))

METHODS IN DICTIONARY

1.dict.clear()
Removes all elements of dictionary dict
Ex.
dict = {'Name': 'Zara', 'Age': 7}
OUTPUT:
print ("Start Len :",len(dict))
dict.clear() Start Len : 2
print ("End Len :",len(dict))
End Len : 0
2. dict. copy()
Returns a shallow copy of dictionary dict
Ex.
dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = dict1.copy()
print ("The copied value:",dict2)

3.dict.values()
The method values() returns a list of all the values available in a given dictionary.
For ex.
dict = {'Name': 'Zara', 'Age': 7}
print ("Values:",dict.values())

4.dict.key()
The method keys() returns a list of all the available keys in the dictionary
Example:
dict = {'Name': 'Zara', 'Age': 7}
print("The keys are:",dict.keys())

5. dict.has_key(key)
The method has_key() returns true if a given key is available in the dictionary, otherwise it returns a false.
Ex.
dict = {'Name': 'Zara', 'Age': 7}
print "Value :”, dict.has_key('Age')
print "Value :”,dict.has_key('Sex')

6.dict.item()
The items() method returns a view object that displays a list of a given dictionary's (key, value) tuple
pair.The items() method doesn't take any parameters.
For.ex
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print(sales.items())

7.dict.fromkeys()
The method fromkeys() creates a new dictionary with keys from seq and values set to value.
Syntax:
dict.fromkeys(seq [ , value] )
For ex.
keys = {'a', 'e', 'i', 'o', 'u' }
value = 'vowel'
vowels = dict.fromkeys(keys, value)
print(vowels)
8. update()
The method update() adds dictionary dict2's key-values pairs in to dict. This function does not
return anything.
For ex.
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Gender': 'female' }
dict.update(dict2)
print ("The updated value :",dict)

ADVANCED LIST PROCESSING


LIST COMPREHENSION

Python supports a concept called “list comprehensions”.It can be used to construct lists in a very
natural,easy way,like a mathematics is used to do.
In python, we can write the expression almost exactly like a mathematics with special cryptic syntax.

For example:
>>> L=[X**2 for x in range (10)]
>>> L
[0,1,4,9,16,25,36,49,64,81]
The above code creates a list of square numbers from 0 to 9.This list can be created using a
simplified expression “X**2 for x in range (10)”.This is basically list comprehension.

The list comprehension is achieved using the tools like map, lambda, reduce and filter

MAP:
The map() function applies the values to every member of the list and returns the result.
The map function takes two arguments .

Syntax: result=map(function,sequence)
Example:
>>>def increment_by_three(x):
return x+3
>>>new_list=list(map(increment_by_three,range(10)))
>>>new_list

OUTPUT:
[3,4,5,6,7,8,9,10,11,12]

Another example: There is a build in function for calculating length of a string and and i.e len().We can pass
this function to map and find the length of every element in the list.
>>> names=[‘Sandip’,’Lucky’,’Mahesh’,’Sachin’]
>>>lengths=list(map(len,names))
>>>lengths
[6,5,6,6]

FILTER:
The filter() function selects some of the elements and filters out others .If we use it wit list
comprehension,it is almost equivalent to the filter build-in. This function takes two arguments.

Syntax: result=filter(function,sequence)
for example:
>>>def even_fun(x):
return x%2= =0
>>>r=filter(even_fun,[1,2,3,4,5])
>>>list(r)
[2,4]
In above example,using filter() function the odd numbers are filtered out and only even numbers are
displayed.

LAMBDA:
The lambda function is a simple inline function that is used to evaluate the expression using the given list
of arguments.

Syntax: lamda argument_list:expression

Where the argument_list consists of a comma separated list of arguments and the expression is an arithmetic
expression using these arguments.
Example: >>>sum=lambda x,y:x+y
>>>sum(1,3)
4
REDUCE:
The kind of function that combines sequence of elements into a single value is called reduce function.
This function takes two arguments.
Result=reduce(function,sequence)
The function reduce() had been dropped from core of python when migratin to python 3
Hence for using the reduce function we have to import functools to be capable of using reduce.\
>>>import functools
>>>functools.reduce(lambda x,y:x+y[1,2,3,4])
10
ILLUSTRATIVE PROGRAMS

1.Selection Sort
4. Merge Sort
source = [10,90,30,20]
for i in range(len(source)): def mergeSort(alist):
mini = min(source[i:]) print("Splitting ",alist)
min_index = source[i:].index(mini) if len(alist)>1:
source[i + min_index] = source[i] mid = len(alist)//2
source[i] = mini lefthalf = alist[:mid]
print(source) righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
2.Insertion Sort i=0
def insertionSort(alist): j=0
for index in range(1,len(alist)): k=0
currentvalue = alist[index] while (i < len(lefthalf)) and (j < len(righthalf)):
position = index if lefthalf[i] < righthalf[j]:
while position>0 and alist[position- alist[k]=lefthalf[i]
1]>currentvalue:
i=i+1
alist[position]=alist[position-1]
position = position-1 else:
alist[position]=currentvalue alist[k]=righthalf[j]
j=j+1
alist=[12,34,67,30,82] k=k+1
insertionSort(alist) while i < len(lefthalf):
print(alist) alist[k]=lefthalf[i]
i=i+1
3.Histogram
k=k+1
while j < len(righthalf):
def histogram(s):
d=dict() alist[k]=righthalf[j]
for c in s: j=j+1
if c not in d: k=k+1
d[c]=1 print("Merging ",alist)
else: n = input("Enter the size of the list: ")
d[c]+=1 alist = [30,50,10,70]
return d
mergeSort(alist)
def print_hist(h): print(alist)
for c in h:
print c, h[c]
PART- A (2 Marks)
1. What is a list?(Jan-2018)
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.

2. Relate String and List? (Jan 2018)(Jan 2019) String:


String is a sequence of characters and it is represented within double quotes or single quotes. Strings are
immutable.
Example: s=”hello”
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 and it is mutable.
Example:
b= [’a’, ’b’, ’c’, ’d’, 1, 3]

3. Solve a)[0] * 4 and b) [1, 2, 3] * 3.


>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

4. 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’]

5. Mention any 5 list methods.


 append()  pop()  remove()
 extend ()  index()
 sort()  insert

6. State the difference between lists and dictionary.


Lists Dictionary
 List is a mutable type meaning that it can  Dictionary is immutable and is a key
be modified. value store.
 List can store a sequence of objects in a  Dictionary is not ordered and it requires
certain order. that the keys are hashable.
 Example: list1=[1,’a’,’apple’]  Example: dict1={‘a’:1, ‘b’:2}
7. What is List mutability in Python? Give an example.
Python represents all its data as objects. Some of these objects like lists and dictionaries are mutable, i.e., their
content can be changed without changing their identity. Other objects like integers, floats, strings and tuples are
objects that cannot be changed.
Example:
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print numbers [17, 5]

8. What is aliasing in list? Give an example.


An object with more than one reference has more than one name, then the object is said to be aliased.
Example:If a refers to an object and we assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a True

9. Define cloning in list.


In order to modify a list and also keep a copy of the original, it is required to make a copy of the list itself, not
just the reference. This process is sometimes called cloning, to avoid the ambiguity of the word “copy”.
Example:
def Cloning(li1): li_copy = li1[:] return li_copy
# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1) print("Original List:", li1) print("After Cloning:", li2) Output:
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

10. Explain List parameters with an example.


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:
Example: def head(list):
return list[0]
Here’s how it is used:
>>> numbers = [1, 2, 3]
>>> head(numbers)
>>> 1

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]
12. Write a program in Python to delete first element from a list.
def deleteHead(list): del list[0]
Here’s how deleteHead is used:
>>> numbers = [1, 2, 3]
>>> deleteHead(numbers)
>>> print numbers [2, 3]

13. 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 temporary variable would
be used.
For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a

14. Define key-value pairs.


The elements of a dictionary appear in a comma-separated list. Each entry contains an index and a value
separated by a colon. In a dictionary, the indices are called keys, so the elements are called key-value pairs.

15. Define dictionary with an example.


A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated (or mapped)
to a value. The values of a dictionary can be any Python data type. So dictionaries are unordered key-value-
pairs.
Example:
>>> eng2sp = {} # empty dictionary
>>> eng2sp[’one’] = ’uno’
>>> eng2sp[’two’] = ’dos’

16. 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 you 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)

17. List two dictionary operations.


 Del -removes key-value pairs from a dictionary
 Len - returns the number of key-value pairs

18. Define dictionary methods with an example.


A method is similar to a function. It takes arguments and returns a value but the syntax is different. For example,
the keys method takes a dictionary and returns a list of the keys that appear, but instead of the function syntax
keys(dictionary_name), method syntax dictionary_name.keys() is used.
Example:>>> eng2sp.keys() [’one’, ’three’, ’two’]
19. Define List Comprehension.
List comprehensions apply an arbitrary expression to items in an iterable rather than applying function. It
provides a compact way of mapping a list into another list by applying a function to each of the elements of the
list.

20. Write a Python program to swap two variables.


x=5
y = 10
x,y=y,x
print('The value of x after swapping: {}'.format(x)) print('The value of y after swapping: {}'.format(y))

21. Write the syntax for list comprehension.


The list comprehension starts with a '[' and ']', to help you remember that the result is going to be a list. The
basic syntax is[ expression for item in list if conditional ].
Example:
new_list = [] for i in old_list:
if filter(i): new_list.append(expressions(i))

22. How list differs from tuple. (Jan-2018)


List Tuple
 List is a mutable type meaning that it can be  Tuple is an immutable
modified. type meaning that it cannot be
 Syntax: list=[] modified.
 Example: list1=[1,’a’]  Syntax: tuple=()
 Example: tuple1=(1,’a’)

23. How to slice a list in Python. (Jan-2018)


The values stored in a list can be accessed using slicing operator, the colon (:) with indexes starting at 0 in the
beginning of the list and end with -1.
Example:
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3]
[’b’, ’c’]

24. Write python program for swapping two numbers using tuple assignment?
a=10 b=20
a,b=b,a
print(“After swapping a=%d,b=%d”%(a,b))

25. What is list loop?


In Python lists are considered a type of iterable . An iterable is a data type that can return its elements separately,
i.e., one at a time.
Syntax: for <item> in <iterable>:
<body>
Example:
>>>names = ["Uma","Utta","Ursula","Eunice","Unix"]
>>>for name in names:
print("Hi "+ name +"!")

26. What is mapping?


A list as a relationship between indices and elements. This relationship is called a mapping; each index
“maps to” one of the elements.The in operator also works on lists.
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses True
>>> 'Brie' in cheeses False

27. Give a function that can take a value and return the first key mapping to that value in a dictionary.(Jan
2019)
a={‘aa’:2, ”bb”:4}
print(a.keys()[0])

28. How to create a list in python? Illustrate the use of negative indexing of list with example. (May 2019)
List Creation:
days = ['mon', 2]
days=[] days[0]=’mon’ days[1]=2
Negative Indexing:
Example:
>>> print(days[-1])
Output: 2

29. Demonstrate with simple code to draw the histogram in python. (May 2019)
def histogram( items ): Output:
for n in items: **
output = '' times = n ***
while( times > 0 ): ******
output += '*' times = times - 1 print(output)
histogram([2, 3, 6, 5])

30. How will you update list items? Give one example. (Nov / Dec 2019)
Using the indexing operator (square brackets) on the left side of an assignment, we can update one of the
list items
fruit = ["banana","apple","cherry"] print(fruit)
['banana', 'apple', 'cherry'] fruit[0] = "pear"
fruit[-1] = "orange" print(fruit)
['pear', 'apple', 'orange']

31. Can function return tuples? If yes Give examples. (Nov / Dec 2019)
Function can return tuples as return values. def circle_Info(r):
#Return circumference and area and tuple c = 2 * 3.14 * r Output
a = 3.14 * r * r return(c,a) (62.800000000000004, 314.0)
print(circle_Info(10))
UNIT V FILES, MODULES, PACKAGES
Files and exceptions: text files, reading and writing files, format operator; command line arguments, errors
and exceptions, handling exceptions, modules, packages; Illustrative programs: word count, copy file, Voter’s age
validation, Marks range validation (0-100).

FILES AND EXECPTION


Definition:
Files is a named location on disk to store related information, settings, or commands in secondary storage
device like magnetic disks, magnetic tapes and optical disks.
Types of Files:
There are two types of files:
Text files
Binary files
Text files:
Text files are sequence of lines, where each line included type equation here, S a sequence of character. Each
line is terminated with a special character, called EOL or end of line character.
Binary files:
Binary files is any type of files other than a text files.
File Operation:
1. Open()
2. read()
3. write()
4. close()

Opening a file:
This function creates a file object, which would be utilized to call other support methods associates with it.

Syntax : file_object= open(‘filename’ , ’mode’)


Here,
Filename: The file name argument is a string value that contains the name of the file that you want to access.
Mode: The access mode determines the mode in which the files have to be opened, (i.e)., read, write, append
etc.

Modes Description
Open a file for reading only. The file pointer is placed at the beginning of the
r
file. This is default mode.
Open a file for reading only in binary format. The file pointer is placed at the
rb
beginning of the file. This is default mode.
Open a file for both read and write. The file pointer is placed at the beginning of
r+
the file.
Open a file for both read and write in binary format. The file pointer is placed at
rb+
the beginning of the file
Open a file for writing only. Overwrite the file if exists. If the files does not
w
exists, creates a new file for writing.

1
Open a file for writing only in binary format. Overwrite the file if exists. If the
wb
files does not exists, creates a new file for writing.
Open a file for both read and write. Overwrite the file if exists. If the files does
w+
not exists, creates a new file for writing and reading.
Open a file for both read and write in binary format. Overwrite the file if exists.
wb+
If the files does not exists, creates a new file for writing and reading.
a Open a file for appending. This file pointer is placed at the end of the file.
Open a file for appending only in binary format. This file pointer is placed at the
ab end of the file, if exists. That is, the file is in the appending mode. If the files
does not exists, creates a new file for writing.
Open a file for appending and reading. This file pointer is placed at the end of
a+
the file, if exists.
Open a file for appending and reading in binary format. This file pointer is placed
ab+
at the end of the file, if exists. It creates a new file for reading and writing.

Example: fn=open(‘D:/ex.txt’,’r’)

Writing into a file:


write() is used to write a string to an already opened files. To write into a file, it is needed to open a file in write
‘w’, append ‘a’ or exclusive ‘x’ mode.

Syntax : filevariable.write(“filename”,”mode”)

Example:
f=open(‘D:/ex.txt’,’w’)
f.write(“welcome\n”)
f.write(“thank you”)
f.close()

New file is created in the name “test.txt” and content is written


Welcome
Thank you
Use of with statement:
 Because every call on function open should have a corresponding call on method close, python
provides a with statement that automatically closes a file when the end of the block is reached.

Syntax:
with open (filename, mode) as variable :
block
Example:
with open (“file.txt”, “r”) as file:
contents=file.read( )
Print(contents)

Methods of writing a file:


1. Write() – writes a single line into the specified file.
2. Writelines()- writes multiple line into specified file.

2
Writelines():
The writelines method put multiple data into the file.
The writelines() method writes any string to an open file.
Syntax: filevariable.writelines(string)

Example.py:
Output:
f=open(‘D:/ex.txt’,’w’)
This is my book
str=‘this is my book\n I found it here’ I found it here

f.writelines(str)
f.close()

Reading a file:
This method helps to just view the content of given input files. To read the content of a file, one must open the
file in reading mode.
Syntax: filevariable=open(‘filename’,’r’)
Methods used in reading a file.
1. read(size)
2. Readline()
3. Readlines()
file.read(size)
This read() specifies the size of data to be read from input files.
If size not mentioned, it reads the entire files and cursor waits in last position of files.
Ex.
f=open(“file100.txt”, ”r”)
print(“The first 5 characters of the file are:\n”, f.read(5))
f.close()

The content of the file100 is:

OUTPUT:

3
Readline():
This method is used to read a single line from the input file, till the new line character occur.
It doesn’t takes any argument.

Syntax: f.readline()
ex.
f=open(“file.txt”,”r”)
print(“reading content of the file by realine() method:\n”)
print(f.readline())
f.close()

Readlines():
This method is used to read and display all the line from the input file.

Syntax: f.readlines()
ex.
f=open(“file.txt”,”r”)
print(“reading content of the file by realines() method:\n”)
print(f.readlines())
f.close()

File object attributes:


name: Return the name of the file. It is a read-only attribute and may not be present on all file-like objects. If
the file object was created using the open() function, the file’s name is returned. Otherwise, some string indicates the
source of the file object is returned.

encoding: It returns the encoding this file uses, such as UTF-8. This attribute is read-only. When Unicode
strings are written to a file, they will be converted to byte strings using this encoding. It may also be None. In that
case, the file uses the system default encoding for converting Unicode strings.

mode: Returns the file access mode used while opening a file.

closed: Returns True if a file is closed. It is a Boolean value indicating the current state of the file object.

newline: Files opened in universal newline read mode keep track of the newlines encountered while reading
the file. The values are ‘\r’, ‘\n’, ‘\r\n’, None (no newlines read yet), or a tuple containing all the newline types seen.
For files not opened in universal newline read mode, the value of this attribute will be None.
Closing a file:
The close() methods of a file object flushes any unwritten information and closes the file object, after which
no more writing can be done.

Syntax: filevariable.close()
Example.py: Output:
Open(‘input.txt’,’wb’) Name of the file: input.txt

Print(“name of the file:”,f.name)


f.close()

4
Example: Python program to implement all file read operation:
fn=open(‘D:/ex.txt’,’r’)
print(fn.read())
fn.seek(0)
Output:
print(fn.read(4)) Welcome to the world of robotics
print(fn.tell()) Welc
4
fn.seek(0) Welcome to the world of robotics
Welcome to the world of robotics
print(fn.readline()) and automation
fn.seek(0)
print(fn.readlines())

ex.txt:
Welcome to the world of robotics
and automation

FILE METHODS

Methods Description
File.close() Close the file. A closed file cannot be read or write anymore.
Flush the internal buffer, like stdio’s fflush. This may be a no-op on
File.flush()
some file like objects.
Return the integer file description that is used by underlying
File.fileno()
implementation to request I/O operation from os.
File.isatty() Return True if the file is connected to a tty(-like) devices, else False.
Read at most size bytes from files (less if the read hits EOF before
File.read([size])
obtaining size bytes)
Read one entries line from the file. A trailing newline character is kept
File.readline([size])
in the string.
Read until EOF using readline() and return a list containing the lines.
File.readlines([sizehint]) If the optional sizehint of argument is present, instead of reading up to
EOF, whole line totaling approximately sizehint bytes are read.
File.seek(offset[,whence]) Set the files current position.
File.tell() Return the files current position
Truncates the files size. If the optional size argument is present, the file
File.truncate([size])
is truncated to that size.
File.write(str) Writes a string to the files. There is no return value.
Writes a sequence of string to a file. The sequences can be any
File.writelines(sequence)
iterable. Object producing string, typically a list of strings.
File.readable() Return true if file stream can be read from.
File.seekable() Return true if file stream supports random access.
File.writable(0 Return true if file stream can be written to.

5
Tell() and seek():
Tell() method display the current position of cursor from the input files.
Seek() takes an argument and moves the cursor to the specified position which is mentioned as argument.
Syntax: print(f.tell())
print(f.seek())

FORMAT OPERATOR
String formatting is the process of infusing things in the strings dynamically and presenting the strings.
There are four different ways to perform string formatting.
1. Formatting with % operator
2. Formatting with format() string methods.
3. Formatting with string literals, called f-strings.
4. String template class

1. Formatting with % operator:


It’s the oldest method of string formatting. Here we use the modulo % operator. The modulo % is also known
as the “string formatting operator”.
‘%s’ is used to inject strings.
‘%d’ is used to integer
‘%f’ for floating point values.
‘%b’ for binary format.
Example:
Print(‘joe stood up and %s to the crowd.’%’spoke’)
Print(‘there are %d dogs.’%4)
Print(‘floating point numbers:%.2f’ %(13.144))
Output:
Joe stood up and spoke to the crowd
There are 4 dogs
Floating point numbers:13.14

2. Formatting with format() string method:


Format() method was introduced with Python3 for handling complex string formatting more efficiently.
Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces {}
into a string and calling the str.format().

Syntax: ‘String here {} then also {}’.format(‘something1′,’something2’)

Example:
print('We all are {}.'.format('equal'))
Output: We all are equal.
The format() method has many advantages over the placeholder method:
 We can insert object by using index-based position:
Example: print('{2} {1} {0}'.format('directions','the', 'Read'))
Output: Read the directions.

 We can insert objects by using assigned keywords:


Example: print('a: {a}, b: {b}, c: {c}'.format(a = 1, b = 'Two',c = 12.3))
Output: a: 1, b: Two, c: 12.3

6
 We can reuse the inserted objects to avoid duplication:
Example: print ('The first {p} was alright, but the {p} {p} was tough.'.format(p = 'second'))
Output: The first second was alright, but the second second was tough.

Float precision with the format() method:

Syntax: {[index]:[width][.precision][type]}

The type can be used with format codes:


 ‘d’ for integers
 ‘f’ for floating-point numbers
 ‘b’ for binary numbers
 ‘o’ for octal numbers
 ‘x’ for octal hexadecimal numbers
 ‘s’ for string
 ‘e’ for floating-point in an exponent format
Example:
print('The value of pi is: %1.5f' %3.141592) # vs.
print('The value of pi is: {0:1.5f}'.format(3.141592))

Output:
The value of pi is: 3.14159
The value of pi is: 3.14159

COMMAND LINE ARGUMENT


The arguments that are given after the name of the program in the command line shell of the operating
system are known as Command Line Arguments. Python provides various ways of dealing with these types of
arguments. The three most common are:
1. Using sys.argv
2. Using argparse module

1.Using sys.argv:
The sys module provides functions and variables used to manipulate different parts of the Python runtime
environment. This module provides access to some variables used or maintained by the interpreter and to functions
that interact strongly with the interpreter.
One such variable is sys.argv which is a simple list structure. It’s main purpose are:
 It is a list of command line arguments.
 len (sys.argv) provides the number of command line arguments.
 sys.argv[0] is the name of the current Python script.

Example: Let’s suppose there is a Python script for adding two numbers and the numbers are passed as command-
line arguments.

# Python program to demonstrate command line arguments


import sys

# total arguments
n = len (sys.argv)
print ("Total arguments passed:", n)

# Arguments passed
print("\nName of Python script:", sys.argv[0])
print("\nArguments passed:", end = " ")
for i in range(1, n):
print(sys.argv[i], end = " ")

7
# Addition of numbers using argparse module
Sum = 0
for i in range(1, n):
Sum += int(sys.argv[i])
print("\n\nResult:", Sum)

Output:

2. Using argparse module:


Using argparse module is a better option than the above two options as it provides a lot of options such as
positional arguments, default value for arguments, help message, specifying data type of argument etc.
Example:
import argparse
# Initialize parser
parser = argparse.ArgumentParser()
parser.parse_args()
Output:

ERRORS AND EXCEPTION


Exception:
Errors are normally referred as bugs in the program .They are almost always the fault of the
programmer. The process of finding and eliminating errors is called debugging.
When a Python code comes across a condition it can't handle, it raises an exception. An object in Python that
describes an error is called an exception.

8
They are mainly two types of errors:
1. Syntax errors :
The python finds the syntax errors when it parses the source program. Once it finds a syntax error,
the python will exit the program without running anything. Commonly occurring syntax errors are:
(i) Putting a keyword at wrong place.
(ii) Misspelling the keyword
(iii) Incorrect Indentation
(iv) Forgetting symbols such as comma, colon, brackets, quotes
(v) Empty blocks
2. Runtime errors:
If a program is syntactically correct-that is, free of syntax errors it will be executed by the python
interpreter. However, the program may exit unexpectedly during execution if it encounters a runtime error.
The run time errors are not detected while parsing the source program, but will occur due to some logical
mistake.
Eg of runtime error are:
1) Trying to access a file which does not exist.
2) Using an identifier which is not defined.
3) Performing operations of incompatible type elements
4) Division by Zero
Such errors are handled using exception handling.

S.No. Name of the Exception Description of the Exception

1 Exception All exceptions of Python have a base class.

2 StopIteration If the next() method returns null for an iterator, this exception is raised.

3 SystemExit The sys.exit() procedure raises this value.

Excluding the StopIteration and SystemExit, this is the base class for all
4 StandardError
Python built-in exceptions.

5 ArithmeticError All mathematical computation errors belong to this base class.

This exception is raised when a computation surpasses the numeric data


6 OverflowError
type's maximum limit.

7 FloatingPointError If a floating-point operation fails, this exception is raised.

For all numeric data types, its value is raised whenever a number is
8 ZeroDivisionError
attempted to be divided by zero.

9 AssertionError If the Assert statement fails, this exception is raised.

9
10 AttributeError This exception is raised if a variable reference or assigning a value fails.

When the endpoint of the file is approached, and the interpreter didn't
11 EOFError get any input value by raw_input() or input() functions, this exception is
raised.

This exception is raised if using the import keyword to import a module


12 ImportError
fails.

If the user interrupts the execution of a program, generally by hitting


13 KeyboardInterrupt
Ctrl+C, this exception is raised.

14 LookupError LookupErrorBase is the base class for all search errors.

This exception is raised when the index attempted to be accessed is not


15 IndexError
found.

When the given key is not found in the dictionary to be found in, this
16 KeyError
exception is raised.

This exception is raised when a variable isn't located in either local or


17 NameError
global namespace.

This exception is raised when we try to access a local variable inside a


18 UnboundLocalError
function, and the variable has not been assigned any value.

All exceptions that arise beyond the Python environment have this base
19 EnvironmentError
class.

If an input or output action fails, like when using the print command or
20 IOError the open() function to access a file that does not exist, this exception is
raised.

22 SyntaxError This exception is raised whenever a syntax error occurs in our program.

23 IndentationError This exception was raised when we made an improper indentation.

This exception is raised when the sys.exit() method is used to terminate


24 SystemExit the Python interpreter. The parser exits if the situation is not addressed
within the code.

This exception is raised whenever a data type-incompatible action or


25 TypeError
function is tried to be executed.

This exception is raised if the parameters for a built-in method for a


26 ValueError particular data type are of the correct type but have been given the wrong
values.

This exception is raised when an error that occurred during the program's
27 RuntimeError
execution cannot be classified.

If an abstract function that the user must define in an inherited class is


28 NotImplementedError
not defined, this exception is raised.

10
Handling an exception
When it raises an exception, it must either handle the exception immediately else it terminates and
quits. The exception handling mechanism uses the try….except…..else blocks.
try: includes suspicious code.
After the try: block, include an except: statement, followed by a block of code which handles the problem as
elegantly as possible.
Syntax
Here is simple syntax of try....except...else blocks −
try:
write the suspicious code here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.

Note:
1. A single try statement can have multiple except statements. This is useful when the try block contains
statements that may throw different types of exceptions.
2. You can also provide a general except clause, which handles any exception.
3. After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in
the try: block does not raise an exception.
4. The else-block is a good place for code that does not need the try: block's protection.

Example 1:
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()

Output:
Written content in the file successfully

Example 2:
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"

Output:
Error: can't find file or read data

11
The except Clause with No specific Exceptions:
You can also use the except statement with no exceptions defined as follows –
Syntax:
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.

Example:
try:
n=int(input(“Enter some number”))
except
print(“you have entered wrong data”)
else:
print(“You have entered:”,n)

Output:
Enter some number a
You have entered a wrong data
Enter some number 10
You have entered :10
Note: This kind of a try-except statement catches all the exceptions that occur.

The except Clause with Multiple Exceptions:


You can also use the same except statement to handle multiple exceptions as follows −
Syntax:
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
Example:
try:
a=int(input(“Enter the value of a”))
b=int(input(“Enter the value of b”))
c=a/b
except value error:
print (“You have entered wrong data”)
except Zerodivision error:
print (“Divide by zero error!!!”)
else:
print (“The result”,c)
Output:
Enter the value of a:10
Enter the value of b:a
You have entered wrong data

12
The try-finally Clause:
You can use a finally: block along with a try: block. The finally block is a place to put any code that must
execute, whether the try-block raised an exception or not.
The syntax of the try-finally statement is this −

Syntax:
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................

Example:
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"

Output:
Error: can't find file or read data

Raising an Exceptions:
You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as
follows.
Syntax
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception
argument. The argument is optional; if not supplied, the exception argument is None.
The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback
object used for the exception.
Example:

def functionName( level ):


if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception

User-Defined Exceptions:
Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError.
This is useful when you need to display more specific information when an exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to
create an instance of the class Networkerror.

class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg

13
So once you defined above class, you can raise the exception as follows −

try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args

MODULES
A Python module is a file containing Python definitions and statements. A module can define functions,
classes, and variables. A module can also include runnable code. Grouping related code into a module makes the
code easier to understand and use.

Example:
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)

Import Module in Python


We can import the functions, and classes defined in a module to another module using the import
statement in some other Python source file.
Syntax
import module

Example:
# importing module calc.py
import calc
print(calc.add(10, 2))

Output: 12

The from-import Statement in Python


Python’s from statement lets you import specific attributes from a module without importing the module as
a whole.
Example:
from math import sqrt, factorial
print(sqrt(16))
print(factorial(6))

Output:
4.0
720
Import all Names :
The * symbol used with the from import statement is used to import all the names from a module to a current
namespace.
Syntax:
from module_name import *

Example:
from math import *
print(sqrt(16))
print(factorial(6))
Output: 4.0
720

14
Renaming the Python module:
We can rename the module while importing it using the keyword.
Syntax: Import Module_name as Alias_name
Example: # importing sqrt() and factorial from the

# module math
import math as mt
print(mt.sqrt(16))
print(mt.factorial(6))

Python built-in modules


There are several built-in modules in Python, which you can import whenever you like.

Example:
import math
print(math.sqrt(25))
print(math.pi)
print(math.degrees(2))
print(math.radians(60))
print(math.sin(2))
print(math.cos(0.5))
print(math.tan(0.23))
print(math.factorial(4))

import random
print(random.randint(0, 5)) # printing random integer between 0 and 5
print(random.random()) # print random floating point number between 0 and 1
print(random.random() * 100) # random number between 0 and 100
List = [1, 4, True, 800, "python", 27, "hello"]
print(random.choice(List))

import datetime
from datetime import date
import time
# Returns the number of seconds since the
# Unix Epoch, January 1st 1970
print(time.time())
# Converts a number of seconds to a date object
print(date.fromtimestamp(454554))

15
Packages
A package is a collection of modules. A Python package can have sub-packages and modules. A directory
must contain a file named __init__.py in order for Python to consider it as a package. This file can be left empty but
we generally place the initialization code for that package in this file.

Importing module from a package:


We can import modules from packages using the dot (.) operator.
For example, if want to import the start module in the above example, it is done as follows. import Game.Level.start.
Now if this module contains a function named select_difficulty(), we must use the full name to reference it.
Game.Level.start.select_difficulty(2)
If this construct seems lengthy, we can import the module without the package prefix as follows.
from Game.Level import start
We can now call the function simply as follows.
start.select_difficulty(2)
Yet another way of importing just the required function (or class or variable) form a module within a package
would be as follows.
From Game.Level.start
import select_difficulty
Now we can directly call this function.
select_difficulty(2)
Although easier, this method is not recommended. Using the full namespace avoids confusion and prevents
two same identifier names from colliding.
While importing packages, Python looks in the list of directories defined in sys.path, similar as for module
search path.

16
ILLUSTRATIVE PROGRAM
1. Word Count 2.copy files:
import sys def copyFile(oldFile, newFile):
file=open("/Python27/note.txt","r+") f1 = open(oldFile, "r")
wordcount={} f2 = open(newFile, "w")
for word in file.read().split(): while True:
if word not in wordcount: text = f1.read(50)
wordcount[word] = 1 if text == "":
else: break
wordcount[word] += 1 f2.write(text)
file.close(); f1.close()
print ("%-30s %s " %('Words in the File' , 'Count')) f2.close()
for key in wordcount.keys(): return
print ("%-30s %d " %(key , wordcount[key]))

2 Mark Questions and Answers

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()

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()
print(words)

4.What are the two arguments taken by the open() function?


The open function takes two arguments : name of the file and the mode of operation.
Example:
f = open("test.dat","w")

5.What is a file object?


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.
Example:
f = open("test.dat","w") // f is the file object.

6.What information is displayed if we print a file object in the given program?


f= open("test.txt","w")
print f
The name of the file, mode and the location of the object will be displayed.

7.What is an exception?
Whenever a runtime error occurs, it creates an exception. The program stops execution and prints an error
message.
Example:
#Dividing by zero creates an exception: print 55/0
ZeroDivisionError: integer division or modulo

17
8.What are the two parts in an error message?
The error message has two parts: the type of error before the colon, and specification about the error after
the colon.
Example:
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero

9.What are the error messages that are displayed for the following exceptions?
1. Accessing a non-existent list item
2. Accessing a key that isn’t in the dictionary
3. Trying to open a non-existent file
4. IndexError: list index out of range
5. KeyError: what
6. IOError: [Errno 2] No such file or directory: 'filename'

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.
Example:
try:
print "Hello World" except:
print "This is an error message!"

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.

13.What is a pickle?
Pickling saves an object to a file for later retrieval. The pickle module helps to translate almost any type of
object to a string suitable for storage in a database and then translate the strings back in to objects.

14.What is the use of the format operator?


The format operator % takes a format string and a tuple of expressions and yields a string that includes the
expressions, formatted according to the format string.
Example:
>>> nBananas = 27
>>> "We have %d bananas." % nBananas 'We have 27 bananas.'

15.What are the two methods used in pickling?


The two methods used in pickling are,
1. pickle.dump()
2. pickle.load().

To store a data structure, dump method is used and to load the data structures that are dumped, load
method is used.

16.What are modules?(or) Write a note on modular design (Jan-2018)


• Modules are files containing Python definitions and statements (ex: name.py)
• Modules can contain executable statements along with function definitions.
• Each modules has its own private symbol table used as the global symbol table all functions in the
module.
• Modules can import other modules.

18
17.What is a package?
Packages are namespaces that contain multiple packages and modules themselves. They are simply
directories.
Example:
from Game.Level.start
import select_difficulty

18.Write a Python script to display the current date and time. (Jan-2018)
import datetime
print(“date and time”, datetime.datetime.now())

19.What is the special file that each package in Python must contain?
Each package in Python must contain a special file called init .py. init .py can be an empty file but it
is often used to perform setup needed for the package(import things, load things into path, etc).
Example :
package/
init .py file.py file2.py file3.py subpackage/
init .py submodule1.py submodule2.py

20.How do you use command line arguments to give input to the program? (or) What is command line
argument? (May 2019) (Nov / Dec 2019)
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.
Example:
import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)

21.What are the different file operations?


In Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file

22.What are the different file modes?


 'r' - Open a file for reading. (default)
 'w - Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
 'x' - Open a file for exclusive creation. If the file already exists, the operation fails.
 'a' - Open for appending at the end of the file without truncating it. Creates a new file if it does not
exist.
 't' - Open in text mode. (default)
 'b' - Open in binary mode.
 '+' - Open a file for updating (reading and writing)

23.How to view all the built-in exception in python.


The built-in exceptions using the local() built-in functions as follows.
Syntax: >>> locals()[' builtins ']
This will return us a dictionary of built-in exceptions, functions and attributes.

24.What do you mean IndexError?


IndexError is raised when index of a sequence is out of range.
Example:
>>> l=[1,2,3,4,5]
>>> print l[6]
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module> print l[6]
IndexError: list index out of range

19
25.Find the syntax error in the code given:
while True print(‘Hello World’) (Jan 2019)
In the above given program, colon is missing after the condition. The right way to write the above program is,
while True:
print(‘Hello World’)

26.Categorize the different types errors arises during programming. Interpret the following python code
>>>import os (May 2019)
>>>cwd = os.getcwd()
>>>print cwd

Basic types of errors:


1. Syntax Error: Raised by the parser when a syntax error is encountered. Semantic Error:
2. Semantic Error: Raised by the parser when there is logical error in the program.
Here in the above given program, Syntax error occurs in the third line (print cwd) SyntaxError: Missing
parentheses in call to 'print'.

28.Write method to rename and delete files (Nov/Dec 2019)


os.rename(current_file_name, new_file_name)
os.remove(file_name)

20

You might also like