Sem 2 Python
Sem 2 Python
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:
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 valueor 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
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")
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
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)
Inline if:
An inline if statement is a simpler form of if statement and is more convenient ,if we
need to perform simple task.
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)
sum=sum+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")
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.
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
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
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”):
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)
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)
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)
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.
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.
[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.
Standardmodules 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)
32
ILLUSTRATIVE PROGRAMS:
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.
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.
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
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]
>>> 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
List methods:
Python provides methods that operate on lists.
syntax:
list [Link] name( element/index/list)
>>>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:
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 canbe 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
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 tuplehas 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
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
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
Methods in 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.
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.
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)
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)
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.
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
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:
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]'
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]'
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.
randomList = ['a', 0, 2]
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
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.
If this construct seems lengthy, we can import the module without the package prefix as follows.
from [Link] import start
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
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.
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.
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')
‘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')
output_file=open('[Link]','w')
output_file.close()
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]()
>>> x = 52
>>> [Link](str(x))
>>> 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:
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:
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:
[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.
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
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].
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:
This statement creates a module object named math. If you print the module object, you
get some information about it:
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.
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:
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:
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.
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
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).
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.
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.
86
Finally, we create a file named __init__.py inside the Animals directory and put the
following code in it:
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:
myMammal = Mammals()
[Link]()
myBird = Birds()
[Link]()
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,
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.
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):
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
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:
None
>>>type(None)
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
def funct(param1,param2):
statements
return value
Once the function is defined,it can be called from main program or from another function.
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
def cube(x):
Result:
Enter the number=2
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
A local variable is a variable that is only accessible from within a given function. Such
variables are said to have local 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.
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
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:
Example:
add=x+y+z
return add
Output:
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:
def fact(n):
if(n<=1):
return n
else:
return n*fact(n-1)
n=int(input("Enter a number:"))
Output:
>>>
Explanation:
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:"))
Output:
The Sum is 15
Explanation:
2. A complex task can be broken down into simpler sub-problems using recursion.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.