0% found this document useful (0 votes)
11 views98 pages

Sem 2 Python

This document covers control flow and functions in Python, including conditionals, iteration, and various operators. It explains boolean values, arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators, along with their examples. Additionally, it provides illustrative programs for conditionals and loops, demonstrating practical applications such as calculating sums, factorials, and checking for odd/even numbers.

Uploaded by

udtbooks
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)
11 views98 pages

Sem 2 Python

This document covers control flow and functions in Python, including conditionals, iteration, and various operators. It explains boolean values, arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators, along with their examples. Additionally, it provides illustrative programs for conditionals and loops, demonstrating practical applications such as calculating sums, factorials, and checking for odd/even numbers.

Uploaded by

udtbooks
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

UNIT III

CONTROL FLOW, FUNCTIONS


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, scope: local and global, composition,
recursion; Strings: string slices, immutability, string functions and methods, string
module; Lists as arrays. Illustrative programs: square root, gcd, exponentiation, sum the
array of numbers, linear search, binary search.

BOOLEAN VALUES:
Boolean:
  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

1
OPERATORS:
  Operators are the constructs which can manipulate the value of operands.
 
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.

Types of Operators:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

2
Arithmetic operators:

They are used to perform mathematical operations like addition, subtraction,


multiplication etc.
Operator Description Example
a=10,b=20
+ Addition Adds values on either side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
* Multiplication Multiplies values on either side of the operator a * b = 200
/ Division Divides left hand operand by right hand operand b/a=2
% Modulus Divides left hand operand by right hand operand and b % a = 0
returns remainder
** Exponent Performs exponential (power) calculation on a**b =10 to the
operators power 20
// Floor Division - The division of operands where the 5//2=2
result is the quotient in which the digits after the
decimal point are removed

Comparison (Relational) Operators:


  
Comparison operators are used to compare values.
 
It either returns True or False according to the condition.

Operator Description Example


a=10,b=20
== If the values of two operands are equal, then the condition (a == b) is not
becomes true. true.
!= If values of two operands are not equal, then condition becomes (a!=b) is true
true.
> If the value of left operand is greater than the value of right (a > b) is not
operand, then condition becomes true. true.
< If the value of left operand is less than the value of right (a < b) is true.
operand, then condition becomes true.
>= If the value of left operand is greater than or equal to the value (a >= b) is not
of right operand, then condition becomes true. true.
<= If the value of left operand is less than or equal to the value of (a <= b) is
right operand, then condition becomes true. true.

3
Assignment Operators:
Assignment operators are used in Python to assign values to variables.
Operator Description Example
= Assigns values from right side operands to left c = a + b assigns
side operand value of a + b into c
+= Add AND It adds right operand to the left operand and c += a is equivalent
assign the result to left operand to c = c + a
-= Subtract AND It subtracts right operand from the left operand c -= a is equivalent
and assign the result to left operand to c = c - a

4
*= Multiply AND It multiplies right operand with the left operand
c *= a is equivalent
and assign the result to left operand to c = c * a
/= Divide AND It divides left operand with the right operand and
c /= a is equivalent
assign the result to left operand to c = c / ac /= a is
equivalent to c = c
/a
%= Modulus AND It takes modulus using two operands and assign c %= a is
the result to left operand equivalent to c = c
%a
**= Exponent AND Performs exponential (power) calculation on c **= a is
operators and assign value to the left operand equivalent to c = c
** a
//= Floor Division It performs floor division on operators and c //= a is
assign value to the left operand equivalent to c = c
// a
Logical Operators:
Logical operators are and, or, not operators.

Bitwise Operators:
Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Membership Operators:

 Evaluates to find a valueor a variable is in the specified sequence of string, list,
tuple, dictionary or not.
  
To check particular element is available in the list or not.
 
Operators are in and not in.

5
Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
Identity Operators:
They are used to check if two values (or variables) are located on the same part of
the memory.

Example
x=5
y=5
a = 'Hello'
b = 'Hello'
print(x is not y) // False
print(a is b)//True

CONDITIONALS
  Conditional if
  
Alternative execution- if… else
  
Chained if…elif…else
 Nested if….else

 Inline if

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

Flowchart:

6
Example:
1. Program to provide flat rs 500, if the purchase amount is greater than 2000.
2. Program to provide bonus mark if the category is sports.
Program to provide flat rs 500, if the purchase amount output
is greater than 2000.
purchase=eval(input(“enter your purchase amount”)) enter your purchase
if(purchase>=2000): amount
purchase=purchase-500 2500
print(“amount to pay”,purchase) amount to pay
2000
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

Alternative execution (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:

7
Examples:
1. odd or even number
2. positive or negative number
3. leap year or not
4. greatest of two numbers
5. eligibility for voting
Odd or even number Output
n=eval(input("enter a number")) enter a number4
if(n%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 yaer")) enter a yaer2000
if(y%4==0): leap year
print("leap year")
else:
print("not leap year")

greatest of two numbers Output


a=eval(input("enter a value:")) enter a value:4
b=eval(input("enter b value:")) enter b value:7
if(a>b): greatest: 7
print("greatest:",a)
else:
print("greatest:",b)
eligibility for voting Output
age=eval(input("enter ur age:")) enter ur age:78
if(age>=18): you are eligible for vote
print("you are eligible for vote")
else:
print("you are eligible for vote")

8
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:

9
Example:
1. student mark system
2. traffic light system
3. compare two numbers
4. roots of quadratic equation

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")
compare two numbers Output
x=eval(input("enter x value:")) enter x value:5
y=eval(input("enter y value:")) enter y value:7
if(x == y): x is less than y
print("x and y are equal")
elif(x < y):
print("x is less than y")
else:
print("x is greater than y")
Roots of quadratic equation output
a=eval(input("enter a value:")) enter a value:1
b=eval(input("enter b value:")) enter b value:0
c=eval(input("enter c value:")) enter c value:0
d=(b*b-4*a*c) same and real roots
if(d==0):
print("same and real roots")
elif(d>0):
print("diffrent real roots")
else:
print("imaginagry roots")

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

Syntax:

Flowchart:

11
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:
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")
else:
print("the number is negative")

Inline if:
An inline if statement is a simpler form of if statement and is more convenient ,if we
need to perform simple task.

Syntax: do task A if condition is true else do task B

Example:
>>> b=True
>>> a=1 if b else None
>>> a
1
>>> b=False
>>> a=1 if b else None
>>> a
#None 12
ITERATION/CONTROL
STATEMENTS/LOOPs:

state

while

for

break

continue
pass

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

 The statements inside the while starts with indentation and the first
unindented line marks the end.

Syntax:

Flowchart:

13
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): 6
a=n%10

sum=sum+a
n=n//10
print(sum)

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)

14
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")

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

15
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

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

16
Examples:
1. print nos divisible by 5 not by 10:
2. Program to print fibonacci series.
3. Program to find factors of a given number
4. check the given number is perfect number or not
5. check the no is prime or not
6. Print first n prime numbers
7. Program to print prime numbers in range

print nos divisible by 5 not by 10 output


n=eval(input("enter a")) enter a:30
for i in range(1,n,1): 5
if(i%5==0 and i%10!=0): 15
print(i) 25

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
find factors of a number Output
n=eval(input("enter a number:")) enter a number:10
for i in range(1,n+1,1): 1
if(n%i==0): 2
print(i) 5
10

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.")

17
check a number is perfect number or not Output
n=eval(input("enter a number:")) enter a number:6
sum=0 the number is perfect number
for i in range(1,n,1):
if(n%i==0):
sum=sum+i
if(sum==n):
print("the number is perfect number")
else:
print("the number is not perfect number")
Program to print first n prime numbers Output
number=int(input("enter no of prime enter no of prime numbers to be
numbers to be displayed:")) displayed:5
count=1 2
n=2 3
while(count<=number): 5
for i in range(2,n): 7
if(n%i==0): 11
break
else:
print(n)
count=count+1
n=n+1
Program to print prime numbers in range output:
lower=eval(input("enter a lower range")) enter a lower range50
upper=eval(input("enter a upper range")) enter a upper range100
for n in range(lower,upper + 1): 53
if n > 1: 59
for i in range(2,n): 61
if (n % i) == 0: 67
break 71
else: 73
print(n) 79
83
89
97

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

19
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.

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

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
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.
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

21
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

Fruitful Function
  Fruitful function
  
Void function
  
Return values
  
Parameters
  
Local and global scope
  
Function composition
 Recursion
Fruitful function:
A function that returns a value is called fruitful function.
Example:
Root=sqrt(25)
Example:
def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)

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

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

Parameters are the variables which used in the function definition. Parameters
 are
inputs to functions. Parameter receives the input from the function call.
 
It is possible to define more than one parameter in the function definition.
Types of parameters/Arguments:
1. Required/Positional parameters
2. Keyword parameters
3. Default parameters
4. Variable length parameters
Required/ Positional Parameter:

The number of parameter in the function definition should match exactly with
number of arguments in the function call.

Example Output:
def student( name, roll ): George 98
print(name,roll)
student(“George”,98)
Keyword parameter:
When we call a function with some values, these values get assigned to the
parameter according to their position. When we call functions in keyword parameter, the
order of the arguments can be changed.
Example Output:
def student(name,roll,mark): 90 102 bala
print(name,roll,mark)
student(90,102,"bala")

23
Default parameter:

Python allows function parameter to have default values; if the function is called
without the argument, the argument gets its default value in function definition.

Example Output:
def student( name, age=17): Kumar 17
print (name, age)
Ajay 17
student( “kumar”):
student( “ajay”):

Variable length parameter


Sometimes, we do not  know in advance the number of arguments that will be
passed into a function.


Python allows us to handle
 this kind of situation through function calls with
number of arguments.


In the function definition we use an asterisk(*) before the parameter name to
denote this is variable length of parameter.

Example Output:
def student( name,*mark): bala ( 102 ,90)
print(name,mark)
student (“bala”,102,90)

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
24
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.

Example: Output:
[Link]([Link](10))
def add(a,b): 900
c=a+b
return c
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)

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)
25
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
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)
26
Strings:
  Strings
  
String slices
  
Immutability
  
String functions and methods
 String module

Strings:
  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
27
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)
saveearth

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


Repetitions: >>>print(3*a) left hand side times the value on right
panimalarpanimalar hand side.
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 is not defined
28
print(a)
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.
29
14 [Link]() >>> [Link]() checks whether the string
False consists of alphanumeric
characters.
15 [Link]() >>> [Link]() checks whether the string
False consists of digits only.
16 [Link]() >>> [Link]() checks whether the string
False consists of whitespace only.
17 [Link]() >>> [Link]() checks whether string is title
False cased.
18 [Link](substring) >>> [Link]("h") checks whether string starts
True with substring
19 [Link](substring) >>> [Link]("y") checks whether the string
True ends with the substring
20 [Link](substring) >>> [Link]("happy") returns index of substring, if
0 it is found. Otherwise -1 is
returned.
21 len(a) >>>len(a) Return the length of the
>>>14 string
22 min(a) >>>min(a) Return the minimum
>>>’ ‘ character in the string
23 max(a) max(a) Return the maximum
>>>’y’ character in the string

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
30
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”)

List as array:
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)

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

Methods in 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.
[Link]() This is used to count number of
7 count() 4 elements in an array

32
ILLUSTRATIVE 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")
33
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("elemrnt found at",mid+1)
break
elif(search<a[mid]):
stop=mid-1
else:
start=mid+1
else:
print("not found")

Function:
Lambda function (Anonymous Functions)
A function is said to be anonymous function when it is defined without a
name and def keyword.
In python, normal function are defined using def keyword and
Anonymous function are defined using lambda keyword.

Syntax: lambda arguments: expression

Lambda function can have any number of argument but only one
[Link] expression are evaluated and returned.

Example:
>>> a=lambda b: b*2+b
>>> print(a(3))

34
9
Or
def a(b):
return b*2+b

Part A:
1. What are Boolean values?
2. Define operator and operand?
3. Write the syntax for if with example?
4. Write the syntax and flowchart for if else.
5. Write the syntax and flowchart for chained if.
6. define state
7. Write the syntax for while loop with flowchart.
8. Write the syntax for for loopwith flowchart.
9. Differentiate break and continue.
10. mention the use of pass
11. what is fruitful function
12. what is void function
13. mention the different ways of writing return statement
14. What is parameter and list down its type?
15. What is local and global scope?
16. Differentiate local and global variable?
17. What is function composition, give an example?
18. Define recursion.
19. Differentiate iteration and recursion.
20. Define string. How to get a string at run time.

21. What is slicing? Give an example.

35
22. What is immutability of string?
23. List out some string built in function with example?
24. Define string module?
25. How can list act as array?
26. write a program to check the number is odd or even.
27. write a program to check the number positive or negative
28. write a program to check the year is leap year or not
29. write a program to find greatest of two numbers
30. write a program for checking eligibility for vote
31. write a program to find sum of n numbers
32. write a program to find factorial of given numbers
33. write a program to find sum of digits of a number
34. Write a program to reverse the given number.
35. Write a program to check the given number is palindrome or not.
36. write a program to check the given number is Armstrong or not
37. how can you use for loop in sequence.
38. how can you use else statement if loops.
39. What is the use of map() function?
Part B:
1. Explain conditional statements in detail with example(if, if..else, if..elif..else)
2. explain in detail about operators in detail
3. Explain in detail about iterations with example.(for, while)
4. Explain the usage of else statements in loops
5. Explain in detail about using for loop in sequence.
6. Explain in detail about string built in function with suitable examples?
7. Explain about loop control statement(break, continue, pass)
8. Breifly discuss about fruitful function.
9. Discuss with an example about local and global variable
10. Discuss with an example about function composition
11. Explain in detail about recursion with example.
12. Explain in detail about strings and its operations(slicing,immutablity)
13. Program to find square root of a given number using newtons method
14. program to find gcd of given nnumber
15. program to find exponentiation of given number using recursion

36
UNIT IV
COMPOUND DATA: 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: selection sort, insertion sort, merge sort, quick sort.
Lists
  List is an ordered sequence of items. Values in the list are called elements / items.

It can be written
 as a list of comma-separated items (values) between square
brackets[ ].

Items in the lists can be of different data types.
Eg: a=[10, 20, 30, 40]; b=[10, 20, “abc”, 4.5]
The following list contains a string, a float, an integer, and (lo!) another list:
['spam', 2.0, 5, [10, 20]]
A list within another list is nested. A list that contains no elements is called an empty
list; you can create one with empty brackets, [].
As you might expect, you can assign list values to variables:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [17, 123]
>>> empty = []
>>> print cheeses, numbers, empty
['Cheddar', 'Edam', 'Gouda'] [17, 123] []
Operations on list:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison

operations examples description


create a list >>> a=[2,3,4,5,6,7,8,9,10] in this way we can create a
>>> print(a) list at compile time
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> print(a[0]) Accessing the item in the
Indexing 2 position 0
>>> print(a[8]) Accessing the item in the
10 position 8
>>> print(a[-1]) Accessing a last element
10 using negative indexing.

37
>>> print(a[0:3])
Slicing [2, 3, 4]
>>> print(a[0:]) Printing a part of the list.
[2, 3, 4, 5, 6, 7, 8, 9, 10]

>>>b=[20,30] Adding and printing the


Concatenation >>> print(a+b) items of two lists.
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
>>> print(b*3) Create a multiple copies of
Repetition [20, 30, 20, 30, 20, 30] the same list.

>>> print(a[2])
4 Updating the list using
Updating >>> a[2]=100 index value.
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
>>> a=[2,3,4,5,6,7,8,9,10]
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in list. Otherwise
False returns false.
>>> 2 not in a
False
>>> a=[2,3,4,5,6,7,8,9,10]
>>>b=[2,3,4] Returns True if all elements
Comparison
>>> a==b in both elements are same.
False Otherwise returns false
>>> a!=b
True

List slices:

List slicing is an operation
 that extracts a subset of elements from an list and packages
them as another list.
Syntax:
Listname[start:stop]
Listname[start:stop:steps]
  default start value is 0
 
 default stop value is n-1
 
 [:] this will print the entire list
 
[2:2] this will create a empty slice

 38



slices example description


a[0:3] >>> a=[9,8,7,6,5,4] Printing a part of a list from
>>> a[0:3] 0 to 2.
[9, 8, 7]
a[:4] >>> a[:4] Default start value is 0. so
[9, 8, 7, 6] prints from 0 to 3
a[1:] >>> a[1:] default stop value will be
[8, 7, 6, 5, 4] n-1. so prints from 1 to 5
a[:] >>> a[:] Prints the entire list.
[9, 8, 7, 6, 5, 4]

slices example description

a[2:2] >>> a[2:2] print an empty slice


[]
a[0:6:2] >>> a=[9,8,7,6,5,4] Slicing list values with step
>>> a[0:6:2] size 2.(from index[0] to 2nd
[9, 7, 5] element and from that
>>> a[0:6:3] position to next 2nd element
[9,6]

List methods:
Python provides methods that operate on lists.
syntax:
list [Link] name( element/index/list)

syntax example description


1 >>> a=[1,2,3,4,5]
>>> [Link](6) Add an element to
[Link](element) >>> print(a) the end of the list
[1, 2, 3, 4, 5, 6]
2 [Link](index,element) >>> [Link](0,0) Insert an item at the
>>> print(a) defined index
[0, 1, 2, 3, 4, 5, 6]
3 [Link](b) >>> a=[1,2,3,4,5]
>>> b=[7,8,9]
>>> [Link](b) Add all elements of a
>>> print(a) list to the another
[0, 1, 2, 3, 4, 5, 6, 7, 8,9] list
39
4 >>>a=[0, 1, 2, 3, 8,5, 6, 7, 8,9] Returns the index of
[Link](element) >>> [Link](8) the first matched
4 item
5 >>> a=[1,2,3,4,5]
>>> sum(a) Sort items in a list in
sum()
>>> print(a) ascending order
[0, 1, 2, 3, 4, 5, 6, 7, 8,9]
6 >>> [Link]()
Reverse the order of
[Link]() >>> print(a)
items in the list
[8, 7, 6, 5, 4, 3, 2, 1, 0]

>>>a=[8, 7, 6, 5, 4, 3, 2, 1, 0]
7 [Link]() >>> [Link]() Removes and
0
>>>print(a)
=[8, 7, 6, 5, 4, 3, 2, 1] returns an element
at the last element
8 [Link](index) >>> [Link](0) Remove the
8
>>>print(a)
[7, 6, 5, 4, 3, 2, 1, 0] particular element
and return it.
>>>a=[7, 6, 5, 4, 3, 2, 1]
9 [Link](element) >>> [Link](1) Removes an item
>>> print(a) from the list
[7, 6, 5, 4, 3, 2]
>>>a=[7, 6, 5, 4, 3, 2,6]
10 [Link](element) >>> [Link](6) Returns the count of
2 number of items
passed as an
argument
>>>a=[7, 6, 5, 4, 3, 2]
11 [Link]() >>> b=[Link]() Returns a
>>> print(b) copy of the list
[7, 6, 5, 4, 3, 2]
>>>a=[7, 6, 5, 4, 3, 2]
12 len(list) >>> len(a) return the length of
6 the length
>>>a=[7, 6, 5, 4, 3, 2]
17 sum(list) >>> sum(a) return the sum of
27 element in a list
14 max(list) >>> max(a) return the maximum
40
element in a list.
7
15 [Link]() >>> [Link]() Removes all items
>>> print(a) from the list.
[]
16 del(a) >>> del(a) delete the entire list.
>>> print(a)
Error: name 'a' is not
defined

List loops:
1. For loop
2. While loop
3. Infinite loop
List using For Loop:

 The for loop in Python
 is used to iterate over a sequence (list, tuple, string) or other
iterable objects.
  Iterating over a sequence is called traversal.
 
 Loop continues until we reach the last item in the sequence.
 
The body of for loop is separated from the rest of the code using indentation.

Syntax:
for val in sequence:

Accessing element output


a=[10,20,30,40,50] 10
for i in a: 20
print(i) 30
40
50
Accessing index output
a=[10,20,30,40,50] 0
for i in range(0,len(a),1): 1
print(i) 2
3
4
Accessing element using range: output
a=[10,20,30,40,50] 10
for i in range(0,len(a),1): 20
print(a[i]) 30
40
4150
List using While loop

The while loop in Python is used to iterate over a block of code as long as the test
 expression (condition) is true.

When the condition is tested and the result is false, the
 loop body will be skipped and the
first statement after the while loop will be executed.
Syntax:
while (condition):
body of while

Sum of elements in list Output:


a=[1,2,3,4,5] 15
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)

Infinite Loop
A loop becomes infinite loop if the condition given never becomes false. It keeps on
running. Such loops are called infinite loop.
Example Output:
a=1 Enter the number 10
while (a==1): you entered:10
n=int(input("enter the number")) Enter the number 12
print("you entered:" , n) you entered:12
Enter the number 16
you entered:16

Mutability:
  Lists are mutable. (can be changed)

Mutability is the ability for certain types of data to be changed without entirely
 recreating it.

An item canbe changed in a list by accessing it directly as part of the assignment
 statement.

Using the indexing operator (square brackets[ ]) on the left side of an assignment,
one of the list items can be updated.



 42

Example description
changing single element
>>> a=[1,2,3,4,5]
>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
changing multiple element
>>> a=[1,2,3,4,5]
>>> a[0:3]=[100,100,100]
>>> print(a)
[100, 100, 100, 4, 5]
>>> a=[1,2,3,4,5] The elements from a list can also be
>>> a[0:3]=[ ] removed by assigning the empty list to
>>> print(a) them.
[4, 5]
>>> a=[1,2,3,4,5] The elements can be inserted into a list by
>>> a[0:0]=[20,30,45] squeezing them into an empty slice at the
>>> print(a) desired location.
[20,30,45,1, 2, 3, 4, 5]

Aliasing(copying):
 
Creating a copy of a list is called aliasing.


When

you create a copy both the list will be having same memory location. 
 
changes in one list will affect another list.
 
Alaising refers to having different names for same list values.

Example Output:
a= [1, 2, 3 ,4 ,5]
b=a
print (b) [1, 2, 3, 4, 5]
a is b True
a[0]=100
print(a) [100,2,3,4,5]
print(b) [100,2,3,4,5]

 In this a single list object is created and modified using the subscript operator.

When the first element of the  list named43“a” is replaced, the first element of the list
named “b” is also replaced.



 This type of change is what is known as a side effect. This happens because 
the assignment b=a, the variables a and b refer to the exact same list object.
after

 They are aliases for the same object. This phenomenon is known as aliasing.

To prevent aliasing, a new object can be
created and the contents of the original
can be copied which is called cloning.

Clonning:

To avoid the disadvantages of copying we are using cloning.

Creating a copy of a same list of elements with two different memory locations is called cloning.


Changes in one list will not affect locations of aother list.
 
Cloning is a process of making a copy of the list without modifying the original list.

1. Slicing
2. list()method
3. copy() method

clonning using Slicing


>>>a=[1,2,3,4,5]
>>>b=a[:]
>>>print(b)
[1,2,3,4,5]
>>>a is b
False #because they have different memory location
clonning using List( ) method
>>>a=[1,2,3,4,5]
>>>b=list
>>>print(b)
[1,2,3,4,5]
>>>a is b
false
>>>a[0]=100
>>>print(a)
>>>a=[100,2,3,4,5]
>>>print(b)
>>>b=[1,2,3,4,5]
clonning using copy() method

a=[1,2,3,4,5]
>>>b=[Link]()
>>> print(b)
[1, 2, 3, 4, 5]
>>> a is b
False 44
List as parameters:
  In python, arguments are passed by reference.

 If any changes are done in the parameter which refers  within the function, then the
changes also reflects back in the calling function.
  When a list to a function is passed, the function gets a reference to the list.
 
 Passing a list as an argument actually passes a reference to the list, not a copy of the list.

Since lists are mutable, changes made to the elements referenced by the parameter
change the same list that the argument is referencing.
Example 1`: Output
def remove(a): [2,3,4,5]
[Link](1)
a=[1,2,3,4,5]
remove(a)
print(a)

Example 2: Output
def inside(a): inside [11, 12, 13, 14, 15]
for i in range(0,len(a),1): outside [11, 12, 13, 14, 15]
a[i]=a[i]+10
print(“inside”,a)
a=[1,2,3,4,5]
inside(a)
print(“outside”,a)

Example 3 output
def insert(a): [30, 1, 2, 3, 4, 5]
[Link](0,30)
a=[1,2,3,4,5]
insert(a)
print(a)

Tuple:

A tuple is same as list,
 except that the set of elements is enclosed in parentheses instead
 of square brackets.

A tuple is an immutable list. i.e. once a tuplehas been created, you can't add elements to
a tuple or remove elements from the tuple.
 
But tuple can be converted into list and list can be converted in to tuple.

45

methods example description


list( ) >>> a=(1,2,3,4,5) it convert the given tuple
>>> a=list(a) into list.
>>> print(a)
[1, 2, 3, 4, 5]
tuple( ) >>> a=[1,2,3,4,5] it convert the given list into
>>> a=tuple(a) tuple.
>>> print(a)
(1, 2, 3, 4, 5)
Benefit of Tuple:
  Tuples are faster than lists.
 
 If the user wants to protect the data from accidental changes, tuple can be used.
 
Tuples can be used as keys in dictionaries, while lists can't.
Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison

46
Operations examples description
Creating the tuple with
Creating a tuple >>>a=(20,40,60,”apple”,”ball”) elements of different data
types.
>>>print(a[0]) Accessing the item in the
Indexing 20 position 0
>>> a[2] Accessing the item in the
60 position 2
Slicing >>>print(a[1:3]) Displaying items from 1st
(40,60) till 2nd.
Concatenation >>> b=(2,4) Adding tuple elements at
>>>print(a+b) the end of another tuple
>>>(20,40,60,”apple”,”ball”,2,4) elements
Repetition >>>print(b*2) repeating the tuple in n no
>>>(2,4,2,4) of times
>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in tuple. Otherwise
False returns false.
>>> 2 not in a
False
>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4) Returns True if all elements
Comparison
>>> a==b in both elements are same.
False Otherwise returns false
>>> a!=b
True
Tuple methods:

Tuple is immutable
 so changes cannot be done on the elements of a tuple once it is
assigned.
methods example description
[Link](tuple) >>> a=(1,2,3,4,5) Returns the index of the
>>> [Link](5) first matched item.
4
[Link](tuple) >>>a=(1,2,3,4,5) Returns the count of the
>>> [Link](3) given element.
1
len(tuple) >>> len(a) return the length of the
5 tuple

47
min(tuple) >>> min(a) return the minimum
1 element in a tuple
max(tuple) >>> max(a) return the maximum
5 element in a tuple
del(tuple) >>> del(a) Delete the entire tuple.

Tuple Assignment:

Tuple assignment allows, variables on the left of an assignment operator and values of
 tuple on the right of the assignment operator.

Multiple assignment works by creating a tuple of expressions from the right hand
 side, and
target.
 a tuple of targets from the left, and then matching each expression to a
 
Because multiple assignments use tuples to work, it is often termed tuple
assignment.
Uses of Tuple assignment:
 It is often useful to swap the values of two variables.

Example:
Swapping using temporary variable: Swapping using tuple assignment:
a=20 a=20
b=50 b=50
temp = a (a,b)=(b,a)
a=b print("value after swapping is",a,b)
b = temp
print("value after swapping is",a,b)

Multiple assignments:
Multiple values can be assigned to multiple variables using tuple assignment.
>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3

Tuple as return value:


 A Tuple is a comma separated sequence of items.
 
 It is created with or without ( ).

A function can return one value. if you wantto return more than one value from a
function. we can use tuple as return value.

48
Example1: Output:
def div(a,b): enter a value:4
r=a%b enter b value:3
q=a//b reminder: 1
return(r,q) quotient: 1
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
Example2: Output:
def min_max(a): smallest: 1
small=min(a) biggest: 6
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small)
print("biggest:",big)

Tuple as argument:
 
The parameter name that begins with * gathers argument into a tuple.
Example: Output:
def printall(*args): (2, 3, 'a')
print(args)
printall(2,3,'a')

Dictionaries:

Dictionary is an unordered collection of elements. An element in dictionary has a key:
value pair.
  All elements in dictionary are placed inside the curly braces i.e. { }
 
 Elements in Dictionaries are accessed via keys and not by their position.
 
 The values of a dictionary can be any data type.
 
Keys must be immutable data type (numbers, strings, tuple)

Operations on dictionary:
1. Accessing an element
2. Update
3. Add element
4. Membership

49
Operations Example Description

Creating a >>> a={1:"one",2:"two"} Creating the dictionary with


dictionary >>> print(a) elements of different data types.
{1: 'one', 2: 'two'}
accessing an >>> a[1] Accessing the elements by using
element 'one' keys.
>>> a[0]
KeyError: 0
Update >>> a[1]="ONE" Assigning a new value to key. It
>>> print(a) replaces the old value by new value.
{1: 'ONE', 2: 'two'}
add element >>> a[3]="three" Add new element in to the
>>> print(a) dictionary with key.
{1: 'ONE', 2: 'two', 3: 'three'}
membership a={1: 'ONE', 2: 'two', 3: 'three'} Returns True if the key is present in
>>> 1 in a dictionary. Otherwise returns false.
True
>>> 3 not in a
False

Methods in dictionary:

Method Example Description

[Link]( ) a={1: 'ONE', 2: 'two', 3: 'three'} It returns copy of the


>>> b=[Link]() dictionary. here copy of
>>> print(b) dictionary ’a’ get stored
{1: 'ONE', 2: 'two', 3: 'three'} in to dictionary ‘b’
[Link]() >>> [Link]() Return a new view of
dict_items([(1, 'ONE'), (2, 'two'), (3, the dictionary's items. It
'three')]) displays a list of
dictionary’s (key, value)
tuple pairs.
[Link]() >>> [Link]() It displays list of keys in
dict_keys([1, 2, 3]) a dictionary
[Link]() >>> [Link]() It displays list of values
dict_values(['ONE', 'two', 'three']) in dictionary
[Link](key) >>> [Link](3) Remove the element
'three' with key and return its
>>> print(a) value from the
{1: 'ONE', 2: 'two'} dictionary.

50
setdefault(key,value) >>> [Link](3,"three") If key is in the
'three' dictionary, return its
>>> print(a) value. If key is not
{1: 'ONE', 2: 'two', 3: 'three'} present, insert key with
>>> [Link](2) a value of dictionary and
'two' return dictionary.
[Link](dictionary) >>> b={4:"four"}
It will add the dictionary
>>> [Link](b)
with the existing
>>> print(a)
{1: 'ONE', 2: 'two', 3: 'three', 4: 'four'} dictionary
fromkeys() >>> key={"apple","ball"} It creates a dictionary
>>> value="for kids" from key and values.
>>> d=[Link](key,value)
>>> print(d)
{'apple': 'for kids', 'ball': 'for kids'}
len(a) a={1: 'ONE', 2: 'two', 3: 'three'} It returns the length of
>>>lena(a) the list.
3
clear() a={1: 'ONE', 2: 'two', 3: 'three'} Remove all elements
>>>[Link]() form the dictionary.
>>>print(a)
>>>{ }
del(a) a={1: 'ONE', 2: 'two', 3: 'three'} It will delete the entire
>>> del(a) dictionary.

Difference between List, Tuples and dictionary:

List Tuples Dictionary


A list is mutable A tuple is immutable A dictionary is mutable
Lists are dynamic Tuples are fixed size in nature In values can be of any
data type and can
repeat, keys must be of
immutable type
List are enclosed in Tuples are enclosed in parenthesis ( ) Tuples are enclosed in
brackets[ ] and their and cannot be updated curly braces { } and
elements and size consist of key:value
can be changed
Homogenous Heterogeneous Homogenous
Example: Example: Example:
List = [10, 12, 15] Words = ("spam", "egss") Dict = {"ram": 26, "abi":
Or 24}
Words = "spam", "eggs"
Access: Access: Access:
print(list[0]) print(words[0]) print(dict["ram"])

51
Can contain duplicate Can contain duplicate elements. Cant contain duplicate
elements Faster compared to lists keys, but can contain
duplicate values
Slicing can be done Slicing can be done Slicing can't be done
Usage: Usage: Usage:
  
List is used if a Tuple can be used when data Dictionary is used
collection of data that cannot be changed. when a logical

doesnt need random A tuple is used in combination association between
access. with a dictionary i.e.a tuple might key:value pair.
 
List is used when represent a key. When in need of fast
data can be modified lookup for data, based
frequently on a custom key.

Dictionary is used
when data is being
constantly modified.

Advanced list processing:


List Comprehension:
  
List comprehensions provide a concise way to apply operations on a list.

It creates
 a new list in which each element is the result of applying a given operation in a
 list.
 
It consists of brackets containing an expression followed by a “for” clause, then a list.
 
The list comprehension always returns a result list.
Syntax
list=[ expression for item in list if conditional ]
List Comprehension Output

>>>L=[x**2 for x in range(0,5)] [0, 1, 4, 9, 16]


>>>print(L)
>>>[x for x in range(1,10) if x%2==0] [2, 4, 6, 8]
>>>[x for x in 'Python Programming' if x in ['a','e','i','o','u']] ['o', 'o', 'a', 'i']
>>>mixed=[1,2,"a",3,4.2] [1, 4, 9]
>>> [x**2 for x in mixed if type(x)==int]

>>>[x+3 for x in [1,2,3]] [4, 5, 6]

>>> [x*x for x in range(5)] [0, 1, 4, 9, 16]

>>> num=[-1,2,-3,4,-5,6,-7] [2, 4, 6]


>>> [x for x in num if x>=0]

>>> str=["this","is","an","example"] ['t', 'i', 'a', 'e']


>>> element=[word[0] for word in str]
>>> print(element)
52
Nested list:
List inside another list is called nested list.
Example:
>>> a=[56,34,5,[34,57]]
>>> a[0]
56
>>> a[3]
[34, 57]
>>> a[3][0]
34
>>> a[3][1]
57

Programs on matrix:
Matrix addition Output
a=[[1,1],[1,1]] [3, 3]
b=[[2,2],[2,2]] [3, 3]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(b)):
c[i][j]=a[i][j]+b[i][j]
for i in c:
print(i)

Matrix multiplication Output


a=[[1,1],[1,1]] [3, 3]
b=[[2,2],[2,2]] [3, 3]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(b)):
for k in range(len(b)):
c[i][j]=a[i][j]+a[i][k]*b[k][j]
for i in c:
print(i)

Matrix transpose Output


a=[[1,3],[1,2]] [1, 1]
c=[[0,0],[0,0]] [3, 2]
for i in range(len(a)):
for j in range(len(a)):
c[i][j]=a[j][i]
for i in c:
print(i)

53
Illustrative programs:
Selection sort Output
a=input("Enter list:").split() Enter list:23 78 45 8 32 56
a=list(map(eval,a)) [8,2 3, 32, 45,56, 78]
for i in range(0,len(a)):
smallest = min(a[i:])
sindex= [Link](smallest)
a[i],a[sindex] = a[sindex],a[i]
print (a)

Insertion sort output


a=input("enter a list:").split()
a=list(map(int,a))
for i in a: enter a list: 8 5 7 1 9 3
j = [Link](i) [1,3,5,7,8,9]
while j>0:
if a[j-1] > a[j]:
a[j-1],a[j] = a[j],a[j-1]
else:
break
j = j-1
print (a)
54
Merge sort output
def merge(a,b):
c = [] [3,9,10,27,38,43,82]
while len(a) != 0 and len(b) != 0:
if a[0] < b[0]:
[Link](a[0])
[Link](a[0])
else:
[Link](b[0])
[Link](b[0])
if len(a) == 0:
c=c+b
else:
c=c+a
return c

def divide(x):
if len(x) == 0 or len(x) == 1:
return x
else:
middle = len(x)//2
a = divide(x[:middle])
b = divide(x[middle:])
return merge(a,b)

x=[38,27,43,3,9,82,10]
c=divide(x)
print(c)
55
Histogram Output
def histogram(a): ****
for i in a: *****
sum = '' *******
while(i>0): ********
sum=sum+'#' ************
i=i-1
print(sum)
a=[4,5,7,8,12]
histogram(a)
Calendar program Output
import calendar enter year:2017
y=int(input("enter year:")) enter month:11
m=int(input("enter month:")) November 2017
print([Link](y,m)) Mo Tu We Th Fr Sa Su
12345
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
56
PART - A
1. What is slicing?
2. How can we distinguish between tuples and lists?
3. What will be the output of the given code?
a. List=[‘p’,’r’,’i’,’n’,’t’,]
b. Print list[8:]
4. Give the syntax required to convert an integer number into string?
5. List is mutable. Justify?
6. Difference between del and remove methods in List?
7. Difference between pop and remove in list?
8. How are the values in a tuple accessed?
9. What is a Dictionary in Python
10. Define list comprehension
11. Write a python program using list looping
12. What do you meant by mutability and immutability?
13. Define Histogram
14. Define Tuple and show it is immutable with an example.
15. state the difference between aliasing and cloning in list
16. what is list cloning
17. what is deep cloning
18. state the difference between pop and remove method in list
19. create tuple with single element
20. swap two numbers without using third variable
21. define properties of key in dictionary
22. how can you access elements from the dictionary
23. difference between delete and clear method in dictionary
24. What is squeezing in list? give an example
25. How to convert a tuple in to list
26. How to convert a list in to tuple
27. Create a list using list comprehension
28. Advantage of list comprehension
29. What is the use of map () function.

57
30. How can you return multiple values from function?
31. what is sorting and types of sorting
32. Find length of sequence without using library function.
33. how to pass tuple as argument
34. how to pass a list as argument
35. what is parameter and types of parameter
36. how can you insert values in to dictionary
37. what is key value pair
38. mention different data types can be used in key and value
39. what are the immutable data types available in python
40. What is the use of fromkeys() in dictioanary.

PART-B
1. Explain in details about list methods
2. Discuss about operations in list
3. What is cloning? Explain it with example
4. What is aliasing? Explain with example
5. How can you pass list into function? Explain with example.
6. Explain tuples as return values with examples
7. write a program for matrix multiplication
8. write a program for matrix addition
9. write a program for matrix subtraction
10. write a program for matrix transpose
11. write procedure for selection sort
12. explain merge sort with an example
13. explain insertion with example
14. Explain in detail about dictionaries and its methods.
15. Explain in detail about advanced list processing.

58
UNIT V FILES, MODULES, PACKAGES
Files and exception: text files, reading and writing files, format operator; command line
arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative
programs: word count, copy file.

FILES
File is a named location on disk to store related information. It is used to permanently store
data in a non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when computer is
turned off, we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When we are done, it
needs to be closed, so that resources that are tied with the file are freed. Hence, in Python, a
file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file

Opening a file
Python has a built-in function open() to open a file. This function returns a file object, also
called a handle, as it is used to read or modify the file accordingly.
>>> f = open("[Link]") # open file in current directory
>>> f = open("C:/Python33/[Link]") # specifying full path

We can specify the mode while opening a file. In mode, we specify whether we want to read
'r', write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode
or binary mode.
The default is reading in text mode. In this mode, we get strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing
with non-text files like image or exe files.

Python File Modes


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

f = open("[Link]") # equivalent to 'r' or 'rt'


f = open("[Link]",'w') # write in text mode
1

59
f = open("[Link]",'r+b') # read and write in binary mode

Hence, when working with files in text mode, it is highly recommended to specify the
encoding type.
f = open("[Link]",mode = 'r',encoding = 'utf-8')

Closing a File
When we are done with operations to the file, we need to properly close it.
Closing a file will free up the resources that were tied with the file and is done using the
close() method.
Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to
close the file.
f = open("[Link]",encoding = 'utf-8')
# perform file
operations [Link]()

This method is not entirely safe. If an exception occurs when we are performing some
operation with the file, the code exits without closing the file. A safer way is to use a
try...finally block.
try:
f = open("[Link]",encoding = 'utf-8')
# perform file operations
finally:
[Link]()

This way, we are guaranteed that the file is properly closed even if an exception is raised,
causing program flow to stop.
The best way to do this is using the with statement. This ensures that the file is closed when
the block inside with is exited.
We don't need to explicitly call the close() method. It is done internally.
with open("[Link]",encoding = 'utf-8') as f:
# perform file operations

Reading and writing


A text file is a sequence of characters stored on a permanent medium like a hard drive, flash
memory, or CD-ROM.
To write a file, you have to open it with mode 'w' as a second parameter:
>>> fout = open('[Link]', 'w')
>>> print fout
<open file '[Link]', mode 'w' at 0xb7eb2410>

If the file already exists, opening it in write mode clears out the old data and starts
fresh, so be careful! If the file doesn’t exist, a new one is created.
The write method puts data into the file.
>>> line1 = "This here's the wattle,\n"
>>> [Link](line1)

2
60
Again, the file object keeps track of where it is, so if you call write again, it adds the new data
to the end.
>>> line2 = "the emblem of our land.\n"
>>> [Link](line2)

When you are done writing, you have to close the file.
>>> [Link]()

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.
A format sequence can appear anywhere in the string, so you can embed a value in a
sentence:
>>> camels = 42
>>> 'I have spotted %d camels.' %
camels 'I have spotted 42 camels.'

If there is more than one format sequence in the string, the second argument has to be a tuple.
Each format sequence is matched with an element of the tuple, in order.
The following example uses '%d' to format an integer, '%g' to format a floating-point number
and '%s' to format a string:
>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')
'In 3 years I have spotted 0.1 camels.'

The number of elements in the tuple has to match the number of format sequences in
the string. Also, the types of the elements have to match the format sequences:

>>> '%d %d %d' % (1, 2)


TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: illegal argument type for built-in operation

61
Filenames and paths
Files are organized into directories (also called “folders”). Every running program
has a “current directory,” which is the default directory for most operations. For example,
when you open a file for reading, Python looks for it in the current directory.
The os module provides functions for working with files and directories (“os” stands for
“operating system”). [Link] returns the name of the current directory:
>>> import os
>>> cwd = [Link]()
>>> print cwd
/home/dinsdale

cwd stands for “current working directory.” The result in this example is /home/dinsdale,
which is the home directory of a user named dinsdale.
A string like cwd that identifies a file is called a path. A relative path starts from the current
directory; an absolute path starts from the topmost directory in the file system.
The paths we have seen so far are simple filenames, so they are relative to the current
directory. To find the absolute path to a file, you can use [Link]:
>>> [Link]('[Link]')
'/home/dinsdale/[Link]'

[Link] checks whether a file or directory exists:


>>> [Link]('[Link]')
True

If it exists, [Link] checks whether it’s a directory:


>>> [Link]('[Link]')
False
>>> [Link]('music')
True

Similarly, [Link] checks whether it’s a file.


[Link] returns a list of the files (and other directories) in the given directory:
>>> [Link](cwd) ['music',
'photos', '[Link]']

To demonstrate these functions, the following example “walks” through a directory, prints
the names of all the files, and calls itself recursively on all the directories.
def walk(dirname):
for name in [Link](dirname):
path = [Link](dirname, name)
if [Link](path):
print path
else:
walk(path)

62
[Link] takes a directory and a file name and joins them into a complete path.

EXCEPTION
Python (interpreter) raises exceptions when it encounters errors. Error caused by not
following the proper structure (syntax) of the language is called syntax error or parsing error.
>>> if a < 3
File "<interactive input>", line 1
if a < 3
^
SyntaxError: invalid syntax

Errors can also occur at runtime and these are called exceptions. They occur, for example,
when a file we try to open does not exist (FileNotFoundError), dividing a number by zero
(ZeroDivisionError), module we try to import is not found (ImportError) etc.
Whenever these type of runtime error occur, Python creates an exception object. If not
handled properly, it prints a traceback to that error along with some details about why that
error occurred.
>>> 1 / 0
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ZeroDivisionError: division by zero

>>> open("[Link]")
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '[Link]'

Python Built-in Exceptions


Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that
are raised when corresponding errors occur. We can view all the built-in exceptions using the
local() built-in functions as follows.
>>> locals()['__builtins__']

This will return us a dictionary of built-in exceptions, functions and attributes.


Some of the common built-in exceptions in Python programming along with the error that
cause then are tabulated below.

Python Built-in Exceptions


Exception Cause of Error
AssertionError Raised when assert statement fails.
AttributeError Raised when attribute assignment or reference fails.
EOFError Raised when the input() functions hits end-of-file condition.

63
FloatingPointError Raised when a floating point operation fails.
GeneratorExit Raise when a generator's close() method is called.
ImportError Raised when the imported module is not found.
IndexError Raised when index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in local or global scope.
NotImplementedError Raised by abstract methods.
OSError Raised when system operation causes system related error.
Raised when result of an arithmetic operation is too large to be
OverflowError
represented.
Raised when a weak reference proxy is used to access a garbage
ReferenceError
collected referent.
RuntimeError Raised when an error does not fall under any other category.
Raised by next() function to indicate that there is no further item to
StopIteration
be returned by iterator.
SyntaxError Raised by parser when syntax error is encountered.
IndentationError Raised when there is incorrect indentation.
TabError Raised when indentation consists of inconsistent tabs and spaces.
SystemError Raised when interpreter detects internal error.
SystemExit Raised by [Link]() function.
Raised when a function or operation is applied to an object of
TypeError
incorrect type.
Raised when a reference is made to a local variable in a function or
UnboundLocalError
method, but no value has been bound to that variable.
UnicodeError Raised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.
UnicodeTranslateError Raised when a Unicode-related error occurs during translating.
Raised when a function gets argument of correct type but improper
ValueError
value.
ZeroDivisionError Raised when second operand of division or modulo operation is zero.
We can handle these built-in and user-defined exceptions in Python using try, except and
finally statements.

6
64
Python Exception Handling
Python has many built-in exceptions which forces your program to output an error when
something in it goes wrong.
When these exceptions occur, it causes the current process to stop and passes it to the calling
process until it is handled. If not handled, our program will crash.
For example, if function A calls function B which in turn calls function C and an exception
occurs in function C. If it is not handled in C, the exception passes to B and then to A.
If never handled, an error message is spit out and our program come to a sudden, unexpected
halt.

Catching Exceptions in Python


In Python, exceptions can be handled using a try statement.
A critical operation which can raise exception is placed inside the try clause and the code that
handles exception is written in except clause.
It is up to us, what operations we perform once we have caught the exception. Here is a
simple example.
# import module sys to get the type of
exception import sys

randomList = ['a', 0, 2]

for entry in randomList:


try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!",sys.exc_info()[0],"occured.")
print("Next entry.")
print()
print("The reciprocal of",entry,"is",r)
Output
The entry is a
Oops! <class 'ValueError'> occured.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError' > occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5

In this program, we loop until the user enters an integer that has a valid reciprocal. The
portion that can cause exception is placed inside try block.

7
65
If no exception occurs, except block is skipped and normal flow continues. But if any
exception occurs, it is caught by the except block.
Here, we print the name of the exception using ex_info() function inside sys module and ask
the user to try again. We can see that the values 'a' and '1.3' causes ValueError and '0' causes
ZeroDivisionError.

try...finally
The try statement in Python can have an optional finally clause. This clause is
executed no matter what, and is generally used to release external resources.
For example, we may be connected to a remote data center through the network or working
with a file or working with a Graphical User Interface (GUI).
In all these circumstances, we must clean up the resource once used, whether it was
successful or not. These actions (closing a file, GUI or disconnecting from network) are
performed in the finally clause to guarantee execution. Here is an example of file operations
to illustrate this.
try:
f = open("[Link]",encoding = 'utf-8')
# perform file operations
finally:
[Link]()

MODULES
Any file that contains Python code can be imported as a module. For example,
suppose you have a file named [Link] with the following code:
def linecount(filename):
count = 0
for line in open(filename):
count += 1
return count
print linecount('[Link]')
If you run this program, it reads itself and prints the number of lines in the file, which is 7.
You can also import it like this:
>>> import wc
7
Now you have a module object wc:
>>> print wc
<module 'wc' from '[Link]'>

>>> [Link]('[Link]')
7
So that’s how you write modules in Python.
The only problem with this example is that when you import the module it executes the
test code at the bottom. Normally when you import a module, it defines new functions
but it doesn’t execute them.
Programs that will be imported as modules often use the following
idiom: if __name__ == '__main__':

8
66
print linecount('[Link]')

__name__ is a built-in variable that is set when the program starts. If the program is
running as a script, __name__ has the value __main__; in that case, the test code is
executed. Otherwise, if the module is being imported, the test code is skipped. Eg:

# import module
import calendar

yy = 2017
mm = 8

# To ask month and year from the user


# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))

# display the calendar


print([Link](yy, mm))

PACKAGE
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.
Here is an example. Suppose we are developing a game, one possible organization of
packages and modules could be as shown in the figure below.

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 [Link]
9
67
Now if this module contains a function named select_difficulty(), we must use the full name to
reference it.
[Link].select_difficulty(2)

If this construct seems lengthy, we can import the module without the package prefix as follows.
from [Link] 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 [Link] 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 [Link], similar as
for module search path.

ILLUSTRATION PROGRAM
Word Count of a file:

import sys
fname=[Link][1]
n=0
with open(fname,'r') as f:
for line in f:
words=[Link]()
n+=len(words)
print("Number of words:",n)

68
Copy file:

f1=open(“[Link]”,”r”)
f2=open(“[Link]”,”w”)
for line in f1:
[Link](“\n”+line)
[Link]( )
[Link]( )
print(“Content of Source file:”)
f1=open(“[Link]”,”r”)
print([Link]( ))
print(“Content of Copied file:”)
f2=open(“[Link]”,”r”)
print([Link]( ))

69
UNIT V FILES, MODULES, PACKAGES 9
Files and exception: text files, reading and writing files, format operator; command line
arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative programs:
word count copy file.
PERSISTENCE
Most of the programs we have seen are transient in the sense that they run for a short
time and produce some output, but when they end, their data disappears. If you run the
program again, it starts with a clean slate.
Other programs are persistent: they run for a long time (or all the time); they keep at
least some of their data in permanent storage (a hard drive, for example); and if they shut down
and restart, they pick up where they left off.
Examples of persistent programs are operating systems, which run pretty much
whenever a computer is on, and web servers, which run all the time, waiting for requests to come
in on the network.
One of the simplest ways for programs to maintain their data is by reading and writing
text files. We have already seen programs that read text files; in this chapter we will see
programs that write them. An alternative is to store the state of the program in a database.
5.1 FILES:TEXTFILE
A textfile is a sequence of characters stored on a permanent medium like a hard drive,
flash memory, or CD-ROM.

A text file is a file containing characters, structured as individual lines of text. In


addition to printable characters, text files also contain the nonprinting newline character, \n, to
denote the end of each text line. the newline character causes the screen cursor to move to the
beginning of the next screen line. Thus, text files can be directly viewed and created using a text
editor.
In contrast, binary files can contain various types of data, such as numerical values,
and are therefore not structured as lines of text. Such files can only be read and written via a
computer program.
Using Text Files
Fundamental operations of all types of files include opening a file, reading from a file,
writing to a file, and closing a file. Next we discuss each of these operations when using text files
in Python.
OPENING TEXT FILES

70
All files must first be opened before they can be read from or written to. In Python, when
a file is (successfully) opened, a file object is created that provides methods for accessing the
file.

All files must first be opened before they can be used. In Python, when a file is opened, a file
object is created that provides methods for accessing the file.

5.1.2 OPENING FOR READING


The syntax to open a file object in Python is

file_object = open(“filename”, “mode”) where file_object is the variable to add the file object.

To open a file for reading, the built-in open function is used as shown,
input_file=open('[Link]','r')

The modes are:

 ‘r’ – Read mode which is used when the file is only being read
 ‘w’ – Write mode which is used to edit and write new information to the file (any existing
files with the same name will be erased when this mode is activated)
 ‘a’ – Appending mode, which is used to add new data to the end of the file; that is new
information is automatically amended to the end
 ‘r+’ – Special read and write mode, which is used to handle both actions when working
with a file

The first argument is the file name to be opened, '[Link]'. The second argument, 'r',
indicates that the file is to be opened for reading. (The second argument is optional when
opening a file for reading.) If the file is successfully opened, a file object is created and assigned
to the provided identifier, in this case identifier input_fi le.
When opening a file for reading, there are a few reasons why an I/O error may occur.
First, if the file name does not exist, then the program will terminate with a “no such file or
directory” error.

... open('[Link]','r')
Traceback (most recent call last):
File " , pyshell#1 . ", line 1, in , module .
open('[Link]','r')
IOError: [Errno 2] No such file or directory:
'[Link]' 71
This error can also occur if the file name is not found in the location looked for
(uppercase and lowercase letters are treated the same for file names). When a file is opened,
it is first searched for in the same folder/directory that the program resides in.
However, an alternate location can be specified in the call to open by providing a path to
the file.

input_file=open('data/[Link]','r')

the file is searched for in a subdirectory called data of the directory in which the program
is contained. Thus, its location is relative to the program location. (Although some operating
systems use forward slashes, and other backward slashes in path names, directory paths in
Python are always written with forward slashes and are automatically converted to backward
slashes when required by the operating system executing on.) Absolute paths can also be
provided giving the location of a file anywhere in the file system.

input_file= open('C:/mypythonfiles/data/[Link]','r')

When the program has finished reading the file, it should be closed by calling the close method
on the file object,

input_file=open('C:/mypythonfiles/data/[Link]','r')

The read functions contains different methods,


read(),readline() and readlines()

read() #return one big string


5.1.3 OPENING FOR WRITING
readline #return one line at a time
To write a file, you have to open it with mode 'w' as a second parameter: The write method is
readlines
used to write strings #returns a list of lines
to a file.

output_file=open('[Link]','w')
output_file.close()

f = open("[Link]","w") #opens file with name of "[Link]"


[Link]()

72
f = open("[Link]","w") #opens file with name of "[Link]"
[Link]("I am a test file.")
[Link]("Welcome to python.")
[Link]("Created by Guido van Rossum and first released in 1991 ")
[Link]("Design philosophy that emphasizes code readability.")
[Link]()

This method writes a sequence of strings to the file.

write () #Used to write a fixed sequence of characters to a file

writelines() #writelines can write a list of strings.

Appending to a file example

f = open("[Link]","w") #opens file with name of "[Link]"


[Link]()

To open a text file,read mode:


fh = open("[Link]", "r")
To read a text file:
fh = open("[Link]","r")
print [Link]()
To read one line at a time:
fh = open("hello".txt", "r")
print [Link]()
To read a list of lines:
fh = open("[Link].", "r")
print [Link]()
To write to a file:
fh = open("[Link]","w")
write("Hello World") 73
[Link]()
5.1.4 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 a decimal integer:

>>> camels = 42
>>> '%d' % camels
'42'

The result is the string '42', which is not to be confused with the integer value 42.
A format sequence can appear anywhere in the string, so you can embed a value
in a

74
sentence:

>>> 'I have spotted %d camels.' % camels


'I have spotted 42 camels.'

If there is more than one format sequence in the string, the second argument has to be a
tuple. Each format sequence is matched with an element of the tuple, in order.
The following example uses '%d' to format an integer, '%g' to format a floating-point
number, and '%s' to format a string:

>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')


'In 3 years I have spotted 0.1 camels.'

The number of elements in the tuple has to match the number of format sequences in the
string. Also, the types of the elements have to match the format sequences:

>>> '%d %d %d' % (1, 2)


TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: %d format: a number is required, not str

5.2 COMMAND LINE ARGUMENTS


Command-line arguments in Python show up in [Link] as a list of strings (so you'll
need to import the sys module).
For example, if you want to print all passed command-line arguments:
import sys
print([Link]) # Note the first argument is always the script filename.

[Link] is a list in Python, which contains the command-line arguments passed to the
script.
With the len([Link]) function you can count the number of arguments.
If you are gonna work with command line arguments, you probably want to
use [Link].
To use [Link], you will first have to import the sys module.
Example

import sys
print "This is the name of the script: ", [Link][0]
print "Number of arguments: ", len([Link])
print "The arguments are: " , str([Link])
Output 75
This is the name of the script: [Link]
Number of arguments in: 1
5.3 ERRORS AND EXCEPTIONS, HANDLING EXCEPTIONS

Various error messages can occur when executing Python programs. Such errors are
called exceptions. So far we have let Python handle these errors by reporting them on the screen.
Exceptions can
be “caught” and “handled” by a program, however, to either correct the error and continue
execution,
or terminate the program gracefully.
5.3.1 WHAT IS AN EXCEPTION?
An exception is a value (object) that is raised (“thrown”) signaling that an unexpected, or
“exceptional,”situation has occurred. Python contains a predefined set of exceptions referred to
as standard exceptions .
Base class for all errors that occur for
ArithmeticError
numeric calculation.
Raised when a calculation exceeds
OverflowError
maximum limit for a numeric type.
Raised when a floating point calculation
FloatingPointError
fails.
Raised when division or modulo by zero
ZeroDivisionError
takes place for all numeric types.
Raised when there is no input from either
EOFError the raw_input() or input() function and the
end of file is reached.
ImportError Raised when an import statement fails.
Raised when the user interrupts program
KeyboardInterrupt
execution, usually by pressing Ctrl+c.
Raised when an index is not found in a
IndexError
sequence.

76
Raised when an input/ output operation fails,
such as the print statement or the open()
IOError
function when trying to open a file that does
not exist.
OSError Raised for operating system-related errors.
Raised when there is an error in Python
SyntaxError
syntax.
Raised when indentation is not specified
IndentationError
properly.
Raised when an operation or function is
TypeError attempted that is invalid for the specified
data type.
Raised when the built-in function for a data
ValueError type has the valid type of arguments, but the
arguments have invalid values specified.
Raised when a generated error does not fall
RuntimeError
into any category.

5.3.2 PYTHON EXCEPTION HANDLING - TRY, EXCEPT AND FINALLY

Exception handling can be done by using try statement

Exception handling provides a means for functions and


methods to report errors that cannot be corrected locally. In
try:
such cases, an exception (object) is raised that can be caught
statements
by its client code (the code that called it), or the client’s client
except ExceptionType:
code, etc., until handled (i.e. the exception is caught and the
statements error appropriately dealt with). If an exception is thrown back
except ExceptionType: to the top-level code and never caught, then the program
statements
terminates displaying the exception type that occurred.

5.3.3 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.

77
 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.
 If an exception occurs which does not match the exception named in the except clause, it
is passed on to outer try statements; if no handler is found, it is an unhandled exception
and execution stops with a message
Example

import math
num=int(input('Enter the number'))
print('the factorial is',[Link](num))
Output
Enter the number-5
ValueError:Recovery
Example:Program factorial() via
not defined for negative
Exception Handlingvalues

import math
num=int(input('Enter the number'))
valid_input=False;
while not valid_input:
try:
result=[Link](num);
print('the factorial is',result)
valid_input=True
except ValueError:
print('Cannot recompute reenter again')
num=int(input('Please reenter'))
Output
Enter the number-5 Cannot recompute reenter again
Please reenter5
the factorial is 120

5.4 Modules in Python

A Python module is a file containing Python definitions and statements. The module that
is directly executed to start a Python program is called the main module. Python provides
standard (built-in) modules in the Python Standard Library.
Each module in Python has its own namespace: a named context for its set of identifiers.
The fully

78
qualified name of each identifier in a module is of the form [Link].

5.4.1 MATHEMATICAL FUNCTIONS IN PYTHON

Python has a math module that provides most of the familiar mathematical functions. A
module is a file that contains a collection of related functions.
Before we can use the module, we have to import it:

>>> import math

This statement creates a module object named math. If you print the module object, you
get some information about it:

>>> print math


<module 'math' (built-in)>

The module object contains the functions and variables defined in the module. To access
one of the functions, you have to specify the name of the module and the name of the
function, separated by a dot (also known as a period). This format is called dot notation.

>>> ratio = signal_power / noise_power


>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = [Link](radians)

The first example uses log10 to compute a signal-to-noise ratio in decibels (assuming that
signal_power and noise_power are defined). The math module also provides log, which
computes logarithms base e.
The second example finds the sine of radians. The name of the variable is a hint that sin
and the other trigonometric functions (cos, tan, etc.) take arguments in radians. To convert
from degrees to radians, divide by 360 and multiply by 2p:
>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * [Link]
>>> [Link](radians)
0.707106781187

The expression [Link] gets the variable pi from the math module. The value of this

79
variable is an approximation of p, accurate to about 15 digits.
If you know your trigonometry, you can check the previous result by comparing it to the
square root of two divided by two:

>>> [Link](2) / 2.0 Output:0.707106781187

One of the most useful features of programming languages is their ability to take small
building blocks and compose them. For example, the argument of a function can be any
kind of expression, including arithmetic operators:

x = [Link](degrees / 360.0 * 2 * [Link])

And even function calls:


x = [Link]([Link](x+1))

Almost anywhere you can put a value, you can put an arbitrary expression, with one
exception: the left side of an assignment statement has to be a variable name.

>>> minutes = hours * 60 # right


>>> hours * 60 = minutes # wrong!
SyntaxError: can't assign to operator

In python a number of mathematical operations can be performed with ease by importing


a module named “math” which defines various functions which makes our tasks easier.
1. ceil() :- This function returns the smallest integral value greater than the number. If
number is already integer, same number is returned.
2. floor() :- This function returns the greatest integral value smaller than the number. If
number is already integer, same number is returned.

# Python code to demonstrate the working of ceil() and floor()


# importing "math" for mathematical operations
import math
a = 2.3
# returning the ceil of 2.3
print ("The ceil of 2.3 is : ", end="")
print ([Link](a))
# returning the floor of 2.3
print ("The floor of 2.3 is : ", end="")
print ([Link](a)) 80
Output:
3. fabs() :- This function returns the absolute value of the number.
4. factorial() :- This function returns the factorial of the number. An error message is displayed
if number is not integral.

# Python code to demonstrate the working of


# fabs() and factorial()
# importing "math" for mathematical operations
import math
a = -10
b= 5
# returning the absolute value.
print ("The absolute value of -10 is : ", end="")
print ([Link](a))
# returning the factorial of 5
print ("The factorial of 5 is : ", end="")
print ([Link](b))
Output:
The absolute value of -10 is : 10.0
The factorial of 5 is : 120

5. copysign(a, b) :- This function returns the number with the value of ‘a’ but with the sign of
‘b’. The returned value is float type.
6. gcd() :- This function is used to compute the greatest common divisor of 2
numbers mentioned in its arguments.

81
# Python code to demonstrate the working of copysign() and gcd()
import math
a = -10
b = 5.5
c = 15
d=5
# returning the copysigned value.
print ("The copysigned value of -10 and 5.5 is : ", end="")
print ([Link](5.5, -10))
# returning the gcd of 15 and 5
print ("The gcd of 5 and 15 is : ", end="")
print ([Link](5,15))
Output:
The copysigned value of -10 and 5.5 is : -5.5
The gcd of 5 and 15 is : 5

82
MATH MODULE
This module contains a set of commonly-used mathematical functions, including number-theoretic
functions (such as factorial); logarithmic and power functions; trigonometric (and hyperbolic)
functions; angular conversion functions (degree/radians); and some special functions and constants
(including pi and e). A selected set of function from the math module are presented here.
[Link] returns the ceiling of x (smallest integer greater than or equal to x).
[Link](x) returns the absolute value of x
[Link](x) returns the factorial of x
[Link]() returns the floor of x (largest integer less than x).
[Link](s) returns an accurate floating-point sum of values in s (or other iterable).
[Link]() returns the fractional and integer parts of x.
[Link](X) returns the truncated value of s.
[Link](x) returns e**x, for natural log base e.
[Link](x,base) returns log x for base. If base omitted, returns log x base e.
[Link](x) returns the square root of x.
[Link](x) returns cosine of x radians.
[Link](x) returns sine of x radians.
[Link](x) returns tangent of x radians.
[Link](x) returns arc cosine of x radians.
[Link](x) returns arc sine of x radians.
[Link](x) returns arc cosine of x radians.
[Link](x) returns x radians to degrees.
[Link](x) returns x degrees to radians.
[Link] mathematical constant pi = 3.141592
math.e mathematical constant e = 2.718281

IMPORTING MODULES

83
A Python module is a file containing Python definitions and statements. When a Python
file is directly executed, it is considered the main module of a program. Main modules are given
the special name __main__. Main modules provide the basis for a complete Python program.
They may import (include) any number of other modules (and each of those modules import
other modules, etc.).
Main modules are not meant to be imported into other modules.
As with the main module, imported modules may contain a set of statements. The
statements of imported modules are executed only once, the first time that the module is
imported. The purpose of these statements is to perform any initialization needed for the
members of the imported module. The Python Standard Library contains a set of predefined
Standard (built-in) modules.

1. import modulename
Makes the namespace of modulename available, but not part of, the importing
module. All imported identifiers used in the importing module must be fully
qualified:
import math
print('factorial of 16 = ', [Link](16))
2. from modulename import identifier_1, identifier_2, ...
identifier_1, identifier_2, etc. become part of the importing module’s namespace:
from math import factorial
print('factorial of 16 = ', factorial(16))
3. from modulename import Identifier_1 as identifier_2
identifier_1 becomes part of the importing module’s namespace as identifier_2
from math import factorial as fact
print('factorial of 16 = ', fact(16))
4. from modulename import *
All identifiers of modulename become part of the importing module’s namespace
(except those beginning with an underscore, which are treated as private).
5. from math import *
print('factorial of 16 = ', fact(16))
5.5 PACKAGES IN PYTHON
print('area of circle = ', pi*(radius**2)

84
Packages are namespaces which contain multiple packages and modules themselves.
They are simply directories, but with a change.

Each package in Python is a directory which MUST contain a special file called
__init__.py. This file can be empty, and it indicates that the directory it contains is a Python
package, so it can be imported the same way a module can be imported

5.5.1 STEPS TO CREATE A PYTHON PACKAGE

1. Create a directory and give it your package's name.


2. Put your classes in it.
3. Create a __init__.py file in the directory

The __init__.py file is necessary because with this file, Python will know that this
directory is a Python package directory other than an ordinary directory (or folder – whatever
you want to call it).

5.5.2 EXAMPLE ON HOW TO CREATE A PYTHON PACKAGE

In this tutorial, we will create an Animals package – which simply contains two module
files named Mammals and Birds, containing the Mammals and Birds classes, respectively.

1. Step 1: Create the Package Directory


2. So, first we create a directory named Animals.
3. Step 2: Add Classes

Now, we create the two classes for our package. First, create a file
named [Link] inside the Animals directory and put the following code in it:

3
class Mammals:
4 def __init__(self):
''' Constructor for this class. '''
# Create some member animals
85
[Link] = ['Tiger', 'Elephant', 'Wild Cat']
def printMembers(self):
5

The class has a property named members – which is a list of some mammals we might be
interested in. It also has a method named printMembers which simply prints the list of mammals
of this class!.When you create a Python package, all classes must be capable of being imported,
and won't be executed directly.

Next we create another class named Birds. Create a file named [Link] inside
the Animals directory and put the following code in it:

class Birds:
def __init__(self):
''' Constructor for this class. '''
# Create some member animals
[Link] = ['Sparrow', 'Robin', 'Duck']
def printMembers(self):
print('Printing members of the Birds class')
for member in [Link]:
print('\t%s ' % member)

This code is similar to the code we presented for the Mammals class.

Step 3: Add the __init__.py File

86
Finally, we create a file named __init__.py inside the Animals directory and put the
following code in it:

1 from Mammals import Mammals

2 from Birds import Birds

That's it! That's all there is to it when you create a Python package. For testing, we create
a simple file named [Link] in the same directory where the Animals directory is located.
We place the following code in the [Link] file:

# Import classes from your brand new package

from Animals import Mammals

from Animals import Birds

# Create an object of Mammals class & call a method of it

myMammal = Mammals()

[Link]()

# Create an object of Birds class & call a method of it

myBird = Birds()

[Link]()

ILLUSTRATIVE PROGRAMS: WORD COUNT, COPY FILE

WORD COUNT IN A TEXT FILE

fname = input("Enter file name: ")


num_words = 0
with open(fname, 'r') as f:

87
for line in f:
words = [Link]()
num_words += len(words)
print("Number of words:")
print(num_words)
Case 1:
Contents of file:
Hello world

OUTPUT:
Enter file name: [Link]
Number of words:
2
Case 2:
Contents of file:
This programming language is
Python
Output:
Enter file name: [Link]
Number of words:
5
COPY FILE IN PYTHON
with open("[Link]") as f:
with open("[Link]", "w") as f1:
for line in f:
[Link](line)
OUTPUT:
Case 1:
Contents of file([Link]):
Hello world

Output([Link]):
Hello world

88
3.4. Fruitful functions: return values, parameters, local and global scope,

function composition, recursion

Fruitful Functions
Function that returns value are called as fruitful [Link] return statement is
followed by an expression which is evaluated, its result is returned to the caller as the “fruit” of
calling this function.

Input the value→fruitful function→return the result

len(variable) – which takes input as a string or a list and produce the length of string or a list as
an output.

In a fruitful function the return statement includes a return value. This statement means:
Return immediately from this function and use the following expression as a return value. The
expression provided can be arbitrarily complicated, so we could have written this function more
concisely:

def area(radius):

return 3.14159 * radius**2

On the other hand, temporary variables like temp often makedebugging easier. Sometimes it
is useful to have multiple return statements, one in each branch of a conditional.
We have already seen the built-in abs, now we see how to write our own:

def absolute_value(x):
if x < 0:
return -x
else:
return x

GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING


89
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.
Another way to write the above function is to leave out the else and just follow the if condition
by the second return statement.

def absolute_value(x):
if x < 0:
return -x
return x

Code that appears after a return statement, or any other place the flow of execution can
never reach, is called dead code.

In a fruitful function, it is a good idea to ensure that every possible path through the
program hits a return statement. The following version of absolute_value fails to do this:

def absolute_value(x):
if x < 0:
return -x
elif x > 0:
return x

This version is not correct because if x happens to be 0, neither condition is true, and the
function ends without hitting a return statement. In this case, the return value is a special value
called None:

>>>print absolute value(0)

None

None is the unique value of a type called the NoneType:

>>>type(None)

GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING


90
All Python functions return None whenever they do not return another value.
Example:

Write a python program to find distance between two points:

import math
def distance(x1,y1,x2,y2): # Defining the Function Distance
dx=x2-x1
dy=y2-y1
print("The value of dx is", dx)
print("The value of dy is", dy)
d= (dx**2 + dy**2)
dist=[Link](d)
return dist

x1 = float(input("Enter the first Number: ")) #Getting inputs from user


x2 = float(input("Enter the Second Number: "))
y1 = float(input("Enter the third number: "))
y2 = float(input("Enter the forth number: "))
print("The distance between two points are",distance(x1,x2,y1,y2))
#Calling the function distance
Output:
>>> Enter the first Number: 2
Enter the Second Number: 4
Enter the third number: 6
Enter the forth number: 12
The value of dx is 4.0
The value of dy is 8.0
The distance between two points are 8.94427190999916
>>>
Explanation for Example 2:

Function Name – ‘distance()’

GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING


91
ROHINI COLLEGE OF ENGINEERING & TECHNOLOGY

Function Definition – def distance(x1,y1,x2,y2)

Formal Parameters - x1, y1, x2, y2

Actual Parameter – dx, dy

Return Keyword – return the output value ‘dist’

Function Calling – distance(x1,y1,x2,y2)

Parameter in fruitful function


A function in python

• Take input data,called parameter


• Perform computation
• Return result

def funct(param1,param2):

statements

return value

Once the function is defined,it can be called from main program or from another function.

Functioncall statement syntax

Result=function_name(param1,param2

Parameter is the input data that is sent from one function to [Link] parameters are of two
types
1. Formal parameter

• The parameter defined as part of the function definition.


• The actual parameter is received by the formal parameter.
2. Actual parameter

• The parameter is defined in the function call


Example:

def cube(x):

return x*x*x #x is the formal parameter


a=input(“Enter the number=”)

GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING


92
ROHINI COLLEGE OF ENGINEERING & TECHNOLOGY

b=cube(a) #a is the actual parameter


print”cube of given number=”,b

Result:
Enter the number=2

Cube of given number=8


Scope and Lifetime of variables

Scope of a variable is the portion of a program where the variable is recognized.


Parameters and variables defined inside a function is not visible from outside. Hence, they have
a local scope.

Lifetime of a variable is the period throughout which the variable exits in the memory.
The lifetime of variables inside a function is as long as the function executes.

They are destroyed once we return from the function. Hence, a function does not
remember the value of a variable from its previous calls.
Eg:
def my_func():
x = 10

print("Value inside function:",x)


x = 20
my_func()
print("Value outside function:",x)
Output:
Value inside function: 10
Value outside function: 20

Local Scope and Local Variables

A local variable is a variable that is only accessible from within a given function. Such
variables are said to have local scope .

GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING


93
ROHINI COLLEGE OF ENGINEERING & TECHNOLOGY

Global Variables and Global Scope

A global variable is a variable that is defined outside of any function definition. Such
variables are said to have global scope .

Variable max is defined outside func1 and func2 and therefore “global”
to each.

Function Composition

We can call one function from within another. This ability is called composition.

As an example, we’ll write a function that takes two points, the center of the circle and a
point on the perimeter, and computes the area of the circle.

Assume that the center point is stored in the variables xc and yc, and the perimeter point
is in xp and yp. The first step is to find the radius of the circle, which is the distance between the
two points.

radius = distance(xc, yc, xp, yp)

GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING


94
ROHINI COLLEGE OF ENGINEERING & TECHNOLOGY

The second step is to find the area of a circle with that radius and return it. Again we will
use one of our earlier functions:

result = area(radius)
return result

Wrapping that up in a function, we get:

def area2(xc, yc, xp, yp):

radius = distance(xc, yc, xp, yp)

result = area(radius) return result

We called this function area2 to distinguish it from the area function defined earlier.
There can only be one function with a given name within a given module. The temporary
variables radius and result are useful for development and debugging, but once the program is
working, we can make it more concise by composing the function calls:

def area2(xc, yc, xp, yp):

return area(distance(xc, yc, xp, yp))

Example:

Write a python program to add three numbers by using function:

def addition(x,y,z): #function 1

add=x+y+z

return add

def get(): #function 2

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

b=int(input("Enter second number:"))

c=int(input("Enter third number:"))

print("The addition is:",addition(a,b,c)) #Composition function calling

get() #function calling

GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING


95
ROHINI COLLEGE OF ENGINEERING & TECHNOLOGY

Output:

Enter first number:5

Enter second number:10

Enter third number:15

The addition is: 30

Recursion:
A Recursive function is the one which calls itself again and again to repeat the code. The
recursive function does not check any condition. It executes like normal function definition and
the particular function is called again and again

Syntax:

def function(parameter):

#Body of function

Example-1:

Write a python program to find factorial of a number using Recursion:

(Positive value of n ,then n! can be calculated as n!=(n-1)….2.1 it ncan be written as (n-1)!

Hence n! is the product of n and (n-1)! n!=n.(n-1)! )

def fact(n):

if(n<=1):

return n

else:

return n*fact(n-1)

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

print("The Factorial is", fact(n))

Output:

>>> Enter a number:5

The Factorial is 120

>>>

GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING


96
ROHINI COLLEGE OF ENGINEERING & TECHNOLOGY

Explanation:

First Iteration - 5*fact(4)

Second Iteration - 5*4* fact(3)

Third Iteration - 5*4*3*fact(2)

Fourth Iteration - 5*4*3*2* fact(1)

Fifth Iteration - 5*4*3*2*1

Example-2:

Write a python program to find the sum of a ‘n’ natural number using Recursion:

def nat(n):

if(n<=1):

return n

else:

return n+nat(n-1)

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

print("The Sum is", nat(n))

Output:

>>> Enter a number: 5

The Sum is 15

Explanation:

First Iteration – 5+nat(4)

Second Iteration – 5+4+nat(3)

Third Iteration – 5+4+3+nat(2)

Fourth Iteration – 5+4+3+2+nat(1)

Fifth Iteration – 5+4+3+2+1

GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING


97
ROHINI COLLEGE OF ENGINEERING & TECHNOLOGY

The Advantages of recursion

1. Recursive functions make the code look clean and elegant.

2. A complex task can be broken down into simpler sub-problems using recursion.

3. Sequence generation is easier with recursion than using some nested


iteration.

The Disadvantages of recursion

1. Sometimes the logic behind recursion is hard to follow through.

2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.

3. Recursive functions are hard to debug.

GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING


98

You might also like