0% found this document useful (0 votes)
2 views56 pages

II Unit Notes

This document covers fundamental concepts in Python programming, including defining functions, conditional statements, loops, and file handling. It explains various control structures such as if-else statements, while and for loops, and the use of break, continue, and pass statements. Additionally, it discusses fruitful and void functions, local and global scope, function composition, and recursion, along with examples to illustrate these concepts.

Uploaded by

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

II Unit Notes

This document covers fundamental concepts in Python programming, including defining functions, conditional statements, loops, and file handling. It explains various control structures such as if-else statements, while and for loops, and the use of break, continue, and pass statements. Additionally, it discusses fruitful and void functions, local and global scope, function composition, and recursion, along with examples to illustrate these concepts.

Uploaded by

urssugi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT II- FUNCTIONS AND FILES

Defining a Function, Passing Arguments, Return Values, Passing a List, Creating and Using
a Class, Strings: Working with Strings, String Methods, Files: Reading from a File, Writing to
a File, Exceptions, Python Libraries: Importing libraries.

1) Conditional Statements
 Conditional if
 Alternative if… else
 Chained if…elif…else
 Nested if….else

Conditional (if):
conditional (if) is used to test a condition, if the condition is true the statements inside if will be
executed.
syntax:

Flowchart:

Program to provide bonus mark if the category is output


sports
m=eval(input(“enter ur mark out of 100”)) enter ur mark out of 100
c=input(“enter ur categery G/S”) 85
if(c==”S”): enter ur categery G/S
m=m+5 S
print(“mark is”,m) mark is 90

61
Alternative (if-else):
In the alternative the condition must be true or false. In this else statement can be combined with if
statement. The else statement contains the block of code that executes when the condition is false. If the
condition is true statements inside the if get executed otherwise else part gets executed. The alternatives are
called branches, because they are branches in the flow of execution.
syntax:

Flowchart:

Examples:
1. odd or even number
2. positive or negative number
3. leap year or not

Odd or even number Output


n=eval(input("enter a number")) if(n enter a number4
%2==0): even number
print("even number")
else:
print("odd number")
positive or negative number Output
n=eval(input("enter a number")) enter a number8
if(n>=0): positive number
print("positive number")
else:
print("negative number")
leap year or not Output
y=eval(input("enter a year")) if(y enter a year2000
%4==0): leap year
print("leap year")
else:
print("not leap year")

62
Chained conditionals (if-elif-else)

 The elif is short for else if.


 This is used to check more than one condition.

 If the condition1 is False, it checks the condition2 of the elif block. If all the conditions are
False, then the else part is executed.

 Among the several if...elif...else part, only one part is executed according to the condition.

The if block can have only one else block. But it can have multiple elif blocks.
 The way to express a computation like that is a chained conditional.

syntax:

Flowchart:

63
Example:
1. student mark system
2. traffic light system

student mark system Output


mark=eval(input("enter ur mark:")) enter ur mark:78
if(mark>=90): grade:B
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
traffic light system Output
colour=input("enter colour of light:") enter colour of light:green
if(colour=="green"): GO
print("GO")
elif(colour=="yellow"):
print("GET READY")
else:
print("STOP")

Nested conditionals
One conditional can also be nested within another. Any number of condition can be nested inside
one another. In this, if the condition is true it checks another if condition1. If both the conditions are true
statement1 get executed otherwise statement2 get execute. if the condition is false statement3 gets
executed

Syntax

64
Flowchart:

Example:
1. greatest of three numbers
2. positive negative or zero
greatest of three numbers output
a=eval(input(“enter the value of a”)) enter the value of a 9
b=eval(input(“enter the value of b”)) enter the value of a 1
c=eval(input(“enter the value of c”)) enter the value of a 8
if(a>b): the greatest no is 9
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)

else:
if(b>c):

print(“the greatest no is”,b)

else:
print(“the greatest no is”,c)

positive negative or zero output


n=eval(input("enter the value of n:")) enter the value of n:-9
if(n==0): the number is negative
print("the number is zero")
else:
if(n>0):
print("the number is positive")
65
else:
print("the number is negative")

[Link] Or Control Statements.


 state
 while
 for
 break
 continue
 pass

State:
Transition from one process to another process under specified condition with in a time is called
state.
While loop:
While loop statement in Python is used to repeatedly executes set of statement as long as a given
condition is true.
In while loop, test expression is checked first. The body of the loop is entered only if the test
expression is True. After one iteration, the test expression is checked again. This process continues
until the test expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
The statements inside the while start with indentation and the first unintended line marks the end.

Syntax:

Flow chart:

66
Examples:
1. program to find sum of n numbers:
2. program to find factorial of a number
3. program to find sum of digits of a number:
4. Program to Reverse the given number:
5. Program to find number is Armstrong number or not
6. Program to check the number is palindrome or not
Sum of n numbers: output
n=eval(input("enter n")) enter n
i=1 10
sum=0 55
while(i<=n):
sum=sum+i
i=i+1
print(sum)

Factorial of a numbers: output


n=eval(input("enter n")) enter n
i=1 5
fact=1 120
while(i<=n):
fact=fact*i
i=i+1
print(fact)

Sum of digits of a number: output


n=eval(input("enter a number")) enter a number
sum=0 123
while(n>0): a=n 6
%10
sum=sum+a
n=n//10
print(sum)

67
Reverse the given number: output
n=eval(input("enter a number")) enter a number
sum=0 123
while(n>0): 321
a=n%10
sum=sum*10+a
n=n//10
print(sum)

Armstrong number or not output


n=eval(input("enter a number")) enter a number153
org=n The given number is Armstrong number
sum=0
while(n>0):
a=n%10
sum=sum+a*a*a
n=n//10
if(sum==org):
print("The given number is Armstrong
number")
else:
print("The given number is not
Armstrong number")

Palindrome or not output


n=eval(input("enter a number")) enter a number121
org=n The given no is palindrome
sum=0
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
if(sum==org):
print("The given no is palindrome")
else:
print("The given no is not palindrome")

68
For loop:

for in range:
We can generate a sequence of numbers using range() function. range(10) will
generate numbers from 0 to 9 (10 numbers).
In range function have to define the start, stop and step size
as range(start,stop,step size). step size defaults to 1 if not provided.

syntax

Flowchart:

For in sequence
 The for loop in Python is used to iterate over a sequence (list, tuple, string). Iterating over a

sequence is called traversal. Loop continues until we reach the last element in the sequence.
The body of for loop is separated from the rest of the code using indentation.

Sequence can be a list, strings or tuples

[Link] sequences example output


R
1. For loop in string for i in "Ramu": A
print(i) M
U

69
2
2. For loop in list for i in [2,3,5,6,9]: 3
print(i) 5
6
9

for i in (2,3,1): 2
3. For loop in tuple print(i) 3
1

Examples:
1. Program to print Fibonacci series.
2. check the no is prime or not
Fibonacci series output
a=0 Enter the number of terms: 6
b=1 Fibonacci Series:
n=eval(input("Enter the number of terms: ")) 01
print("Fibonacci Series: ") 1
print(a,b) 2
for i in range(1,n,1): 3
c=a+b 5
print(c) 8
a=b
b=c

check the no is prime or not output


n=eval(input("enter a number")) enter a no:7
for i in range(2,n): The num is a prime number.
if(n%i==0):
print("The num is not a prime")
break
else:
print("The num is a prime number.")

70
3. Loop Control Structures
BREAK
 Break statements can alter the flow of a loop.
 It terminates the current
 loop and executes the remaining statement outside the loop.
 If the loop has else statement, that will also gets terminated and come out of the loop completely.
Syntax:
break

Flowchart

example Output
for i in "welcome": w
if(i=="c"): e
break l
print(i)

71
CONTINUE
It terminates the current iteration and transfer the control to the next iteration in the loop.
Syntax: Continue

Flowchart

Example: Output
for i in "welcome": w
if(i=="c"): e
continue l
print(i) o
m
e
PASS

 It is used when a statement is required syntactically but you don’t want any code to execute.
 It is a null statement, nothing happens when it is executed.

72
Syntax:
pass
break
Example Output
for i in “welcome”: we l
if (i == “c”): c
pass o
print(i) m

Difference between break and continue

break continue

It terminates the current loop and executes It terminates the current iteration and transfer
the remaining statement outside the loop. the control to the next iteration in the loop.

syntax: break syntax: continue

for i in "welcome": for i in "welcome":


if(i=="c"): if(i=="c"):
break continue
print(i) print(i)

we l we l
o
m
e

else statement in loops:

else in for loop:


 If else statement is used in for loop, the else statement is executed when the loop has reached the
limit.

The statements inside for loop and statements inside else will also execute.

73
example output
for i in range(1,6): 1
print(i) 2
else: 3
print("the number greater than 6") 4
5 the number greater than 6

else in while loop:


If else statement is used within while loop , the else part will be executed when the condition become
false.
The statements inside for loop and statements inside else will also execute.
Program output
i=1 1
while(i<=5): 2
print(i) 3
i=i+1 4
else: 5
print("the number greater than 5") the number greater than 5

4) Fruitful Function



Fruitful function

Void function
 Return values
 Parameters
 Local and global scope
 Function composition
Recursion

A function that returns a value is called fruitful function.


Example:
Root=sqrt (25)
Example:
def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)

74
Void Function
A function that perform action but don’t return any value.
Example:
print(“Hello”)
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()

Return values:
return keywords are used to return the values from the function.
example:
return a – return 1 variable
return a,b– return 2 variables
return a+b– return expression
return 8– return value
PARAMETERS / ARGUMENTS(refer 2nd unit)

Local and Global Scope

Global Scope

 The scope of a variable refers to the places that you can see or access a variable.
 A variable with global scope can be used anywhere in the program.
 It can be created by defining a variable outside the function.
Example output
a=50

def add():
Global Variable
b=20 70
c=a+b
print© Local Variable

def sub():
b=30
c=a-b 20
print©
print(a) 50

75
Local Scope A variable with local scope can be used only within the function .
Example output
def add():
b=20

c=a+b 70
Local Variable
print©
def sub():
b=30 20

c=a-b
Local Variable

print©
print(a) error
print(b) error

Function Composition:

Function Composition is the ability to call one function from within another function
It is a way of combining functions such that the result of each function is passed as the argument of
the next function.
In other words the output of one function is given as the input of another function is known as
function composition.

find sum and average using function output


composition
def sum(a,b): enter a:4
sum=a+b enter b:8
return sum the avg is 6.0
def avg(sum):
avg=sum/2
return avg
a=eval(input("enter a:"))
b=eval(input("enter b:"))
sum=sum(a,b)
avg=avg(sum)
print("the avg is",avg)

Recursion
A function calling itself till it reaches the base value - stop point of function call. Example:
factorial of a given number using recursion

76
Factorial of n Output
def fact(n): enter no. to find fact:5
if(n==1): Fact is 120
return 1
else:
return n*fact(n-1)

n=eval(input("enter no. to find


fact:"))
fact=fact(n)
print("Fact is",fact)
Explanation

Examples:
1. sum of n numbers using recursion
2. exponential of a number using recursion
Sum of n numbers Output
def sum(n): enter no. to find sum:10
if(n==1): Fact is 55
return 1
else:
return n*sum(n-1)

n=eval(input("enter no. to find sum: "))

sum=sum(n)
print("Fact is",sum)

77
5) Explain about Strings and its operation:

String is defined as sequence of characters represented in quotation marks


(either single quotes ( ‘ ) or double quotes ( “ ).
An individual character in a string is accessed using a index.
The index should always be an integer (positive or negative).
A index starts from 0 to n-1.
Strings are immutable i.e. the contents of the string cannot be changed after it is created.
Python will get the input at run time by default as a string.
Python does not support character data type. A string of size 1 can be treated as characters.
1. single quotes (' ')
2. double quotes (" ")
3. triple quotes(“”” “”””)

Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship

>>>a=”HELLO” Positive indexing helps in accessing


indexing >>>print(a[0]) the string from the beginning

>>>H Negative subscript helps in accessing


>>>print(a[-1]) the string from the end.
>>>O

Print[0:4] – HELL The Slice[start : stop] operator extracts


Slicing: Print[ :3] – HEL sub string from the strings.
Print[0: ]- HELLO A segment of a string is called a slice.

a=”save” The + operator joins the text on both


Concatenation b=”earth” sides of the operator.
>>>print(a+b)
Save earth

a=”panimalar ” The * operator repeats the string on the


Repetitions: >>>print(3*a) left hand side times the value on right

78
hand side.

panimalarpanimalar
panimalar

Membership: >>> s="good morning" Using membership operators to check a


>>>"m" in s particular character is in string or not.
True Returns true if present

>>> "a" not in s


True

String slices:

A part of a string is called string slices.
 The process of extracting a sub string from a string is called slicing.
Print[0:4] – HELL The Slice[n : m] operator extracts sub
Slicing:
Print[ :3] – HEL string from the strings.
a=”HELLO” Print[0: ]- HELLO A segment of a string is called a slice.

Immutability:
Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.
operations Example output
element assignment a="PYTHON" TypeError: 'str' object does
a[0]='x' not support element
assignment

element deletion a=”PYTHON” TypeError: 'str' object


del a[0] doesn't support element
deletion
delete a string a=”PYTHON” NameError: name 'my_string'
del a
print(a)
is not defined

79
string built in functions and methods:
A method is a function that “belongs to” an object.

Syntax to access the method

[Link]()

a=”happy birthday”
here, a is the string name.
syntax example description
1 [Link]() >>> [Link]() capitalize only the first letter
’ Happy birthday’ in a string
2 [Link]() >>> [Link]() change string to upper case
’HAPPY BIRTHDAY’
3 [Link]() >>> [Link]() change string to lower case
’ happy birthday’
4 [Link]() >>> [Link]() change string to title case i.e.
' Happy Birthday ' first characters of all the
words are capitalized.
5 [Link]() >>> [Link]() change lowercase characters
'HAPPY BIRTHDAY' to uppercase and vice versa
6 [Link]() >>> [Link]() returns a list of words
['happy', 'birthday'] separated by space
7 [Link](width,”fillchar >>>[Link](19,”*”) pads the string with the
”) '***happy birthday***' specified “fillchar” till the
length is equal to “width”
8 [Link](substring) >>> [Link]('happy') returns the number of
1 occurences of substring
9 [Link](old,new) >>>[Link]('happy', replace all old substrings
'wishyou happy') with new substrings
'wishyou happy
birthday'
10 [Link](b) >>> b="happy" returns a string concatenated
>>> a="-" with the elements of an
>>> [Link](b) iterable. (Here “a” is the
'h-a-p-p-y' iterable)
11 [Link]() >>> [Link]() checks whether all the case-
False based characters (letters) of
the string are uppercase.
12 [Link]() >>> [Link]() checks whether all the case-
True based characters (letters) of
the string are lowercase.
13 [Link]() >>> [Link]() checks whether the string
False consists of alphabetic
characters only.

80
String modules:
 A module is a file containing Python definitions, functions, statements.
 Standard library of Python is extended as modules.
 To use these modules in a program, programmer needs to import the module.
 Once we import a module, we can reference or use to any of its functions or variables in our code.
 There is large number of standard modules also available in python.
 Standard modules can be imported the same way as we import our user-defined modules.
Syntax:
import module_name
Example output
import string
print([Link]) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print([Link]) 0123456789
print([Link]) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
print([Link]("happ KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
y birthday")) ./:;<=>?@[\]^_`{|}~
print([Link]) Happy Birthday
print([Link]) 0123456789abcdefABCDEF
01234567

Escape sequences in string


Escape Description example
Sequence
\n new line >>> print("hai \nhello")
hai
hello
\\ prints Backslash (\) >>> print("hai\\hello")
hai\hello
\' prints Single quote (') >>> print("'")
'
\" prints Double quote >>>print("\"")
(") "
\t prints tab sapace >>>print(“hai\thello”)
hai hello
\a ASCII Bell (BEL) >>>print(“\a”)

81
6) Array:

Array is a collection of similar elements. Elements in the array can be accessed by index. Index
starts with 0. Array can be handled in python by module named array.

To create array have to import array module in the program.


Syntax :
import array
Syntax to create array:
Array_name = module_name.function_name(‘datatype’,[elements])
example:
a=[Link](‘i’,[1,2,3,4])
a- array name
array- module name
i- integer datatype

Example
Program to find sum of Output
array elements

import array 10
sum=0
a=[Link]('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)

Convert list into array:


fromlist() function is used to append list to array. Here the list is act like a array.

Syntax:
[Link](list_name)

Example
program to convert list Output
into array

import array 35
sum=0
l=[6,7,8,9,5]
a=[Link]('i',[])
[Link](l)
for i in a:
sum=sum+i
print(sum)

82
Methods of an array

a=[2,3,4,5]

Syntax example Description

1 array(data type, array(‘i’,[2,3,4,5]) This function is used to create


value list) an array with data type and
value list specified in its
arguments.

2 append() >>>[Link](6) This method is used to add the


[2,3,4,5,6] at the end of the array.

3 insert(index,element >>>[Link](2,10) This method is used to add the


) [2,3,10,5,6] value at the position specified in
its argument.

4 pop(index) >>>[Link](1) This function removes the


[2,10,5,6] element at the position
mentioned in its argument, and
returns it.

5 index(element) >>>[Link](2) This function returns the index


0 of value

6 reverse() >>>[Link]() This function reverses the


[6,5,10,2] array.

7 count() [Link]() This is used to count number of

83
[Link] PROGRAMS:

Square root using newtons method: Output:


def newtonsqrt(n): enter number to find Sqrt: 9
root=n/2 3.0
for i in range(10):
root=(root+n/root)/2
print(root)
n=eval(input("enter number to find Sqrt: "))
newtonsqrt(n)
GCD of two numbers output
n1=int(input("Enter a number1:")) Enter a number1:8
n2=int(input("Enter a number2:")) Enter a number2:24
for i in range(1,n1+1): 8
if(n1%i==0 and n2%i==0):
gcd=i
print(gcd)
Exponent of number Output:
def power(base,exp): Enter base: 2
if(exp==1): Enter exponential value:3
return(base) Result: 8
else:
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value:"))
result=power(base,exp)
print("Result:",result)
sum of array elements: output:
a=[2,3,4,5,6,7,8] the sum is 35
sum=0
for i in a:
sum=sum+i
print("the sum is",sum)
Linear search output
a=[20,30,40,50,60,70,89] [20, 30, 40, 50, 60, 70, 89]
print(a) enter a element to search:30
search=eval(input("enter a element to search:")) element found at 2
for i in range(0,len(a),1):
if(search==a[i]):
print("element found at",i+1)
break
else:
print("not found")

84
Binary search
output
a=[20, 30, 40, 50, 60, 70, 89] [20, 30, 40, 50, 60, 70, 89]
print(a) enter a element to search:30
search=eval(input("enter a element to search:")) element found at 2
start=0
stop=len(a)-1
while(start<=stop):
mid=(start+stop)//2
if(search==a[mid]):
print("element found at",mid+1)
break
elif(search<a[mid]):
stop=mid-1
else:
start=mid+1
else:
print("not found")

85
Two marks:
1. What is a Boolean value?
 Boolean data type have two values. They are 0 and 1.
 0 represents False
 1 represents True
 True and False are keyword.

Example:
>>> 3==5
False
>>> 6==6
True
>>> True+True
2
>>> False+True
1
>>> False*True
0

2. Difference between break and continue.

break continue

It terminates the current loop and It terminates the current iteration and
executes the remaining statement outside transfer the control to the next iteration in
the loop. the loop.

syntax: syntax:
break continue

for i in "welcome": for i in "welcome":


if(i=="c"): if(i=="c"):
break continue
print(i) print(i)

w w
e e
l l
o
m
e

86
3. Write a Python program to accept two numbers, multiply them and print the result.

number1 = int(input("Enter first number: "))


number2 = int(input("Enter second number: "))
mul = number1 * number2
print("Multiplication of given two numbers is: ", mul)

4. Write a Python program to accept two numbers, find the greatest and print the result.
number1 = int(input("Enter first number: "))
number2 = int(input("Enter second number: "))
if(number1>number2):
print('number1 is greater',number1)
else:
print('number2 is greater',number2)

5. Define recursive function.


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.

Example:

def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

6. Write a program to find sum of n numbers:

n=eval(input("enter n")) enter n


i=1 10
sum=0 55
while(i<=n):
sum=sum+i
i=i+1
print(sum)

7. What is the purpose of pass statement?


Using a pass statement is an explicit way of telling the interpreter to do nothing.
 It is used when a statement is required syntactically but you don’t want any code to execute.
 It is a null statement, nothing happens when it is executed.

87
Syntax:
pass
break
Example Output
for i in “welcome”: w
if (i == “c”): e
pass l
print(i) c
o
m
e

8. Compare string and string slices.


A string is a sequence of character.
Eg: fruit = ‘banana’
String Slices :
A segment of a string is called string slice, selecting a slice is similar to selecting a character.
Eg: >>> s ='Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
Python

9. Explain global and local scope.


The scope of a variable refers to the places that we can see or access a variable. If we define a
variable on the top of the script or module, the variable is called global variable. The variables that are
defined inside a class or function is called local variable.
Eg:
def my_local():
a=10
print(“This is local variable”)
Eg:
a=10
def my_global():
print(“This is global variable”)

10. Mention a few string functions.


[Link]() – Capitalizes first character of string
[Link](sub) – Count number of occurrences of string
[Link]() – converts a string to lower case
[Link]() – returns a list of words in string

88
LISTS, TUPLES, DICTIONARIES

1. Insertion sort
Insertion sort is an elementary sorting algorithm that sorts one element at a time. Most
humans, when sorting a deck of cards, will use a strategy similar to insertion sort. The algorithm
takes an element from the list and places it in the correct location in the list. This process is repeated
until there are no more unsorted items in the list.
Example:

Program:
a=list()
n=int(input("Enter size of list"))
for i in range(n):
[Link](int(input("Enter list elements")))
print("Before sorting",a)
for i in range(1,n):
key=a[i]
j=i-1
while j>=0 and key<a[j]:
a[j+1]=a[j]
j-=1
a[j+1]=key
print("After sorting(using insertion sort)",a)

Output
Enter size of list6
Enter listelements4
Enter listelements33
Enter list elements6
Enter listelements22
Enter list elements6
Enter list elements-9
Before sorting [4, 33, 6, 22, 6, -9]
After sorting(using insertion sort) [-9, 4, 6, 6, 22, 33]
89
2. Selection Sort
The selection sort algorithm starts by finding the minimum value in the array and moving it to
the first position. This step is then repeated for the second lowest value, then the third, and so on until
the array is sorted.
Example

Program
a=list()
n=int(input("Enter size of list"))
for i in range(n):
[Link](int(input("Enter list elements")))
print("List before sorting",a)
for i in range(0,n):
j=i+1
for j in range(j, n):
if a[i]> a[j]:
temp=a[i]
a[i]=a[j]
a[j]=temp
print("Sorted list(using Selection Sort)=",a)

Output:
Enter size of list5
Enter list elements12
Enter list elements-5
Enter list elements4
Enter listelements48
Enter listelements98
List before sorting [12, -5, 4, 48, 98]
Sorted list(using Selection Sort)= [-5, 4, 12, 48, 98]

90
3. Quadratic Equation:
Formula :
ax2+bx+c = -b±√b2 – 4ac
Program 2a

import cmath
a = int(input("Enter the coefficients a:"))
b=int(input("Enter the coefficients b: "))
c = int(input("Enter the coefficients c: "))
d = b**2-4*a*c # discriminant
x1 = (-b+[Link]((b**2)-(4*(a*c))))/(2*a)
x2 = (-[Link]((b**2)-(4*(a*c))))/(2*a)
print ("This equation has two solutions: ", x1, " or", x2)
Output
Enter the coefficients a: 5
Enter the coefficients b: 1
Enter the coefficients c: 2
This equation has two solutions: (-0.1+0.6244997998398398j) or (-0.1-0.6244997998398398j)

Enter the coefficients a: 1


Enter the coefficients b: -5
Enter the coefficients c: 6
This equation has two solutions: (3+0j) or (2+0j)

4. Merge sort
Merge sort works as follows:
a. Divide the unsorted list into n sub lists, each containing 1 element (a list of 1 element is
considered sorted).
b. Repeatedly merge sub lists to produce new sorted sub lists until there is only 1 sub list
remaining. This will be the sorted list.
Example

91
Program:

def merge(left, right):


result = []
i, j = 0, 0
while (i < len(left) and j<len(right)):
if left[i] < right[j]:
[Link](left[i])
i+= 1
else:
[Link](right[j])
j+= 1
result=result+left[i:]
result=result+right[j:]
return result
def mergesort(list):
if len(list) < 2:
return list
middle = len(list)//2
left = mergesort(list[:middle])
right = mergesort(list[middle:])
return merge(left, right)
a=list()
n=int(input("Enter size of list"))
for i in range(n):
[Link](int(input("Enter list elements")))
print("Unsorted list is",a)
print("Sorted list using merge sort is",a)

Output
Enter size of list5
Enter list elements21
Enter list elements1
Enter list elements-8
Enter list elements14
Enter list elements18
Unsorted list is [21, 1, -8, 14, 18]
Sorted list using merge sort is [-8, 1, 14, 18, 21]

92
5. LIST
o List is a sequence of values, which can be of different types. The values in list are called
"elements" or ''items''
o Each elements in list is assigned a number called "position" or "index"
o A list that contains no elements is called an empty list. They are created with empty
brackets[]
o A list within another list is nested list

Creating a list :
The simplest way to create a new list is to enclose the elements in square brackets ([])
[10,20,30,40]
[100, "python" , 8.02]

1. LIST OPERATIONS:
1. Concatenation of list
2. Repetition of list

Concatenation: the '+' operator concatenate list


>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = a+b
>>> Print (a*2) => [1,2,3,1,2,3]

Repetition: the '*' operator repeats a list a given number of times


>>> a = [1,2,3]
>>> b = [4,5,6]
>>> print (a*2)= [1,2,3,1,2,3]

2. List looping: (traversing a list)


1. Looping in a list is used to access every element in list
2. "for loop" is used to traverse the elements in list
eg: mylist = ["python","problem",100,6.28]
for i in range (len (mylist)):
print (mylist [i])
3. List Slices:
A subset of elements of list is called a slice of list.
Eq: n = [1,2,3,4,5,6,7,8,9,10]
print (n[2:5])
print (n[-5])
print (n[5: ])
print (n[ : ])

93
4. Aliasing and cloning:
 when more than one variables refers to the same objects or list, then it is called aliasing.

a= [5,10,50,100]
b=a
b[0] = 80
print ("original list", a) = [5,10,50,100]
print ("Aliasing list", b) = [80,5,10,50,100]
 Here both a & b refers to the same list. Thus, any change made with one object will affect other,
since they are mutable objects.
 in general, it is safer to avoid aliasing when we are working with mutable objects

5. Cloning:
 Cloning creates a new list with same values under another name. Taking any slice of list create
new list.
 Any change made with one object will not affect others. the easiest way to clone a new list is to
use "slice operators"
a = [5,10,50,100]
b= a[ : ]
b[0] = 80
Print (" original list", a) = [5,10,50,100]
Print (" cloning list", b) = [5,10,50,100]

List parameter:
 List can be passed as arguments to functions the list arguments are always passed by reference
only.
 Hence, if the functions modifies the list the caller also changes.
Eq: def head ():
del t[ 0 ]
>>> letters = ['a','b','c']
>>> head (letters)
>>> letters
['b','c']
In above,
The parameters 't' and the variable 'letters' or aliases for the same objects
An alternative way to write a function that creates and return a new list
Eq: def tail (t):
return t [1:]
>>> letters = ['a','b','c']
>>> result = tail (letters)
>>> result
['b','c']
In above,
The function leaves the original list unmodified and return all element in list except first element

94
6. TUPLES:
A tuple is a sequence of value which can be of any type and they are indexed by integers.
Values in tuple are enclosed in parentheses and separated by comma. The elements in the tuple cannot
be modified as in list (i.e) tuple are immutable objects

Creating tuple:
Tuple can be created by enclosing the element in parentheses separated by comma
t = ('a','b','c','d')
To create a tuple with a single element we have to include a final comma
>>> t = 'a',
>>> type (t)
< class 'tuple'>
Alternative way to create a tuple is the built-in function tuple which mean, it creates an empty tuple
>>> t = tuple ()
>>> t
>>> ( )
Accessing element in tuple:
If the argument in sequence, the result is a tuple with the elements of sequence.
>>>t= tuple('python')
>>> t
('p','y','t','h','o','n')
t = ('a','b',100,8.02)
print (t[0]) = 'a'
print (t[1:3]) = ('b', 100 , 8.02)

Deleting and updating tuple:


Tuple are immutable, hence the elements in tuple cannot be updated / modified
But we can delete the entire tuple by using keyword 'del'
Eg 1: a = (' programming', 200, 16.54, 'c', 'd')
#Try changing an element.
a[ 0 ] = 'python' <---------Error,modifying not possible
print (a [0])
Eg: # Deletion of tuple
a = ('a','b','c','d')
del (a)----------delete entire tuple
del a [1] <----------error,deleting one element in tuple not possible
Eg: # replacing one tuple with another
a = ('a','b','c','d')
t = ('A',) + a[1: ]
print (t) <-------('a','b','c','d')

95
Tuple Assignment:
 Tuple assignment is often useful to swap any number of values
 the number of variables in left and right of assignment operators must be equal
 A single assignment to paralleling assign value to all elements of tuple is the major benefit of
tuple assignment
Eg: Tuple swapping in python
A= 100
B= 345
C= 450
print (" A & B:", A,"&",B)
# Tuple assignments for two
variables A,B = B,A
print (" A&B after tuple assignment : ",A,"&",B)
# Tuple assignment can be done for no of
variables A,B,C = C,A,B
print (" Tuple assignment for more variables:",
A,"&",B,"&",C) Output
A & B: 100 & 345
A&B after tuple assignment : 345 & 100
Tuple assignment for more variables: 450 & 345 & 100

Tuple as return value:


 Generally, function can only return one value but if the value is tuple the same as returning the
multiple value
 Function can return tuple as return value
Eg: # the value of quotient & remainder are returned as tuple
def mod_div
(x,y): quotient
= x/y remainder
= x%y
return quotient, remainder
# Input the seconds & get the hours minutes &
second sec = 4234
minutes,seconds= mod_div
(sec,60)
hours,minutes=mod_div(minutes,
60)
print("%d seconds=%d hrs:: %d min:: %d sec"%
(sec,hours,minutes,seconds)) Output: 4234onds=1
hrs:: 10 min:: 34 sec

7. Histogram

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])
96
Two marks:

1. Write a program to create list with n values


a=list()
n=int(input("Enter the size of list”))
for i in range (n):
[Link](int(input("Enter the list element")))
print("Created List=",a)
Output
Enter the size of list 5
Enter the list of element20
Enter the list of element30
Enter the list of element78
Enter the list of element12
Enter the list of element65
Created List= [20, 30, 78, 12, 65]

2. What is dictionary?
A dictionary is an unordered set of key: value pair. In a list, the indices have to be integers; in a
dictionary they can be any type. A dictionary contains a collection of indices, which are called keys, and
a collection of values. Each key is associated with a single value. The association of a key and a value is
called a key-value pair. Dictionary is created by enclosing with curly braces {}.
Eg:
>>>
dictionary={"RollNo":101,2:(1,2,3),"Name":"Ramesh",20:20.50,Loc":['Chennai']}
>>> dictionary
{'Name':'Ramesh', 'Loc':['Chennai'], 2:(1,2.3), 20: 20.0, 'RollNo': 101}

3. Write program to rotate values in the list.(counter-clock wise)


a=list()
n=int(input("Enter the number of list elements"))
for i in range (n):
[Link](int(input("Enter list element")))
rotate=int(input("Enter the rotation value(Give negative value for
counter cock-wise)"))
print("Created List=",a)
print("List rotated is",a[rotate:]+a[:rotate] )
Output
Enter the number of list elements 5
Enter list element 30
Enter list element
98 Enter list
element 45 Enter
list element 49
Created List= [30, 98, 45, 49]
Enter the rotation value(Give negative value for counter cock-wise)-2
List rotated in counter clockwise [45, 49, 30, 98]

97
4. What is data structure? List out the data structures used in Python
A data structure is a particular way of organizing and storing data in a computer so that it can be
accessed and modified efficiently.
Python data structures:-
1. List
2. Tuples
3. Dictionary

5. Compare all the three data structures in Python

List Tuples Dictionary


Mutable List is mutable Tuples are immutable Keys must be
immutable. Values
may mutable
Indexing A positive integer is used A positive integer is used Indexing is done with ‘key’.
for indexing and always for indexing and always Index may be of any type.
starts with zero. Reverse starts with zero. Reverse Values can be accessed only
index is supported. index is supported. through key
Declaration List=[05,’Ashok’,450] Tuple=(‘Sun’,’Mon’) Dictionary={“Key”:”value”}

6. Difference between list append and list extend


1. append() is a function adds a new element to the end of a list.
2. extend() is a function takes a list as an argument and appends all of the elements.

append() extend()
>>>a=[10,20,30] >>>a=[10,20,30]
>>>b=[40,50] >>>b=[40,50]
>>>[Link](b) >>>[Link](b)
>>>print(a) >>>print(a)
[10,20,30,[40,50]] [10,20,30,40,50]

98
7. What is mutability? Is tuple is mutable
In object-oriented and functional programming, an immutable object (unchangeable
object) is an object whose state cannot be modified after it is created. This is in contrast to a
mutable object (changeable object), which can be modified after it is created.
Tuple is immutable.

8. Write a program to add or change elements in a dictionary.


>>> dictionary={"Roll No":101,2:(20.00,30),"Name":"Ramesh",20:200.00, "Loc":['Chennai']}
>>> dictionary
{'Name': 'Ramesh', 'Loc': ['Chennai'], 2: (20.0, 30), 20: 200.0, 'Roll No': 101}
>>> dictionary['Roll No']=105
>>> dictionary
{'Name': 'Ramesh', 'Loc': ['Chennai'], 2: (20.0, 30), 20: 200.0, 'Roll No': 105}

9. How to convert a string to list of characters and words.


>>> str1=”Hello”
>>> list1=list(str1)
>>> list1
['H', 'e', 'l', 'l', 'o']

10. What is zip operation in tuples. Give an example.


Zip is a built-in function that takes two or more sequences and returns a list of tuples
where each tuple contains one element from each sequence. This example zips a string and a list:
>>> s = 'abc'
>>> t = [0, 1, 2]
>>> zip(s, t)
<zip object at 0x7f7d0a9e7c48>
The result is a zip object that knows how to iterate through the pairs. The most common
use of zip is in a for loop:
>>> for pair in zip(s, t):
print(pair)
('a', 0)
('b', 1)
('c', 2)

99
100
UNIT V
FILES, MODULES, PACKAGES

1. FILE AND ITS OPERATION


 File is a collection of record.
 A file stores related data, information, settings or commands in secondary storage
device like magnetic disk, magnetic tape, optical disk, flash memory.

File Type
1. Text file
2. Binary file

Text file Binary file


Text file is a sequence of characters that can A binary files store the data in the binary
be sequentially processed by a computer in format(i.e .0’s and 1’s)
forward direction
It contains any type of data
Each line is terminated with a special (pdf,images,word doc,spreadsheet,zip
character called the E0L or end of line files,etc)
character
Mode in File
Module Description
r Read only
w mode Write
a only Appending
r+ only
Read and write only
Differentiate write and append mode:
Write mode Append mode

 It is used to write a string in a file  It is used to append (add) a string


 If file is not exist it creates a new file into a file
 If file is exit in the specified name,  If file is not exist it creates a new file
the existing content will overwrite in  It will add the string at the end of the
a file by the given string old file

File Operation:
 Open a file
 Reading a file
 Writing a file
 Closing a file

101
1. Open ( ) function:
 Pythons built in open function to get a file object.
 The open function opens a file.
 It returns a something called a file object.
 File objects can turn methods and attributes that can be used to collect

Syntax:
file_object=open(“file_name” , ”mode”)

Example:
fp=open(“[Link]”,”r”)
Create a text file
fp=open (“[Link]”,”w”)
2. Read ( ) function
Read functions contains different methods
 read() – return one big string
 readline() – return one line at a time
 readlines() – return a list of lines

Syntax:
file_name.read ()
Example:
fp=open(“[Link]”,”w”)
print([Link]())
print([Link](6))
print ([Link]())
print ([Link](3))
print ([Link]())

[Link]

A file stores related data,


information, settings or commands
in secondary storage device like
magnetic disk, magnetic tape,
optical disk, flash memory.
hello guys
Output

102
Reading file using looping:
 Reading a line one by one in given file
fp=open(“[Link]”,”r”)
for line in fp:
print(line)

3. Write ( ) function
This method is used to add information or content to existing file.

Syntax:
file_name.write( )
Example:
fp=open(“[Link]”,”w”)
[Link](“this file is [Link]”)
[Link](“to add more lines”)
[Link]()
Output: [Link]

A file stores related data,


information, settings or commands
in secondary storage device like
magnetic disk, magnetic tape,
optical disk, flash memory.
this file is [Link] to
add more lines

4. Close ( ) function
It is used to close the file.

Syntax:
File [Link]()

Example:
fp=open(“[Link]”,”w”)
[Link](“this file is [Link]”)
[Link](“to add more lines”)
[Link]()

103
Splitting line in a text line:
fp=open(“[Link]”,”w”)
for line in fp:
words=[Link]()
print(words)

2. Write a program for one file content copy into another file:
source=open(“[Link]”,”r”)
destination=open(“[Link]”,”w”)
for line in source:
[Link](line)
source. close()
[Link]()
Output:
Input [Link] Output [Link]
A file stores related data, information, A file stores related data, information,
settings or commands in secondary storage settings or commands in secondary storage
device like magnetic disk, magnetic tape, device like magnetic disk, magnetic tape,
optical disk, flash memory optical disk, flash memory

3. Write a program to count number of lines, words and characters in a text file:
fp = open(“[Link]”,”r”)
line =0
word = 0
character = 0
for line in fp:
words = line . split ( )
line = line + 1
word = word + len(words)
character = character +len(line)
print(“Number of line”, line)
print(“Number of words”, word)
print(“Number of character”, character)
Output:
Number of line=5
Number of words=15
Number of character=47

104
4. ERRORS,EXCEPTION HANDLING
Errors
 Error is a mistake in python also referred as bugs .they are almost always the fault of
the programmer.
 The process of finding and eliminating errors is called debugging
Types of errors
o Syntax error or compile time error
o Run time error
o Logical error
Syntax errors
 Syntax errors are the errors which are displayed when the programmer do mistakes
when writing a program, when a program has syntax errors it will not get executed
 Leaving out a keyword
 Leaving out a symbol, such as colon, comma, brackets
 Misspelling a keyword
 Incorrect indentation
Runtime errors
 If a program is syntactically correct-that is ,free of syntax errors-it will be run by
the python interpreter
 However, the program may exit unexpectedly during execution if it encounters a
runtime error.
 When a program has runtime error it will get executed but it will not produce output
 Division by zero
 Performing an operation on incompatible types
 Using an identifier which has not been defined
 Trying to access a file which doesn’t exit
Logical errors
 Logical errors are the most difficult to fix
 They occur when the program runs without crashing but produces incorrect result
 Using the wrong variable name
 Indenting a blocks to the wrong level
 Using integer division instead of floating point division
 Getting operator precedence wrong

Exception handling

Exceptions
 An exception is an error that happens during execution of a program. When that Error
occurs
Errors in python
 IO Error-If the file cannot be opened.
 Import Error -If python cannot find the module
 Value Error -Raised when a built-in operation or function receives an argument that
has the right type but an inappropriate value
 Keyboard Interrupt -Raised when the user hits the interrupt
 EOF Error -Raised when one of the built-in functions (input() or raw_input()) hits an
end-of-file condition (EOF) without reading any data

105
Exception Handling Mechanism
1. try –except
2. try –multiple except
3. try –except-else
4. raise exception
5. try –except-finally

1. Try –Except Statements


 The try and except statements are used to handle runtime errors
Syntax:
try :
statements
except :
statements

The try statement works as follows:-


 First, the try clause (the statement(s) between the try and except keywords) is
executed.
 If no exception occurs, the except clause is skipped and execution of
the try statement is finished.
 If an exception occurs during execution of the try clause, the rest of the clause is
skipped. Then if its type matches the exception named after the except keyword,
the except clause is executed, and then execution continues after the try statement.

Example:
X=int(input(“Enter the value of X”))
Y=int(input(“Enter the value of Y”))
try:
result = X / ( X – Y )
print(“result=”.result)
except ZeroDivisionError:
print(“Division by Zero”)

Output:1 Output : 2
Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 10
Result = 2 Division by Zero

2. Try – Multiple except Statements


o Exception type must be different for except statements
Syntax:
try:
statements
except errors1:
statements
except errors2:
statements
except errors3:
statements

106
Example
X=int(input(“Enter the value of X”))
Y=int(input(“Enter the value of y”))
try:
sum = X + Y
divide = X / Y
print (“ Sum of %d and %d = %d”, %(X,Y,sum))
print (“ Division of %d and %d = %d”, %(X,Y,divide))
except NameError:
print(“ The input must be number”)
except ZeroDivisionError:
print(“Division by Zero”)

Output:1 Output 2: Output 3:


Enter the value of X = 10 Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 0 Enter the value of Y = a
Sum of 10 and 5 = 15 Sum of 10 and 0 = 10 The input must be number
Division of 10 and 5 = 2 Division by Zero

3. Try –Except-Else
o The else part will be executed only if the try block does not raise the exception.

o Python will try to process all the statements inside try block. If value error occur,
the flow of control will immediately pass to the except block and remaining
statements in try block will be skipped.
Syntax:
try:
statements
except:
statements
else:
statements
Example

X=int(input(“Enter the value of X”))


Y=int(input(“Enter the value of Y”))
try:
result = X / ( X – Y )
except ZeroDivisionError:
print(“Division by Zero”)
else:
print(“result=”.result)
Output:1 Output : 2
Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 10
Result = 2 Division by Zero

107
4. Raise statement
 The raise statement allows the programmer to force a specified exception to occur.
Example:
>>> raise NameError('HiThere')
Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere
 If you need to determine whether an exception was raised but don’t intend to handle
it, a simpler form of the raise statement allows you to re-raise the exception:
Example
try:
... raise NameError('HiThere')
... except NameError:
... print('An exception flew by!')
... raise
Output:
An exception flew by! Traceback
(most recent call last):
File "<stdin>", line 2, in <module>
NameError: HiThere
5. Try –Except-Finally
 A finally clause is always executed before leaving the try statement, whether an
exception has occurred or not.
 The finally clause is also executed “on the way out” when any other clause of the
try statement is left via a break, continue or return statement.
Syntax
try: statements statements statements

except:

finally:

Example
X=int(input(“Enter the value of X”))
Y=int(input(“Enter the value of Y”))
try:
result = X / ( X – Y )
except Zero DivisionError:
print(“Division by Zero”)
else:
print(“result=”.result)
finally:
print (“executing finally clause”)
Output:1 Output : 2
Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 10
Result = 2 Division by Zero
executing finally clause executing finally clause

108
5. MODULES IN PYTHON
 A python module is a file that consists of python definition and statements. A module
can define functions, classes and variables.
 It allows us to logically arrange related code and makes the code easier to understand
and use.
1. Importstatement:
 An import statement is used to import python module in some python source file.
Syntax: import module1 [, module2 […module]]
Example:
>>>import math
>>>print ([Link])
3.14159265

2. Importwith renaming:
The import a module by renaming it as follows,
>>>import math as a
>>>print(“The value of pi is “,[Link])
The value of pi is 3.14159265
Writing modules:
 Any python source code file can be imported as a module into another python source
file. For example, consider the following code named as [Link], which is python
source file defining two function add(), display().
[Link]:
def add(a,b):
print(“The result is “,a+b)
return
def display(p):
print(“welcome “,p)
return
The [Link] file can be imported as a module into another python source file and
its functions can be called from the new files as shown in the following code:
3. Import file name
import support #import module support
[Link](3,4) #calling add() of support module with two integers
[Link] (3.5,4.7) #calling add() of support module with two real values
[Link] (‘a’,’b’) #calling add() of support module with two character values
[Link] (“yona”,”alex”)#calling add() of support module with two string values
[Link] (‘fleming’) #calling display() of support module with a string value

109
Output:
The result is 7
The result is 8.2
The result is ab
The result is yonaalex
Welcome, fleming
4. from……import statement:

 It allows us to import specific attributes from a module into the current


namespace.
Syntax: from modulename import name1 [, name2[,……nameN]]
from support import add #import module support
[Link](3,4) #calling add() of support module with two integers
[Link](3.5,4.7) #calling add() of support module with two real values
[Link](‘a’,’b’) #calling add() of support module with two character values
[Link] (“yona”,”alex”)#calling add() of support module with two string values
[Link] (‘fleming’) #calling display() of support module with a string value
Output:
The result is 7
The result is 8.2
The result is ab
The result is yonaalex
Welcome, fleming

5. OS Module
 The OS module in python provide function for interacting with operating
system
 To access the OS module have to import the OS module in our program
import os
method example description
name Osname ‘nt’ This function gives the name
of the operating system
getcwd() Os,getcwd() Return the current working
,C;\\Python34’ directory(CWD)of the file
used to execute the code
mkdir(folder) [Link](“python”) Create a directory(folder)
with the given name
rename(oldname,newname) [Link](“python”,”pspp”) Rename the directory or
folder
remove(“folder”) [Link](“pspp”) Remove (delete)the directory
or folder

110
getuid() [Link]() Return the current process’s
user id
environ [Link] Get the users environment

6. Sys Module
 Sys module provides information about constant, function and methods
 It provides access to some variables used or maintained by the interpreter

import sys
methods example description
[Link] [Link] Provides the list of
command line arguments
passed to a python script
[Link](0) Provides to access the file
name
[Link](1) Provides to access the first
input

[Link] [Link] It provide the search path


for module
[Link]() [Link]() Provide the access to
specific path to our program
[Link] [Link] Provide information about
‘win32’ the operating system
platform
[Link] [Link] Exit from python
<[Link] function exit>

Steps to Create the Own Module


 Here we are going to create a calc module ; our module contains four functions
i.e add(),sub(),mul(),div()
Program for calculator module output
Module name ;[Link] import calculator
def add(a,b); [Link](2,3)
print(a+b)
def sub(a,b);
print(a-b)
def mul(a,b); Outcome
print(a*b) >>>5
def div(a,b);
print(a/b)

111
6. PACKAGES IN PYTHON
 A package is a collection of python module. Module is a single python file containing
function definitions
 A package is a directory(folder)of python module containing an additional init py
file, to differentiate a package from a directory
 Packages can be nested to any depth, provided that the corresponding directories
contain their own init py file.
 init py file is a directory indicates to the python interpreter that the directory
should be treated like a python package init py is used to initialize the python
package
Steps to Create a Package
Step1: create the package directory
 Create the directory (folder)and give it your packages name
 Here the package name is calculator
Name Data modified Type
1. pycache 05-12-2017 File folder
[Link] 08-12-2017 File folder
3. DLLs 10-12-2017 File folder

Step2: write module for calculator directory add save the module in calculator directory
 Here four module have create for calculator directory

Local Disk (C)>Python34>Calculator


Name Data modified Type Size
1. add 08-12-2017 File folder 1KB
2. div 08-12-2017 File folder 1KB
3. mul 08-12-2017 File folder 1KB
4. sub 08-12-2017 File folder 1KB

[Link] [Link] [Link] [Link]


def add(a,b); def div(a,b); def mul(a,b); def sub(a,b);
print(a+b) print(a/b) print(a*b) print(a-b)

Step3: add the init .py file in the calculator directory


 A directory must contain the file named init .py in order for python to consider it
as a package

112
Add the following code in the init .py file

from * add import add


from * sub import sub
from * mul import mul
from * div import div

Local Disk (C):/Python34>Calculator


Name Data modified Type Size
1. init 08-12-2017 File folder 1KB
2. add 08-12-2017 File folder 1KB
3. div 08-12-2017 File folder 1KB
4. mul 08-12-2017 File folder 1KB
5. sub 08-12-2017 File folder 1KB

Step4: To test your package


 Import calculator package in your program and add the path of your package in your
program by using [Link]()
Example
import calculator
importsys
[Link](“C:/Python34”)
print ( [Link](10,5))
print ( [Link](10,5))
print ( [Link](10,5))
print ( [Link](10,5))

Output :
>>> 15
5
50
2

113
Two marks:

1. Why do we go for file?


File can a persistent object in a computer. When an object or state is created and needs to be
persistent, it is saved in a non-volatile storage location, like a hard drive.

2. What are the three different mode of operations of a file?


The three mode of operations of a file are,
i. Open – to open a file to perform file operations
ii. Read – to open a file in read mode
iii. Write – to open a file in write mode

3. State difference between read and write in file operations.


Read Write
A "Read" operation occurs when a computer A "Write" operation occurs when a computer
program reads information from a computer program adds new information, or changes
file/table (e.g. to be displayed on a screen). existing information in a computer file/table.
The "read" operation gets
information out of a file.
After a "read", the information from the After a "write", the information from the
file/table is available to the computer program file/table is available to the computer program
but none of the information that was read but the information that was read from the
from the file/table is changed in file/table can be changed in any
any way. way.

4. Differentiate error and exception.


Errors
 Error is a mistake in python also referred as bugs .they are almost always the fault of the
programmer.
 The process of finding and eliminating errors is called debugging
 Types of errors
 Syntax error or compile time error
 Run time error
 Logical error
Exceptions
An exception is an error that happens during execution of a program. When that Error occurs

5. Give the methods of exception handling.


1. try –except
2. try –multiple except
3. try –except-else
4. raise exception
5. try –except-finally

114
6. State the syntax for try…except block
The try and except statements are used to handle runtime errors
Syntax:
try :
statements
except:
statements

7. Write a program to add some content to existing file without effecting the existing content.
file=open(“[Link]”,’a) [Link](“hello”)

[Link] [Link](after updating)


Hello!!World!!! Hello!!!World!!!hello

8. What is package?
 A package is a collection of python module. Module is a single python file containing function
definitions
 A package is a directory(folder)of python module containing an additional init py file, to
differentiate a package from a directory
 Packages can be nested to anydepth, provided that the corresponding directories contain their
own init py file

9. What is module?
A python module is a file that consists of python definition and statements. A module can define
functions, classes and variables. makes
the code easier to understand and use.

10. Write the snippet to find the current working directory.


Import os print([Link]))

Output:
C:\\Users\\Mano\\Desktop

115
11. Give the use of format operator
The argument of write has to be a string, so if we want to put other values in a file, we
have to convert them to strings. The easiest way to do that is with str:
>>> x = 52
>>> [Link](str(x))
An alternative is to use the format operator, %. When applied to integers, % is the
modulus operator. But when the first operand is a string, % is the format operator. The
first operand is the format string, which contains one or more format sequences,
which specify how the second operand is formatted. The result is a string. For
example, the format sequence '%d' means that the second operand should be
formatted as an integer (d stands for “decimal”):
>>> camels = 42
>>>'%d' % camels '42'
The result is the string '42', which is not to be confused with the integer value 42.
12. Write the snippet to find the absolute path of a file.
import os
[Link]('w
[Link]')
Output:
'C:\\Users\\Mano\\Desktop\\[Link]'

13. What is the use of [Link]() function.


[Link]() is a function defined in the package os. The main function of isdir(“some
input”) function is to check whether the passed parameter is directory or not. isdir()
function will only return only true or false.

14. What is the use of [Link]() function.


[Link] () is a function defined in the package os. The main function of isfile (“some
input”) function is to check whether the passed parameter is file or not. isfile () function
will only return only true or false.

15. What is command line argument?


[Link] is the list of command line arguments passed to the Python program.
Argv represents all the items that come along via the command line input, it's basically
an array holding the command line arguments of our program.

116

You might also like