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

Important Ques Python

The document provides an overview of Python's data structures, specifically focusing on lists, tuples, and dictionaries. It covers definitions, operations, methods, and differences between these data types, along with examples for clarity. Key topics include list slicing, cloning, aliasing, and the mutable vs immutable nature of these data types.

Uploaded by

Satyam Singh
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)
2 views56 pages

Important Ques Python

The document provides an overview of Python's data structures, specifically focusing on lists, tuples, and dictionaries. It covers definitions, operations, methods, and differences between these data types, along with examples for clarity. Key topics include list slicing, cloning, aliasing, and the mutable vs immutable nature of these data types.

Uploaded by

Satyam Singh
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/ 56

1

UNIT-III
LIST,TUPLES,DICTIONARIES
TWO MARKS:

1. Define List with 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.
Example 1:[10, 20, 30, 40] # list of four integers Example 2:['frog', 'Dog', 'Cow'] # list of
three strings

2. What are the list operations?


• 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. The + operator
concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c
[1, 2, 3, 4, 5, 6]

• Similarly, the * operator repeats a list a given number of times:


>>> [0] * 4
[0, 0, 0, 0]# It repeats [0] four times
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3] # It repeats the list [1, 2, 3] three times.

3. Describe list slicing with examples.

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


subsequence is called slicing.

The slice operator also works on lists:


>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
Output : ['b', 'c']

>>> t[:4]
Output:['a', 'b', 'c', 'd']

>>> t[3:]
Output:['d', 'e', 'f']

>>> t[:]
Output : ['a', 'b', 'c', 'd', 'e', 'f']
2

4. What is Cloning of List?


➢ 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.
➢ This process is sometimes called cloning, to avoid the ambiguity of the copy.
➢ The easiest way to clone a list is to use the slice operator.

Example:
>>>a=[1,2,3]
>>>b=a[:]
>>>print b
[1,2,3].

5. Illustrate negative indexing in list with an example.

Index can have negative value, it counts backward from the list.
Example:
>>> Fruit = ['Apple', 'Grapes', 'Orange']
>>>Fruit(0) = ‘pear’
>>>Fruit(-1) = ‘Jackfruit’
>>>print (fruit)
[‘pear’, ‘grape’, ‘Jackfruit’]

6. What is Aliasing?
• More than one list variable can point to the same data. This is called an alias.
• If ‘A’ refers to an object and you assign ‘ B = A’, then both variables refer to the same
object:
>>> A = [1, 2, 3]
>>> B= A
>>> B is A
True

7. What is the purpose of list methods? Types of List method?


• Python has a number of built-in data structures, including lists.
• Data structures provides us with a way to organize and store data. We can use built-in
methods to retrieve or manipulate that data.

1.List.append( ) 5.List.insert ( ) 9.List.reverse( )


2.List.remove( ) 6.List.pop ( ) 10.List.clear ( )
3.List.copy ( ) 7.List.sort ( ) 11.List.index ( )
4.List. Count ( ) 8.List.extend ( )

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.
Since list mutable changes made to the parameter changes the argument as well.
• 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.
3

For example, delete_head removes the first element from a list:


def delete_head(t):
del t[0]
Here’s how it is used:
>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> print letters
['b', 'c'].
9. Define Tuples?
• A tuple is a sequence of values.
• The values can be any type, and they are indexed by integers, so in that respect tuples are a
lot like lists. The important difference is that tuples are immutable.

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:
>>> t = ('a', 'b', 'c', 'd', 'e')

To create a tuple with a single element, you have to include the final comma:
>>> t1 = ('a',)
>>> type(t1)
<type 'tuple'>

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

Example:
Two element in list (which is a sequence ) and assign the first and second elements of the variables
x and y in a single statement.

>>> m = ( ‘have’, ‘fun’)


>>> x,y= m
>>> x
‘have’
>>>y
‘fun’

11. Give Example for Tuple as Return Values?

• A function can only return one value, but if the value is a tuple, the effect is the same as
returning multiple values.
Example:

>>> t = divmod(7, 3)
>>> print t
(2, 1)
4

Or use tuple assignment to store the elements separately:


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

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]


Example:
>>> a = [11,22,33,44]
>>> b =[x*2 for x in a]
>>>b
[22,44,66,88]

13. List the function of Tuple Data Types?


S.No Function Description
1 Cmp(tup1,tup2) Compare elements of both tuples
2 Len(tuple) Gives the total length of the tuple
3 Max(tuple) Returns item from the tuple with max value
4 Min(tuple) Returns item from the tuple with min value
5 Sorted(tuple) Sort the tuple in ascending or descending

14. What is the difference between Tuples and List in Python?

• The main difference between list and tuples are:


• List are enclose in square bracket [ ] and their elements size can be changed, while tuples
are enclosed in parentheses ( ) and cannot be updated.

15. Define Mutable and Immutable data type?

• Immutable data value: A data value which cannot be modified. Assignments to elements
or slices of immutable values causes a runtime error
• Mutable data value: A data value which can be modified .The Types of all mutable value
are compound types.List and dictionaries are Mutable; Strings and Tuple are not.

16. Differentiate between append( ) and extend ( ) methods?


• Both append ( ) and extend ( ) methods belong to the list method.These methods are used
to add the elements to the list.
• Append(element) – adds the given element at the end of the list or at the given index
postion which has called this method
• Extend (another_list)- adds the element of another-list at the end of the list which is
called the extend method.
5

17. When is a dictionary used instead of a list?


• Dictionaries are best suited when the data is labelled ie. The data is a record with field
names.
• List are better option to store collection of un-labelled items say all the files and
subdirectories in a folder.
• Generally search operation on dictionary object is faster than searching a list objects
.
18. Differentiate between tuples and dictionaries.

Tuples Dictionaries
• A tuple is a sequence of values. • Python dictionary are kind of hash table
• The values can be any type, and they are type.
indexed by integers, so in that respect • Dictionary work like associative arrays or
tuples are a lot like lists. The important hashes found in perl and consist of key
difference is that tuples are immutable. value pairs.

19. Define dictionary with an example.

• Dictionary is one of the compound data type like strings, list and tuple. Every element in a
dictionary is the key-value pair.
• An empty dictionary without any items is written with just two curly braces, like this: {}.

Example:
>>> eng2sp = {}
>>> eng2sp["one"] = "uno"
>>> eng2sp["two"] = "dos"
>>> print(eng2sp)

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={ }
6

22. List out the methods on dictionaries?

S.No Method Description

1 dict.clear() Removes all elements of dictionary dict

2 dict.copy() Removes all elements of dictionary dict

3 dict.items() Returns a list of dict's (key, value) tuple pairs

4 dict.keys() Returns list of dictionary dict's keys

5 dict.values() Returns list of dictionary dict's values

23. List out the operations on dictionaries?

Operation Description
cmp(dict1, dict2) Compares elements of both dict.

len(dict) Gives the total length of the dictionary.

str(dict) Produces a printable string representation of a dictionary

type (variable) Returns the type of the passed variable. If passed variable is dictionary,
then it would return a dictionary type.

16 MARKS

1. Explain Python implementation of Stack ADT.


2. What is List Values? Describe about creating a list, accessing the values in list, deleting a
list, updating a list.

LIST VALUES:

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

There are several ways to create a new list, the simplest is to enclose the elements in square
Bracket
[]

[10, 20, 30, 40] # list of four integers


['frog', 'Dog', 'Cow'] # list of three strings

The elements of a list don’t have to be the same type.


['spam', 2.0, 5, [10, 20]] # list contains a string, a float, an integer, and another list:
7

A list within another list is nested.


A list that contains no elements is called an empty list;
We can create one with empty brackets [].

ACCESSING VALUES IN LIST:

We can assign list values to variables:


>>> Fruits = ['Apple', 'Watermelon', 'Banana']
>>> numbers = [17, 12.3]
>>> empty = [ ]
>>> print ( Fruits)
>>>print( numbers)
>>>print(empty)

Output:
['Apple', 'Watermelon', 'Banana']
[17, 12.3]
[]

DELETING A LIST:
➢ Any element in the list can be deleted, del removes an element from a list.
Example:

>>> a=(‘one’,’two’,’three’)
>>>del a(1)
>>>a

Output:
(‘one’,’three’)

UPDATING A LIST:
A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print t
Output: ['a', 'x', 'y', 'd', 'e', 'f'].

2. Explain the basic List Operations and list slices in details with necessary programs.
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.
8

Python Expression Description Results


len([1, 2, 3]) Length 3
[1, 2, 3] + [4, 5, 6] Concatenation [1, 2, 3, 4, 5, 6]
['Hi!'] * 4 Repetition ['Hi!', 'Hi!', 'Hi!', 'Hi!']
3 in [1, 2, 3] Membership True

The + operator concatenates lists:


>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c
[1, 2, 3, 4, 5, 6]

Similarly, the * operator repeats a list a given number of times:


>>> [0] * 4
[0, 0, 0, 0]# It repeats [0] four times
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3] # It repeats the list [1, 2, 3] three times.

LIST SLICES:
➢ A sub-sequence of a sequence is called a slice and the operation that performs on
subsequence is called slicing.

The slice operator also works on lists:


>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
Output : ['b', 'c']

>>> t[:4]
Output:['a', 'b', 'c', 'd']

>>> t[3:]
Output:['d', 'e', 'f']

>>> t[:]
Output : ['a', 'b', 'c', 'd', 'e', 'f']

Since lists are mutable, it is often useful to make a copy before performing operations..
A slice operator on the left side of an assignment can update multiple elements:

>>> t = ['a', 'b', 'c', 'd', 'e', 'f']


>>> t[1:3] = ['x', 'y']
>>> print t
Output: ['a', 'x', 'y', 'd', 'e', 'f'].
9

3. Discuss the Python List Methods with examples.(16 mark)

Python provides methods that operate on lists.

The various methods used in list are:

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


2.List.remove( ) 6.List.sort ( ) 10. List.index ( )
3. List. Count ( ) 7.List.extend ( )
4. List.insert ( ) 8.List.reverse( )

1.List.append( ): 2. List.remove ( )
➢ 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
Example Eg value but removes the given object from
1: the list.
x = [123, 'xyz', 'zara', 'abc']; x.append Example
( 2009 ); y = [123, 'xyz', 'zara', 'abc',
print ( "Updated List : ", x) 'xyz']; y.remove('xyz'); print(
Output: Updated List: [123, 'xyz', 'zara', 'abc', "List 1 : ", y); y.remove('abc');
2009] print( "List 2: ", y)
Output:
Eg 2: List 1: [123, 'zara', 'abc', 'xyz']
>>> t = ['a', 'b', 'c'] List 2: [123, 'zara', 'xyz'
>>> t.append('d')
>>> print ( t)
Output:['a', 'b', 'c', 'd']
3. List.count ( ) 4. List.insert ( )
➢ The method returns the count of how many ➢ List.insert ( ) method inserts an object
times an element occurs in specified list. into the list at the offset of an index.
Example ➢ Syntax : List.insert (index,object) #index
X = [123, 'xyz', 'zara', 'abc', 'xyz',123, ‘xyz’]; position starts from 0.
Print (“Count for 123:”,X.count(123)) Example
Print (“Count for Zara:”,X.count(‘zara’)) X = [123, 'xyz', 'zara', 'abc'];
Print (“Count for xyz:”,X.count(‘xyz’)) X.insert (3,2009)
Print( “Final List :”,X)
Output:
Output:
Count for 123: 2
Count for Zara: 1 Final List: [123, 'xyz', 'zara', 2009,'abc'];
Count for xyz: 3
5. List.pop ( ) 6. List.Sort ( )
10

➢ List.pop ( ) method is used to return the item ➢ List.Sort ( ) method is used to sort the items
at the given index position from the list and in the list.
the removes that item.
Example
Example X = [54, 12, 85, 65, 74, 90];
X = [123, 'xyz', 'zara', 'abc']; Print(“sorted list:”, X.sort ( ))
Print( “List 1 :”,X.pop(0))
Print (“List 2: ”, X.pop(3)) Output: Output:
Sorted list= [12,54 ,65,74,85,90]
List 1: [ 'xyz', 'zara', 2009,'abc'];
List 2: [123, 'xyz', 'zara',]

7.List.reverse ( ) 8. List.clear ( )
➢ List.reverse ( )can reverse the order of items ➢ List.clear() can remove all values contained
in a list by using this method. in it by using this method.

Example Example
X = [123, 'xyz', 'zara', 'abc',’xyz’]; X = [123, 'xyz', 'zara', 'abc',’xyz’];
X.reverse( ) X..clear( )
Print ( “List 1 :”,X) Print (X)

Output: List 1: ['xyz', 'abc', 'zara', 'xyz', Output:


123] []

➢ We get square bracket as our output after


using list.clear ( ) method , it implies that
the list is now clear of all items.
9.List.index ( ) 10.List.extend ( )
➢ When list starts to get long, it becomes ➢ If we want to combine more than one list ,
more difficult for us to count out the items we use extend method .
in the list.
➢ So we determine at what index position the Example Eg
items are located. 1:
X = [123, 'xyz', 'zara', 'abc', 123];
Example Y = [2009, 'manni'];
x = [123, 'xyz', 'zara', 'abc']; X.extend(Y)
Print(“Index for xyz:”, x.index(‘xyz’)) Print(X)
Print(“Index for 123:”,x.index(123))
Print(“Index for zara:”,x.index(‘Zara’) Output:
Extended List= [123, 'xyz', 'zara', 'abc', 123,2009,
Output: ‘manni’];
Index for xyz: 1
Index for 123: 0
Index for zara: 2
11

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
repeats itself until it run out of items to work with or until a certain condition is met.
• Our loop will run once for every item in our list,

#LIST LOOPING EXAMPLE 1:


Colours_list=[“red”, “green”, “yellow”, “blue”,
“purple”] for i in colours_list: Print(i)
Output:
Colours in the list
Red
Green
Yellow Blue
Purple.

EXAMPLE 2:
Month_list = [“Jan”, “Feb”, “March”, “April”,
“May”] Print(“months in the list”) for month in
month_list: Print (month)
OUTPUT:
Months in the list
Jan
Feb
March
April
May

List Mutability:

• 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 a string—the bracket operator.
• The expression inside the brackets specifies the index. Remember that the indices start at
0.

>>> Fruit = ['Apple', 'Grapes', 'Orange']


>>>print (fruit(0))
Apple
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print numbers
12

.
The in operator also works on lists.
>>> Fruit = ['Apple', 'Grapes', 'Orange']
>>> ‘Apple’ in Fruit
True
>>> ‘Watermelon’ in Fruit
False

Index can have negative value, it counts backward from the list.
Example:

>>> Fruit = ['Apple', 'Grapes', 'Orange']


>>>Fruit(0) = ‘pear’
>>>Fruit(-1) = ‘Jackfruit’
>>>print (fruit)
[‘pear’, ‘grape’, ‘Jackfruit’]

#List Mutable Example


Colours_list=[“red”, “green”, “blue”, “purple”]
Print (“original list:”,colour_list)
#red is changed to pink
Colour_list[0]= “pink”

#blue is change to orange


Colour_list [-2] = “orange”
Print(colour_list)

Output:
Original List =[“red”, “green”, “blue”, “purple”]
[“pink”, “green”, “orange”, “purple”].

5. Discuss about the list aliasing, cloning list and list parameter with examples.

LIST ALIASING:
• Since variables refer to object, If ‘A’ refers to an object and you assign ‘ B = A’, then both
variables refer to the same object:
>>> A = [1, 2, 3]
>>> B= A
>>> B is A
True
• In this case, Diagram looks like this

[1,2,3]

• The association of a variable with an object is called a reference. In this example, there are
two references to the same object.
13

• An object with more than one reference has more than one name, then the object is said to
be aliased.
If the aliased object is mutable, changes made with one alias affect the other:
>>> B[0] = 9
>>> print A
[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.

• For immutable objects like strings, aliasing is not as much of a problem.

In this example:
A = ('banana')
B=( 'banana')
It almost never makes a difference whether A and B refer to the same string or not.

CLONING LIST:
• If we want to modify a list and also keep a copy of the original, we need to be able to make
a copy of the list itself, not just the reference.
• This process is sometimes called cloning, to avoid the ambiguity of the copy.
• The easiest way to clone a list is to use the slice operator
>>>a=[1,2,3]
>>>b=a[:]
>>>print b
[1,2,3]
• Taking any slice, creates a new list. In this case the slice happens to consists of the whole
list.
• Now we are free to make changes to b without worrying about list ‘a’.
>>>b[0]=5
>>>print a
>>>print b
[1,2,3]
[5,2,3]

LIST PARAMETERS:

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

For example, delete_head removes the first element from a list:


def delete_head(t):
del t[0]
Here’s how it is used:
>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> print letters
['b', 'c']
• The parameter t and the variable letters are aliases for the same object. The stack diagram
looks like this:
14

__Main__ Letters
0 → ‘a’

1 → ‘b’
Delete_head t
2 → ‘c’

• 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 new lists.
For example, the append method modifies a list, but the + operator creates a new list:
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print t1
[1, 2, 3]
>>> print t2
None
>>> t3 = t1 + [3]
>>> print t3
[1, 2, 3]
>>> t2 is
t3 False.

6. Explain about tuples and also the concept of tuple assignment and tuples as return value
with example.
• A tuple is a sequence of values.
• The values can be any type, and they are indexed by integers, so in that respect tuples a
like lists. The important difference is that tuples are immutable.

➢ 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:
>>> t = ('a', 'b', 'c', 'd', 'e')

➢ To create a tuple with a single element, you have to include the final comma:
>>> t1 = ('a',)
>>> type(t1)
<type 'tuple'>

➢ Without the comma, Python treats ('a') as a string in parentheses: >>> t2 = ('a')
>>> type(t2)
<type 'str'>

➢ Another way to create a tuple is the built-in function tuple. With no argument, it
creates an empty tuple:
>>> t = tuple()
>>> print (t)
()
➢ If the argument is a sequence (string, list or tuple), the result is a tuple with the
elements of the sequence:
>>> t = tuple('lupins')
>>> print (t)
('l', 'u', 'p', 'i', 'n', 's')
15

➢ Because tuple is the name of a built-in function, avoid using it as a variable name.

➢ Most list operators also work on tuples. The bracket operator indexes an element:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print (t[0])
'a'
And the slice operator selects a range of elements.
>>> print t[1:3]
('b', 'c')
But if you try to modify one of the elements of the tuple, you get an error:
>>> t[0] = 'A'
TypeError: object doesn't support item assignment

➢ can’t modify the elements of a tuple, but you can replace one tuple with another:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>>t = ('A',) + t[1:]
>>> print (t)
('A', 'b', 'c', 'd', 'e')

TUPLE ASSIGNMENT:

• One of the unique features of the python language is the ability to have a tuple on the left
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
sequence.

In the below example , we have two element list (which is a sequence ) and assign the first and
second elements of the variables x and y in a single statement.
>>> m = ( ‘have’, ‘fun’)
>>> x,y= m
>>> x
‘have’
>>>y
‘fun’

Python roughly translates the tuple assignment syntax to be the following;


>>>m = (‘have’, ‘fun’)
>>>x = m(0)
>>>y = m(1)
>>>x
‘have’
>>>y
‘fun’
• It is often useful to swap the values of two variables. With conventional assignments, you
have to use a temporary variable. For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp

Tuple assignment is more elegant:


>>> a, b = b, a
16

• The left side is a tuple of variables; the right side is a tuple of expressions. Each value is
assigned to its respective variable. All the expressions on the right side are evaluated
before any of the assignments.
• The number of variables on the left and the number of values on the right have to be the
same:
>>> a, b = 1, 2, 3

ValueError: too many values to unpack.

TUPLES AS RETURN VALUES:

• A function can only return one value, but if the value is a tuple, the effect is the same as
returning multiple values.
• For example, if you want to divide two integers and compute the quotient and remainder, it
is inefficient to compute x/y and then x%y. It is better to compute them both at the same
time.
• The built-in function divmod takes two arguments and returns a tuple of two values, the
quotient and remainder.
You can store the result as a tuple:
>>> t = divmod(7, 3)
>>> print t
(2, 1)

Or use tuple assignment to store the elements separately:


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

Example of a function that returns a tuple:


def min_max(t):
return min(t), max(t) max and min are built-in functions that find the largest and
smallest elements of a sequence.
min_max computes both and returns a tuple of two values.

7. What is dictionary in python? List out the operations and methods with example.

• Keys are unique within a dictionary while values may not be.
• The values of a dictionary can be of any type, but the keys must be of an immutable data
type such as strings, numbers, or tuples.
• Dictionary is one of the compound data type like strings, list and tuple. Every element in a
dictionary is the key-value pair.
• An empty dictionary without any items is written with just two curly braces, like this: {}.

Creating a Dictionary:
• 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 {}.
17

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={ }

Example:
#Keys-Value can have mixed datatype

Dict1 = {1: “Fruit”, 2: “Vegetabe”,3: “Fish”}


Dict2={“Name”: “Zara”, “Subject”:[“Maths”, “Phy”, “Chemistry”],
“Marks”:[198,192,193],
“Avg”:92}

Accessing Elements in Dictionary:


• To access dictionary elements, you can use the familiar square brackets along with the key
to obtain its value.
• Since Dictionary is an unordered Data type. Hence the indexing operator cannot be used to
access the Values.
• To access the data, we have to use key which is associated with the Value.

Example:
>>Dict2={“Name”: “Zara”, “Subject”:[“Maths”, “Phy”, “Chemistry”],
“Marks”:[198,192,193], “Avg”:92}
>>Dict2[“Name”]
>>Dict2[“Avg”]
>>Dict2[“Subject”]

Output:
Zara
20.1
[“Maths”, “Phy”, “Chemistry”]

Deleting Element in Dictionary:


• The element in the dictionary can be deleted by using Del statement.
• The entire dictionary can be deleted by specifying the dictionary variable name.

Syntax: Del (dictionary_Name)<Key-Value>

Example:

>>> dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


>>> del dict['Name']
>>> dict
{'Age': 7, 'Class': 'First'
Updating Element in Dictionary:
18

• In Dictionary the Keys are immutable, however the values are mutable.
• Hence only the Value pair can be Updated

Example

>>> My_dict={'Name':'Nivetha','rank':5,'Average':78.9}
>>> My_dict['rank']=3
>>> My_dict
{'Name': 'abi', 'rank': 3, 'Average': 78.9}

DICTIONARY METHODS:

S.No Method Description


1 dict.clear() Removes all elements of dictionary dict
2 dict.copy() Removes all elements of dictionary dict
3 dict.items() Returns a list of dict's (key, value) tuple pairs
4 dict.keys() Returns list of dictionary dict's keys
5 dict.values() Returns list of dictionary dict's values

6 dict.update(dict2) Adds dictionary dict2's key-values pairs to dict


Create a new dictionary with keys from seq and
7 dict.fromkeys()
values set to value.

8 dict.get(key, default=None) For key, returns value or default if key not in dictionary

dict.has_key(key)
9 Returns true if key in dictionary dict, false otherwise

DICTIONARY OPERATION:
Operation Description Input Function Output
Dict1={“Name”:”zara”,”Age”:14,”sex”:”M Cmp(dict1,di 1
Compares ”} ct2) 0
cmp(dict1,
elements of both Cmp(dict2,d
dict2) Dict2={“Name”:”zara”,”Age”:14}
dict.
ict3)
Dict3={“Name”:”zara”,”Age”:14}
len(dict) Gives the total Dict1={“Name”:”zara”,”Age”:14,”sex”:”M Len(dict1) 2
length of the ”} Len(dict2) 3
dictionary. Dict2={“Name”:”zara”,”Age”:14}
str(dict) Produces a Dict1={“Name”:”zara”,”Age”:14,”sex”:”M Str(dict1) {“Name”:
printable string ”zara”,”A
”}
representation of a ge”:14,
dictionary ,”sex”:”M
”}
type Returns the type of Dict1={“Name”:”zara”,”Age”:14,”sex”:”M Type(dict1) <type
(variable) the passed variable. ‘dict’>
”}
If passed variable
is dictionary, then it
would return a
dictionary type.
19

Example:
>>>dict1 = {1: “Fruit”, 2: “Vegetabe”,3: “Fish”}
>>>Print(dict1)
>>>{1: “Fruit”, 2: “Vegetabe”,3: “Fish”}
>>> del dict[1]
>>>print(dict1)
>>>{ 2: “Vegetabe”,3: “Fish”}

The len function also works on dictionaries; it returns the number of key:value pairs:
>>> len(dict1)
3

8. Illustrate List Comprehension with suitable examples.


(or)
Explain about the advanced list processing.

• 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.
• However,in a list Comprehension, the for statement header is prefixed with an expression and
surrounded by square bracket.

Syntax : [Expr(x) for x in iterable]

Where:
Expr(x) is an expression,usually but not always containing X.
Iterable is some iterable.An itrable may be a sequence or an unordered collection a list, string or
tuple.
Example 1:
>>> a = [11,22,33,44]
>>> b =[x*2 for x in a]
>>>b
[22,44,66,88]
Example 2:
Given the following list of strings:
Names= [‘alice’, ‘ramesh’, ‘nitya’]
A list of all upper case Names
A List of Capitalized ( first letter upper case)
>>>[x.upper() for x in names]
[‘ALICE’, ‘RAMESH’, ‘NITA’]
>>>[x.capitalize() for x in names]
[‘Alice’ , ‘Ramesh’ , ‘Nita’]
Example 3:
>>> fish_tuple=('blowfish','clowfish','catfish','octopus')
>>> fish_list=[fish for fish in fish_tuple if fish != 'octopus']
>>> print(fish_list)
['blowfish', 'clowfish', 'catfish']
20

Example 4: My_list=[] for


x in [20,40,60]: for
y in [2,4,6]:
My_list.append(x*y)
print (My_list)
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
iteration
Program For Example 4 using List Comprehension
My_list=[x*y for x in [20,40,60] for y in [2,4,6]]
print(My_list)
Output: [40, 80, 120, 80, 160, 240, 120, 240, 360]
List Comprehensions allows us to transform one list or other sequence into a new list. They
Provide a concise syntax for completing the task and limiting the lines of code.
Example 5:
#To create a simple list
x=[ i for i in range (10)]
print (x)
Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

ILLUSTRATIVE PROGRAMS:
1. SELECTION SORT: def
selectionSort(alist): for fill slot in
range(len(alist) - 1, 0, -1):
positionOfMax = 0 for location in
range(1, fillslot + 1): if
alist[location]
>alist[positionOfMax]:
positionOfMax = location
temp = alist[fillslot]
alist[fillslot] = alist[positionOfMax]
alist[positionOfMax] = temp
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
selectionSort(alist)
print(alist)

OUTPUT:
[26, 54, 93, 17, 77, 31, 44, 55, 20]

2. INSERTION SORT: def


insertionSort(alist): for index in
range(1,len(alist)):
currentvalue = alist[index] position = index while
position > 0 and alist[position - 1] >currentvalue:
alist[position] = alist[position - 1] position = position
- 1 alist[position] = currentvalue alist = [54, 26, 93,
17, 77, 31, 44, 55, 20] insertionSort(alist)
print(alist)

OUTPUT:
[54, 26, 93, 17, 20, 77, 31, 44, 55]
21

3. MERGE SORT: def mergeSort(alist):


print("Splitting ",alist) if len(alist)>1:
mid = len(alist)//2 lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf) mergeSort(righthalf)
i=0 j=0 k=0 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]
Splitting [31]
Merging [31]
Merging [31, 77]
Splitting [44, 55, 20]
Splitting [44]
Merging [44]
Splitting [55, 20]
22

Splitting [55]
Merging [55]
Splitting [20]
Merging [20]
Merging [20, 55]
Merging [20, 44, 55]
Merging [20, 31, 44, 55, 77]
Merging [17, 20, 26, 31, 44, 54, 55, 77, 93]

CONTROL FLOW, FUNCTIONS


SYLLABUS:

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

TWO MARKS

1. Define Boolean values

The Boolean data type have 2 values (usually denoted by True or False), When 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.
2. List out the Boolean operators.

 Or operator.
 And operator.  Not operator.

3. Define conditional statements.

 The execution of the program acts according the conditions. This concept is known as
Conditional statements or Branching Statements.

 Conditional Statements are used to perform different computation or action depending


on whether a condition evaluates to TRUE or FALSE.

1. If Statement
2. If...else Statement
3. If..elif..else Statement
4. Nested if...elif..Else Statement.

4. Write the syntax of if and if-else statements.

 Condition if:The boolean expression after the if statement is called the condition. If it
is true, then the indentedstatement gets executed. Syntax:
23

if (Condition):
True Statement Block
 Alternative(IF....Else Statement):A second form of the if statement is alternative
execution, in which there are two possibilities and the condition determines which one
gets executed.
Syntax:
if (Condition):
True Statement Block
else:
False Statement Block

5. What is the purpose of iteration? Give example.

 A loop statement allows us to execute a statement or group of statements


multiple times.
 Repeated execution of a set of statements is called iteration.

Example:

Count=0
While(count<9):
Print’the count is:’,count
Count=count+1

6. Illustrate the flow chart of if-elif- else statements.

False
Test
Condition 1

False
True
elif Test
Condition 2
Body of if –Statement
True Body of Else
Block 1

Body of elif –
Statement Block 2

7. What are unconditional looping statements?


 Loop that needs to be executed compulsorily without any condition is
called an unconditional loop.
 The loop will be executed in theprogram without any conditional checks.
Example:
 Break statement.
 Continue statement.  Pass statement.
8. Explain about break statement with an example.
 It terminates the current loop and resumes execution at the next statement.
 The most common use for break is when some external condition is triggered
requiring a hasty exit from a loop.
24

 The break statement can be used in both while and for loops.

Syntax:
Break

Example : forletter
in 'Python': if (
letter == 'h'):
break print(“Current Letter :”,
letter)

Output:
Current Letter : P
Current Letter : y
Current Letter : t

9. Discuss about continue and pass statements.

Continue Statement:
• It returns the control to the beginning of the while loop.
• The continue statementrejects all the remaining statements in the current 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.
Syntax:
Continue
Pass Statement:
• It is used when a statement is required syntactically but you do not want any
command or code to execute.
• The pass statement is a null operation; nothing happens when it executes.
Syntax:
Pass

10. What are function and fruitful function?

 Function: It is a block of statement that will execute for a specific task.


 Fruitful function:Functions that return values are called fruitful
function.
Input the value
Return the result
Fruitful functions

 Example: The square function will take one number as parameter and
return the result of squaring that number

11. Define parameter. List out it types.

 Parameter is the input data that is sent from one function to another.
 Parameter is of two types,
Actual parameter.
Formal parameter.

Actual parameter:
 Parameter is defined in the function call.
25

Formal parameter:
 Parameter is defined as part of function definition.
 Actual parameter value is received by formal parameter

12. Classify global variable with local variable.


 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 variable is a variable declared within the function.

Example:

S=10 # s is the global variable


def f1()
S=55# s is the local variable
Print s
Output:
55
13. Describe various methods used on a string. (Any Four)

 is digit()-returns true if string contains only digits and false otherwise.


 islower()-returns true if string has at least 1 cased character and all cased characters are
in lowercase and false otherwise.
 isnumeric()-returns true id a Unicode string contains only numeric characters and false
otherwise.
 isupper()-returns true if string has at least one cased character and all cased characters
are in uppercase and false otherwise.

14. What are the advantages and disadvantages of recursion function?


Advantages:
 Reduces time complexity.
 Performs better in solving problems based on tree structures.
Disadvantages:
 It is usually slower due to the overhead of maintain stack.
 It usually uses more memory of the stack.

15. What is string?Giveexample.


 A string is a sequence of characters.(i.e) it can be a letter , a number, or a
backslash.
 Python strings are immutable, which means they cannot be changed after they
are created.
Example:
Var1='hello world!

16. How will you slice the given string in python?


A segment of a string is called a slice. Selecting a slice is similar to selecting a
character:
Example
>>> s = 'Monty Python'
>>> print s[0:5]
Monty
26

>>> print s[6:13]


Python

17. What will be the output of print str[2:5] if str=’helloworld!’?

H E L L O W O R L D !
0 1 2 3 4 5 6 7 8 9 10

Str=”HELLOWORLD!”
Str[2:5]
O/P = LLO
18. List out the applications of arrays.
Applications - Arrays are used to implement in data structures, such as lists, heaps, hash
tables, deques, queues, stacks and strings.
19. Write a program to iterate a range using continue statement.

for letter in 'Python': if (


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

Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n

20. Define array with an example.

An array is a collection of data that holds fixed number of values of same type.
Forexample: if you want to store marks of 100 students, you can create an array for it.

21.Differentiate for loop and while loop. ?


For Loop While Loop
1.Executes the sequence of statements multiple 1.Repeats a statement until a give
times and abbreviates the code that manages condition is TRUE. It test the While
the loop condition before executing the loop body
2.Eg.Counter = 0 While (counter < 3):
2.Eg. for i in ‘123’:
Print(‘countis:’,counter)
Print (“Welcome”,i, “Times”) Output: Counter=Counter+1
Welcome 1 Times Output:
Welcome 2 Times Count is: 0
Welcome 3 Times Count is: 1
Count is: 2
27

16 MARKS
1. Boolean Value and operators(8m)

 The Boolean data type have 2 values (usually denoted by True or False), When
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.

Boolean and logical operators:

Boolean values respond to logical operators ( AND / OR)

True AND False = False


True AND True = True
False AND True= False
False OR True= True
False Or False= False

 A boolean expression is an expression that is either true or false.

BOOLEAN OPERATORS( and,or,not)


These are the Boolean operation, ordered by ascending priority:

Operation Result
X or Y If X is false then y, else X
X and Y If X is false, then x else Y
Not X If x is false,then true else False

The following examples usethe operator ==, which compares two operands and produces True if
they are equal and False Otherwise:
>>> 5 == 5
True
>>> 5 == 6
False
True and False are special values that belong to the type bool; they are not strings: >>>type
(True)
<type 'bool'>
>>>type(False)
<type 'bool'>

Boolean and Comparison operators:

The == operator is one of the comparison operators; the others are: x!=
y # x is not equal to y
x > y # x is greater than y x < y # x is
less than y x >= y # x is greater than
or equal to y x <= y # x is less than or
equal to y
28

Although these operations are probably familiar to you, the Python symbols are different from
themathematical symbols. A common error is to use a single equal sign (=) instead of a double
equalsign (==). Remember that = is an assignment operator and == is a comparison operator.

2. Explain the branching statements in python with relevant syntax and


example.(16m)
• Control Flow is the order in which individual Statements, instructions are executed
or evaluated.
• 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.
• Some of them are if, if..else, if..elif..else, Nestedif..elif..else, For, While, Nested, Break,
Continue etc

FLOW CONTROL

Conditional Statements Looping Control Structure

• If • While Loop • Break


• If...else • For Loop • Continue
• If..elif..else • Nested loop • Pass
• Nested If..elif..else

Conditional Statements:

• The execution of the program acts according the conditions. This concept is known as
Conditional statements or Branching Statements.

• Conditional Statements are used to perform different computation or action depending


on whether a condition evaluates to TRUE or FALSE.
,
1. If Statement
2. If...else Statement
3. If..elif..else Statement
4. Nested if...elif..Else Statement

1. Conditional (If Statement):

 The Boolean expression after the if statement is called the condition. If it is true, then
the indentedstatement gets executed.
 If the text condition is FALSE, the Statements are not executed.
If statements have the same structure as function definitions: a header followed by an
indented block. Statements like this are called compound statements.
29

Syntax:
if (Condition):
True Statement Block

Flowchart for if statement:


Test
Condition
FALSE

TRUE
True Condition
Example 1: Statement (Body of If)
A=500 B=200
If (A>B):
Print (“A is
greater than B”) Output:
A is Greater than B

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

2.Alternative(IF....Else Statement):

 A second form of the if statement is alternative execution, in which there are two
possibilities and the condition determines which one gets executed.
Syntax:
if (Condition):
True Statement Block
else:
False Statement Block

Flowchart for if..else statement

Test
Condition

If Condition is false If Condition is true

False Condition True Condition


Statement Statement
30

Example 1: X=4
if x%2 == 0:
print 'x is
even' else:
print 'x is odd'
Output:
X is even

Explanation:
 If the remainder when x is divided by 2 is 0, x is even
 If the condition is false, the second set of statements is executed.(i.e) x is odd

3.Chained condidtional (If...elif...else Statement):

 If there are more than two possibilities and need more than two branches.  One
way to express a computation like that is a chained conditional.
Syntax:
if (Condition 1):
Statement Block1
elif(Condition 2):
Statement Block 2
elif(Condition 3):
Statement Block 3
else:
Statement(s)

 elif is an abbreviation of “else if.”


 There is no limit onthe number of elif statements.

Flowchart for if..elif...else statement:

False
Test
Condition 1

True
Elif Test False
Condition 2
Body of if –Statement
Block 1 Body of Else
True

Body of elif –
Statement Block 2
31

Example:
X=10
Y=5
if x < y:
print 'x is less than y'
elif x > y: print 'x is
greater than y' else:
print 'x and y are equal'

Output:
x is greater than y

4.Nested if...elif..Else Statement:

• If..elif..else statement can be used inside another if..elif..else statement.This is called


nesting. One condition can also be nested within another.
Syntax: if (Condition
1): if (Condition
2):
True Statement 2
else:
False Statement 2 else:
False statement 1

Flowchart for Nested if..elif...else statement:

False Test True


Condition 1

True Condition 2 False


False Statement1

False Statement 2
TrueStatement 2

Example:
X=10
Y=5
if x == y:
print 'x and y are equal'
else:
32

if x < y: print 'x is less


than y' else: print 'x is
greater than y'

OUTPUT:
X is greater than y.

3. Explain the iteration in python with relevant syntax and


example.(16m)
• Computers often do repetitive task. There are situation when programmers used to
execute a block of code several number of times.
• Repeated execution of a set of statements is called Iteration/Looping.
Python Programming Language provide following types of Iterative Statements.

1. For Loop
2. While Loop
3. Nested Loop

Loop Type Description

For Loop Executes the sequence of statements multiple times and abbreviates the code that
manages the loop
While Loop Repeats a statement until a give condition is TRUE.It test the While condition
before executing the loop body
Nested Loop You can use one or more loop inside any other While or For Loop

1. For Loop:
• It executes the sequence of statements multiple times and abbreviates the code that
manages the loop.
• The for – loop repeats a given block of codes by specified number of times.

Flowchart:
For each item
Syntax: in sequence
For <variable> in <sequence>:
<statement 1>
<statement 2> Test FALSE
<statement 3> EXPRESION
.
.
.
<statement n> TRUE

Body of the Loop

Exit Loop
33

Example 1 – For Loop Example 2 – For Loop

for i in ‘123’: Pets_List=[‘Parrot’, ‘Rabbit’, ‘Pigeon’,


Print (“Welcome”,i, “Times”) ‘Dog’]
For mypets in Pets_List:
Print(mypets) Output:
Output: Parrot
Welcome 1 Times Rabbit
Welcome 2 Times Pigeon
Welcome 3 Times Dog

Example 3 – For Loop Example 4 – For Loop

Message = “PROGRAM” Language= (“c”, “c++”, “Java”, “Python”) for


For i in message: i in Lanuage:
Print(i) print(i)
Output: Output:
P C
R C++
O Java
G Python
R
A
M

2. While Loop:
• While loop is used, when we need to repeatedly execute a statement or group of
statements until the condition is true.
• It tests the condition before executing the loop body so this technique is known as Entry
Controlled Loop.

Syntax:
While expression:
Statement(s)

• Here, statements may be a single statement or a block of statements.


the loop. • The condition may be any
expression, the loop iterates while
Flowchart: Loop the condition is true, when the
condition becomes false, program
control passes to the line
Test False immediately following

Condition Enter While

True

Body of the Loop


34

Example 1 – While Loop Example 2 – While Loop


#Program to print the number from 0 to 4 #Program to print the number from 0 to 5
Counter = 0 a=0
While (counter < 4): While (a<5):
Print(‘countis:’,counter) a=a+1
Counter=Counter+1 Print (a)
Print(“Exit the loop”)

Output: Output:
Count is: 0 0
Count is: 1 1
Count is: 2 2
Count is: 3 3
Exit the Loop 4

3. Nested Loop:
• 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

Syntax:
For <variable> in <sequence>:
For<variable> in <sequence>:
Statement(s)
Statement(s)

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
source or device, written to an output device, and/or stored for further processing.
 Stored data is regarded as part of the internal state of the algorithm.  The state is
stored in a data structure.

5. Explain about unconditional looping statements with relevant example.


• It controls the flow of program execution to get desired result.
Python supports following three control statements:
1. Break.
2. Continue.
3. Pass.
Control Statements Explanation
Break It terminates the loop statement and transfers execution to the
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.

Break Statement:
35

• It terminates the current loop and resumes execution at the next statement.
• The most common use for break is when some external condition is triggered requiring
a hasty exit from a loop.
• The break statement can be used in both while and for loops.
• 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.

Syntax:
Break

Flow Diagram for Break Statement:

Condition Code

If Condition
is True
Break
Condition

If condition is false

Example 1: for Example 2:


letter in 'Python': var = 10 while
if ( letter == 'h'): var> 0:
break print (“Current variable value :”, var)
print(“Current Letter :”, letter) var = var -1 if (var == 5):
break
Output: print( "Good bye!")
Current Letter : P
Current Letter : y Output:
Current Letter : t Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6 Good
bye!

2.Continue Statement:
• It returns the control to the beginning of the while loop.
• The continue statementrejects all the remaining statements in the current iteration
of the loop and movesthe control back to the top of the loop.
36

• The continue statement can be used in both while and for loops.

Syntax: Continue

Flow Diagram for Break Statement:

Condition Code

If Condition
is True
Continue
Condition

If condition is false

Example 1: for Example 2: var = 10 while (var>


letter in 'Python': 0): var = var -1 print (“Current
if ( letter == 'h'): continue variable value :”, var) if (var == 5):
print(“Current Letter :”, letter) Coninue
Print( "Good bye!")

Output: Output:
Current Letter : P Current Current variable value : 9
Letter : y Current variable value : 8
Current Letter : t Current variable value : 7
Current Letter : o Current variable value : 6
Current Letter : n Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0 Good
bye!

3.Pass Statement:

• It is used when a statement is required syntactically but you do not want any
command or code to execute.
• The pass statement is a null operation; nothing happens when it executes.
• The pass is also useful in places where your code will eventually go, but has not been
written yet (e.g., in stubs for example)
37

Syntax: Pass

Example 1:
forletter in 'Python':
if ( letter == 'h'):
Pass
Print(“This is pass block”)
print(“Current Letter :”, letter)
print(“Good bye”)

Output:
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good Bye

6. Briefly explain about fruitful functions with example.


 Functions that return values are called fruitful function.

Input the value


Return the result
Fruitful functions

 Example: The square function will take one number as parameter and return the result
of squaring that number.

RETURN VALUES:

 The Built-in functions such as the math functions, POW, etc. produce results.
 Calling the function generates a value, which we usually assign to a variable or use as
part of an expression.

 The first example is area, which returns the area of a circle with the given radius:
def area(radius): temp =
math.pi * radius**2 return
temp

 We have seen the return statement before, but in a fruitful function the return statement
includes an expression.

def area(radius):
returnmath.pi * radius**2

PARAMETERS:

A function in python,
38

 Takes input data, called parameters or arguments.  Perform computation 


Returns the result.

Def func(param1,param2);
#computations
Return result

 Parameter is the input data that is sent from one function to another.

 Parameter is of two types,


Actual parameter.
Formal parameter.

Actual parameter:
 Parameter is defined in the function call.
Formal parameter:
 Parameter is defined as part of function definition.
 Actual parameter value is received by formal parameter.

Example:

# Function With Actual And Formal Parameters


def cube(x) return x*x*x
a=input(“enter the number:”)
b=cube(a)
Print(“cube of the given number:”,b)

Output:
Enter the number:2
Cube of the given number:8

Parameter passing techniques:


 Call by value
 Call by reference Call by value:
 A copy of actual parameter is passed to formal arguments and any changes made to
the formal arguments have no effect on the actual arguments.

Call by reference:
 A copy of actual parameter is passed to formal arguments and any changes made to the
formal arguments will affect the actual arguments.

SCOPE OF THE VARIABLE:


 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
variable is a variable declared within the function.

Example:
S=10 # s is the global variable def f1()
S=55# s is the local variable Print s
39

Output:
55

COMPOSITION:

 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
perimeter, and computes the area of the circle.
 Assume that the center point is stored in the variables xc and yc, and the perimeter point
is in xp and yp.
 The first step is to find the radius of the circle, which is the distance between the two
points. radius = distance(xc, yc, xp, yp) result = area(radius)

Encapsulating these steps in a function, we get:

defcircle_area(xc, yc, xp, yp):


radius = distance(xc, yc, xp, yp)
result = area(radius) return
result

we can make it more concise by composing the function calls:

defcircle_area(xc, yc, xp, yp):


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

RECURSION:
 A function is recursive if it calls itself and has a termination condition. 
Termination condition stops the function from calling itself.
Example: def
factorial(n): If
n==0: Return 1
else:
recurse =factorial(n-1)
Result =n* recurse
Return result

7. Explain in detail about strings with examples.


 A string is a sequence of characters.(i.e) it can be a letter , a number, or a backslash.
 Python strings are immutable, which means they cannot be changed after they are
created.

STRING SLICES:

 A segment of a string is called a slice. Selecting a slice is similar to selecting a


character.

Example:
>>> s = 'MontyPython'
>>> print s[0:5]
Monty
>>> print s[6:13]
40

Python

 The operator [n:m] returns the part of the string from the “n-eth” character to the
“meth” character,including the first but excluding the last.

 If you omit the first index (before the colon), the slice starts at the beginning of the
string. If youomit the second index, the slice goes to the end of the string.

Example:
>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'

 If the first indexes is greater than or equal to the second the result is an empty string,
represented by two quotation marks.

Example:
>>> fruit = 'banana'
>>> fruit[3:3]

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

STRINGS ARE IMMUTABLE:

 It is tempting to use the [] operator on the left side of an assignment, with the intention
of changing a character in a string.
For example:
>>> greeting = 'Hello, world!'
>>>greeting[0] = 'J'

TypeError: object does not support item assignment.

 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
one of the values in a sequence.
 The reason for the error is that strings are immutable, which means you can’t change an
existing string.
 The best is to create a new string that is a variation on the original:
>>> greeting = 'Hello, world!'
>>>new_greeting = 'J' + greeting[1:]
41

>>> print new_greeting

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


syntax is different.
 For example, the method upper takes a string and returns a new string with all
uppercase letters:
 Instead of the function syntax upper(word), it uses the method syntax word.upper().

>>>word = 'banana'
>>>new_word = word.upper()
>>> print new_word
BANANA

 This form of dot notation specifies the name of the method, upper, and the name of the
string to apply the method to, word. The empty parentheses indicate that this method
takes no argument.
 A method call is called an invocation; in this case, we would say that we are invoking
upper on the word.

>>>word = 'banana'
>>>index = word.find('a')
>>>print index
1

 The find method is more general than our function; it can find substrings, not just
characters:
>>>word.find('na')
2
 It can take as a second argument the index where it should start:
>>>word.find('na', 3)
4
 And as a third argument the index where it should stop:
>>>name = 'bob'
>>>name.find('b', 1, 2)
-1
METHODS:

METHODS DESCRIPTION
Capitalize() Capitalizes first for letter of string
is digit() returns true if string contains only digits and false otherwise.

islower() returns true if string has at least 1 cased character and all cased
characters are in lowercase and false otherwise.
42

isnumeric()- returns true id a Unicode string contains only numeric characters and
false otherwise
isupper() returns true if string has at least one cased character and all cased
characters are in uppercase and false otherwise.

STRING MODULE

• The string module provides tools to manipulate strings. Some methods available in the
standard data structure are not available in the string module (e.g. isalpha).
Example:

>>>import string >>>string.digits


‘0123456789’
>>>string.ascii_letters
‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’
>>>string.ascii_lowercase
‘abcdefghijklmnopqrstuvwxyz’
>>>string.ascii_uppercase
‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’
>>>string.hexdigits
‘0123456789abcdefABCDEF’
>>>string.octdigits
‘01234567’
>>>string.punctuation
‘!”@#$%^&*()”:><{}[]’
>>>string.whitespace
‘\t\n\r\x0b\x0c’
>>>string.Capwords(“python”)
‘PYTHON’

8.Why we need list instead of array in Python?Explain in detail


about lists with example?
LIST AS ARRAY

 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
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.
 A list is also a dynamic mutable type and this means you can add and delete elements
from the list at any time.
 To define a list you simply write a comma separated list of items in square brackets,
myList=[1,2,3,4,5,6]

 This looks like an array because you can use "slicing" notation to pick out an individual
element - indexes start from 0. For example print myList[2]
 It will display the third element, i.e. the value 3 in this case. Similarly to change the
third element you can assign directly to it:
myList[2]=100
43

 The slicing notation looks like array indexing but it is a lot more flexible.
For example myList[2:5]

 It is a sublist from the third element to the fifth i.e. from myList[2] to myList[4].

 The final element specified i.e. [5] is not included in the slice.

 Also notice that you can leave out either of the start and end indexes and they will be
assumed to have their maximum possible value.

For example myList[5:] is the list from List[5] to the end of the list andmyList[:5] is
the list up to and not including myList[5] andmyList[:] is the entire list.
 List slicing is more or less the same as string slicing except that you can modify a slice.

For example:
myList[0:2]=[0,1] has the same effect as
myList[0]=0
myList[1]=1
 List slicing is more or less the same as string slicing except that it can modify a slice.

Basic array operations

 For example, to find the maximum value (forgetting for a moment that there is a builtin
max function) you could use: m=0 for e in myList: if m<e: m=e
 This uses the for..in construct to scan through each item in the list. This is a very useful
way to access the elements of an array but it isn't the one that most programmers will be
familiar with. In most cases arrays are accessed by index and you can do this in Python:
m=0 for i in
range(len(myList)): if
m<myList[i]:
m=myList[i]
 Notice that we are now using range to generate the sequence 0, 1, and so on up to the
length of myList.
 You have to admit that there is a lot to be said for the simplicity of the non-index
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
problems.

ILLUSTRATIVE PROGRAMS:

1. Find the square root of number.

n = int(input("Enter a number"))
howmany = int(input("Enter another
number")) approx = 0.5 * n for i in
range(howmany): betterapprox = 0.5 *(approx
+ n/approx) approx = betterapprox
print("The square root of a number is:", betterapprox)

OUTPUT:
Enter a number25
44

Enter another number36


The square root of a number is: 5.0

2. GCD of a given number.

d1 = int(input("Enter a number:")) d2 =
int(input("Enter another number"))
rem = d1 % d2
while rem != 0 :
d1 = d2
d2 = rem
rem=d1 % d2
print ("gcd of given numbers is :", d2)

OUTPUT:

Enter a number:2
Enter another number4
gcd of given numbers is : 2

3. Exponentiation n = input ("Enter a


number : ") n = int(n)
e = input ("Enter an exponent : ")
e = int(e) r = n for
i in range (1,e): r
=n*r
print(r)

OUTPUT:
Enter a number : 2
Enter an exponent : 2
4
4. Sum an array of elements. a = [] n =
int(input("Enter number of elements:")) for
i in range(1, n+1):
b = int(input("Enter element:"))
a.append(b)
a.sort() print("Largest element
is:",a[n-1])

OUTPUT:
Enter number of elements:5
Enter element:5
Enter element:54
Enter element:24
Enter element:58
Enter element:1
Largest element is: 58

5. Linear search
45

list = [4,1,2,5,3] #Set up array


search = int(input("Enter search number")) # Ask for a number
for i in range(0,len(list)): # Repeat for each item in list if
search==list[i]: #if item at position i is search time
print(str(search)+"found at position " + str(i)) #Report found

OUTPUT:
Enter search number 4
4 found at position 0

6. Binary search defbinary_search(item_list,item):


first = 0
last = len(item_list)-1 found =
False while( first<=last and not
found):
mid = (first + last)//2 ifitem_list[mid]
== item :
found = True else: if
item <item_list[mid]:
last = mid - 1 else: first = mid + 1
return found
print(binary_search([1,2,3,5,8], 6))
print(binary_search([1,2,3,5,8], 5))
OUTPUT:
False
True
UNIT-IV and V
FILES, MODULES, PACKAGES
PART-A
1. What is file? List out its types.
• FILES refer to a location with Filename that stores information.
• File must be opened to 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.
Types:
➢ Data files ➢
Text files ➢
Program files.

2. List out the types of file operations.


➢ Open the file.
➢ Read or write
➢ 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.
Division by zero.
Trying to access a file which doesn’t exist. Accessing a list
element or dictionary values which doesn’t exist.

7. Give some examples of logical errors.

➢ Using integer division instead of floating point division.


➢ Wrong operator precedence.
➢ Mistakes in Boolean expression.
➢ Indenting a block to the wrong level. ➢ Error in Boolean Expression.

8. What is exception in python?


➢ Exception is an event, which occurs during the execution of a program.
➢ Exception disrupts the normal flow of the programs instructions.
➢ Exception is a python object that represents an error.

9. How to handle exception in python.


➢ Python provides two very important features to handle any unexpected error in the
python programs and to add debugging capabilities in item.
• Exception handling.
• Assertions.

10. List any four standard exceptions in python.

Standard Exceptions:
1. Floating Point Error-Raised when floating point calculation fails.
2. Import error-Raised when an import statement fails.
3. Syntax error-Raised when there is an error in python syntax.
4. Indentation error-Raised when indentation is not specified properly

11. Give the syntax for raise exception.


12. We can raise exceptions in several ways by using the raise statement.
Syntax:
Raise(Exception(,args(,traceback)))

Example: def get_age(): age =


int(input("Please enter your age: ")) if age <
0:
my_error = ValueError("{0} is not a valid age".format(age)) raise
my_error
return age

Output:
raise ValueError("{0} is not a valid age".format(age))

12. What are the advantages of exception handling?


• It separates normal code from code that handles errors.
• Exception can easily be passed along functions in the stack until they reach a
function.

13. Differentiate module and package in python.

Module Package
1. A module is a single file 1. A package is a collection of modules
that are imported under one in directories that give a package
import. hierarchy.
2. Example:
2. Example: import from pots import pots
my_module

PART-B

1. Discuss with suitable example (i) Read a File (ii) Write a file (iii) Close a file
(or)
Explain the file concepts in detail with example.
FILES

• FILES refer to a location with Filename that stores information. Like a book a File must be opened to
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. A File is a named location on disk
to store related information.
CREATE A TEXT FILE:

• Text file in Python, Lets Create a new text file: Example: file = open(“sample1.txt”, “w”)
file.write(“Hello World”) file.write(“God is great”) file.write(“Think Positive”) file.close()
• If you Open the text file, Python interpreter will add the text into the file.
Output:
Hello World
God is great Think
Positive.

OPENING A FILE:

• Python has a built-in function Open( ) to open a file.


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

Syntax:
File_VariableName=Open (“Filename”, ‘mode’)
Where
• “File_VariableName” is the variable to add the file object.
• “Mode” tells the interpreter and developer which way the file will be used. 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

READING AND WRITING FILES:


• In General,there are two methods to manipulate the files, They are given below: ➢ Write( )
➢ Read ()

Write ( ) Method:
• This method writes any string to an open file.
Syntax:
File_Variablename.Write(string);
Example
#open a file
f = open(“sample.txt”, ‘w’)
f.write(“ God is Great.\n God is always with me!\n”);
#close the opened file f.close( )
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.
Sample.txt
God is Great
God is always with me!

Read ( ) Method:
This Method read a string from a file. It is important to note that Python strings can have binary data apart
from text data.
Syntax
File_variablename.read(count); Example:
#opens a file f = open
(“sample.txt”, “r+”)
str=f.read(10); print(“Read
the string:”,str) f.close()
Output: Read the string: God is great.

Question: Explain different file opening modes. Also, write a Python program to read a file and capitalize the
first letter of every word in the file.

Question: Summarize the difference between readline() and readlines() in Python file handling.

2. Explain about the concepts of format operator.


➢ Format operator is used to print the output in a desired format.
➢ The % operator is the format operator.
➢ It is also called as interpolation operator.
➢ The % operator is also used for modulus.
➢ The usage varies according to the operands of the operator.
Syntax:
<format operator>% values.
Example:
>>>camels=42
>>>’%d’% camels
‘42’
>>>camels=42
>>>’I have spotted %d camels’% camels
‘I have spotted 42 camels’
>>>In %d years I have spotted %f %s’(3,0.1,’camels’)
‘In 3 years I have spotted 0.1 camels’

3. Illustrate about the concept of errors and exception. Explain the types 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.

4. Syntax errors.
5. Runtime errors.
6. Logical errors.
SYNTAX ERRORS:

➢ Python can only execute a program, if the syntax is correct, otherwise interpreter displays error
message.
➢ Python will find these kinds of error when it tries to parse a program and exit with an error message
without running anything.
➢ Syntax errors are mistakes in the use of the python language or grammar mistakes.

Common python syntax errors include:

➢ Leaving out a keyword.


➢ Leaving a symbols such as colon, comma or brackets. ➢ Misspelling a keyword ➢ Incorrect
indentation.

RUNTIME ERROR:

➢ The second type of error is a runtime error. It does not appear until after the program has started
running.
➢ The program may exit unexpectedly during execution.
➢ Runtime error was not detected when the program was parsed.

Common python runtime errors include:

➢ Division by zero.
Ex:
>>> print(55/0)
ZeroDivisionError: integer division or modulo by zero.
➢ Trying to access a file which doesn’t exist.
➢ Accessing a list element or dictionary values which doesn’t exist. Ex:
>>> a = []
>>> print(a[5])
IndexError: list index out of range
➢ Using an identifier which has not be defined.

LOGICAL ERRORS:

➢ Logical errors are more difficult to fix.


➢ The program runs without crashing, but produces an incorrect result.
➢ The error is caused by a mistake in the programs logic.
➢ Error message will not be appeared, because no syntax or runtime error has occurred.

Common python logical errors include:

➢ Using integer division instead of floating point division.


➢ Wrong operator precedence.
➢ Mistakes in Boolean expression.
➢ Indenting a block to the wrong level.
➢ Error in Boolean Expression.

4. Describe in detail how exceptions are handled in python. Give relevant examples.
➢ Exception is an event, which occurs during the execution of a program.
➢ Exception disrupts the normal flow of the programs instructions.
➢ Exception is a python object that represents an error.

Standard Exceptions:
1. Floating Point Error-Raised when floating point calculation fails.
2. Import error-Raised when an import statement fails.
3. Syntax error-Raised when there is an error in python syntax.
4. Indentation error-Raised when indentation is not specified properly.
5. EOF error-Raised when there is no input until the end of while.
6. IOError- open()function when trying to open a file that does not exist.
7. ArithmeticError-Base class for all errors that occur for numeric calculation.
8. AssertionError-Raised in case of failure of the assert statement.
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
have invalid values specified.

Syntax:
Try:
Operator
……
Except exception:
If there is exception, execute this block.
Except Exception
If there is exception, execute this block.
…..
else
If there is no exception, then execute this block.

Example:

It tries to open a file where do not have write permission, so it raises exception. Try:
fh=open(“testfile”,’r’)
fh.write(“This is my test file for exception handling!”) Except
IOerror
Print(“error:can’t find file or read data”) else:
Print(“written content in the file successfully”)

Output:
Error: can’t find file or read data.

Raising An Exceptions:
We can raise exceptions in several ways by using the raise statement.
Syntax:
Raise(Exception(,args(,traceback)))

Example:

def get_age(): age = int(input("Please


enter your age: ")) if age < 0:

# Create a new instance of an exception


my_error = ValueError("{0} is not a valid age".format(age))
raise my_error return age

Output:
raise ValueError("{0} is not a valid age".format(age))

5. Illustrate the important of modules with examples.

• Modules refer to a file containing Python statements and definitions.


• Modules to break down large programs into small manageable and organized files.

# Python Module example


def add(a, b):
"""This program adds two
numbers and return the result"""
result = a + b
return result
How to import modules in Python?

➢ We can import the definitions inside a module to another module or the interactive interpreter in
Python.
➢ >>> import example
➢ Using the module name we can access the function using dot (.) operation.
➢ For example:
>>> example.add(4,5.5)

Python import statement:


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

# Import statement example


import math
print("The value of pi is", math.pi)

OUTPUT:
The value of pi is 3.14

Python from...import statement:

➢ Import specific names form a module without importing the module as a whole. Here is an
example.

# import only pi from math

module from math import pi

print("The value of pi is", pi)

The value of pi is 3.14

The from...import * Statement:

➢ It is also possible to import all names from a module into the current namespace by using the
following import statement.

from modname import *

This provides an easy way to import all the items from a module into the current namespace.

6. Discuss Python Package in detail.

➢ A package is a collection of modules in directories that give a package hierarchy.

➢ The package gives the hierarchical file director structure of the python application environment
that consists of modules and package.
➢ A package is a directory which contains a special file called __init__.py

Question: Describe how to generate random numbers using NumPy. Write a python program to create an array of
5 random integers between 10 and 50.

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

Example: Construct a plot for following dataset using matplotlib:

Food Calories Potassium Fat

Meat 250 40 8

Banana 130 55 5

Avocados 140 20 3

Sweet Potatoes 120 30 6

Spinach 20 40 1

Watermelon 20 32 1.5

Coconut Water 10 10 0

Beans 50 26 2

Legumes 40 25 1.5

Tomato 19 20 2.5

You might also like