Passing Parameters in Functions: Output: Hello - Python None
Passing Parameters in Functions: Output: Hello - Python None
Output:
hello – Python
None
Syntax:
def function_name (parameter(s) separated by comma):
Let us see the use of parameters while defining functions. The parameters that you
place in the parenthesis will be used by the function itself. You can pass all sorts of data to the
functions. Here is an example program that defines a function that helps to pass parameters
into the function.
Example: 7.4
# assume w = 3 and h = 5
def area(w,h):
return w * h
print (area (3,5))
The above code assigns the width and height values to the parameters w and h. These
parameters are used in the creation of the function “area”. When you call the above function,
it returns the product of width and height as output.
The value of 3 and 5 are passed to w and h respectively, the function will return 15 as
output.
We often use the terms parameters and arguments interchangeably. However, there
is a slight difference between them. Parameters are the variables used in the function
definition whereas arguments are the values we pass to the function parameters
Arguments are used to call a function and there are primarily 4 types of functions that
one can use: Required arguments, Keyword arguments, Default arguments and Variable-length
arguments.
1 Required arguments
2 Keyword arguments
3 Default arguments
4 Variable-length arguments
Instead of printstring() in the above code if we use printstring (“Welcome”) then the
output is
Output:
Example - Required arguments
Welcome
93 Python Functions
Output:
Example-1 Keyword arguments
Name :Gshan
Output:
Example-3 Keyword arguments
Name : Gshan
Age : 25
Note
In the above program the parameters orders are changed
Example: 7.5.3
def printinfo( name, salary = 3500):
print (“Name: “, name)
print (“Salary: “, salary)
return
printinfo(“Mani”)
Output:
Name: Mani
Salary: 3500
Output:
Name: Ram
Salary: 2000
In the above code, the value 2000 is passed to the argument salary, the default value
already assigned for salary is simply ignored.
95 Python Functions
Example: 7.5.4
def sum(x,y,z):
print("sum of three nos :",x+y+z)
sum(5,10,15,20,25)
Example: 7.5.4. 1
def printnos (*nos): Output:
for n in nos: Printing two values
print(n) 1
return 2
# now invoking the printnos() function Printing three values
print ('Printing two values') 10
printnos (1,2) 20
print ('Printing three values') 30
printnos (10,20,30)
Evaluate Yourself ?
In the above program change the function name printnos as printnames in all places
wherever it is used and give the appropriate data Ex. printnos (10, 20, 30) as printnames ('mala',
'kala', 'bala') and see output.
Note
Keyword variable arguments are beyond the scope of this book.
Note
filter(), map() and reduce() functions are beyond the scope of this book.
Lambda function can take any number of arguments and must return one
value in the form of an expression. Lambda function can only access global variables
and variables in its parameter list.
97 Python Functions
The above lambda function that adds argument arg1 with argument arg2 and stores the
result in the variable sum. The result is displayed using the print().
• The return statement causes your function to exit and returns a value to its caller. The
point of functions in general is to take inputs and return something.
• The return statement is used when a function is ready to return a value to its caller. So,
only one return statement is executed at run time even though the function contains
multiple return statements.
• Any number of 'return' statements are allowed in a function definition but only one of
them is executed at run time.
7.7.1 Syntax of return
This statement can contain expression which gets evaluated and the value is returned.
If there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object.
99 Python Functions
When we run the above code, the output shows the following error:
The above error occurs because we are trying to access a local variable ‘y’ in a global
scope.
Note
Without using the global keyword we cannot modify the global variable inside
the function but we can only access the global variable.
In the above program, x is defined as a global variable. Inside the add() function, global
keyword is used for x and we increment the variable x by 5. Now We can see the change on the
global variable x outside the function i.e the value of x is 5.
In the above program, we declare x as global and y as local variable in the function
loc().
After calling the function loc(), the value of x becomes 16 because we used x=x * 2.
After that, we print the value of local variable y i.e. local.
Example : 7.8.3 (b) Global variable and Local variable with same name
x=5
def loc():
x = 10
print ("local x:", x)
loc()
print ("global x:", x)
Output:
local x: 10
global x: 5
In above code, we used same name ‘x’ for both global variable and local variable. We get
different result when we print same variable because the variable is declared in both scopes, i.e.
the local scope inside the function loc() and global scope outside the function loc().
The output :- local x: 10, is called local scope of variable.
The output:- global x: 5, is called global scope of variable.
Output:
25
125.0
343
Mathematical Functions
Note
Specify import math module before using all mathematical
functions in a program
Example : 7.10
def fact(n):
if n == 0:
return 1
else:
return n * fact (n-1)
print (fact (0))
print (fact (5))
Output:
1
120
print(fact (2000)) will give Recursion Error after maximum recursion depth exceeded
in comparison. This happens because python stops calling recursive function after
1000 calls by default. It also allows you to change the limit using sys.setrecursionlimit
(limit_value).
Example:
import sys
sys.setrecursionlimit(3000)
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
print(fact (2000))
• Functions are named blocks of code that are designed to do one specific job.
• Types of Functions are User defined, Built-in, lambda and recursion.
• Function blocks begin with the keyword “def ” followed by function name and
parenthesis ().
• A “return” with no arguments is the same as return None. Return statement
is optional in python.
• In Python, statements in a block should begin with indentation.
• A block within a block is called nested block.
• Arguments are used to call a function and there are primarily 4 types of
functions that one can use: Required arguments, Keyword arguments, Default
arguments and Variable-length arguments.
• Required arguments are the arguments passed to a function in correct
positional order.
• Keyword arguments will invoke the function after the parameters are
recognized by their parameter names.
• A Python function allows to give the default values for parameters in the
function definition. We call it as Default argument.
• Variable-Length arguments are not specified in the function’s definition and
an asterisk (*) is used to define such arguments.
• Anonymous Function is a function that is defined without a name.
• Scope of variable refers to the part of the program, where it is accessible, i.e.,
area where you can refer (use) it.
• The value returned by a function may be used as an argument for another
function in a nested manner. This is called composition.
• A function which calls itself is known as recursion. Recursion works like a
loop but sometimes it makes more sense to use recursion than loop.
1 eval(‘25*2-5*4')
2 math.sqrt(abs(-81))
3 math.ceil(3.5+4.6)
4 math.floor(3.5+4.6)
Evaluation
Part - I
Choose the best answer: (1 Mark)
1. A named blocks of code that are designed to do one specific job is called as
(a) Loop (b) Branching
(c) Function (d) Block
2. A Function which calls itself is called as
(a) Built-in (b) Recursion
(c) Lambda (d) return
3. Which function is called anonymous un-named function
(a) Lambda (b) Recursion
(c) Function (d) define
4. Which of the following keyword is used to begin the function block?
(a) define (b) for
(c) finally (d) def
5. Which of the following keyword is used to exit a function block?
(a) define (b) return
(c) finally (d) def
6. While defining a function which of the following symbol is used.
(a) ; (semicolon) (b) . (dot)
(c) : (colon) (d) $ (dollar)
Part - II
Part - IV
Answer the following questions: (5 Marks)
1. Explain the different types of function with an example.
2. Explain the scope of variables with an example.
3. Explain the following built-in functions.
(a) id()
(b) chr()
(c) round()
(d) type()
(e) pow()
4. Write a Python code to find the L.C.M. of two numbers.
5. Explain recursive function with an example.
Reference Books
1. Python Tutorial book from tutorialspoint.com
2. Python Programming: A modular approach by Pearson – Sheetal, Taneja
3. Fundamentals of Python –First Programs by Kenneth A. Lambert
Learning Objectives
8.1 Introduction
String is a data type in python, which is used to handle array of characters. String is
a sequence of Unicode characters that may be a combination of letters, numbers, or special
symbols enclosed within single, double or even triple quotes.
Example
In python, strings are immutable, it means, once you define a string, it cannot be
changed during execution.
8.2 Creating Strings
As we learnt already, a string in Python can be created using single or double or even
triple quotes. String in single quotes cannot hold any other single quoted string in it, because
the interpreter will not recognize where to start and end the string. To overcome this problem,
you have to use double quotes. Strings which contains double quotes should be define within
triple quotes. Defining strings within triple quotes also allows creation of multiline strings.
The positive subscript 0 is assigned to the first character and n-1 to the last character,
where n is the number of characters in the string. The negative index assigned from the last
character to the first character in reverse order begins with -1.
Example
String S C H O O L
Positive subscript 0 1 2 3 4 5
Negative subscript -6 -5 -4 -3 -2 -1
In the above example, string variable str1 has been assigned with the string “How are
you” in statement 1. In the next statement, we try to update the first character of the string with
character ‘A’. But python will not allow the update and it shows a TypeError.
To overcome this problem, you can define a new string value to the existing string
variable. Python completely overwrite new string on the existing string.
Example
>>> str1="How are you"
>>> print (str1)
How are you
>>> str1="How about you"
>>> print (str1)
How about you
Usually python does not support any modification in its strings. But, it provides a
function replace() to temporarily change all occurrences of a particular character in a string.
The changes done through replace () does not affect the original string.
General formate of replace function:
replace(“char1”, “char2”)
The replace function replaces all occurrences of char1 with char2.
Example
>>> str1="How are you"
>>> print (str1)
How are you
>>> print (str1.replace("o", "e"))
Hew are yeu
Similar as modification, python will not allow deleting a particular character in a string.
Whereas you can remove entire string variable using del command.
(ii) Append (+ =)
Adding more strings at the end of an existing string is known as append. The operator
+= is used to append a new string with an existing string.
Example
>>> str1="Welcome to "
str1="COMPUTER"
index=0
for i in str1:
print (str1[:index+1])
index+=1
Output
C
CO
COM
COMP
COMPU
COMPUT
COMPUTE
COMPUTER
Example
>>> str1 = "Welcome to learn Python"
>>> print (str1[10:16])
learn
>>> print (str1[10:16:4])
r
>>> print (str1[10:16:2])
er
>>> print (str1[::3])
Wceoenyo
Syntax:
(“String to be display with %val1 and %val2” %(val1, val2))
Example
name = "Rajarajan"
mark = 98
print ("Name: %s and Marks: %d" %(name,mark))
Output
Name: Rajarajan and Marks: 98
Example
# String within triple quotes to display a string with single quote
>>> print ('''They said, "What's there?"''')
They said, "What's there?"
# String within single quotes to display a string with single quote using escape sequence
>>> print ('They said, "What\'s there?"')
They said, "What's there?"
# String within double quotes to display a string with single quote using escape sequence
>>> print ("They said, \"What's there?\"")
He said, "What's there?"
Example
str1=input ("Enter a string: ")
str2="chennai"
if str2 in str1:
print ("Found")
else:
print ("Not Found")
Output : 1
Enter a string: Chennai G HSS, Saidapet
Found
Output : 2
Enter a string: Govt G HSS, Ashok Nagar
Not Found
*
* *
* * *
* * * *
* * * * *
str1=' * '
i=1
while i<=5:
print (str1*i)
i+=1
Output
*
* *
* * *
* * * *
* * * * *
Output
Enter a string: Tamilnadu School Education
The given string contains 11 vowels and 13 consonants
Example 8.11.5 : Program that accept a string from the user and display
the same after removing vowels from it
def rem_vowels(s):
temp_str=''
for i in s:
if i in "aAeEiIoOuU":
pass
else:
temp_str+=i
print ("The string without vowels: ", temp_str)
str1= input ("Enter a String: ")
rem_vowels (str1)
Output
Enter a String: Mathematical fundations of Computer Science
The string without vowels: Mthmtcl fndtns f Cmptr Scnc
Points to remember:
• String is a data type in python.
• Strings are immutable, that means once you define string, it cannot be changed during
execution.
• Defining strings within triple quotes also allows creation of multiline strings.
• In a String, python allocate an index value for its each character which is known as
subscript.
• The subscript can be positive or negative integer numbers.
• Slice is a substring of a main string.
• Stride is a third argument in slicing operation.
• Escape sequences starts with a backslash and it can be interpreted differently.
• The format( ) function used with strings is very versatile and powerful function used
for formatting strings.
• The ‘in’ and ‘not in’ operators can be used with strings to determine whether a string
is present in another string.
Hands on Experience
4. Write a program to print integers with ‘*’ on the right of specified width.
5. Write a program to create a mirror image of the given string. For example, “wel” = “lew“.
9. Write a program to replace a string with another string without using replace().
10. Write a program to count the number of characters, words and lines in a given string.
Evaluation
Part - I
Part -II
Part -IV
Reference Books
1. https://docs.python.org/3/tutorial/index.html
2. https://www.techbeamers.com/python-tutorial-step-by-step/#tutorial-list
3. Python programming using problem solving approach – Reema Thareja – Oxford University
press.
4. Python Crash Course – Eric Matthes – No starch press, San Francisco.
Learning Objectives
Python programming language has four collections of data types such as List, Tuples,
Set and Dictionary. A list in Python is known as a “sequence data type” like strings. It is an
ordered collection of values enclosed within square brackets [ ]. Each value of a list is called
as element. It can be of any type such as numbers, characters, strings and even the nested lists
as well. The elements can be modified or mutable which means the elements can be replaced,
added or removed. Every element rests at some position in the list. The position of an element
is indexed with numbers beginning with zero which is used to locate and access a particular
element. Thus, lists are similar to arrays, what you learnt in XI std.
9.1.1 Create a List in Python
In python, a list is simply created by using square bracket. The elements of list should
be specified within square brackets. The following syntax explains the creation of list.
Syntax:
Variable = [element-1, element-2, element-3 …… element-n]
In the above example, the list Marks has four integer elements; second list Fruits has
four string elements; third is an empty list. The elements of a list need not be homogenous type
of data. The following list contains multiple type elements.
In the above example, Mylist contains another list as an element. This type of list is
known as “Nested List”.
Example
Marks = [10, 23, 41, 75]
Marks 10 23 41 75
Index (Positive) 0 1 2 3
IndexNegative) -4 -3 -2 -1
Positive value of index counts from the beginning of the list and negative value means
counting backward from end of the list (i.e. in reverse order).
To access an element from a list, write the name of the list, followed by the index of the
element enclosed within square brackets.
Syntax:
List_Variable = [E1, E2, E3 …… En]
print (List_Variable[index of a element])
In the above example, print command prints 10 as output, as the index of 10 is zero.
Note
A negative index can be used to access an element in reverse order.
Example
Marks = [10, 23, 41, 75]
i=0
while i < 4:
print (Marks[i])
i=i+1
Output
10
23
41
75
In the above example, Marks list contains four integer elements i.e., 10, 23, 41, 75. Each
element has an index value from 0. The index value of the elements are 0, 1, 2, 3 respectively.
Here, the while loop is used to read all the elements. The initial value of the loop is zero, and
the test condition is i < 4, as long as the test condition is true, the loop executes and prints the
corresponding output.
The next statement i = i + 1 increments the value of i from 0 to 1. Now, the flow of
control shifts to the while statement for checking the test condition. The process repeats to
print the remaining elements of Marks list until the test condition of while loop becomes false.
The following table shows that the execution of loop and the value to be print.
print
Iteration i while i < 4 i=i+1
(Marks[i])
5 4 4 < 4 False -- --
Example
Marks = [10, 23, 41, 75]
i = -1
while i >= -4:
print (Marks[i])
i = i + -1
Output
75
41
23
10
The following table shows the working process of the above python coding
Syntax:
for index_var in list:
print (index_var)
Example
In the above example, Marks list has 5 elements; each element is indexed from 0 to 4. The
Python reads the for loop and print statements like English: “For (every) element (represented
as x) in (the list of) Marks and print (the values of the) elements”.
Syntax:
List_Variable [index of an element] = Value to be changed
List_Variable [index from : index to] = Values to changed
Where, index from is the beginning index of the range; index to is the upper limit of
the range which is excluded in the range. For example, if you set the range [0:5] means, Python
takes only 0 to 4 as element index. Thus, if you want to update the range of elements from 1 to
4, it should be specified as [1:5].
Example
>>> MyList=[34,98,47,'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan' ]
>>> print(MyList)
[34, 98, 47, 'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan']
>>> MyList.insert(3, 'Ramakrishnan')
>>> print(MyList)
[34, 98, 47, 'Ramakrishnan', 'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan']
In the above example, insert() function inserts a new element ‘Ramakrishnan’ at the
index value 3, ie. at the 4th position. While inserting a new element in between the existing
elements, at a particular location, the existing elements shifts one position to the right.
Syntax:
del List [index of an element]
# to delete a particular element
del List [index from : index to]
# to delete multiple elements
del List
# to delete entire list
Example
>>> MySubjects = ['Tamil', 'Hindi', 'Telugu', 'Maths']
>>> print (MySubjects)
['Tamil', 'Hindi', 'Telugu', 'Maths']
>>> del MySubjects[1]
>>> print (MySubjects)
['Tamil', 'Telugu', 'Maths']
In the above example, the list MySubjects has been created with four elements. print
statement shows all the elements of the list. In >>> del MySubjects[1] statement, deletes an
element whose index value is 1 and the following print shows the remaining elements of the
list.
Example
>>> del MySubjects[1:3]
>>> print(MySubjects)
['Tamil']
In the above codes, >>> del MySubjects[1:3] deletes the second and third elements
from the list. The upper limit of index is specified within square brackets, will be taken as -1 by
the python.
Here, >>> del MySubjects, deletes the list MySubjects entirely. When you try to print the
elements, Python shows an error as the list is not defined. Which means, the list MySubjects
has been completely deleted.
As already stated, the remove() function can also be used to delete one or more elements
if the index value is not known. Apart from remove() function, pop() function can also be
used to delete an element using the given index value. pop() function deletes and returns the
last element of a list if the index is not given.
The function clear() is used to delete all the elements in list, it deletes only the elements
and retains the list. Remember that, the del statement deletes entire list.
Syntax:
List.remove(element) # to delete a particular element
List.pop(index of an element)
List.clear( )
Example
>>> MyList=[12,89,34,'Kannan', 'Gowrisankar', 'Lenin']
>>> print(MyList)
[12, 89, 34, 'Kannan', 'Gowrisankar', 'Lenin']
>>> MyList.remove(89)
>>> print(MyList)
[12, 34, 'Kannan', 'Gowrisankar', 'Lenin']
In the above example, MyList has been created with three integer and three string
elements, the following print statement shows all the elements available in the list. In the
statement >>> MyList.remove(89), deletes the element 89 from the list and the print statement
shows the remaining elements.
In the above code, pop() function is used to delete a particular element using its index
value, as soon as the element is deleted, the pop() function shows the element which is deleted.
pop() function is used to delete only one element from a list. Remember that, del statement
deletes multiple elements.
Example
>>> MyList.clear( )
>>> print(MyList)
[ ]
In the above code, clear() function removes only the elements and retains the list. When
you try to print the list which is already cleared, an empty square bracket is displayed without
any elements, which means the list is empty.
where,
• start value – beginning value of series. Zero is the default beginning value.
• end value – upper limit of series. Python takes the ending value as upper limit – 1.
• step value – It is an optional argument, which is used to generate different interval of
values.
Syntax:
List_Varibale = list ( range ( ) )
Note
In the above code, list() function takes the result of range() as Even_List elements. Thus,
Even_List list has the elements of first five even numbers.
Similarly, we can create any series of values using range() function. The following example
explains how to create a list with squares of first 10 natural numbers.
In the above program, an empty list is created named “squares”. Then, the for loop
generates natural numbers from 1 to 10 using range() function. Inside the loop, the current
value of x is raised to the power 2 and stored in the variables. Each new value of square is
appended to the list “squares”. Finally, the program shows the following values as output.
Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Syntax:
List = [ expression for variable in range ]
items=[]
prod=1
for i in range(5):
print ("Enter price for item { } : ".format(i+1))
p=int(input())
items.append(p)
for j in range(len(items)):
print("Price for item { } = Rs. { }".format(j+1,items[j]))
prod = prod * items[j]
print("Sum of all prices = Rs.", sum(items))
print("Product of all prices = Rs.", prod)
print("Average of all prices = Rs.",sum(items)/len(items))
count=0
n=int(input("Enter no. of employees: "))
print("No. of Employees",n)
salary=[]
for i in range(n):
print("Enter Monthly Salary of Employee { } Rs.: ".format(i+1))
s=int(input())
salary.append(s)
for j in range(len(salary)):
annual_salary = salary[j] * 12
print ("Annual Salary of Employee { } is:Rs. { }".format(j+1,annual_salary))
if annual_salary >= 100000:
count = count + 1
print("{ } Employees out of { } employees are earning more than Rs. 1 Lakh per annum".
format(count, n))
Output
The list of numbers from 1 to 10 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The list after deleting even numbers = [1, 3, 5, 7, 9]
9.2 Tuples
Introduction to Tuples
Tuples consists of a number of values separated by comma and enclosed within
parentheses. Tuple is similar to list, values in a list can be changed but not in a tuple.
The term Tuple is originated from the Latin word represents an abstraction of the
sequence of numbers:
single(1), double(2), triple(3), quadruple(4), quintuple(5), sextuple(6), septuple(7),
octuple(8), ..., n‑tuple, ...,
2. The elements of a list are enclosed within square brackets. But, the elements of a tuple are
enclosed by paranthesis.
Syntax:
# Empty tuple
Tuple_Name = ( )
Example
>>> MyTup1 = (23, 56, 89, 'A', 'E', 'I', "Tamil")
>>> print(MyTup1)
(23, 56, 89, 'A', 'E', 'I', 'Tamil')
Syntax:
Tuple_Name = tuple( [list elements] )
Example
>>> MyTup3 = tuple( [23, 45, 90] )
>>> print(MyTup3)
(23, 45, 90)
>>> type (MyTup3)
<class ‘tuple’>
Example
>>> MyTup4 = (10)
>>> type(MyTup4)
<class 'int'>
>>> MyTup5 = (10,)
>>> type(MyTup5)
<class 'tuple'>
Example
>>> Tup1 = (12, 78, 91, “Tamil”, “Telugu”, 3.14, 69.48)
# to access all the elements of a tuple
>>> print(Tup1)
(12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)
#accessing selected elements using indices
>>> print(Tup1[2:5])
(91, 'Tamil', 'Telugu')
#accessing from the first element up to the specified index value
>>> print(Tup1[:5])
(12, 78, 91, 'Tamil', 'Telugu')
# accessing from the specified element up to the last element.
>>> print(Tup1[4:])
('Telugu', 3.14, 69.48)
# accessing from the first element to the last element
>>> print(Tup1[:])
(12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)
Example
# Program to join two tuples
Tup1 = (2,4,6,8,10)
Tup2 = (1,3,5,7,9)
Tup3 = Tup1 + Tup2
print(Tup3)
Output
(2, 4, 6, 8, 10, 1, 3, 5, 7, 9)
Syntax:
del tuple_name
Example
Tup1 = (2,4,6,8,10)
print("The elements of Tup1 is ", Tup1)
del Tup1
print (Tup1)
Output:
The elements of Tup1 is (2, 4, 6, 8, 10)
Traceback (most recent call last):
File "D:/Python/Tuple Examp 1.py", line 4, in <module>
print (Tup1)
NameError: name 'Tup1' is not defined
Note that, the print statement in the above code prints the elements. Then, the del statement
deletes the entire tuple. When you try to print the deleted tuple, Python shows the error.
a b c
= 34 90 76
Example
>>> (a, b, c) = (34, 90, 76)
>>> print(a,b,c)
34 90 76
# expression are evaluated before assignment
>>> (x, y, z, p) = (2**2, 5/3+4, 15%2, 34>65)
>>> print(x,y,z,p)
4 5.666666666666667 1 False
Note that, when you assign values to a tuple, ensure that the number of values on both sides of
the assignment operator are same; otherwise, an error is generated by Python.
Output:
Maximum value = 99
Minimum value = 1
Example
Output:
('Vinodini', 'XII-F', 98.7)
('Soundarya', 'XII-H', 97.5)
('Tharani', 'XII-F', 95.3)
('Saisri', 'XII-G', 93.8)
Note
Some of the functions used in List can be applicable even for tuples.
Output:
Enter value of A: 54
Enter value of B: 38
Value of A = 54
Value of B = 38
Value of A = 38
Value of B = 54
Output:
Enter the Radius: 5
Area of the circle = 78.5
Circumference of the circle = 31.400000000000002
Program 3: Write a program that has a list of positive and negative numbers.
Create a new tuple that has only positive numbers from the list
Output:
Positive Numbers: (5, 6, 8, 3, 1)
9.3 Sets
Introduction
In python, a set is another type of collection data type. A Set is a mutable and an unordered
collection of elements without duplicates. That means the elements within a set cannot be
repeated. This feature used to include membership testing and eliminating duplicate elements.
Syntax:
Set_Variable = {E1, E2, E3 …….. En}
Example
>>> S1={1,2,3,'A',3.14}
>>> print(S1)
{1, 2, 3, 3.14, 'A'}
>>> S2={1,2,2,'A',3.14}
>>> print(S2)
{1, 2, 'A', 3.14}
In the above examples, the set S1 is created with different types of elements without
duplicate values. Whereas in the set S2 is created with duplicate values, but python accepts
only one element among the duplications. Which means python removed the duplicate value,
because a set in python cannot have duplicate elements.
Note
When you print the elements from a set, python shows the values in different order.
Example
MyList=[2,4,6,8,10]
MySet=set(MyList)
print(MySet)
Output:
{2, 4, 6, 8, 10}
Set A Set B
In python, the operator | is used to union of two sets. The function union() is also used
to join two sets in python.
set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
U_set=set_A|set_B
print(U_set)
Output:
{2, 4, 6, 8, 'A', 'D', 'C', 'B'}
set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
set_U=set_A.union(set_B)
print(set_U)
Output:
{'D', 2, 4, 6, 8, 'B', 'C', 'A'}
Set A Set B
The operator & is used to intersect two sets in python. The function intersection() is also
used to intersect two sets in python.
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A & set_B)
Output:
{'A', 'D'}
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.intersection(set_B))
Output:
{'A', 'D'}
Set A Set B
The minus (-) operator is used to difference set operation in python. The function
difference() is also used to difference operation.
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A - set_B)
Output:
{2, 4}
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.difference(set_B))
Output:
{2, 4}
Set A Set B
The caret (^) operator is used to symmetric difference set operation in python. The
function symmetric_difference() is also used to do the same operation.
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A ^ set_B)
Output:
{2, 4, 'B', 'C'}
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.symmetric_difference(set_B))
Output:
{2, 4, 'B', 'C'}
Example
9.4 Dictionaries
Introduction
In python, a dictionary is a mixed collection of elements. Unlike other collection data
types such as a list or tuple, the dictionary type stores a key along with its element. The keys in
a Python dictionary is separated by a colon ( : ) while the commas work as a separator for the
elements. The key value pairs are enclosed with curly braces { }.
Key in the dictionary must be unique case sensitive and can be of any valid Python type.
Syntax
Dict = { expression for variable in sequence [if condition] }
The if condition is optional and if specified, only those values in the sequence are evaluated
using the expression which satisfy the condition.
Example
Note that, the first print statement prints all the values of the dictionary. Other statements
are printing only the specified values which is given within square brackets.
In an existing dictionary, you can add more values by simply assigning the value along
with key. The following syntax is used to understand adding more elements in a dictionary.
dictionary_name [key] = value/element
Modification of a value in dictionary is very similar as adding elements. When you assign
a value to a key, it will simply overwrite the old value.
In Python dictionary, del keyword is used to delete a particular element. The clear()
function is used to delete all the elements in a dictionary. To remove the dictionary, you can
use del keyword with dictionary name.
XII Std Computer Science 164
Dict = {'Roll No' : 12001, 'SName' : 'Meena', 'Mark1' : 98, 'Marl2' : 86}
print("Dictionary elements before deletion: \n", Dict)
del Dict['Mark1'] # Deleting a particular element
print("Dictionary elements after deletion of a element: \n", Dict)
Dict.clear() # Deleting all elements
print("Dictionary after deletion of all elements: \n", Dict)
del Dict
print(Dict) # Deleting entire dictionary
Output:
Dictionary elements before deletion:
{'Roll No': 12001, 'SName': 'Meena', 'Mark1': 98, 'Marl2': 86}
Dictionary elements after deletion of a element:
{'Roll No': 12001, 'SName': 'Meena', 'Marl2': 86}
Dictionary after deletion of all elements:
{ }
Traceback (most recent call last):
File "E:/Python/Dict_Test_02.py", line 8, in <module>
print(Dict)
NameError: name 'Dict' is not defined
(2) The index values can be used to access a particular element. But, in dictionary key
represents index. Remember that, key may be a number of a string.
(3) Lists are used to look up a value whereas a dictionary is used to take one value and look
up another value.
Hands on Experience
3. Write a program that finds the sum of all the numbers in a Tuples using while loop.
7. Write a program that creates a list of numbers from 1 to 50 that are either divisible by 3 or
divisible by 6.
8. Write a program to create a list of numbers in the range 1 to 20. Then delete all the numbers
from the list that are divisible by 3.
9. Write a program that counts the number of times a value appears in the list. Use a loop to
do the same.
10. Write a program that prints the maximum and minimum value in a dictionary.
Evaluation
Part - I
Part - II
Part - III
Part - IV
References
1. https://docs.python.org/3/tutorial/index.html
2. https://www.techbeamers.com/python-tutorial-step-by-step/#tutorial-list
3. Python programming using problem solving approach – Reema Thareja – Oxford
University press.
4. Python Crash Course – Eric Matthes – No starch press, San Francisco.
Learning Objectives
10.1 Introduction
Python is an Object Oriented Programming language. Classes and Objects are the key
features of Object Oriented Programming. Theoretical concepts of classes and objects are very
similar to that of C++. But, creation and implementation of classes and objects is very simple
in Python compared to C++.
Class is the main building block in Python. Object is a collection of data and function
that act on those data. Class is a template for the object. According to the concept of Object
Oriented Programming, objects are also called as instances of a class. In Python, everything is
an object. For example, all integer variables that we use in our program is an object of class int.
Similarly all string variables are also object of class string.
10.2 Defining classes
In Python, a class is defined by using the keyword class. Every class has a unique name
followed by a colon ( : ).
Syntax:
class class_name:
statement_1
statement_2
…………..
…………..
statement_n
Syntax:
Object_name = class_name( )
Note that the class instantiation uses function notation ie. class_name with ()
Note
• The statements defined inside the class must be properly indented.
• Parameters are the variables in the function definition.
• Arguments are the values passed to the function definition.
class Student:
mark1, mark2, mark3 = 45, 91, 71 #class variable
S=Student()
S.process()
In the above program, after defining the class, an object S is created. The statement
S.process( ), calls the function to get the required output.
XII Std Computer Science 172
Note
Instance variables are the variables whose value varies from object to object.
For every object, a separate copy of the instance variable will be created.
Instance variables are declared inside a method using the self keyword. In
the above example, we use constructor to define instance variable.
S1=Sample(15)
S2=Sample(35)
S3=Sample(45)
Output
The object value is = 15
The count of object created = 1
The object value is = 35
The count of object created = 2
The object value is = 45
The count of object created = 3
Destructor is also a special method to destroy the objects. In Python, _ _del_ _( )
method is used as destructor. It is just opposite to constructor.
Example : Program to illustrate about the __del__( ) method
class Sample:
num=0
def __init__(self, var):
Sample.num+=1
self.var=var
print("The object value is = ", self.var)
print("The value of class variable is= ", Sample.num)
def __del__(self):
Sample.num-=1
print("Object with value %d is exit from the scope"%self.var)
S1=Sample(15)
S2=Sample(35)
S3=Sample(45)
del S1, S2, S3
Note
The __del__ method gets called automatically when we deleted the object
reference using the del.
The variables which are defined inside the class is public by default. These variables can
be accessed anywhere in the program using dot operator.
A variable prefixed with double underscore becomes private in nature. These variables
can be accessed only within the class.
In the above program, there are two class variables n1 and n2 are declared. The variable
n1 is a public variable and n2 is a private variable. The display( ) member method is defined to
show the values passed to these two variables.
The print statements defined within class will successfully display the values of n1 and
n2, even though the class variable n2 is private. Because, in this case, n2 is called by a method
defined inside the class. But, when we try to access the value of n2 from outside the class
Python throws an error. Because, private variable cannot be accessed from outside the class.
Output
Class variable 1 = 12
Class variable 2 = 14
Value 1 = 12
Output:
Enter Radius: 5
The Area = 78.5
The Circumference = 31.400000000000002
Points to remember
1. Write a program using class to store name and marks of students in list and print total
marks.
2. Write a program using class to accept three sides of a triangle and print its area.
3. Write a menu driven program to read, display, add and subtract two distances.
Evaluation
Part - I
Part -II
1. What is class?
2. What is instantiation?
3. What is the output of the following program?
class Sample:
__num=10
def disp(self):
print(self.__num)
S=Sample()
S.disp()
print(S.__num)
4. How will you create constructor in Python?
5. What is the purpose of Destructor?
References
1. https://docs.python.org/3/tutorial/index.html
2. https://www.techbeamers.com/python-tutorial-step-by-step/#tutorial-list
3. Python programming using problem solving approach – Reema Thareja – Oxford University
press.
4. Python Crash Course – Eric Matthes – No starch press, San Francisco.
11.2 Information
Learning Objectives
Information is processed data, which
At the completion of this chapter, the student allows to be utilized in a significant way.
will be able to know Example
• the concept of a database and relational SCERT
database. College Road
• different components of the database. DPI Campus
Chennai 600006
• types of database models.
As you can see
• types of relationship.
from the example above,
• the concepts of relational algebra. data appears as a set of
Introduction words and numbers. However, when the
data is processed, organized and formatted,
A database is an organized collection it gives a meaningful information about the
of data, generally stored and accessed SCERT institution contact address.
electronically from a computer system. The
11.3 Database
term "database" is also used to refer to any
Database is a repository collection of
of the DBMS, the database system or an
related data organized in a way that data can
application associated with the database.
be easily accessed, managed and updated.
Because of the close relationship between
Database can be a software or hardware
them, the term "database" is often used
based, with one sole purpose of storing data.
casually to refer to both a database and
the DBMS used to manipulate it. A school 11.4 DataBase Management
class register is a database where names are System (DBMS)
arranged alphabetically. Databases have A DBMS is a software that allows us
been around since people started recording to create, define and manipulate database,
things. Here we tend to focus on electronic allowing users to store, process and analyze
ones. data easily. DBMS provides us with an
interface or a tool, to perform various
11.1 Data operations to create a database, storing of
Data are raw facts stored in a data and for updating data, etc. DBMS also
computer. A data may contain any character, provides protection and security to the
text, word or a number. databases. It also maintains data consistency
Example : 600006, DPI Campus, SCERT, in case of multiple users.
Chennai, College Road Examples of DBMS softwares : Foxpro, dbase.
182
182
2. Reduced Redundancy In the modern world hard drives are very cheap, but earlier
when hard drives were too expensive, unnecessary repetition
of data in database was a big problem But RDBMS follows
Normalisation which divides the data in such a way that
repetition is minimum.
4. Support Multiple user RDBMS allows multiple users to work on it(update, insert,
and Concurrent Access delete data) at the same time and still manages to maintain the
data consistency.
5.Query Language RDBMS provides users with a simple query language, using
which data can be easily fetched, inserted, deleted and updated
in a database.
6. Security The RDBMS also takes care of the security of data, protecting
the data from unauthorized access. In a typical RDBMS, we can
create user accounts with different access permissions, using
which we can easily secure our data by restricting user access.
7. DBMS Supports It allows us to better handle and manage data integrity in real
Transactions world applications where multi-threading is extensively used.
183
Languages
or Table where the data is organized as row
USER and column.
Components of DBMS
Each row in a table represents a
Figure 11.1 record, which is a set of data for each
database entry.
1. Hardware: The computer, hard disk, I/O
channels for data, and any other physical Each table column represents a Field,
component involved in storage of data which groups each piece or item of data
2. Software: This main component is among the records into specific categories or
a program that controls everything. The types of data. Eg. StuNo., StuName, StuAge,
DBMS software is capable of understanding StuClass, StuSec.
the Database Access Languages and A Table is known as a RELATION
interprets into database commands for
execution. A Row is known as a TUPLE
A column is known as an ATTRIBUTE
Table / Relation
DataBase Structure
Fig 11.2
11.6 Data Model
• A data model describes how the data can be represented and accessed from a software after
complete implementation
• It is a simple abstraction of complex real world data gathering environment.
• The main purpose of data model is to give an idea as how the final system or software will
look like after development is completed.
• Hierarchical Model
• Relational Model
• Network Database Model
• Entity Relationship Model
• Object Model
1. Hierarchical Model
Hierarchical model was developed by IBM as Information Management System.
In Hierarchical model, data is represented as a simple tree like structure form. This
model represents a one-to-many relationship i.e parent-child relationship. One child can have
only one parent but one parent can have many children. This model is mainly used in IBM
Main Frame computers.
Course Resources
Theory Lab
2. Relational Model
The Relational Database model was first proposed by E.F. Codd in 1970 . Nowadays, it
is the most widespread data model used for database applications around the world.
The basic structure of data in relational model is tables (relations). All the information’s
related to a particular type is stored in rows of that table. Hence tables are also known as
relations in a relational model. A relation key is an attribute which uniquely identifies a
particular tuple (row in a relation (table)).
3. Network Model
Network database model is an extended form of hierarchical data model. The difference
between hierarchical and Network data model is :
• In hierarchical model, a child record has only one parent node,
School
Library Office Staff Room This child has one parent node
Network Model
Fig. 11.5
5. Object Model
Object model stores the data in the form of objects, attributes and methods, classes and
Inheritance. This model handles more complex applications, such as Geographic information
System (GIS), scientific experiments, engineering design and manufacturing. It is used in file
Management System. It represents real world objects, attributes and behaviors. It provides a
clear modular structure. It is easy to maintain and modify the existing code.
Shape
get_area()
get_perimeter()
An example of the Object model is Shape, Circle, Rectangle and Triangle are all objects
in this model.
• Circle has the attribute radius.
• Rectangle has the attributes length and breadth.
• Triangle has the attributes base and height .
• The objects Circle, Rectangle and Triangle inherit from the object Shape.
Database normalization was first proposed by Dr. Edgar F Codd as an integral part
of RDBMS in order to reduce data redundancy and improve data integrity. These rules are
known as E F Codd Rules.
2. One-to-Many Relationship
Computer Bindhu
3. Many-to-One Relationship
4. Many-to-Many Relationship Tamil Radha
1. One-to-One Relationship
In One-to-One Relationship, one Maths Ramesh
entity is related with only one other entity.
One row in a table is linked with only one
row in another table and vice versa. Malaiarasu
Table 11.1
PROJECT (symbol : Π)
The projection eliminates all attributes of the input relation but those mentioned in
the projection list. The projection method defines a relation that contains a vertical subset of
Relation.
Course
Big Data
R language
Python Programming
Note
duplicate row is removed in the result
Table A Table B
INTERSECTION (symbol : ∩) A ∩ B
Defines a relation consisting of a set of all tuple that are in both in A and B. However, A
and B must be union-compatible.
A∩B
cs1 Kannan
cs3 Lenin
1 S 1 S
2 1 R
R
3 2 S
2 R
Table A = 3
Table B = 2 3 S
Table A x B = 3 x 2 = 6
3 R
Cartesian Product
Fig. 11.12
Table A Table B
studno name course subject
cs1 Kannan cs28 Big Data
cs2 Gowri Shankar cs62 R language
cs4 Padmaja cs25 python programming
Table 11.3
Points to remember:
• DBMS is a computer based record keeping system
• Data is unprocessed data which contains any character, text, word or number
has no meaning
• Information is processed data, organized and formatted.
• Examples of RDBMS are mysql, oracle, sql server, ibm db2
• Redundancy means duplication of data in a database.
• Data Consistency means that data values are the same at all instances of a
database
• Data Integrity is security from unauthorized users
• Table is known a relation
• A row is called a tuple
• A column is known as an attribute
• Types of data model are Hierarchical, Relational, Network, ER and Object
model.
• Hierarchical model is a simple tree like structure form with one-to-many
relationship called parent-child relationship
• Relational Model represents data as relations or tables
• Network model is similar to Hierarchical model but it allows a record to have
more than one parent
• ER model consists of entities, attributes and relationships
Evaluation
Part - I
Part -II
Learning Objectives
Note
Latest SQL standard as of now is SQL 2008, released in 2008.
RDBMS stands for Relational DataBase Management System. Oracle, MySQL, MS SQL
Server, IBM DB2 and Microsoft Access are RDBMS packages. SQL is a language used to access
data in such databases.
The Data Definition Language (DDL) consist of SQL statements used to define the
database structure or schema. It simply deals with descriptions of the database schema and is
used to create and modify the structure of database objects in databases.
The DDL provides a set of definitions to specify the storage structure and access
methods used by the database system.
1. It should identify the type of data division such as data item, segment, record and database
file.
2. It gives a unique name to each data item type, record type, file type and data base.
Truncate Remove all records from a table, also release the space occupied by those records.
Delete Deletes all records from a table, but not the space occupied by them.
The data in a database is stored based on the kind of value stored in it. This is identified
as the data type of the data or by assigning each field a data type. All the values in a given field
must be of same type.
The ANSI SQL standard recognizes only Text and Number data type, while some
commercial programs use other datatypes like Date and Time etc. The ANSI data types are
listed in the following Table 12.1
Variable width character string. This is similar to char except the size of the
varchar
data entry vary considerably.
It represents a fractional number such as 15.12, 0.123 etc. Here the size
argument consist of two parts : precision and scale. The precision indicates
dec (Decimal) how many digits the number may have and the scale indicates the maximum
number of digits to the right of the decimal point. The size (5, 2) indicates
precision as 5 and scale as 2. The scale cannot exceed the precision.
It is same as decimal except that the maximum number of digits may not
numeric
exceed the precision argument.
int It represents a number without a decimal point. Here the size argument is
(Integer) not used.
smallint It is same as integer but the default size may be smaller than Integer.
It is same as float, except the size argument is not used and may define a
real
precision up to a maximum of 64.
Tables are the only way to store data, therefore all the information has to be arranged in
the form of tables. The SQL provides a predetermined set of commands to work on databases.
Keywords They have a special meaning in SQL. They are understood as instructions.
They are instructions given by the user to the database also known as
Commands
statements.
Clauses They begin with a keyword and consist of keyword and argument.
Arguments They are the values given to make the clause complete.
Now let us use the above syntax to store some information about the students of a class
in a database, for this you first need to create table. To create a student table, let us take some
information related to students like admission number which we can use it in short form as
(admno), name of student (name), gender, age etc. of the student. Let us create a table having
the field names Admno, Name, Gender, Age and Place.
The SQL command will be as follows:
The above one is a simple table structure without any restrictions. You can also set
constraints to limit the type of data that can go into the fields of the table. Constraints are used
to limit the type of data that can go into a table. This ensures the accuracy and reliability of the
data in the database. Constraints could be either on a column level or a table level.
Note
Constraint is a condition applicable on a field or set of fields.
Following is an example for student table with “NOT NULL” column constraint. This
constraint enforces a field to always contain a value.
CREATE TABLE Student
(
Admno integer NOT NULL PRIMARY KEY, → Primary Key constraint
Name char(20) NOT NULL,
Gender char(1),
Age integer,
Place char(10),
);
The above command creates a table “student” in which the field Admno of integer type
is defined NOT NULL, Name of char type is defined as NOT NULL which means these two
fields must have values. The fields Gender, Age and Place do not have any constraints.
12.7.2 Type of Constraints
Constraints ensure database integrity, therefore known as database integrity constraints.
The different types of constraints are :
Unique Constraint
Primary Key Constraint
Constraint
Default Constraint
Check Constraint
The UNIQUE constraint can be applied only to fields that have also been declared as
NOT NULL.
When two constraints are applied on a single field, it is known as multiple constraints. In
the above Multiple constraints NOT NULL and UNIQUE are applied on a single field Admno,
the constraints are separated by a space and at the end of the field definition a comma(,) is
added. By adding these two constraints the field Admno must take some value ie. will not be
NULL and should not be duplicated.
In the above example the Admno field has been set as primary key and therefore will
help us to uniquely identify a record, it is also set NOT NULL, therefore this field value cannot
be empty.
12.7.2.3 DEFAULT Constraint
The DEFAULT constraint is used to assign a default value for the field. When no value
is given for the specified field having DEFAULT constraint, automatically the default value will
be assigned to the field.
In the above example the “Age” field is assigned a default value of 17, therefore when no
value is entered in age by the user, it automatically assigns 17 to Age.
12.7.2.4 Check Constraint
This constraint helps to set a limit value placed for a field. When we define a check
constraint on a single column, it allows only the restricted values on that field. Example
showing check constraint in the student table:
CREATE TABLE Student
(
Admno integer PRIMARY KEY
Name char(20)NOT NULL,
Gender char(1),
Age integer CHECK (Age <=19), → Check Constraint
Place char(10),
);
In the above example the check constraint is set to Age field where the value of Age
must be less than or equal to 19.
Note
The check constraint may use relational and logical operators for condition.
The order of values must match the order of columns in the CREATE TABLE command.
Specifying the column names is optional if data is to be added for all columns. The command
to add values into the student table can also be used in the following way:
INSERT INTO Student VALUES ( 102, ‘Akshith’, ‘M’, 17, ‘Bangalore’);
102 Akshith M 17 Bangalore
The above command inserts the record into the student table.
To add data to only some columns in a record by specifying the column name and their data,
it can be done by:
In the INSERT command the fields that are omitted will have either default value
defined or NULL value.
For example to rename the column Address to City, the command is used as :
ALTER TABLE Student CHANGE Address City char(20);
The ALTER command can also be used to remove a column or all columns, for example
to remove a particular column, the DROP COLUMN is used with the ALTER TABLE to
remove a particular field. The command can be used as:
ALTER TABLE <table-name> DROP COLUMN <column-name>;
To remove the column City from the Student table, the command is used as :
For example to delete all the records of the student table and delete the table the SQL statement
is given as follows:
TRUNCATE TABLE Student;
The table Student is removed and the space is freed.
The DELETE command deletes only the rows from the table based on
the condition given in the where clause or deletes all the rows from the
DELETE
table if no condition is specified. But it does not free the space containing
the table.
The TRUNCATE command is used to delete all the rows, the structure
TRUNCATE
remains in the table and free the space containing the table.
The DROP command is used to remove an object from the database. If you
DROP drop a table, all the rows in the table is deleted and the table structure is
removed from the database. Once a table is dropped we cannot get it back.
SELECT <column-list>FROM<table-name>;
• Table-name is the name of the table from which the information is retrieved.
For example to view only admission number and name of students from the Student table the
command is given as follows:
If the Student table has the following data:
Place
Chennai
Bangalore
Delhi
In the above output you can see, there would be no duplicate rows in the place field.
When the keyword DISTINCT is used, only one NULL value is returned, even if more NULL
values occur.
For example to display the students admission number and name of only those students who
belong to Chennai, the SELECT command is used in the following way :
SELECT Admno, Name, Place FROM Student WHERE Place = ῾Chennai᾿;
The NOT BETWEEN is reverse of the BETWEEN operator where the records not satisfying
the condition are displayed.
SELECT Admno, Name, Age FROM Student WHERE Age NOT BETWEEN 18 AND 19;
12.7.5.4 IN Keyword
The IN keyword is used to specify a list of values which must be matched with the
record values. In other words it is used to compare a column with more than one value. It is
similar to an OR condition.
For example :
SELECT Admno, Name, Place FROM Student WHERE Place IN (῾Chennai᾿, ῾Delhi᾿);
For example:
SELECT Admno, Name, Place FROM Student WHERE Place NOT IN (῾Chennai᾿, ῾Delhi᾿);
will display students only from places other than “Chennai” and “Delhi”.
Admno Name Place
102 Akshith Bangalore
106 Devika Bangalore
NULL Value :
The NULL value in a field can be searched in a table using the IS NULL in the WHERE
clause. For example to list all the students whose Age contains no value, the command is used
as:
SELECT * FROM Student WHERE Age IS NULL;
Note
Non NULL values in a table can be listed using IS NOT NULL.
Note
The ORDER BY clause does not affect the original table.