0% found this document useful (0 votes)
22 views51 pages

Vino

The document provides an overview of Python data structures, specifically lists, tuples, and dictionaries. It covers definitions, examples, operations, and methods associated with these data types, including list slicing, negative indexing, and the differences between mutable and immutable types. Additionally, it explains how to create and manipulate these structures, highlighting their unique characteristics and use cases.
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)
22 views51 pages

Vino

The document provides an overview of Python data structures, specifically lists, tuples, and dictionaries. It covers definitions, examples, operations, and methods associated with these data types, including list slicing, negative indexing, and the differences between mutable and immutable types. Additionally, it explains how to create and manipulate these structures, highlighting their unique characteristics and use cases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

1 2

UNIT-IV Example:
>>>a=[1,2,3]
LIST,TUPLES,DICTIONARIES >>>b=a[:]
>>>print b
TWO MARKS: [1,2,3].

1. Define List with example?


5. Illustrate negative indexing in list with an example.
 A List is an ordered set of values, where each value is identified by an index.
 The Values that make up a list are called its elements or items.  Index can have negative value, it counts backward from the list.
Example:
Example 1:[10, 20, 30, 40] # list of four integers >>> Fruit = ['Apple', 'Grapes', 'Orange']
Example 2:['frog', 'Dog', 'Cow'] # list of three strings >>>Fruit(0) = ‘pear’
>>>Fruit(-1) = ‘Jackfruit’
2. What are the list operations? >>>print (fruit)
 Lists respond to the + and * operators much like strings; they mean concatenation and [‘pear’, ‘grape’, ‘Jackfruit’]
repetition here too, except that the result is a new list, not a string.
6. What is Aliasing?
 The + operator concatenates lists:
 More than one list variable can point to the same data. This is called an alias.
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]  If ‘A’ refers to an object and you assign ‘ B = A’, then both variables refer to the same
>>> c = a + b object:
>>> print c >>> A = [1, 2, 3]
[1, 2, 3, 4, 5, 6] >>> B= A
>>> B is A
 Similarly, the * operator repeats a list a given number of times: True
>>> [0] * 4
[0, 0, 0, 0]# It repeats [0] four times
>>> [1, 2, 3] * 3 7. What is the purpose of list methods? Types of List method?
[1, 2, 3, 1, 2, 3, 1, 2, 3] # It repeats the list [1, 2, 3] three times.  Python has a number of built-in data structures, including lists.
 Data structures provides us with a way to organize and store data.
3. Describe list slicing with examples.  We can use built-in methods to retrieve or manipulate that data.

 A sub-sequence of a sequence is called a slice and the operation that performs on


1.List.append( ) 5.List.insert ( ) 9.List.reverse( )
subsequence is called slicing.
2.List.remove( ) 6.List.pop ( ) 10.List.clear ( )
The slice operator also works on lists: 3.List.copy ( ) 7.List.sort ( ) 11.List.index ( )
>>> t = ['a', 'b', 'c', 'd', 'e', 'f'] 4.List. Count ( ) 8.List.extend ( )
>>> t[1:3]
Output : ['b', 'c'] 8. What is the List Parameter?
 Passing a list as an argument actually passes a reference to the list, not a copy of the list.
>>> t[:4] Since list mutable changes made to the parameter changes the argument as well.
Output:['a', 'b', 'c', 'd']  When you pass a list to a function, the function gets a reference to the list. If the function
modifies a list parameter, the caller sees the change.
>>> t[3:]
Output:['d', 'e', 'f']
For example, delete_head removes the first element from a list:
>>> t[:] def delete_head(t):
Output : ['a', 'b', 'c', 'd', 'e', 'f'] del t[0]
Here’s how it is used:
4. What is Cloning of List? >>> letters = ['a', 'b', 'c']
 Cloning is the process of modifying a list and also keeps a copy of the original.
The entire list is copied not just the reference. >>> delete_head(letters)
 This process is sometimes called cloning, to avoid the ambiguity of the copy. >>> print letters
 The easiest way to clone a list is to use the slice operator. ['b', 'c'].
3 4

9. Define Tuples? Example:


 A tuple is a sequence of values. >>> a = [11,22,33,44]
 The values can be any type, and they are indexed by integers, so in that respect tuples are a >>> b =[x*2 for x in a]
lot like lists. The important difference is that tuples are immutable. >>>b
[22,44,66,88]
Syntactically, a tuple is a comma-separated list of values:
>>> t = 'a', 'b', 'c', 'd', 'e'
Although it is not necessary, it is common to enclose tuples in parentheses: 13. List the function of Tuple Data Types?
>>> t = ('a', 'b', 'c', 'd', 'e')
S.No Function Description
1 Cmp(tup1,tup2) Compare elements of both tuples
To create a tuple with a single element, you have to include the final comma:
>>> t1 = ('a',) 2 Len(tuple) Gives the total length of the tuple
>>> type(t1) 3 Max(tuple) Returns item from the tuple with max value
<type 'tuple'> 4 Min(tuple) Returns item from the tuple with min value
5 Sorted(tuple) Sort the tuple in ascending or descending
10. Give Example for Tuple Assignment?

 One of the unique features of the python language is the ability to have a tuple on the left 14. What is the difference between Tuples and List in Python?
hand side of an assignment statement.
 This allows you to assign more than one variable at a time when the left hand side is a  The main difference between list and tuples are:
sequence.  List are enclose in square bracket [ ] and their elements size can be changed, while tuples
are enclosed in parentheses ( ) and cannot be updated.
Example:
Two element in list (which is a sequence ) and assign the first and second elements of the variables
15. Define Mutable and Immutable data type?
x and y in a single statement.

>>> m = ( ‘have’, ‘fun’)  Immutable data value: A data value which cannot be modified. Assignments to elements
>>> x,y= m or slices of immutable values causes a runtime error
>>> x  Mutable data value: A data value which can be modified .The Types of all mutable value
‘have’ are compound types.List and dictionaries are Mutable; Strings and Tuple are not.
>>>y
‘fun’
16. Differentiate between append( ) and extend ( ) methods?
11. Give Example for Tuple as Return Values?  Both append ( ) and extend ( ) methods belong to the list method.These methods are used to
add the elements to the list.
 A function can only return one value, but if the value is a tuple, the effect is the same as  Append(element) – adds the given element at the end of the list or at the given index
returning multiple values. postion which has called this method
Example:
 Extend (another_list)- adds the element of another-list at the end of the list which is called
>>> t = divmod(7, 3) the extend method.
>>> print t
(2, 1) 17. When is a dictionary used instead of a list?
Or use tuple assignment to store the elements separately:  Dictionaries are best suited when the data is labelled ie. The data is a record with field
>>> quot, rem = divmod(7, 3) names.
>>> print quot
2  List are better option to store collection of un-labelled items say all the files and sub-
>>> print rem directories in a folder.
1  Generally search operation on dictionary object is faster than searching a list objects

12. What is List comprehension?Give Eg.


 A list Comprehension is a convenient way to produce a list from an iterable (a sequence
or other object that can be iterated over).
 In the simplest form, a list comprehension resembles the header line of a “for Statement”
inside square brackets.
.
Syntax : [Expr(x) for x in iterable]
5 6

18. Differentiate between tuples and dictionaries.


22. List out the methods on dictionaries?
Tuples Dictionaries
 A tuple is a sequence of values.  Python dictionary are kind of hash table S.No Method Description
 The values can be any type, and they are type.
indexed by integers, so in that respect  Dictionary work like associative arrays or 1 dict.clear() Removes all elements of dictionary dict
tuples are a lot like lists. The important hashes found in perl and consist of key 2 dict.copy() Removes all elements of dictionary dict
difference is that tuples are immutable. value pairs.
3 dict.items() Returns a list of dict's (key, value) tuple pairs
4 dict.keys() Returns list of dictionary dict's keys
19. Define dictionary with an example. 5 dict.values() Returns list of dictionary dict's values

 Dictionary is one of the compound data type like strings, list and tuple. Every element in a
23. List out the operations on dictionaries?
dictionary is the key-value pair.
 An empty dictionary without any items is written with just two curly braces, like this: {}.
Operation Description
Example: cmp(dict1, dict2) Compares elements of both dict.
>>> eng2sp = {} len(dict) Gives the total length of the dictionary.
>>> eng2sp["one"] = "uno"
>>> eng2sp["two"] = "dos" str(dict) Produces a printable string representation of a dictionary
>>> print(eng2sp)
type (variable) Returns the type of the passed variable. If passed variable is dictionary,
then it would return a dictionary type.
Output:
{"two": "dos", "one": "uno"}

20. What is the output of Print List + tinylist*2?


If List = [‘abcd’, ‘786’, ‘2.23’, ‘Nita’, ‘70.2’] and tinylist = [‘123’, ‘Nita’]?
 It will print the concatenated list since it has the (+) operator.
 Ouput will be [‘abcd’, ‘786’, ‘2.23’, ‘Nita’, ‘70.2’, ‘123’, ‘Nita’, ‘123’, ‘Nita’]

21. How will u create a Dictionary in Python?

 A dictionary can be Created by specifying the key and value separated by colon(:) and the
elements are separated by comma (,).The entire set of elements must be enclosed by curly
braces {}.

Syntax: #To Create a Dictionary with Key-Value Pairs:

dict={Key 1:Value 1, Key 2:Value 2, Key 3:Value 3, Key 4:Value 4}

#To create an empty Dictionary

Dict={ }
7 8

16 MARKS Output:
(‘one’,’three’)
1. What is List Values? Describe about creating a list, accessing the values in list, deleting a list,
UPDATING A LIST:
updating a list.
A slice operator on the left side of an assignment can update multiple elements:
LIST VALUES: >>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
 A List is an ordered set of values, where each value is identified by an index. >>> print t
 The Values that make up a list are called its elements or items. Output: ['a', 'x', 'y', 'd', 'e', 'f'].
 Lists are similar to strings, which are ordered set of characters, except that the element of
a list can have any type.

CREATING A LIST: 2. Explain the basic List Operations and list slices in details with necessary programs.

There are several ways to create a new list, the simplest is to enclose the elements in square Bracket LIST OPERATIONS:
[] 24. Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.
[10, 20, 30, 40] # list of four integers
['frog', 'Dog', 'Cow'] # list of three strings
Python Expression Description Results
The elements of a list don’t have to be the same type. len([1, 2, 3]) Length 3
['spam', 2.0, 5, [10, 20]] # list contains a string, a float, an integer, and another list: [1, 2, 3] + [4, 5, 6] Concatenation [1, 2, 3, 4, 5, 6]
['Hi!'] * 4 Repetition ['Hi!', 'Hi!', 'Hi!', 'Hi!']
A list within another list is nested. 3 in [1, 2, 3] Membership True
A list that contains no elements is called an empty list;
We can create one with empty brackets []. The + operator concatenates lists:
>>> a = [1, 2, 3]
ACCESSING VALUES IN LIST: >>> b = [4, 5, 6]
>>> c = a + b
>>> print c
We can assign list values to variables: [1, 2, 3, 4, 5, 6]
>>> Fruits = ['Apple', 'Watermelon', 'Banana']
>>> numbers = [17, 12.3] Similarly, the * operator repeats a list a given number of times:
>>> empty = [ ] >>> [0] * 4
>>> print ( Fruits) [0, 0, 0, 0]# It repeats [0] four times
>>>print( numbers) >>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3] # It repeats the list [1, 2, 3] three times.
>>>print(empty)
LIST SLICES:
Output:  A sub-sequence of a sequence is called a slice and the operation that performs on
['Apple', 'Watermelon', 'Banana'] subsequence is called slicing.
[17, 12.3] The slice operator also works on lists:
[] >>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
DELETING A LIST: Output : ['b', 'c']

 Any element in the list can be deleted, del removes an element from a list. >>> t[:4]
Output:['a', 'b', 'c', 'd']
Example:
>>> a=(‘one’,’two’,’three’) >>> t[3:]
>>>del a(1) Output:['d', 'e', 'f']
>>>a
9 10

>>> t[:] 5. List.pop ( ) 6. List.Sort ( )


Output : ['a', 'b', 'c', 'd', 'e', 'f']  List.pop ( ) method is used to return the  List.Sort ( ) method is used to sort the
item at the given index position from the items in the list.
Since lists are mutable, it is often useful to make a copy before performing operations.. list and the removes that item.
A slice operator on the left side of an assignment can update multiple elements: Example
Example X = [54, 12, 85, 65, 74, 90];
>>> t = ['a', 'b', 'c', 'd', 'e', 'f'] X = [123, 'xyz', 'zara', 'abc']; Print(“sorted list:”, X.sort ( ))
>>> t[1:3] = ['x', 'y'] Print( “List 1 :”,X.pop(0))
>>> print t Print (“List 2: ”, X.pop(3)) Output:
Output: ['a', 'x', 'y', 'd', 'e', 'f']. Output: Sorted list= [12,54 ,65,74,85,90]

List 1: [ 'xyz', 'zara', 2009,'abc'];


3. Discuss the Python List Methods with examples.(16 mark) List 2: [123, 'xyz', 'zara',]

Python provides methods that operate on lists. 7.List.reverse ( ) 8. List.clear ( )


 List.reverse ( )can reverse the order of  List.clear() can remove all values
The various methods used in list are: items in a list by using this method. contained in it by using this method.

1.List.append( ) 5.List.pop ( ) 9. List.clear ( ) Example Example


2.List.remove( ) 6.List.sort ( ) 10. List.index ( ) X = [123, 'xyz', 'zara', 'abc',’xyz’]; X = [123, 'xyz', 'zara', 'abc',’xyz’];
3. List. Count ( ) 7.List.extend ( ) X.reverse( ) X..clear( )
4. List.insert ( ) 8.List.reverse( ) Print ( “List 1 :”,X) Print (X)

1.List.append( ): 2. List.remove ( ) Output: List 1: ['xyz', 'abc', 'zara', 'xyz', Output:


123] []
 The method append () appends a passed  List.remove() method is to remove the
obj into the existing list. object from the list.
 List.remove() method does not return any  We get square bracket as our output after
Example value but removes the given object from using list.clear ( ) method , it implies that
Eg 1: the list. the list is now clear of all items.
x = [123, 'xyz', 'zara', 'abc']; Example 9.List.index ( ) 10.List.extend ( )
x.append ( 2009 ); y = [123, 'xyz', 'zara', 'abc', 'xyz'];  When list starts to get long, it becomes  If we want to combine more than one list
print ( "Updated List : ", x) y.remove('xyz'); more difficult for us to count out the , we use extend method .
Output: Updated List: [123, 'xyz', 'zara', 'abc', print( "List 1 : ", y); items in the list.
2009] y.remove('abc');  So we determine at what index position Example
print( "List 2: ", y) the items are located. Eg 1:
Eg 2: Output: X = [123, 'xyz', 'zara', 'abc', 123];
>>> t = ['a', 'b', 'c'] List 1: [123, 'zara', 'abc', 'xyz'] Example Y = [2009, 'manni'];
>>> t.append('d') List 2: [123, 'zara', 'xyz' x = [123, 'xyz', 'zara', 'abc']; X.extend(Y)
>>> print ( t) Print(“Index for xyz:”, x.index(‘xyz’)) Print(X)
Output:['a', 'b', 'c', 'd'] Print(“Index for 123:”,x.index(123))
3. List.count ( ) 4. List.insert ( ) Print(“Index for zara:”,x.index(‘Zara’) Output:
Extended List= [123, 'xyz', 'zara', 'abc', 123,2009,
 The method returns the count of how  List.insert ( ) method inserts an object
Output: ‘manni’];
many times an element occurs in specified into the list at the offset of an index.
Index for xyz: 1
list.  Syntax : List.insert (index,object) #index
Index for 123: 0
Example position starts from 0.
Index for zara: 2
X = [123, 'xyz', 'zara', 'abc', 'xyz',123, ‘xyz’]; Example
Print (“Count for 123:”,X.count(123)) X = [123, 'xyz', 'zara', 'abc'];
Print (“Count for Zara:”,X.count(‘zara’)) X.insert (3,2009)
Print (“Count for xyz:”,X.count(‘xyz’)) Print( “Final List :”,X)

Output: Output:

Count for 123: 2 Final List: [123, 'xyz', 'zara', 2009,'abc'];


Count for Zara: 1
Count for xyz: 3
11 12

4. Discuss about the list loop, list mutability with examples.(8 mark)

 In List loop, we use a loop to access all the element in a list. A loop is a block of code that  Lists are represented by boxes with the word “list” outside and the elements of the list
repeats itself until it run out of items to work with or until a certain condition is met. inside.
 Our loop will run once for every item in our list,  Fruits refer to a list with three elements indexed 0, 1 and 2.
 Numbers contains two elements; the diagram shows that the value of the second element has
#LIST LOOPING EXAMPLE 1: been reassigned from 123 to 5.
Colours_list=[“red”, “green”, “yellow”, “blue”, “purple”] .
for i in colours_list: The in operator also works on lists.
Print(i) >>> Fruit = ['Apple', 'Grapes', 'Orange']
Output: >>> ‘Apple’ in Fruit
Colours in the list True
Red >>> ‘Watermelon’ in Fruit
Green False
Yellow
Blue Index can have negative value, it counts backward from the list.
Purple. Example:
EXAMPLE 2:
Month_list = [“Jan”, “Feb”, “March”, “April”, “May”] >>> Fruit = ['Apple', 'Grapes', 'Orange']
Print(“months in the list”) >>>Fruit(0) = ‘pear’
for month in month_list: >>>Fruit(-1) = ‘Jackfruit’
Print (month) >>>print (fruit)
OUTPUT: [‘pear’, ‘grape’, ‘Jackfruit’]
Months in the list
Jan #List Mutable Example
Feb Colours_list=[“red”, “green”, “blue”, “purple”]
March Print (“original list:”,colour_list)
April #red is changed to pink
May Colour_list[0]= “pink”

#blue is change to orange


List Mutability: Colour_list [-2] = “orange”
Print(colour_list)
 Mutability is the ability for certain types of data to be changed without entirely recreating it.
 List is a mutable data type; which mean we can change their element.
 The syntax for accessing the elements of a list is the same as for accessing the characters of Output:
a string—the bracket operator. Original List =[“red”, “green”, “blue”, “purple”]
 The expression inside the brackets specifies the index. Remember that the indices start at 0. [“pink”, “green”, “orange”, “purple”].

>>> Fruit = ['Apple', 'Grapes', 'Orange'] 5. Discuss about the list aliasing, cloning list and list parameter with examples.
>>>print (fruit(0))
Apple LIST ALIASING:
>>> numbers = [17, 123]
 Since variables refer to object, If ‘A’ refers to an object and you assign ‘ B = A’, then both
>>> numbers[1] = 5
>>> print numbers variables refer to the same object:
[17, 5] >>> A = [1, 2, 3]
List >>> B= A
List >>> B is A
Number 0  17 True
Fruit 0  “Apple”
1  “Grapes” 1 123  In this case, Diagram looks like this
2  “Orange”
5 A

[1,2,3]

B
13 14

 The parameter t and the variable letters are aliases for the same object. The stack diagram
looks like this:
 The association of a variable with an object is called a reference. In this example, there are
two references to the same object.
 An object with more than one reference has more than one name, then the object is said to __Main__ Letters
be aliased. 0  ‘a’
If the aliased object is mutable, changes made with one alias affect the other:
1  ‘b’
>>> B[0] = 9
>>> print A Delete_head t 2  ‘c’
[9, 2, 3]
 Although this behaviour can be useful, it is error-prone. In general, it is safer to avoid
aliasing when you are working with mutable objects.  Since the list is shared by two frames, I drew it between them.
 It is important to distinguish between operations that modify lists and operations that create
 For immutable objects like strings, aliasing is not as much of a problem. new lists.
For example, the append method modifies a list, but the + operator creates a new list:
In this example: >>> t1 = [1, 2]
A = ('banana') >>> t2 = t1.append(3)
B=( 'banana')
>>> print t1
It almost never makes a difference whether A and B refer to the same string or not.
[1, 2, 3]
>>> print t2
CLONING LIST:
None
 If we want to modify a list and also keep a copy of the original, we need to be able to make
>>> t3 = t1 + [3]
a copy of the list itself, not just the reference.
>>> print t3
 This process is sometimes called cloning, to avoid the ambiguity of the copy.
[1, 2, 3]
 The easiest way to clone a list is to use the slice operator
>>> t2 is t3
>>>a=[1,2,3]
False.
>>>b=a[:]
>>>print b
6. Explain about tuples and also the concept of tuple assignment and tuples as return value with
[1,2,3] example.
 Taking any slice, creates a new list. In this case the slice happens to consists of the whole  A tuple is a sequence of values.
list.  The values can be any type, and they are indexed by integers, so in that respect tuples a like
 Now we are free to make changes to b without worrying about list ‘a’. lists. The important difference is that tuples are immutable.
>>>b[0]=5
 Syntactically, a tuple is a comma-separated list of values:
>>>print a
>>> t = 'a', 'b', 'c', 'd', 'e'
>>>print b  Although it is not necessary, it is common to enclose tuples in parentheses:
[1,2,3] >>> t = ('a', 'b', 'c', 'd', 'e')
[5,2,3]
 To create a tuple with a single element, you have to include the final comma:
LIST PARAMETERS: >>> t1 = ('a',)
>>> type(t1)
 Passing a list to a function, the function gets a reference to the list. If the function modifies a <type 'tuple'>
list parameter, the caller sees the change.
 Without the comma, Python treats ('a') as a string in parentheses:
>>> t2 = ('a')
For example, delete_head removes the first element from a list:
>>> type(t2)
def delete_head(t): <type 'str'>
del t[0]
Here’s how it is used:  Another way to create a tuple is the built-in function tuple. With no argument, it creates an
>>> letters = ['a', 'b', 'c'] empty tuple:
>>> delete_head(letters) >>> t = tuple()
>>> print (t)
>>> print letters
()
['b', 'c']
15 16

Tuple assignment is more elegant:


 If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of >>> a, b = b, a
the sequence:  The left side is a tuple of variables; the right side is a tuple of expressions. Each value is
>>> t = tuple('lupins') assigned to its respective variable. All the expressions on the right side are evaluated before
>>> print (t) any of the assignments.
('l', 'u', 'p', 'i', 'n', 's')  The number of variables on the left and the number of values on the right have to be the
same:
 Because tuple is the name of a built-in function, avoid using it as a variable name. >>> a, b = 1, 2, 3

 Most list operators also work on tuples. The bracket operator indexes an element: ValueError: too many values to unpack.
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print (t[0])
'a' TUPLES AS RETURN VALUES:
And the slice operator selects a range of elements.
>>> print t[1:3]  A function can only return one value, but if the value is a tuple, the effect is the same as
('b', 'c') returning multiple values.
But if you try to modify one of the elements of the tuple, you get an error:  For example, if you want to divide two integers and compute the quotient and remainder, it
>>> t[0] = 'A' is inefficient to compute x/y and then x%y. It is better to compute them both at the same
TypeError: object doesn't support item assignment time.
 The built-in function divmod takes two arguments and returns a tuple of two values, the
 can’t modify the elements of a tuple, but you can replace one tuple with another: quotient and remainder.
>>> t = ('a', 'b', 'c', 'd', 'e') You can store the result as a tuple:
>>>t = ('A',) + t[1:] >>> t = divmod(7, 3)
>>> print (t) >>> print t
('A', 'b', 'c', 'd', 'e') (2, 1)
TUPLE ASSIGNMENT: Or use tuple assignment to store the elements separately:
>>> quot, rem = divmod(7, 3)
 One of the unique features of the python language is the ability to have a tuple on the left >>> print quot
hand side of an assignment statement. 2
 This allows you to assign more than one variable at a time when the left hand side is a >>> print rem
sequence. 1

In the below example , we have two element list (which is a sequence ) and assign the first and Example of a function that returns a tuple:
second elements of the variables x and y in a single statement. def min_max(t):
>>> m = ( ‘have’, ‘fun’) return min(t), max(t)
>>> x,y= m max and min are built-in functions that find the largest and smallest elements of a sequence.
>>> x min_max computes both and returns a tuple of two values.
‘have’
>>>y
‘fun’
7. What is dictionary in python? List out the operations and methods with example.
Python roughly translates the tuple assignment syntax to be the following;
 Keys are unique within a dictionary while values may not be.
>>>m = (‘have’, ‘fun’)
>>>x = m(0)  The values of a dictionary can be of any type, but the keys must be of an immutable data
>>>y = m(1) type such as strings, numbers, or tuples.
>>>x  Dictionary is one of the compound data type like strings, list and tuple. Every element in a
‘have’ dictionary is the key-value pair.
>>>y  An empty dictionary without any items is written with just two curly braces, like this: {}.
‘fun’
 It is often useful to swap the values of two variables. With conventional assignments, you Creating a Dictionary:
have to use a temporary variable. For example, to swap a and b:  A dictionary can be Created by specifying the key and value separated by colon(:) and the
>>> temp = a elements are separated by comma (,).The entire set of elements must be enclosed by curly
>>> a = b braces {}.
>>> b = temp
17 18

Updating Element in Dictionary:


 In Dictionary the Keys are immutable, however the values are mutable.
 Hence only the Value pair can be Updated
Syntax: #To Create a Dictionary with Key-Value Pairs:
Example
dict={Key 1:Value 1, Key 2:Value 2, Key 3:Value 3, Key 4:Value 4}
>>> My_dict={'Name':'Nivetha','rank':5,'Average':78.9}
#To create an empty Dictionary
>>> My_dict['rank']=3
Dict={ } >>> My_dict
{'Name': 'abi', 'rank': 3, 'Average': 78.9}

Example: DICTIONARY METHODS:


#Keys-Value can have mixed datatype
S.No Method Description
Dict1 = {1: “Fruit”, 2: “Vegetabe”,3: “Fish”}
Dict2={“Name”: “Zara”, “Subject”:[“Maths”, “Phy”, “Chemistry”], “Marks”:[198,192,193], 1 dict.clear() Removes all elements of dictionary dict
“Avg”:92} 2 dict.copy() Removes all elements of dictionary dict
3 dict.items() Returns a list of dict's (key, value) tuple pairs
Accessing Elements in Dictionary:
 To access dictionary elements, you can use the familiar square brackets along with the key 4 dict.keys() Returns list of dictionary dict's keys
to obtain its value. 5 dict.values() Returns list of dictionary dict's values
 Since Dictionary is an unordered Data type. Hence the indexing operator cannot be used to
6 dict.update(dict2) Adds dictionary dict2's key-values pairs to dict
access the Values.
 To access the data, we have to use key which is associated with the Value. 7 dict.fromkeys()
Create a new dictionary with keys from seq and
values set to value.
Example: 8 dict.get(key, default=None) For key, returns value or default if key not in dictionary
>>Dict2={“Name”: “Zara”, “Subject”:[“Maths”, “Phy”, “Chemistry”],
“Marks”:[198,192,193], “Avg”:92} dict.has_key(key)
9 Returns true if key in dictionary dict, false otherwise
>>Dict2[“Name”]
>>Dict2[“Avg”]
>>Dict2[“Subject”] DICTIONARY OPERATION:
Operation Description Input Function Output
Output: Dict1={“Name”:”zara”,”Age”:14,”sex”:”M Cmp(dict1,di 1
Compares
Zara cmp(dict1, ”} ct2) 0
20.1 dict2) elements of both
Dict2={“Name”:”zara”,”Age”:14} Cmp(dict2,d
[“Maths”, “Phy”, “Chemistry”] dict.
Dict3={“Name”:”zara”,”Age”:14} ict3)
len(dict) Gives the total Dict1={“Name”:”zara”,”Age”:14,”sex”:”M Len(dict1) 2
Deleting Element in Dictionary: length of the
 The element in the dictionary can be deleted by using Del statement. dictionary. ”} Len(dict2) 3
Dict2={“Name”:”zara”,”Age”:14}
 The entire dictionary can be deleted by specifying the dictionary variable name.
str(dict) Produces a Dict1={“Name”:”zara”,”Age”:14,”sex”:”M Str(dict1) {“Name”:
printable string ”zara”,”A
Syntax: Del (dictionary_Name)<Key-Value> representation of a ”} ge”:14,
dictionary ,”sex”:”M
Example: ”}
type Returns the type of Dict1={“Name”:”zara”,”Age”:14,”sex”:”M Type(dict1) <type
>>> dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} (variable) the passed variable. ‘dict’>
If passed variable ”}
>>> del dict['Name']
is dictionary, then
>>> dict it would return a
{'Age': 7, 'Class': 'First' dictionary type.
19 20

Example: Example 4:
>>>dict1 = {1: “Fruit”, 2: “Vegetabe”,3: “Fish”} My_list=[]
>>>Print(dict1) for x in [20,40,60]:
>>>{1: “Fruit”, 2: “Vegetabe”,3: “Fish”} for y in [2,4,6]:
>>> del dict[1] My_list.append(x*y)
>>>print(dict1) print (My_list)
>>>{ 2: “Vegetabe”,3: “Fish”} Output: [40, 80, 120, 80, 160, 240, 120, 240, 360]
Note: This code multiplies the items in the first list (x) by the items in the second list (y) over each
The len function also works on dictionaries; it returns the number of key:value pairs: iteration
>>> len(dict1) Program For Example 4 using List Comprehension
3
My_list=[x*y for x in [20,40,60] for y in [2,4,6]]
print(My_list)
8. Illustrate List Comprehension with suitable examples.
Output: [40, 80, 120, 80, 160, 240, 120, 240, 360]
(or)
List Comprehensions allows us to transform one list or other sequence into a new list. They Provide
Explain about the advanced list processing.
a concise syntax for completing the task and limiting the lines of code.
Example 5:
 A list Comprehension is a convenient way to produce a list from an iterable (a sequence or
#To create a simple list
other object that can be iterated over).
x=[ i for i in range (10)]
 In the simplest form, a list comprehension resembles the header line of a “for Statement” inside
print (x)
square brackets.
Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 However,in a list Comprehension, the for statement header is prefixed with an expression and
surrounded by square bracket.
ILLUSTRATIVE PROGRAMS:
Syntax : [Expr(x) for x in iterable] 1. SELECTION SORT:
def selectionSort(alist):
Where: for fill slot in range(len(alist) - 1, 0, -1):
Expr(x) is an expression,usually but not always containing X. positionOfMax = 0
Iterable is some iterable.An itrable may be a sequence or an unordered collection a list, string or for location in range(1, fillslot + 1):
tuple. if alist[location] >alist[positionOfMax]:
Example 1: positionOfMax = location
temp = alist[fillslot]
>>> a = [11,22,33,44]
alist[fillslot] = alist[positionOfMax]
>>> b =[x*2 for x in a] alist[positionOfMax] = temp
>>>b alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
[22,44,66,88] selectionSort(alist)
Example 2: print(alist)
Given the following list of strings:
Names= [‘alice’, ‘ramesh’, ‘nitya’] OUTPUT:
[26, 54, 93, 17, 77, 31, 44, 55, 20]
A list of all upper case Names
A List of Capitalized ( first letter upper case)
2. INSERTION SORT:
>>>[x.upper() for x in names]
def insertionSort(alist):
[‘ALICE’, ‘RAMESH’, ‘NITA’]
for index in range(1,len(alist)):
>>>[x.capitalize() for x in names] currentvalue = alist[index]
[‘Alice’ , ‘Ramesh’ , ‘Nita’] position = index
Example 3: while position > 0 and alist[position - 1] >currentvalue:
>>> fish_tuple=('blowfish','clowfish','catfish','octopus') alist[position] = alist[position - 1]
>>> fish_list=[fish for fish in fish_tuple if fish != 'octopus'] position = position - 1
>>> print(fish_list) alist[position] = currentvalue
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
['blowfish', 'clowfish', 'catfish'] insertionSort(alist)
print(alist)
21 22

OUTPUT: Splitting [31]


[54, 26, 93, 17, 20, 77, 31, 44, 55] Merging [31]
Merging [31, 77]
3. MERGE SORT: Splitting [44, 55, 20]
def mergeSort(alist): Splitting [44]
print("Splitting ",alist) Merging [44]
if len(alist)>1: Splitting [55, 20]
mid = len(alist)//2 Splitting [55]
lefthalf = alist[:mid] Merging [55]
righthalf = alist[mid:] Splitting [20]
mergeSort(lefthalf) Merging [20]
mergeSort(righthalf) Merging [20, 55]
i=0 Merging [20, 44, 55]
j=0 Merging [20, 31, 44, 55, 77]
k=0 Merging [17, 20, 26, 31, 44, 54, 55, 77, 93]
while i <len(lefthalf) and j <len(righthalf):
if lefthalf[i] <righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i <len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j <len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)

OUTPUT:
Splitting [54, 26, 93, 17, 77, 31, 44, 55, 20]
Splitting [54, 26, 93, 17]
Splitting [54, 26]
Splitting [54]
Merging [54]
Splitting [26]
Merging [26]
Merging [26, 54]
Splitting [93, 17]
Splitting [93]
Merging [93]
Splitting [17]
Merging [17]
Merging [17, 93]
Merging [17, 26, 54, 93]
Splitting [77, 31, 44, 55, 20]
Splitting [77, 31]
Splitting [77]
Merging [77]
PROBLEM SOLVING & PYTHON PROGRAMMING 8. What are the rules for drawing a flowchart?
UNIT – I ALGORITHMIC PROBLEM SOLVING  The standard symbols should only be used.
PART-A  The arrowheads in the flowchart represent the direction of flow in the problem.
 The direction of the flow from top to bottom (or) left to right.
1. What is an algorithm?  The flow lines should not cross each other.
Algorithm is defined as a step by step procedure for solving any problem. The sequence of steps to be  Keep flowchart as simple as possible.
performed in order to solve a problem by the computer is known as an algorithm.  Words in the flowchart should be common and easy to understand.
 More than one flowcharts connected by using connectors.
2. What are the characteristics of an algorithm?
 Algorithm has a finite number of inputs. 9. What are the rules for writing Pseudocode?
 Every instruction should be precise and unambiguous.  Write one statement per line.
 Ensure that the algorithm has proper termination.  Capitalize initial keywords.
 Effectiveness of each step is very important.  Ident to show hierarchy.
 The desired output must be obtained only after the algorithm terminates.  End multi line structure.
 The algorithm should be in sequence.  Keep statement language independent.

3. How can measure the quality of algorithm? 10. List out the basic design structure (or) basic logic structure.
 Time - Lesser the time taken better the quality.  Sequence structure.
 Memory - Require minimum computer memory.  Selection structure.
 Accuracy – Should provide accurate result.  Loop structure.
 Sequence - Procedure of an algorithm in a sequential form.
 Generality – fit to all type of inputs. 11. List out the advantages of flowchart.
 Communication.
4. What are the kinds of statement available in algorithm?  Effective analysis.
 Simple statement  Proper documentation.
 Compound Statement.  Efficient coding.
 Proper Testing and Debugging.
5. What are the representations of algorithm?  Efficient Program Maintenance.
 Normal English
 Program 12. What are the limitations (or) disadvantages of flowchart?
 Flowchart  Complex Logic
 Pseudo code  Alteration or Modification
 Decision table  No update.

6. What is Flowchart? Why it is required? 13. List the advantages of Pseudocode.


Flowchart is a diagrammatic representation (or) graphical representation of an algorithm, often used in  Can be done easily on a word processor
the design phase of programming to work out the logic flow of a program.  Easily modified
 No symbols are used
7. What is Pseudocode?  It is simple because it uses English-like statements.
Pseudocode came from two words. Pseudo and Code Pseudo means imitation and Code  No specific syntax is used.
refer to instructions written in a programming language.
14. List out the Disadvantages of Flowchart.
 It’s not visual
 There is no accepted standard. 21. List the advantages of Recursive functions.
 Cannot be compiled not executed.  Recursion can produce simpler, more natural solutions to a problem.
 It is written with less number of statements.
15. Define Functions.  Recursive functions are effective.
Functions are “self-contained” modules of code that accomplish a specific task. Functions usually “take  It requires few variables which makes program clean.
in” data, process it, and “return” a result.  It is useful for branching.

16. What are the elements of functions? 22. List the applications of iteration algorithm.
 Function declaration  Factorial of a given number.
 Function call  Reverse of a number.
 Function definition  Fibonacci series.
 Convert the string into lowercase.
17. Define State  Sum of digits.
 Sate is the result of a test (or) condition.  Armstrong number.
 If the result is “TRUE”, take a certain course of action and if the result is “FALSE”, take another
course of action. 23. List the applications of recursion algorithm.
 Factorial of a given number using recursion.
18. Give the types of programming languages used in computer programming.  GCD using recursion
 Machine language  Towers of Hanoi.
 Assembler language  8 Queen Problem.
 High level programming language.
24. Differentiate testing and debugging
19. What are the steps required to solve the problem using algorithm?
 Understanding the problem. Testing Debugging
 Ascertaining the capabilities of the computational device. Finding and locating the defect. Fixing the defect.
Done by testing team. Done by development team.
 Choosing between exact and approximate problem solving.
Testing is to find the defects Debugging is to remove the defects
 Algorithm design techniques.
 Method of specifying an algorithm
 Proving an algorithm’s correctness
 Analysing an algorithm.
 Coding an algorithm.
20. Differentiate Iteration and Recursion.

Iteration Recursion
An iterative function is one that loops to repeat A recursive is a function calls itself repeatedly
some part of the code. until some specified condition has been satisfied.
Iterative approach involves four steps, In recursive function, only base condition
initialization, condition, execution and updation. (terminate condition) is specified.
Whereas iterative approach makes your code
Recursion keeps your code short and simple
longer.
Recursion is slower than iteration due to
Iteration is faster.
overhead of maintaining stack
PART – B
1. What is algorithm? Explain characteristics, quality and representation. 2. Explain in detail about building blocks of algorithms.
Algorithm is defined as a step by step procedure for solving any problem. The
sequence of steps to be performed in order to solve a problem by the computer is known  Instruction/Statements
as an algorithm.  State/Selection
 Control flow
Characteristics of an algorithm:
 Functions
 Algorithm has a finite number of inputs.
 Every instruction should be precise and unambiguous. (i) Instruction/Statements:
 Ensure that the algorithm has proper termination.  A statement is the smallest standalone element of a programming language that
 Effectiveness of each step is very important. expresses some action to be carried out.
 The desired output must be obtained only after the algorithm terminates.
 The algorithm should be in sequence.  An instruction written in a high-level language that commands the computer to
perform a specified action.
Quality of algorithm:
 A program written in a language is formed by a sequence of one or more
 Time - Lesser the time taken better the quality. statements. A statement may have internal components like expressions.
 Memory - Require minimum computer memory.
 Accuracy – Should provide accurate result. Kinds of statements:
 Sequence - Procedure of an algorithm in a sequential form. i. Simple statements
 Assignment:A=A+2
 Generality – fit to all type of inputs.
 Goto:goto next;
Representation of algorithm:  Return: return 10;
ii. Compound statements
 Algorithm has a starting point and a final point. Between these two points are the Block:begin------------end
instructions that solve the problem. Do-loop:do-------------while(i!=10)
 Algorithms often have steps that repeat or require decisions. For-loop:for(…)----------------
 Algorithm can be expressed in any language from natural languages to  A statement is executed, with an expression is evaluated.
programming languages.
(ii) State:
Example:
 An algorithm is deterministic automation for accomplishing a goal which, given an
Algorithm (find the area) initial state, will terminate in a defined end-state.
 When an algorithm is associated with processing information, data is read from an
Step 1: start input source or device, written to an output device, and/or stored for further
Step 2: Read the value of radius r processing.
Step 3: calculate area=3.14*r*r  Stored data is regarded as part of the internal state of the algorithm.
Step 4: Print the area of circle.  The state is stored in a data structure.
Step 5: Stop
(iii) Control flow :( Explain the control structures in detail) Pseudocode
IF condition THEN
 Flow of control (or) control flow is the order function calls, instructions, and Process 1
……..
statements are executed or evaluated when a program is running.
……..
 Program control structures are defined as the program statements that specify the ENDIF
order in which statements are executed.
(i)Sequence Control Structures Flowchart
 Sequential control structure is used to perform the actions one after another.
 This structure is represented by writing one process after another. YES
IF
Example CONDITION

PROCESS
Algorithm (Add two numbers) Flowchart

Step 1: Start NO
START
Step 2: Get the value of a and b.
Step 3: c=a+b
Read a, b
Step 4: print value c.
Step 5: End. Example:
C=a+b
Pseudocode IF age>=58 THEN
READ a, b WRITE person gets retirement
Print C ENDIF
C=a+b
WRITE C
END

(ii)Selection Control Structures


 Selection control structures (or) Decision structures allows the program to make a (b) IF…THEN…ELSE Structures
choice between two alternate paths whether it is true or false.
 IF…THEN…ELSE or a case structures are the selection structures. Pseudocode Flowchart
 This logic is used for making decisions.

(a)IF…THEN Structures IF condition THEN


Process 1
 This makes a choice between two processes. If the condition is true it performs …..
the process. If the condition in false it skips over the process. .
ELSE
Process 2
…..
…..
ENDIF
Example
(iv) Functions:
IF n%2= = 0 THEN
WRITE n is even
ELSE  Functions are self-contained modules of code that accomplish a specific task.
WRITE n is odd.  Functions usually take in data, process it, and return a result. Once a function is written,
it can be used again and again.
 Functions can be from inside of other functions.

Importance of function(Need of function)


 It allows to divide the larger programs into sub-programs (or) sub-modules.
(iii) Case Structure  It allows to reuse code instead of rewriting it.
 This is a multiway selection structures that is used to choose one option from many  Functions allow to keep variable namespace clean.
options.  Functions allow to test small parts of our program in isolation from the rest.
 ENDCASE is used to indicate the end of the CASE structure. Steps to Writing a function
 Understand the purpose of the function.
Pseudocode  Define the data that comes into the function from the caller.
CASE TYPE  Define data variables are needed inside the function to accomplish a goal.
Case choice – 1:  Decide on the steps that the program will use to accomplish this goal.
Process 1 Parts of a function
break;
 Function declaration – int add(int,int);
Case choice – 2:
Process 2  Function call – add(a,b);
….  Function definition – int add( int x, int y){ z=x+y,return z}
….
Case choice-n:
Process n
….
END CASE 3. Explain in detail about notations.

Choice (i) Pseudocode:


Flowchart
 Pseudocode is a kind of structure English for designing algorithm.
 Pseudo means false and code refers to instructions written in programming
Choice 1 Choice 2 Choice 3
languages.
Process 1 Process 2 Process 3
 Pseudocode cannot be compiled or executed and there are no real formatting or
syntax rules.
 The benefit of pseudocode is that it enables the programmer to concentrate on
algorithms without worrying about all syntactic details of a particular language.
Example: (ii) Flowchart:

READ num1,num 2
 A flow chart is a diagrammatic representation that illustrates the sequence of operations
Result=num1 +num 2
to be performed to arrive at the solutions.
WRITE result
 Each step in the process is represented by a different symbol and contains a of the
Guidelines for writing pseudocode:
process step.
 Only one statement per line: Readability improves if just one action for the  The flowchart symbols are linked together with arrows showing the flow of directions.
computer is written in one statement.
 Capitalized initial keyword: Keyword like READ,WRITE etc.
Example: IF,ELSE,ENFIF,WHILE,ENDWHILE etc. S.NO NAME OF SYMBOL SYMBOL DESCRIPTION

 Indent to show hierarchy: In loop, states and iterations the logically


dependent statements must be indent. Represent the start and stop
1. Terminal symbols
Example: of the program.
If a>b then
Print a Denoted either an input or
2. Input/Output
output operation.
ELSE
Print b
Denotes the process to be
 End multi-line structures: To improve readability the initial state and end of 3. Process symbol
carried out
the several line must be specified properly.
Example: ENDIF for IF statement. Represent decision making
4. Decision
 Keep statement language independent: The programmer must never use the and branching
syntax of any programming language.
Represent the sequence of
Advantages of pseudocode: 5. Flow lines steps and direction of flow
.Used to connect symbols.
 Can be done easily on a word processor. A connector symbol is
 Easily modified. 6. Connectors
represented by a circle. The
symbol are used to conect
 Implements structured concepts. the flowchart
 No special symbols are used.
 No specific syntax is used
Guidelines For Preparing Flowchart:
Disadvantages of pseudocode:
 In drawing a proper flow chart all necessary requirements should be listed out in logical
 It’s not visual. order.
 Cannot be compiled not executed.  The flowchart should be clear and easy to follow.
 There is no accepted standard, so it varies widely from company to company.  Only one flow line should come out from process symboL
 Only one flow line should enter a decision symbol, but two or more flow lines, can leave Disadvantages of flowcharts:
the decision symbol  Complex logic.
 Alterations and modifications.
 No update.

(iii) Programming Language:


In computer technology, a set of conventions in which instructions for the machine
 Only one flow line is used in conjunction with terminal symbol are written. There are many languages that allow humans to communicate with
computers.
(a)Machine Language
Start Stop  The machine language consists of binary numbers that encode instructions for
the computer.
 Every computer has its own machine language.
Example: 10110101-B5
 If the flow chart becomes complex, it is better to use connector symbol to reduce the (b)Assembler Language
number of flow lines.  An assembler language consists of mnemonics
Example: Adding two numbers  There is one mnemonic for each machine instruction of the computer.
 Each assembler instruction is a mnemonic that corresponds to a unique machine
instruction.
Example:
Start
Add x,y
Sub x,y
…………….
……………..
END
(c)High level language
 A high level programming language allows the programmer to write sentences
in this language which can be easily translated into machine instructions.
Advantages of flow chart:
 The sentences written in a high level programming language are called
 Communication: Flowcharts are better way of communicating the logic of a system.
statements.
 Effective analysis: Problem can be analyzed in effective way.
Example:
 Proper documentation: Programs flowcharts serve as a good proper documentation,
main()
which is need for various purposes. {
 Efficient coding: The flowchart acts as a guide or blueprint during the system if(x<y)
analysis. min=x
 Proper Testing and debugging: Flowchart helps in debugging process. }
4. Explain about algorithmic problem solving in detail. (i) Understanding The Problem:
Or  The given problem must be understood completely.
Explain about the steps needed to solve a problem using algorithm in detail.
 An input to an algorithm specifies an instance of the problem the algorithm solves.
 Algorithms are procedural solutions to problems. (ii) Ascertaining The Capabilities Of The Computational Device:
 These solutions are not answers but specific instructions for getting answers.  After understanding a problem, ascertain the capabilities of the computational
 The sequence of steps for designing and analyzing algorithm follows, device.
1. Understanding the problem.  Sequential algorithm: Instructions are executed one after another, one operation
2. Ascertaining the capabilities of the computational device. at a time.
 Parallel algorithms: The central assumption of the RAM model does not hold for
3. Choosing between exact and approximate problem solving.
some newer computers that can execute operations concurrently, (i.e) in parallel.
4. Algorithm design techniques. (iii) Choosing between exact and approximate problem solving:
5. Method of specifying an algorithm
6. Proving an algorithm’s correctness  Solving the problem exactly is called an exact algorithm.
 Solving it approximately is called an approximation algorithm.
7. Analyzing an algorithm.
8. Coding an algorithm. (iv) Algorithm design techniques:

Understand the problem


 Algorithm design technique is a general approach to solving problems
algorithmically that is applicable to a variety of problems from different areas of
computing.
Decide on:  It provides guidance for designing algorithms for new problem.
Computational means exact vs
approximate, algorithm design (v) Methods of specifying an algorithm:
technique solving  Pseudo code
 Flowchart
Design an algorithm Pseudo code:
 It is a mixture of a natural language and programming language like constructs.
 Pseudo code is usually more precise than programming language.
Prove correctness

Flowchart:
Analyze the algorithm  Flow chart is a method of expressing an algorithm by a collection of connected geometric
shapes containing descriptions of the algorithm steps.

Code the algorithm (vi) Proving an algorithm correctness:


Fig: Algorithm design and analysis process  After specifying the algorithm, it should be proved for its correctness.
 A common technique for proving correctness is to use mathematical induction.
 Tracing the algorithm correctness for specific inputs can be very worthwhile activity, it 5. Explain about Simple Strategies for Defining An Algorithm (Iteration and recursion).
cannot prove the algorithm’s correctness conclusively.
Iteration and recursion are key computer science techniques used in creating algorithms and
 The notion of correctness for approximation algorithms is less straight forward than it is
developing software.
for exact algorithms.
ITERATION
(vii) Analysing an algorithm
 Iterative are programs that follow a path from the starting instruction till the end of the
Three Characteristics of algorithm algorithm.
 Efficiency  Iterative functions are on that loops to repeat some part of the code.
 Simplicity  Using a simple loop to display the numbers from one to ten is iterative process.
 Generality.
Efficiency: Steps to develop an iterative algorithm:
 There are two kinds of algorithm efficiency:  Define problem: The problem that needs iteration has to be identified and defined.
 Time efficiency-Indicating how fast the algorithm runs  Initial conditions: The condition that has to be satisfied, to start the iteration.
 Space efficiency-Indicating how much extra memory it uses.  Define loop variants: The variable that controls the number of iteration has to be
defined.
Simplicity:  Define step: The steps that are to be repeated must be defined.
 Simpler algorithms are easier to understand and easier to program.  Define measure of progress: The loop invariant that have been defined would be
 The resulting programs usually contain fewer bugs. changed when algorithm progress.
 Define Exit condition: When the iteration would be stopped has to be identified.
Generality:  Make progress: Move forward after executing an instruction.
 Generality of the problem the algorithm solves.  Maintain Loop variants: In order to repeat the steps the loop invariant must be
 The set of input it accepts. maintained in range.
 Ending: When the iteration has stop.
(viii) Coding an Algorithm:
 Coding or programming is the process of translating the algorithm into the syntax of a Example algorithm for iteration process:
given programming language. 1.Factorial of a given number.
 Convert each step in the algorithm into one or more statements in a programming 2.Reverse of a number.
language 3.Sum of digits.

RECURSION:
 Recursive function is one that calls itself again to repeat the code.
 Recursion is a problem, solving approach by which a function calls itself repeatedly until
some specified condition has been satisfied.
 Recursion splits a problem into one or more simpler versions of itself.
 In a recursive algorithm the algorithm calls itself with smaller input values.
 The recursive programs require more memory and computation compared with iterative
algorithms.
Example: factorial of a given number. .
n!=n x (n-1)!
4!=4 x(4-1)!
=4 x (3!)
=4 x 3 x 2 x1
=24
Advantages of recursive functions:
 Recursion can produce simpler, more natural solutions to a problem.
 It is written with less number of statements.
 Recursive functions are effective where the terms are generated successively to compute
a value.
 It requires few variables.
 It is useful for branching process.

Example algorithm for recursion:


1. GCD using recursion.
2. Factorial given number using recursion.

6. ILLUSTRATIVE PROBLEMS:
1. To find a minimum in a list:
Problem statement: Find in a minimum in a list.
Problem description:
 Minimum in a list of elements can be achieved in different ways.
 One way is to sort the list of element in ascending order and get the first element as
minimum.
 Another method is to compare each element with other.
 Assume the first element as minimum element and start comparing with the next
element.
 If the next element is smaller than assume the second the minimum and keep
repeating the procedure till the last element.
Algorithm:
Step1: Get the list of elements.
Step2: Assume first element as Min.
Step 3: Compare Min with next element.
Step 4: If MIN is greater than next element; Set MIN=next element
Step 5: Repeat step 3 and 4 till the last element.
Step 6: Display MIN as the minimum element of the list.
1 2

UNIT-III Syntax:
if (Condition):
CONTROL FLOW, FUNCTIONS True Statement Block
else:
SYLLABUS:
False Statement Block
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained
conditional(if-elif-else); Iteration: state, while, for, break, continue, pass; Fruitful 5. What is the purpose of iteration? Give example.
functions: return values,parameters, local and global scope, function composition,
recursion; Strings: string slices,immutability, string functions and methods, string ➢ A loop statement allows us to execute a statement or group of statements
module; Lists as arrays. Illustrative programs:square root, gcd, exponentiation, sum an
multiple times.
array of numbers, linear search, binary search.
➢ Repeated execution of a set of statements is called iteration.

TWO MARKS Example:

Count=0
1. Define Boolean values
While(count<9):
Print’the count is:’,count
The Boolean data type have 2 values (usually denoted by True or False), When
Count=count+1
converting a Boolean to an integer, the integer value is always 0 or 1, but when
converting an integer to a Boolean, the Boolean value is true for all integers except 0.
6. Illustrate the flow chart of if-elif- else statements.
2. List out the Boolean operators.
False
➢ Or operator. Test
➢ And operator. Condition 1
➢ Not operator.

False
3. Define conditional statements. True
elif Test
Condition 2
➢ The execution of the program acts according the conditions. This concept is known as
Conditional statements or Branching Statements. Body of if –Statement
True Body of Else
Block 1
➢ Conditional Statements are used to perform different computation or action depending
Body of elif –
on whether a condition evaluates to TRUE or FALSE.
Statement Block 2
1. If Statement
2. If...else Statement
3. If..elif..else Statement
7. What are unconditional looping statements?
4. Nested if...elif..Else Statement.
➢ Loop that needs to be executed compulsorily without any condition is called an
unconditional loop.
4. Write the syntax of if and if-else statements.
➢ The loop will be executed in theprogram without any conditional checks.
Example:
➢ Condition if:The boolean expression after the if statement is called the condition. If it
is true, then the indentedstatement gets executed. ➢ Break statement.
Syntax: ➢ Continue statement.
if (Condition): ➢ Pass statement.
True Statement Block 8. Explain about break statement with an example.
➢ Alternative(IF....Else Statement):A second form of the if statement is alternative ➢ It terminates the current loop and resumes execution at the next statement.
execution, in which there are two possibilities and the condition determines which one ➢ The most common use for break is when some external condition is triggered
gets executed. requiring a hasty exit from a loop.
3 4

➢ The break statement can be used in both while and for loops.
Actual parameter:
Syntax: ➢ Parameter is defined in the function call.
Break Formal parameter:
➢ Parameter is defined as part of function definition.
Example : ➢ Actual parameter value is received by formal parameter
forletter in 'Python':
if ( letter == 'h'): 12. Classify global variable with local variable.
break ➢ A variable in the program can be either local variable or global variable.
print(“Current Letter :”, letter) ➢ A global variable is a variable that is declared in the main program while a
local variable is a variable declared within the function.
Output:
Example:
Current Letter : P
Current Letter : y S=10 # s is the global variable
Current Letter : t def f1()
S=55# s is the local variable
9. Discuss about continue and pass statements. Print s
Output:
Continue Statement: 55
• It returns the control to the beginning of the while loop.
• The continue statementrejects all the remaining statements in the current 13. Describe various methods used on a string. (Any Four)
iteration of the loop and movesthe control back to the top of the loop.
• The continue statement can be used in both while and for loops. ➢ is digit()-returns true if string contains only digits and false otherwise.
Syntax: ➢ islower()-returns true if string has at least 1 cased character and all cased characters are
Continue
in lowercase and false otherwise.
Pass Statement:
➢ isnumeric()-returns true id a Unicode string contains only numeric characters and false
• It is used when a statement is required syntactically but you do not want any
command or code to execute. otherwise.
• The pass statement is a null operation; nothing happens when it executes. ➢ isupper()-returns true if string has at least one cased character and all cased characters
Syntax: are in uppercase and false otherwise.
Pass
14. What are the advantages and disadvantages of recursion function?
10. What are function and fruitful function? Advantages:
➢ Reduces time complexity.
➢ Function: It is a block of statement that will execute for a specific task. ➢ Performs better in solving problems based on tree structures.
➢ Fruitful function:Functions that return values are called fruitful function. Disadvantages:
Input the value ➢ It is usually slower due to the overhead of maintain stack.
Return the result ➢ It usually uses more memory of the stack.
Fruitful functions

15. What is string?Giveexample.


➢ Example: The square function will take one number as parameter and ➢ A string is a sequence of characters.(i.e) it can be a letter , a number, or a
return the result of squaring that number backslash.
➢ Python strings are immutable, which means they cannot be changed after they
11. Define parameter. List out it types. are created.
Example:
➢ Parameter is the input data that is sent from one function to another. Var1='hello world!
➢ Parameter is of two types,
✓ Actual parameter.
✓ Formal parameter.
5 6

16. How will you slice the given string in python? 16 MARKS
A segment of a string is called a slice. Selecting a slice is similar to selecting a
character:
1. Boolean Value and operators(8m)
Example
>>> s = 'Monty Python'
>>> print s[0:5] ➢ The Boolean data type have 2 values (usually denoted by True or False), When
Monty converting a Boolean to an integer, the integer value is always 0 or 1, but when
>>> print s[6:13] converting an integer to a Boolean, the Boolean value is true for all integers except 0.
Python
Boolean and logical operators:
17. What will be the output of print str[2:5] if str=’helloworld!’?

H E L L O W O R L D ! Boolean values respond to logical operators ( AND / OR)


0 1 2 3 4 5 6 7 8 9 10
True AND False = False
True AND True = True
Str=”HELLOWORLD!”
False AND True= False
Str[2:5]
False OR True= True
O/P = LLO
False Or False= False
18. List out the applications of arrays.
Applications - Arrays are used to implement in data structures, such as lists, heaps, hash
➢ A boolean expression is an expression that is either true or false.
tables, deques, queues, stacks and strings.
19. Write a program to iterate a range using continue statement.
BOOLEAN OPERATORS( and,or,not)
for letter in 'Python': These are the Boolean operation, ordered by ascending priority:
if ( letter == 'h'):
continue Operation Result
print(“Current Letter :”, letter) X or Y If X is false then y, else X
Output: X and Y If X is false, then x else Y
Current Letter : P Not X If x is false,then true else False
Current Letter : y
Current Letter : t
Current Letter : o The following examples usethe operator ==, which compares two operands and produces True
Current Letter : n if they are equal and False
Otherwise:
20. Define array with an example.
>>> 5 == 5
An array is a collection of data that holds fixed number of values of same type. True
Forexample: if you want to store marks of 100 students, you can create an array for it. >>> 5 == 6
False
21.Differentiate for loop and while loop. ? True and False are special values that belong to the type bool; they are not strings:
>>>type (True)
For Loop While Loop <type 'bool'>
1.Executes the sequence of statements multiple 1.Repeats a statement until a give condition
>>>type(False)
times and abbreviates the code that manages is TRUE. It test the While condition before
the loop executing the loop body <type 'bool'>
2.Eg. for i in ‘123’: 2.Eg.Counter = 0
Print (“Welcome”,i, “Times”) While (counter < 3): Boolean and Comparison operators:
Output: Print(‘countis:’,counter)
Welcome 1 Times Counter=Counter+1 The == operator is one of the comparison operators; the others are:
Welcome 2 Times Output: x!= y # x is not equal to y
Welcome 3 Times Count is: 0
Count is: 1
Count is: 2
7 8

x > y # x is greater than y ➢ If the text condition is FALSE, the Statements are not executed.
x < y # x is less than y If statements have the same structure as function definitions: a header followed by an
x >= y # x is greater than or equal to y indented block. Statements like this are called compound statements.
x <= y # x is less than or equal to y
Syntax:
Although these operations are probably familiar to you, the Python symbols are different from
if (Condition):
themathematical symbols. A common error is to use a single equal sign (=) instead of a double
True Statement Block
equalsign (==). Remember that = is an assignment operator and == is a comparison operator.

Flowchart for if statement:


2. Explain the branching statements in python with relevant syntax and
example.(16m) Test
• Control Flow is the order in which individual Statements, instructions are executed Condition
or evaluated. FALSE
• Flow is just a way or sequence of program Execution.
• Every Statement of a program is executed one by one. Python provides various tools
for flow Control. TRUE
• Some of them are if, if..else, if..elif..else, Nestedif..elif..else, For, While, Nested, Break,
Continue etc Example 1: True Condition
A=500 Statement (Body of If)
B=200
FLOW CONTROL If (A>B):
Print (“A is greater than B”)
Output:
A is Greater than B
Conditional Statements Looping Control Structure
Explanation:
A>B is a test condition, namely 500>200, if it returns TRUE, it will execute the code
“print ( )”, if it returns FALSE, it will not execute the code “ print( )”.
• If • While Loop • Break
2.Alternative(IF....Else Statement):
• If...else • For Loop • Continue
• If..elif..else • Nested loop • Pass ➢ A second form of the if statement is alternative execution, in which there are two
• Nested If..elif..else possibilities and the condition determines which one gets executed.
Syntax:
if (Condition):
Conditional Statements: True Statement Block
else:
• The execution of the program acts according the conditions. This concept is known as
Conditional statements or Branching Statements. False Statement Block

• Conditional Statements are used to perform different computation or action depending Flowchart for if..else statement
on whether a condition evaluates to TRUE or FALSE.
,
1. If Statement Test
2. If...else Statement Condition
3. If..elif..else Statement
If Condition is false If Condition is true
4. Nested if...elif..Else Statement
False Condition True Condition
1. Conditional (If Statement):
Statement Statement
➢ The Boolean expression after the if statement is called the condition. If it is true, then
the indentedstatement gets executed.
9 10

Example 1: Example:
X=4 X=10
Y=5
if x%2 == 0:
if x < y:
print 'x is even' print 'x is less than y'
else: elif x > y:
print 'x is odd' print 'x is greater than y'
else:
Output: print 'x and y are equal'
X is even
Output:
Explanation: x is greater than y
➢ If the remainder when x is divided by 2 is 0, x is even
4.Nested if...elif..Else Statement:
➢ If the condition is false, the second set of statements is executed.(i.e) x is odd
• If..elif..else statement can be used inside another if..elif..else statement.This is
3.Chained condidtional (If...elif...else Statement):
called nesting. One condition can also be nested within another.
Syntax:
➢ If there are more than two possibilities and need more than two branches.
if (Condition 1):
➢ One way to express a computation like that is a chained conditional.
Syntax: if (Condition 2):
if (Condition 1): True Statement 2
Statement Block1 else:
elif(Condition 2): False Statement 2
Statement Block 2 else:
elif(Condition 3): False statement 1
Statement Block 3
else:
Flowchart for Nested if..elif...else statement:
Statement(s)

➢ elif is an abbreviation of “else if.”


➢ There is no limit onthe number of elif statements. False True
Test
Condition 1
Flowchart for if..elif...else statement:

True Condition 2 False


False Statement1
False
Test
Condition 1 False Statement 2
TrueStatement 2

True
Elif Test False
Condition 2 Example:
X=10
Body of if –Statement
Body of Else
Y=5
Block 1 True if x == y:
print 'x and y are equal'
Body of elif – else:
Statement Block 2
11 12

if x < y: Example 1 – For Loop Example 2 – For Loop


print 'x is less than y'
else: for i in ‘123’: Pets_List=[‘Parrot’, ‘Rabbit’, ‘Pigeon’,
print 'x is greater than y' Print (“Welcome”,i, “Times”) ‘Dog’]
For mypets in Pets_List:
OUTPUT: Print(mypets)
X is greater than y. Output: Output:
Welcome 1 Times Parrot
3. Explain the iteration in python with relevant syntax and Welcome 2 Times Rabbit
Welcome 3 Times Pigeon
example.(16m) Dog
• Computers often do repetitive task. There are situation when programmers used to Example 3 – For Loop Example 4 – For Loop
execute a block of code several number of times.
• Repeated execution of a set of statements is called Iteration/Looping. Message = “PROGRAM” Language= (“c”, “c++”, “Java”, “Python”)
For i in message: for i in Lanuage:
Python Programming Language provide following types of Iterative Statements. Print(i) print(i)
Output: Output:
1. For Loop P C
2. While Loop R C++
O Java
3. Nested Loop
G Python
R
Loop Type Description A
M
For Loop Executes the sequence of statements multiple times and abbreviates the code that
manages the loop
2. While Loop:
While Loop Repeats a statement until a give condition is TRUE.It test the While condition
before executing the loop body • While loop is used, when we need to repeatedly execute a statement or group of
Nested Loop You can use one or more loop inside any other While or For Loop statements until the condition is true.
• It tests the condition before executing the loop body so this technique is known as Entry
Controlled Loop.
1. For Loop:
Syntax:
• It executes the sequence of statements multiple times and abbreviates the code that
While expression:
manages the loop.
Statement(s)
• The for – loop repeats a given block of codes by specified number of times.

Flowchart:
• Here, statements may be a single statement or a block of statements.
Syntax: For each item • The condition may be any expression, the loop iterates while the condition is true, when
For <variable> in <sequence>: in sequence the condition becomes false, program control passes to the line immediately following
<statement 1> the loop.
Enter While
<statement 2> Flowchart: Loop
<statement 3> Test FALSE
. EXPRESION
. Test False
.
<statement n> Condition
TRUE

True
Body of the Loop

Body of the Loop


Exit Loop

Exit Loop
13 14

Example 1 – While Loop Example 2 – While Loop Break Statement:


#Program to print the number from 0 to 4 #Program to print the number from 0 to 5
Counter = 0 a=0 • It terminates the current loop and resumes execution at the next statement.
While (counter < 4): While (a<5): • The most common use for break is when some external condition is triggered requiring
Print(‘countis:’,counter) a=a+1 a hasty exit from a loop.
Counter=Counter+1 Print (a) • The break statement can be used in both while and for loops.
Print(“Exit the loop”) • If you are using nested loops, the break statement stops the execution of the
innermost loop and start executing the next line of code after the block.
Output: Output:
Count is: 0 0 Syntax:
Count is: 1 1 Break
Count is: 2 2
Count is: 3 3 Flow Diagram for Break Statement:
Exit the Loop 4

3. Nested Loop:
Condition Code
• Nesting is defined as placing of one loop inside the body of another loop.
• It can use one or more loop inside any another while, for..loopetc
If Condition
Syntax: is True
For <variable> in <sequence>: Break
Condition
For<variable> in <sequence>:
Statement(s)
Statement(s)
If condition is false
4. STATE:
➢ An algorithm is deterministic automation for accomplishing a goal which, given an
initial state, will terminate in a defined end-state.
➢ When an algorithm is associated with processing information, data is read from an input Example 1: Example 2:
source or device, written to an output device, and/or stored for further processing. for letter in 'Python': var = 10
➢ Stored data is regarded as part of the internal state of the algorithm. if ( letter == 'h'): while var> 0:
➢ The state is stored in a data structure. break print (“Current variable value :”, var)
print(“Current Letter :”, letter) var = var -1
5. Explain about unconditional looping statements with relevant example. if (var == 5):
Output: break
• It controls the flow of program execution to get desired result. Current Letter : P print( "Good bye!")
Current Letter : y
Python supports following three control statements:
Current Letter : t Output:
1. Break. Current variable value : 9
2. Continue. Current variable value : 8
3. Pass. Current variable value : 7
Control Statements Explanation Current variable value : 6
Break It terminates the loop statement and transfers execution to the Good bye!
statement immediately following loop.
Continue Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating
Pass The pass statement in python is used when a statement is required
syntactically but we do not want any command or code to execute.
15 16

2.Continue Statement: 3.Pass Statement:


• It returns the control to the beginning of the while loop.
• The continue statementrejects all the remaining statements in the current iteration • It is used when a statement is required syntactically but you do not want any
of the loop and movesthe control back to the top of the loop. command or code to execute.
• The continue statement can be used in both while and for loops. • The pass statement is a null operation; nothing happens when it executes.
• The pass is also useful in places where your code will eventually go, but has not been
Syntax: written yet (e.g., in stubs for example)
Continue
Syntax:
Flow Diagram for Break Statement: Pass

Example 1:
forletter in 'Python':
if ( letter == 'h'):
Pass
Condition Code Print(“This is pass block”)
print(“Current Letter :”, letter)
print(“Good bye”)
If Condition
is True Output:
Continue Current Letter : P
Condition Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
If condition is false Current Letter : o
Current Letter : n
Good Bye

6. Briefly explain about fruitful functions with example.


Example 1: Example 2:
for letter in 'Python': var = 10
if ( letter == 'h'): while (var> 0): ➢ Functions that return values are called fruitful function.
continue var = var -1
print(“Current Letter :”, letter) print (“Current variable value :”, var)
if (var == 5): Input the value
Coninue Return the result
Fruitful functions
Output: Print( "Good bye!")
Current Letter : P
Current Letter : y Output: ➢ Example: The square function will take one number as parameter and return the result
Current Letter : t Current variable value : 9 of squaring that number.
Current Letter : o Current variable value : 8
Current Letter : n Current variable value : 7 RETURN VALUES:
Current variable value : 6
Current variable value : 4 ➢ The Built-in functions such as the math functions, POW, etc. produce results.
Current variable value : 3 ➢ Calling the function generates a value, which we usually assign to a variable or use as
Current variable value : 2 part of an expression.
Current variable value : 1
Current variable value : 0 ➢ The first example is area, which returns the area of a circle with the given radius:
Good bye! def area(radius):
temp = math.pi * radius**2
return temp
17 18

Call by reference:
➢ We have seen the return statement before, but in a fruitful function the return statement ➢ A copy of actual parameter is passed to formal arguments and any changes made to the
includes an expression. formal arguments will affect the actual arguments.

def area(radius): SCOPE OF THE VARIABLE:


returnmath.pi * radius**2 ➢ A variable in the program can be either local variable or global variable.
➢ A global variable is a variable that is declared in the main program while a local
PARAMETERS: variable is a variable declared within the function.

A function in python, Example:


➢ Takes input data, called parameters or arguments. S=10 # s is the global variable
➢ Perform computation def f1()
➢ Returns the result. S=55# s is the local variable
Print s
Def func(param1,param2); Output:
#computations 55
Return result

➢ Parameter is the input data that is sent from one function to another.
COMPOSITION:
➢ Parameter is of two types,
✓ Actual parameter. ➢ When a function is called from within another function, it is called composition.
➢ A function that takes two points, the center of the circle and a point onthe
✓ Formal parameter.
perimeter, and computes the area of the circle.
➢ Assume that the center point is stored in the variables xc and yc, and the perimeter
Actual parameter: point is in xp and yp.
➢ Parameter is defined in the function call. ➢ The first step is to find the radius of the circle, which is the distance between the two
Formal parameter: points.
➢ Parameter is defined as part of function definition. radius = distance(xc, yc, xp, yp)
➢ Actual parameter value is received by formal parameter. result = area(radius)

Example: Encapsulating these steps in a function, we get:

# Function With Actual And Formal Parameters defcircle_area(xc, yc, xp, yp):
def cube(x) radius = distance(xc, yc, xp, yp)
return x*x*x result = area(radius)
a=input(“enter the number:”) return result
b=cube(a)
Print(“cube of the given number:”,b) we can make it more concise by composing the function calls:

Output: defcircle_area(xc, yc, xp, yp):


Enter the number:2 return area(distance(xc, yc, xp, yp))
Cube of the given number:8
RECURSION:
➢ A function is recursive if it calls itself and has a termination condition.
Parameter passing techniques: ➢ Termination condition stops the function from calling itself.
➢ Call by value Example:
➢ Call by reference def factorial(n):
Call by value: If n==0:
➢ A copy of actual parameter is passed to formal arguments and any changes made to Return 1
the formal arguments have no effect on the actual arguments. else:
recurse =factorial(n-1)
Result =n* recurse
Return result
19 20

STRINGS ARE IMMUTABLE:


7. Explain in detail about strings with examples.
➢ It is tempting to use the [] operator on the left side of an assignment, with the intention
➢ A string is a sequence of characters.(i.e) it can be a letter , a number, or a backslash. of changing a character in a string.
➢ Python strings are immutable, which means they cannot be changed after they are For example:
created. >>> greeting = 'Hello, world!'
>>>greeting[0] = 'J'
STRING SLICES:
TypeError: object does not support item assignment.
➢ A segment of a string is called a slice. Selecting a slice is similar to selecting a
character. ➢ The “object” in this case is the string and the “item” is the character you tried to assign.
➢ An object is the same thing as a value, but we will refine that definition later. An item is
Example: one of the values in a sequence.
>>> s = 'MontyPython' ➢ The reason for the error is that strings are immutable, which means you can’t change an
>>> print s[0:5] existing string.
Monty ➢ The best is to create a new string that is a variation on the original:
>>> print s[6:13] >>> greeting = 'Hello, world!'
Python >>>new_greeting = 'J' + greeting[1:]
>>> print new_greeting

➢ The operator [n:m] returns the part of the string from the “n-eth” character to the “m- Output:
eth” character,including the first but excluding the last. Jello, world!

➢ This example concatenates a new first letter onto a slice of greeting. It has no effect on
the original string.

STRING FUNCTIONS AND METHODS:

➢ A method is similar to a function—it takes arguments and returns a value—but the


➢ If you omit the first index (before the colon), the slice starts at the beginning of the syntax is different.
string. If youomit the second index, the slice goes to the end of the string. ➢ For example, the method upper takes a string and returns a new string with all
uppercase letters:
Example: ➢ Instead of the function syntax upper(word), it uses the method syntax word.upper().
>>> fruit = 'banana'
>>> fruit[:3] >>>word = 'banana'
'ban' >>>new_word = word.upper()
>>> fruit[3:] >>> print new_word
'ana' BANANA

➢ This form of dot notation specifies the name of the method, upper, and the name of the
➢ If the first indexes is greater than or equal to the second the result is an empty string, string to apply the method to, word. The empty parentheses indicate that this method
represented by two quotation marks. takes no argument.
➢ A method call is called an invocation; in this case, we would say that we are invoking
Example: upper on the word.
>>> fruit = 'banana'
>>> fruit[3:3] >>>word = 'banana'
>>>index = word.find('a')
➢ An empty string contains no characters and has length 0, but other than that, it is the >>>print index
same as anyother string. 1

➢ The find method is more general than our function; it can find substrings, not just
characters:
>>>word.find('na')
21 22

2
➢ It can take as a second argument the index where it should start: 8.Why we need list instead of array in Python?Explain in detail
>>>word.find('na', 3)
4 about lists with example?
➢ And as a third argument the index where it should stop:
>>>name = 'bob' LIST AS ARRAY
>>>name.find('b', 1, 2)
-1 ➢ A list in Python is just an ordered collection of items which can be of any type.
➢ By comparison an array is an ordered collection of items of a single type - so in
METHODS: principle a list is more flexible than an array but it is this flexibility that makes things
slightly harder when you want to work with a regular structure.
METHODS DESCRIPTION ➢ A list is also a dynamic mutable type and this means you can add and delete elements
from the list at any time.
Capitalize() Capitalizes first for letter of string ➢ To define a list you simply write a comma separated list of items in square brackets,
is digit() returns true if string contains only digits and false otherwise. myList=[1,2,3,4,5,6]

islower() returns true if string has at least 1 cased character and all cased ➢ This looks like an array because you can use "slicing" notation to pick out an individual
element - indexes start from 0.
characters are in lowercase and false otherwise.
For example print myList[2]
isnumeric()- returns true id a Unicode string contains only numeric characters and ➢ It will display the third element, i.e. the value 3 in this case. Similarly to change the
false otherwise third element you can assign directly to it:
isupper() returns true if string has at least one cased character and all cased myList[2]=100
characters are in uppercase and false otherwise.
➢ The slicing notation looks like array indexing but it is a lot more flexible.
STRING MODULE
For example myList[2:5]
• The string module provides tools to manipulate strings. Some methods available in the ➢ It is a sublist from the third element to the fifth i.e. from myList[2] to myList[4].
standard data structure are not available in the string module (e.g. isalpha).
➢ The final element specified i.e. [5] is not included in the slice.
Example:

>>>import string ➢ Also notice that you can leave out either of the start and end indexes and they will be
>>>string.digits assumed to have their maximum possible value.
‘0123456789’
>>>string.ascii_letters For example myList[5:] is the list from List[5] to the end of the list andmyList[:5]
‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’ is the list up to and not including myList[5] andmyList[:] is the entire list.
>>>string.ascii_lowercase ➢ List slicing is more or less the same as string slicing except that you can modify a slice.
‘abcdefghijklmnopqrstuvwxyz’
For example:
>>>string.ascii_uppercase
myList[0:2]=[0,1] has the same effect as
‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’ myList[0]=0
>>>string.hexdigits myList[1]=1
‘0123456789abcdefABCDEF’ ➢ List slicing is more or less the same as string slicing except that it can modify a slice.
>>>string.octdigits
‘01234567’ Basic array operations
>>>string.punctuation
➢ For example, to find the maximum value (forgetting for a moment that there is a built-
‘!”@#$%^&*()”:><{}[]’
in max function) you could use:
>>>string.whitespace
m=0
‘\t\n\r\x0b\x0c’
for e in myList:
>>>string.Capwords(“python”) if m<e:
‘PYTHON’ m=e
23 24

➢ This uses the for..in construct to scan through each item in the list. This is a very useful 3. Exponentiation
way to access the elements of an array but it isn't the one that most programmers will be n = input ("Enter a number : ")
familiar with. In most cases arrays are accessed by index and you can do this in Python: n = int(n)
m=0 e = input ("Enter an exponent : ")
for i in range(len(myList)): e = int(e)
if m<myList[i]: r=n
m=myList[i]
for i in range (1,e):
➢ Notice that we are now using range to generate the sequence 0, 1, and so on up to the
length of myList. r=n*r
➢ You have to admit that there is a lot to be said for the simplicity of the non-index print(r)
version of the for loop but in many cases the index of the entry is needed. There is the
option of using the index method to discover the index of an element but this has its OUTPUT:
problems. Enter a number : 2
Enter an exponent : 2
ILLUSTRATIVE PROGRAMS: 4
4. Sum an array of elements.
1. Find the square root of number.
a = []
n = int(input("Enter a number")) n = int(input("Enter number of elements:"))
howmany = int(input("Enter another number")) for i in range(1, n+1):
approx = 0.5 * n b = int(input("Enter element:"))
for i in range(howmany): a.append(b)
betterapprox = 0.5 *(approx + n/approx) a.sort()
approx = betterapprox print("Largest element is:",a[n-1])
print("The square root of a number is:", betterapprox)
OUTPUT:
OUTPUT: Enter number of elements:5
Enter a number25 Enter element:5
Enter another number36 Enter element:54
The square root of a number is: 5.0 Enter element:24
Enter element:58
2. GCD of a given number. Enter element:1
Largest element is: 58
d1 = int(input("Enter a number:"))
d2 = int(input("Enter another number")) 5. Linear search
rem = d1 % d2
while rem != 0 : list = [4,1,2,5,3] #Set up array
d1 = d2 search = int(input("Enter search number")) # Ask for a number
d2 = rem for i in range(0,len(list)): # Repeat for each item in list
rem=d1 % d2 if search==list[i]: #if item at position i is search time
print ("gcd of given numbers is :", d2) print(str(search)+"found at position " + str(i)) #Report found

OUTPUT: OUTPUT:
Enter search number 4
Enter a number:2 4 found at position 0
Enter another number4
gcd of given numbers is : 2 6. Binary search
defbinary_search(item_list,item):
first = 0
25

last = len(item_list)-1
found = False
while( first<=last and not found): 6
mid = (first + last)//2
ifitem_list[mid] == item :
PART-B
found = True 1. Explain the concepts Python interpreter and interactive mode in detail.
else:
if item <item_list[mid]:  A Python is a high-level programming language. Python is an easy to learn,
last = mid - 1 powerful programming language.
else:  Python is programming language as well as scripting language. Python is also
first = mid + 1 called as Interpreted language.
return found
print(binary_search([1,2,3,5,8], 6)) Advantages of High-level language:
print(binary_search([1,2,3,5,8], 5))
 It is much easier to program in a high-level language
OUTPUT:
 Programs written in a high-level language take less time to write
False
 They are shorter and easier to read
True
 High-level languages are portable, meaning that they can run on different
kinds of computers with few or no modifications.

Two kinds of programs process high-level languages into low-level languages:


interpreters and Compilers.

Interpreter:
 Translates program one statement at a time.
 It takes less amount of time to analyze the source code but the overall
execution time is slower.
 No intermediate object code is generated, hence are memory efficient.
 Continues translating the program until the first error is met, in which case it
stops. Hence debugging is easy.
 Programming language like Python, Ruby use interpreters.

Compiler:
 Scans the entire program and translates it as a whole into machine code.
 It takes large amount of time to analyze the source code but the overall
execution time is comparatively faster.
 Generates intermediate object code which further requires linking, hence
requires more memory.
 It generates the error message only after scanning the whole program. Hence
debugging is comparatively hard.
 Programming language like C, C++ uses compilers.
7 8

Program:
A computer program is a collection of instructions that performs a
specific task when executed by a computer. A computer requires programs to
function and typically executes the program's instructions in a central processing
unit. A computer program is usually written by a computer programmer in a
There are two ways to use the interpreter: interactive mode and script mode.
high-level programming language.
Interactive mode:
Elements of program:
 Working in interactive mode is convenient for testing small pieces of code
because you can type and execute them immediately.  input: Get data from the keyboard, a file, or some other device.
 Interactive mode is a command line shell which gives immediate feedback for  output: Display data on the screen or send data to a file or other device.
each statement, while running previously fed statements in active memory.  math: Perform basic mathematical operations like addition and
 As new lines are fed into the interpreter, the fed program is evaluated both in multiplication.
part and in whole.  conditional execution: Check for certain conditions and execute the
 Interactive mode is a good way to play around and try variations on syntax. appropriate sequence of statements.
 repetition: Perform some action repeatedly, usually with some variation.
Example:
>>> 1 + 1 Debugging:
Output:2
 Programming errors are called bugs and the process of tracking them down is
>>> print (5*7) called debugging.
Output: 35  Three kinds of errors can occur in a program: syntax errors, runtime errors,
and semantic errors.
 >>>, is the prompt the interpreter uses to indicate that it is ready.
Syntax Errors:
Script mode:
 Store code in a file and use the interpreter to execute the contents of the file,  Python can only execute a program if the syntax is correct; otherwise, the
which is called a script. interpreter displays an error message.
 Python scripts have names that end with .py.  Syntax refers to the structure of a program and the rules about that structure.
 To execute the script, you have to tell the interpreter the name of the file.
 Save code as a script which can modify and execute it in the future. Runtime Errors:
 In script mode, however, Python doesn't automatically display results.  The second type of error is a runtime error, so called because the error does
not appear until after the program has started running.
 Explicitly from the command line. In this case running Python file and
providing the name of the script as an argument.  These errors are also called exceptions because they usually indicate that
something exceptional (and bad) has happened.
EX:
Sample.py  Runtime errors are rare in the simple programs.
a=10 Semantic errors:
b=20  The third type of error is the semantic error. If there is a semantic error in
print (a+b) your program, it will run successfully in the sense that the computer will not generate
any error messages, but it will not do the right thing.
Output : 3

Scope of Python:
9 10

• Web Development, Internet scripting, Test scripts, Embedded Scripting Where,

• Graphical user Interface [GUI], Variable_name is user defined name

• Game Programming, Distributed Programming Initial_name is the value to initialized (Integer, Floating Point, Complex, Boolean)
Integer : a = 10 Complex Integer : Z = 1+2j
2. Explain in detail about values and data types available in python with examples. Floating Point : b = 5.6 Boolean Value : Flag = True / False
1.Integers:
 A Value is one of the fundamental things, like a letter or a number that a program
 Integers are whole Numbers with no Fractional parts and Decimal Point. They can
manipulates. They are grouped into different data types. have Positive, Negative or zero Values.
 Data type is a set of values and allowable operations on those values. Data types
allow programming languages to organize different kinds of data. Data Type Example
Integer type -55,-45,-28,-2,0,5,19,56

Integers belong to the type int.


Example for integers:
>>>1+1
2
>>> a = 4
>>>type(a)
<type „int‟>

2.Floating Point:

 Numbers with fractions or decimal points are called floating point numbers. A
Numbers: floating point number will consists of signs (+,-) sequence of decimal digits.

A Numerical literals Containing only the digits (0-9), Optional sign character (+ or -) and a
Data Type Example
decimal point.
Floating Point numbers -1.25,-1.0,0.0,0.5,12.6,15.2
The types of Numerical Data types are:
Floating Point belongs to the type Float.
 Integer (signed integer and long int) Example for Float:
 Floating Point
>>> c=2.5
 Boolean Value
 Complex integer >>>type(c)
<type „Float‟
3.Boolean Value:
Syntax:  Boolean is a data type named after George Boole. Boolean often called bools, which
are either TRUE or FALSE condition.It is the Simplest Built-in type in python.
Variable_name = initial_value
11 12

 A Boolean variable can take only two values True (1) and False (0) Output: AAAAA
2. Lists:
Data Type Example  Lists in Python are used to store a list of values.
Boolean Value True / false  It is an ordered sequence of values which may consists of any type of data
( Intger, Float,String etc)
 Boolean Value belongs to the type Bool.  Values in the list are called element/items.
Example for Float:  They are Mutable and indexed ordered.
>>> c=True To create a list, we define a variable to contain an ordered series of items separated by a
>>>type(c) comma. A square bracket is used to enclose the items.
<type „bool‟> Syntax:
 A Boolean true value is always considered to be a Non-zero, Non-null and Non- To create an empty list : My_list=[ ]
empty value. To create a list of items : My_list=[ item1, item2,item3….]
Example:
Sequence: #List with Integer
A sequence is an ordered collection of items, indexed by positive integers. It is a Num_list=[ 0,5,4,7,8]
combination of mutable and non mutable data types. #List with String
The types of sequence data types are String_list=[ „cat‟, „rat‟, „dog‟, „lion‟]
 String
 lists 3. Define variable. Explain how to declare variable and explain about the scope of
1.Strings: variable.
 Strings are literal or it is a sequence of characters which may consists of letters,
number, special symbols or a combination of these types represented within the pair  A variable is basically a name that represent some value, Variable are reserved
of double or single quotation marks. memory location to store values.
Creating string is as Simple as assigning a value to a variable.  Every value in Python has a datatype.Diffferent data types in python are Number,
>>> a = “Hello” List, Tuple, Strings etc.
>>>type(a)
Syntax : Variable_name = Value
<type „str‟>
Operations on Strings: Rules for Naming a variable:
1. + Operator
2. * Operator  A variable name can contain both Upper case (A-Z) and Lower case characters(a-z)
and Underscore character ( _ ).
 Numbers are allowed, but they should not be used at the beginning of the variable
 The + operator concatenate strings
name. Eg: 1firstname is not valid, firstname1 is valid.
>>> „Horse‟+ „and‟+ „dog‟
 No Special symbol other than underscore is allowed.
Output : „ Horse and dog‟
 There are some Keywords that cannot be used as a variable name because they
 The * operator creates a multiple Concatenated Copies of a string
already have pre-assigned meaning , some of the reserved word are
>>> A * 5 Print,Input,if,while etc
13 14

Assigning Values to the variable: >>>2+2

The declaration happens automatically while assigning values to a variable. The equal sign 4
(=) is used to assign values to variables.
The evaluation of an expression produces a value. Some legal expression are a follows:
Eg: Name = “Dog”
>>> a= 15
Int_num= 500
>>> a
Float_num=45.5
Output: 15
List_num= [“Dog”, 50,25, 0.5]
>>> a + 15
Re-declare a Variable:
In this we can re-declare the variable even after you have declared it once. Output: 30

#Declare a variable and Initialize it: When we type an expression at the prompt, the interpreter evaluates it, which means that it
C=0 finds the value of the expression. In the above example “ a” has a value 15 and “a+15” has
Print c a value 15.
#re-declare the variable
C= “Welcome” Evaluating an expression is not the same as printing a value
Print c
>>> Line = “God is Great”
 Here variable initialized to c=0.
>>>Line
 If we re-assign the assign the Variable c
to value “ welcome” Output: “God is Great”

>>> Print Line


Output:
Output: God is Great.
0

Welcome
5. Explain about Statements.

 A statement is an instruction that python interpreter can execute.


 There are two kinds of statements.
 Print statement
 Assignment statement.
 When a statement is typed in interactive mode, the interpreter executes it and
4. Write short on Expressions. displays the result.
 A script usually contains a sequence of statements. If there is more than one
An Expression is combination of values, variables and operators.
statement, the results appear one at a time as the statements execute.
If we type an expression on the command line, the interpreter evaluates it and displays the For example, the script
results. print 1
15 16

x=2  Logical Operators


print x  Bitwise Operators
 Membership Operators
output:  Identity Operators
1
2 Python Arithmetic Operators
The assignment statement produces no output. Assume variable a =10,b=20

6. Explain about the concept of tuple assignment. Operator Description Example


 The tuple of variables on the left of an assignment to be assigned values from a tuple
on the right of the assignment. + Addition Adds values on either side of the operator. a + b = 30
 It is useful to swap the value of two variables.

Example: To swap a, b - Subtraction Subtracts right hand operand from left hand operand. a – b = -10

Temp=a
a=b *Multiplication Multiplies values on either side of the operator a * b = 200
b=temp
Tuple assignment solves this problem neatly
/ Division Divides left hand operand by right hand operand b/a=2
(a,b)=(b,a)

 The number of variables on the left and the number of values on the right have to be % Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder
the same:

>>> a, b = 1, 2, 3 ** Exponent Performs exponential (power) calculation on operators a**b =10 to


the power 20
ValueError: too many values to unpack.

7. What are the types of operators supported by python language? List the // Floor Division – that divides two numbers and chops off the 9//2 = 4
operators and explain them. fraction part.

Operator:
 An operator is a special symbol that represents a simple computation like Python Comparison or relational Operators:
addition, subtraction,…
These operators compare the values on either sides of them and decide the relation among
 The values (or) the variables are applied on the operator is called as operands.
them. They are also called Relational operators. Assume a=15, b=23
Types of Operator:
Python language supports the following types of operators.
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
17 18

+= Add AND It adds right operand to the left operand and assign the result c += a is
Operator Description Example
to left operand equivalent to
c=c+a
== If the values of two operands are equal, then the condition becomes (a == b)
true.
-= Subtract It subtracts right operand from the left operand and assign the c - = a is
False(0)
AND result to left operand equivalent to
c=c-a
!= If values of two operands are not equal, then condition becomes true.
*= Multiply It multiplies right operand with the left operand and assign c * = a is
AND the result to left operand equivalent to
> If the value of left operand is greater than the value of right operand, (a > b) is c=c*a
then condition becomes true. not true.

< If the value of left operand is less than the value of right operand, (a < b) is
then condition becomes true. true.
/= Divide AND It divides left operand with the right operand and assign the c / = a is
result to left operand equivalent to
c = c / ac /= a
>= If the value of left operand is greater than or equal to the value of (a >= b) is
is equivalent
right operand, then condition becomes true. not true.
to c = c / a

<= If the value of left operand is less than or equal to the value of right (a <= b) is
%= Modulus It takes modulus using two operands and assign the result to c %= a is
operand, then condition becomes true. true
AND left operand equivalent to
c=c%a

**= Exponent Performs exponential (power) calculation on operators and c **= a is


AND assign value to the left operand equivalent to
c = c ** a

Python Assignment Operators:


//= Floor It performs floor division on operators and assign value to the c //= a is
Assume variable a holds 10 and variable b holds 20, then Division left operand equivalent to
Operator Description Example
c = c // a

= Assigns values from right side operands to left side operand c=a+b
assigns value
of a + b into
c
19 20

Python Bitwise Operators:


Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b =
Python Identity Operators
13; Now in binary format they will be as follows −
Identity operators compare the memory locations of two objects.
a = 0011 1100
Description Example
b = 0000 1101

----------------- is Evaluates to true if the variables on either side of the x is y, here is results in 1 if
operator point to the same object and false otherwise. id(x) equals id(y).
a&b = 0000 1100
is not Evaluates to false if the variables on either side of the x is not y, here is not results
a|b = 0011 1101 operator point to the same object and true otherwise. in 1 if id(x) is not equal to
id(y).
a^b = 0011 0001

There are following Bitwise operators supported by Python language


8. Briefly explain about the concept of precedence of operators.
Operator Description Example

 The list below will show which operator has more precedence over the operators.
& Binary AND Operator copies a bit to the result if it exists in both (a & b) (means  The first operator in the list will run before the second operator below.
operands 0000 1100)
OPERATORS MEANING

| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 () Parentheses


(means 0011
1101) ** Exponent

*, /, //, % Multiplication, Division, Floor division, Modulus


^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49
(means 0011 +,- Addition,subtraction
0001)
<<,>> Bitwise shift operators

<< Binary Left Shift The left operands value is moved left by the number of bits a << 2 = 240 & Bitwise AND
specified by the right operand. (means 1111
0000) ^ Bitwise XOR

| Bitwise OR
>> Binary Right The left operands value is moved right by the number of a >> 2 = 15
==,!=,>,>=,<,<=,is, is not,in
Shift bits specified by the right operand. (means 0000 Comparisons ,Identity, Membership operators
not, not in
1111)
21 22

not Logical NOT  Multiplication will run before an addition equation since multiplication has more
precedence over addition.
and Logical AND
Example:
or Logical OR #Multiplication and addition
>>>2=4*4
18
Addition and subtraction:
Operator precedence examples:
 The equation will run left to right since addition and subtraction are on the same
Exponent and Multiplication: level.
Example:
 Exponent will always run before the multiplication equation.
#Addition and subtraction
Example: >>>2=3-5+8-4+2-9
#Exponent and multiplication
-3
#Exponent runs first
>>>2**4+2
EXAMPLE PROBLEMS:
>>>16+2
1. X=(15=6)-10*4
18
Print (x)
Exponent And Division: In the expression to evaluate the value of x, the brackets have highest of all
 Exponent will always run before a division equation. precedence.
Example: So this is evaluated before anything else, then * is done and lastly the subtraction.
#Exponent and Division 15+6 is 21
#Exponent runs first 1084 is 40
>>4/2**6 21-40 is -19
>>4/64 Ans: -19
0.0625
Mutiplication and Division: 2. X=17/2%2*3**3
Print(x)
 Python will run the equation from left to right since multiplication and division has In the expression to evaluate the value of x, the exponentiation is done first and then
same precedence. division operator followed by modulo and multiplication.
Example: 3**3 is 27
#Multiplication and Division 17/2 is 8.5
#In this case division ran first the multiplied by 3. 8.5%2 is 0.5
>>>5/4*3 0.5*27 is 13.5
3.75 Ans: 13.5
#In this case 3 is multiplied by 4 then divide by 5
>>>3*4/5
2.4
Multiplication and addition:
23 24

9. Illustrate the concept of comments.


 We can define our most used functions in a module and import it, instead of copying
 Comments statements are used to provide a summary of the code in plain English to their definitions into different programs.
Let us create a module. Type the following and save it as example.py
help future developer for better understand of the code.
 There are two types of comments
# Python Module example
 Single line comment.
 Multiline comment. def add(a, b):
Single Line comment:
"""This program adds two
 A single line comment starts with the number sign (#) character:
Example: numbers and return the result"""
# compute the percentage of the hour that has elapsed result = a + b
percentage = (minute * 100) / 60
return result
In this case, the comment appears on a line by itself. You can also put comments at the end
of a line:
percentage = (minute * 100) / 60 # percentage of an hour. Here, we have defined a function add ( ) inside a module named example. The function
takes in two numbers and returns their sum.
Multiline comment: How to import modules in Python?
 Multiple lines can be created by repeating the number sign several times:
#This is a comment  We can import the definitions inside a module to another module or the interactive
#second line interpreter in Python.
X=4  We use the import keyword to do this. To import our previously defined
module example we type the following in the Python prompt.

10. Explain about the features of module. >>> import example

 Modules refer to a file containing Python statements and definitions.  This does not enter the names of the functions defined in example directly in the
current symbol table. It only enters the module name example there.
 Using the module name we can access the function using dot (.) operation. For
example:

>>> example.add(4,5.5)
9.
Python import statement:

We can import a module using import statement and access the definitions inside it using
 A file containing Python code, for e.g.: example.py is called a module and its the dot operator as described above. Here is an example.
module name would be example. # Import statement example
# To import standard module math
 We use modules to break down large programs into small manageable and organized import math
files. Furthermore, modules provide reusability of code. print("The value of pi is", math.pi)

When you run the program, the output will be:


The value of pi is 3.141592653589793
25 26

Python from...import statement: Function calls


 A function is a named sequence of statements that performs a computation.
We can import specific names form a module without importing the module as a whole.  When you define a function, you specify the name and the sequence of statements.
Here is an example.  Later,you can “call” the function by name. We have already seen one example of a
function call:
# import only pi from math module
>>> type(32)
from math import pi <type 'int'>

print("The value of pi is", pi)  The name of the function is type.


 The expression in parentheses is called the argument of the function.
The value of pi is 3.141592653589793  The result, for this function, is the type of the argument. It is common to say that a
function “takes” an argument and “returns” a result. The result is called the return
The from...import * Statement: value.

It is also possible to import all names from a module into the current namespace by using Type conversion functions
the following import statement.  Python provides built-in functions that convert values from one type to another.

The int function takes any value and converts it to an integer, if it can, or complains
from modname import *
otherwise:
This provides an easy way to import all the items from a module into the current >>> int('32')
namespace. 32

11. Explain about the features of function. >>> int('Hello')


ValueError: invalid literal for int(): Hello
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code The int can convert floating-point values to integers, but it doesn’t round off; it chops
reusing. off the fraction part:
Types of Functions:
>>> int(3.99999)
Basically, we can divide functions into the following two types: 3
>>> int(-2.3)
-2
1. Built-in functions - Functions that are built into Python.
Float converts integers and strings to floating-point numbers:
2. User-defined functions - Functions defined by the users themselves.
>>> float(32)
Types of 32.0
Functions >>> float('3.14159')
3.14159

Finally, str converts its argument to a string:


User- Defined Functions Built-in Functions
>>> str(32)
27 28

'32'  That sounds simple enough, until you remember that one function can call another.
>>> str(3.14159)
While in the middle of one function, the program might have to execute the
'3.14159'
statements in another function.
Math functions
Example:
 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. 1. Def pow(5,2)
2. Y=b**p
Before we can use the module, we have to import it:
>>> import math 3. Return y
4.
 This statement creates a module object named math. If you print the module object,
you get some information about it: 5. def square(x)
6. a=pow(x,2)
>>> print math
<module 'math' from '/usr/lib/python2.5/lib-dynload/math.so'> 7. return a
8.
 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 9. X=5
name of the function, separated by a dot (also known as a period). This format is 10. Result=square(x)
called dot notation.
Example: 11. Print(result)
>>> ratio = signal_power / noise_power Output:
>>> decibels = 10 * math.log10(ratio)
25
The example computes the logarithm base 10 of the signal-to-noise ratio. 13. Explain the concept of parameters and arguments
The math module also provides a function called log that computes logarithms base e.
 The arguments are assigned to variables called parameters.
EXAMPLE:
12. Explain about flow of execution. def print_twice(Flower):
Print flower
 The orders in which statements are executed are called flow of execution.
Print flower
 Execution always begins at the first statement of the program. Statements are  This function assigns the argument to a parameter named flower.
executed one at a time, in order from top to bottom.  When the function is called, it prints the value of the parameter twice.
 Function definitions do not alter the flow of execution of the program, but remember EXAMPLE:
>>>print_twice(„world‟)
that statements, inside the function are not executed until the function is called. World
 A function call is like a detour in the flow of execution. World
 Instead of going to the next statement, the flow jumps to the body of the function, >>>print_twice(56)
56
executes all the statements there, and then comes back to pick up where it left off.
56
>>>print_twice(math.pi)
29 UNIT-V
3.14
FILES, MODULES, PACKAGES
3.14
The same rule of composition that apply to built in functions also apply to user PART-A
defined functions, so we can use any kind of expression as an argument for
print_twice: 1. What is file? List out its types.
>>>print_twice(„spam‟*4)
Spam spam spam spam  FILES refer to a location with Filename that stores information.
Spam spam spam spam  File must be opened to read or Write. Moreover it must be closed after read/write operations to avoid
>>>print_twice(math.cos(math.pi)) data damages.
-1.0  Almost all the information Stored in a computer must be in a file.
-1.0 Types:
 The argument is evaluated before the function is called,so in the example the  Data files
expression „spam‟*4 and math.cos (math.pi)are only evaluated once.  Text files
 The variable can also be used as an argument:  Program files.
EXAMPLE:
>>>book=‟python‟ 2. List out the types of file operations.
>>>print_twice(book)  Open the file.
Python  Read or write
python  Close the file
3. Give the syntax and example of file open.
Syntax:
File_VariableName=Open (“Filename”, ‘mode’)

Example:
f = open(“text.txt”) #open file in current directory
f = open (“text.txt”, ‘w’) #write in text mode
f = open(“text.txt”, ‘r+b’) # read in binary mode

4. What is error? List out the basic categories of error.


 Errors or mistakes in a program are often referred to as bugs.
 The process of finding and eliminating error is called debugging.
 Errors are classified into three groups.

1. Syntax errors.
2. Runtime errors.
3. Logical errors.

5. List out the common python syntax errors.


 Leaving out a keyword.
 Leaving a symbols such as colon, comma or brackets.
 Misspelling a keyword.
6. Give some example of runtime errors. return age

Division by zero. Output:


Trying to access a file which doesn’t exist. raise ValueError("{0} is not a valid age".format(age))
Accessing a list element or dictionary values which doesn’t exist.

7. Give some examples of logical errors. 12. What are the advantages of exception handling?
 It separates normal code from code that handles errors.
 Using integer division instead of floating point division.
 Exception can easily be passed along functions in the stack until they reach a
 Wrong operator precedence.
 Mistakes in Boolean expression.
function.
 Indenting a block to the wrong level.
 Error in Boolean Expression. 13. Differentiate module and package in python.

8. What is exception in python? Module Package


 Exception is an event, which occurs during the execution of a program. 1. A module is a single file that are 1. A package is a collection of modules
 Exception disrupts the normal flow of the programs instructions. imported under one import. in directories that give a package
 Exception is a python object that represents an error. hierarchy.
2. Example: 2. Example:
9. How to handle exception in python. import my_module from pots import pots
 Python provides two very important features to handle any unexpected error in the
python programs and to add debugging capabilities in item.
 Exception handling.
PART-B
 Assertions.
1. Discuss with suitable example (i) Read a File (ii) Write a file (iii) Close a file
10. List any four standard exceptions in python.
(or)
Standard Exceptions:
Explain the file concepts in detail with example.
1. Floating Point Error-Raised when floating point calculation fails.
2. Import error-Raised when an import statement fails. FILES
3. Syntax error-Raised when there is an error in python syntax.
 FILES refer to a location with Filename that stores information. Like a book a File must be opened to
4. Indentation error-Raised when indentation is not specified properly
read or Write. Moreover it must be closed after read/write operations to avoid data damages.
 Almost all the information Stored in a computer must be in a file.
11. Give the syntax for raise exception.  A File is a named location on disk to store related information.
12. We can raise exceptions in several ways by using the raise statement.
Syntax: CREATE A TEXT FILE:
Raise(Exception(,args(,traceback)))
 Text file in Python, Lets Create a new text file:
Example:
Example:
file = open(“sample1.txt”, “w”)
def get_age():
age = int(input("Please enter your age: ")) file.write(“Hello World”)
if age < 0: file.write(“God is great”)
my_error = ValueError("{0} is not a valid age".format(age)) file.write(“Think Positive”)
raise my_error file.close()
 If you Open the text file, Python interpreter will add the text into the file. Syntax
Output: File_variablename.read(count);
Hello World Example:
God is great #opens a file
Think Positive. f = open (“sample.txt”, “r+”)
str=f.read(10);
OPENING A FILE: print(“Read the string:”,str)
f.close()
 Python has a built-in function Open( ) to open a file. Output: Read the string: God is great.
 The contents of a file can be read by opening the file in read mode. There are various modes to open a
file. They are listed below:
2. Explain about the concepts of format operator.
Syntax:
File_VariableName=Open (“Filename”, ‘mode’)
Where  Format operator is used to print the output in a desired format.
 “File_VariableName” is the variable to add the file object.  The % operator is the format operator.
 It is also called as interpolation operator.
 “Mode” tells the interpreter and developer which way the file will be used.
 The % operator is also used for modulus.
Example:
 The usage varies according to the operands of the operator.
f = open(“text.txt”) #open file in current directory
f = open (“text.txt”, ‘w’) #write in text mode Syntax:
f = open(“text.txt”, ‘r+b’) # read in binary mode <format operator>% values.
Example:
READING AND WRITING FILES: >>>camels=42
 In General,there are two methods to manipulate the files, They are given below: >>>’%d’% camels
 Write( ) ‘42’
 Read () >>>camels=42
>>>’I have spotted %d camels’% camels
Write ( ) Method: ‘I have spotted 42 camels’
 This method writes any string to an open file. >>>In %d years I have spotted %f %s’(3,0.1,’camels’)
Syntax: ‘In 3 years I have spotted 0.1 camels’
File_Variablename.Write(string);
Example
#open a file 3. Illustrate about the concept of errors and exception. Explain the types of error.
f = open(“sample.txt”, ‘w’)
f.write(“ God is Great.\n God is always with me!\n”);
 Errors or mistakes in a program are often referred to as bugs.
#close the opened file
 The process of finding and eliminating error is called debugging.
f.close( )
 Errors are classified into three groups.
In the above example the methods would create sample.txt file and would write the given content in that file,
finally it would close that file. (\n) adds a newline character.
4. Syntax errors.
Sample.txt
5. Runtime errors.
God is Great
God is always with me! 6. Logical errors.

SYNTAX ERRORS:

Read ( ) Method:  Python can only execute a program, if the syntax is correct, otherwise interpreter displays error
 This Method read a string from a file. It is important to note that Python strings can have binary data message.
apart from text data.
 Python will find these kinds of error when it tries to parse a program and exit with an error message 4. Describe in detail how exceptions are handled in python. Give relevant examples.
without running anything.  Exception is an event, which occurs during the execution of a program.
 Syntax errors are mistakes in the use of the python language or grammar mistakes.  Exception disrupts the normal flow of the programs instructions.
 Exception is a python object that represents an error.
Common python syntax errors include:

 Leaving out a keyword. Standard Exceptions:


 Leaving a symbols such as colon, comma or brackets. 1. Floating Point Error-Raised when floating point calculation fails.
 Misspelling a keyword 2. Import error-Raised when an import statement fails.
 Incorrect indentation. 3. Syntax error-Raised when there is an error in python syntax.
RUNTIME ERROR: 4. Indentation error-Raised when indentation is not specified properly.
5. EOF error-Raised when there is no input until the end of while.
 The second type of error is a runtime error. It does not appear until after the program has started 6. IOError- open()function when trying to open a file that does not exist.
running. 7. ArithmeticError-Base class for all errors that occur for numeric calculation.
 The program may exit unexpectedly during execution. 8. AssertionError-Raised in case of failure of the assert statement.
 Runtime error was not detected when the program was parsed. 9. RuntimeError-Raised when a generated error does not fall into any category.
10. ValueError-Raised when the built in functions for a data type has the valid type of arguments,but the
Common python runtime errors include:
have invalid values specified.
 Division by zero.
Ex:
Syntax:
>>> print(55/0) Try:
ZeroDivisionError: integer division or modulo by zero.
Operator
 Trying to access a file which doesn’t exist.
……
 Accessing a list element or dictionary values which doesn’t exist.
Except exception:
Ex:
>>> a = [] If there is exception, execute this block.
>>> print(a[5]) Except Exception
IndexError: list index out of range If there is exception, execute this block.
 Using an identifier which has not be defined. …..
else
If there is no exception, then execute this block.
LOGICAL ERRORS: Example:
 Logical errors are more difficult to fix. It tries to open a file where do not have write permission, so it raises exception.
 The program runs without crashing, but produces an incorrect result. Try:
 The error is caused by a mistake in the programs logic. fh=open(“testfile”,’r’)
 Error message will not be appeared, because no syntax or runtime error has occurred. fh.write(“This is my test file for exception handling!”)
Common python logical errors include: Except IOerror
Print(“error:can’t find file or read data”)
 Using integer division instead of floating point division. else:
 Wrong operator precedence. Print(“written content in the file successfully”)
 Mistakes in Boolean expression.
 Indenting a block to the wrong level. Output:
 Error in Boolean Expression. Error: can’t find file or read data.

Raising An Exceptions:
 We can raise exceptions in several ways by using the raise statement.
Syntax:
Raise(Exception(,args(,traceback))) # Import statement example
import math
Example: print("The value of pi is", math.pi)

def get_age():
OUTPUT:
age = int(input("Please enter your age: ")) The value of pi is 3.14
if age < 0:

# Create a new instance of an exception


my_error = ValueError("{0} is not a valid age".format(age)) Python from...import statement:
raise my_error
return age
 Import specific names form a module without importing the module as a whole. Here is
an example.
Output:
raise ValueError("{0} is not a valid age".format(age))

5. Illustrate the important of modules with examples. # import only pi from math module

 Modules refer to a file containing Python statements and definitions. from math import pi
 Modules to break down large programs into small manageable and organized files. print("The value of pi is", pi)

The value of pi is 3.14


# Python Module example
The value of pi is 3.141592653589793
The from...import * Statement:
def add(a, b):
"""This program adds two  It is also possible to import all names from a module into the current namespace by using
the following import statement.
numbers and return the result"""
result = a + b from modname import *
return result
This provides an easy way to import all the items from a module into the current namespace.
How to import modules in Python?
6. Discuss Python Package in detail.
 We can import the definitions inside a module to another module or the interactive interpreter in
Python.
 >>> import example  A package is a collection of modules in directories that give a package hierarchy.
 Using the module name we can access the function using dot (.) operation.
 For example:  The package gives the hierarchical file director structure of the python application environment
>>> example.add(4,5.5) that consists of modules and package.

 A package is a directory which contains a special file called __init__.py


Python import statement:

We can import a module using import statement and access the definitions inside it using the dot
operator.
Example:

 If the project team has decided to maintain all the modules in “MyProject” directory, a folder in
the name of “MyProject” is creacted and the file __init__.py is placed in that folder.

 The package has two normal programs and two subpackages.

Importing module from a package:

The modules in package can be used by importing then in python program.

Syntax:

Import<packageName>.{<subpackageName>.}ModuleName>

 The {} braces specify that there can be any number of subpackages.

Example:

Import MyProject.subproject1.prog1_1

MyProject.subProject1.Prog1_1.start()

You might also like