Study Material Cs - Grade 12
Study Material Cs - Grade 12
STUDY MATERIAL
Data Types:
Data Type specifies which type of value a variable can store. type() function is used to
determine a variable's type in Python
Data Types In Python
1. Number
2. String
3. Boolean
4. List
5. Tuple
6. Set
7. Dictionary
Python tokens :
(1) keyword :
Keywords are reserved words. Each keyword has a specific meaning to the Python
interpreter, and we can use a keyword in our program only for the purpose for which it
has been defined. As Python is case sensitive, keywords must be written exactly.
(2) Identifier : Identifiers are names used to identify a variable, function, or other entities in
a program. The rules for naming an identifier in Python are as follows:
• The name should begin with an uppercase or a lowercase alphabet or an
underscore sign (_). This may be followed by any combination of characters a–z, A–
Z, 0–9 or underscore (_). Thus, an identifier cannot start with a digit.
• It can be of any length. (However, it is preferred to keep it short and meaningful).
• It should not be a keyword or reserved word
• We cannot use special symbols like !, @, #, $, %, etc., in identifiers.
(3) Variables: A variable in a program is uniquely identified by a name (identifier).
Variable in Python refers to an object — an item or element that is stored in the memory.
Comments: Comments are used to add a remark or a note in the source code. Comments
are not executed by interpreter. a comment starts with # (hash sign). Everything
following the # till the end of that line is treated as a comment and the interpreter simply
ignores it while executing the statement.
Mutable and immutable data types : Variables whose values can be changed after they
are created and assigned are called mutable. Variables whose values cannot be changed
after they are created and assigned are called immutable.
(4) Operators: An operator is used to perform specific mathematical or logical operation
on values. The values that the operators work on are called operands.
Arithmetic operators :four basic arithmetic operations as well as modular division, floor
division and exponentiation. (+, -, *, /) and (%, //, **)
Relational operators : Relational operator compares the values of the operands on its
either side and determines the relationship among them. ==, != , > , < , <=, , >=
Logical operators : There are three logical operators supported by Python. These
operators (and, or, not) are to be written in lower case only. The logical operator
evaluates to either True or False based on the logical operands on either side. and ,
or, not
Assignment operator : Assignment operator assigns or changes the value of the variable
on its left. a=1+2 Augmented assignment operators : += , -= , /= *= , //= %= , **=
Identity operators : is, is no
Membership operators : in, not in
Type Conversion:
The process of converting the value of one data type (integer, string, float, etc.) to another
data type is called type conversion.Python has two types of type conversion.
Control statements are used to control the flow of execution depending upon the
specified condition/logic.
There are three types of control statements:
1. Decision Making Statements (if, elif, else)
2. Iteration Statements (while and for Loops)
3. Jump Statements (break, continue, pass)
4 MARK QUESTIONS
Q1.Differentiate between break and continue statement used in python.
Q2What is comment in python ? Explain its significance.
Q3.Explain the types of errors occurring in python programming language.
5 MARK QUESTIONS
Q1.Differentiate between type conversion and type casting in python with examples.
Q2.Explain mutable and immutable objects in python with examples.
Q3. What is the use of else statement in for loop and in while loop ? Explain.
ANSWERS
ANSWER OF 1 MARK QUESTIONS
1) (iv)
2) (iv)
3) (ii)
4) ii)
5) (iii)
6) (iii)
7) (iii)
8) (iv)
9) (iii)
10) (ii)
2) Comments in Python are identified with a hash symbol, #, and extend to the end of the
line. Hash characters in a string are not considered comments, however. There are three
ways to write a comment - as a separate line, beside the corresponding statement of code,
or as a multi-line comment block.
here are multiple uses of writing comments in Python. Some significant uses include:
Increasing readability
Explaining the code to others
Understanding the code easily after a long-term
Including resources
Re-using the existing code
3. There are three types of Python errors.
1. Syntax errors
Syntax errors are the most basic type of error. They arise when the Python parser is unable to
understand a line of code. Syntax errors are almost always fatal, i.e. there is almost never a
way to successfully execute a piece of code containing syntax errors.
2.Logical errors
These are the most difficult type of error to find, because they will give unpredictable
results and may crash your program. A lot of different things can happen if you have a logic
error.
3. Run time errors
Run time errors arise when the python knows what to do with a piece of code but is unable to
perform the action.Since Python is an interpreted language, these errors will not occur until
the flow of control in your program reaches the line with the problem. Common example of
runtime errors are using an undefined variable or mistyped the variable name.
2. Mutable in Python can be defined as the object that can change or be regarded as
something changeable in nature. Mutable means the ability to modify or edit a value.
Mutable objects in Python enable the programmers to have objects that can change their
values. They generally are utilized to store a collection of data. It can be regarded as
something that has mutated, and the internal state applicable within an object has changed.
Immutable objects in Python can be defined as objects that do not change their values and
attributes over time.
These objects become permanent once created and initialized, and they form a critical part of
data structures used in Python.
Python is used in numbers, tuples, strings, frozen sets, and user-defined classes with
some exceptions. They cannot change, and their values and it remains permanent once
they are initialized and hence called immutable.
3. Else with loop is used with both while and for loop. The else block is executed at the end
of loop means when the given loop condition is false then the else block is executed.
i=0
while i<5:
i+=1
print("i =",i)
else:
print("else block is executed")
Explanation
declare i=0
we know then while loop is active until the given condition is true. and we check i<5 it’s
true till the value of i is 4.
i+=1 increment of i because we don’t want to execute the while loop infinite times.
print the value of i
else block execute when the value of i is 5.
l = [1, 2, 3, 4, 5]
for a in l:
print(a)
else:
print("else block is executed")
Explanation
declare a list l=[1,2,3,4,5]
for loop print a.
else block is execute when the for loop is read last element of list.
STRINGS
A sequence of characters is called a string. Strings are used by programming languages to
manipulate text such as words and sentences.
Strings literal in Python are enclosed by double quotes or single quotes. String literals can
span multiple lines, to write these strings triple quotes are used.
>>> a = ‘’’ Python Empty string can also be created in
Programming Python .
Language’’’ >>> str = ‘ ‘
Accessing Values in
Strings
Each individual character in a string can be assessed using a technique called indexing .
Python allows both positive and negative indexing.
S = “Python Language”
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
P y t h o n L a n g u a g e
-15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
>>> S[7] >>>S[-10]
L n
Deleting a String
As we know, strings are immutable, so we cannot delete or remove the characters from the
string but we can delete entire string using del >>> strl = " WELCOME "
keyword. >>> del strl
>>> print ( str1 )
NameError : name ' strl ' is not defined .
String Slicing
To access some part of a string or substring, we use a method called slicing.
Syntax: string_name[start : stop]
>>> str1 = " Python Program "
>>> print ( str1[ 3: >>> print ( str1 [ : -4 ] >>> print ( strl [ 5 : ] )
8]) hon P ) Python Pro n Program
Strings are also provide slice steps which used to extract characters from string that are not
consecutive. Syntax string_name [ start : stop : step ]
>>> print ( stri [ 2 : 12 : 3 ] )
tnrr
We can also print all characters of string in reverse order using [ ::-1 ]
>>> print ( strl [ :: - 1 ] )
margorP nohtyP
Traversing a String
1. Using ' for’ loop: for loop can iterate over the elements of a sequence or string . It is used
when you want to traverse all characters of a string. eg. >>> sub = " GOOD "
>>> fo
String Operations:
String Concatenation:
concatenate means to join. Python allows us to join two strings using the concatenation
operator plus which is denoted by symbol +.
>>> str1 = 'Hello' #First string
>>> str2 = 'World!' #Second string
>>> str1 + str2 #Concatenated strings 'HelloWorld!'
String Replication Operator ( * )
Python allows us to repeat the given string using repetition operator which is denoted by
symbol (*) .
>>> a = 2 * " Hello "
>>> print ( a )
HelloHello
Comparison Operators
Python string comparison can be performed using comparison operators ( == , > , < , , < = , >
= ) . These operators are as follows
>>> a = ' python ' < ' program '
>>> print ( a ) False
>>> a = ' Python '
>>> b = ' PYTHON "
>>> a > b True
Membership Operators are used to find out whether a value is a member of a string or not .
(i) in Operator: (ii) not in Operator:
>>> a = "Python Programming >>> a = "Python Programming Language"
Language" >>> "Java" not in a
>>> "Programming" in a True
True
STRING METHODS
Method Description
len() Returns length of the given string
title() Returns the string with first letter of every word in the string in
uppercase and rest in lowercase
lower() Returns the string with all uppercase letters converted to
lowercase
upper() Returns the string with all lowercase letters converted to
uppercase
count(str, start, end) Returns number of times substring str occurs in the given string.
find(str,start, Returns the first occurrence of index of substring stroccurring in
end) the given string. If the substring is not present in the given string,
then the function returns -1
index(str, start, end) Same as find() but raises an exception if the substring is not
present in the given string
endswith() Returns True if the given string ends with the supplied substring
otherwise returns False
startswith() Returns True if the given string starts with the supplied substring
otherwise returns False
isalnum() Returns True if characters of the given string are either
alphabets or numeric. If whitespace or special symbols are part
of the given string or the string is empty it returns False
islower() Returns True if the string is non-empty and has all lowercase
alphabets, or has at least one character as lowercase alphabet
and rest are non-alphabet characters
isupper() Returns True if the string is non-empty and has all uppercase
alphabets, or has at least one character as uppercase character and
rest are non-alphabet characters
isspace() Returns True if the string is non-empty and all characters are
white spaces (blank, tab, newline, carriage return)
istitle() Returns True if the string is non-empty and title case, i.e., the first
letter of every word in the string in uppercase and rest in
lowercase
lstrip() Returns the string after removing the spaces only on the left of the
string
rstrip() Returns the string after removing the spaces only on the right of
the string
strip() Returns the string after removing the spaces both on the left and
the right of the string
replace (oldstr, newstr) Replaces all occurrences of old string with the new string
join() Returns a string in which the characters in the string have been
joined by a separator
partition ( ) Partitions the given string at the first occurrence of the substring
(separator) and returns the string partitioned into three parts.
1. Substring before the separator
2. Separator
3. Substring after the separator If the separator is not found in
the string, it returns the whole string itself and two empty strings
split() Returns a list of words delimited by the specified substring. If no
delimiter is given then words are separated by space.
LIST
List is an ordered sequence, which is used to store multiple data at the same time. List
contains a sequence of heterogeneous elements. Each element of a list is assigned a number
to its position or index. The first index is 0 (zero), the second index is 1 , the third index is
2 and so on .
Creating a List In Python,
a = [ 34 , 76 , 11,98 ]
b=['s',3,6,'t']
d=[]
Creating List From an Existing Sequence: list ( ) method is used to create list from an
existing sequence . Syntax: new_list_name = list ( sequence / string )
You can also create an empty list . eg . a = list ( ) .
Similarity between List and String
• len ( ) function is used to return the number of items in both list and string .
• Membership operators as in and not in are same in list as well as string .
• Concatenation and replication operations are also same done in list and string.
Difference between String and List
Strings are immutable which means the values provided to them will not change in
the program. Lists are mutable which means the values of list can be changed at any
time.
Accessing Lists
To access the list's elements, index number is used.
S = [12,4,66,7,8,97,”computer”,5.5,]
>>>
S[5] 97
Traversing a List
Traversing a list is a technique to access an individual element of that list.
1. Using for loop for loop is used when you want to traverse each element of a list.
>>> a = [‘p’,’r’,’o’,’g’,’r’,’a’,’m’]
>>> fot x in a:
print(x, end = ‘ ‘) output : p r o g r a m
2. Using for loop with range( )
>>> a = [‘p’,’r’,’o’,’g’,’r’,’a’,’m’]
>>> fot x in range(len(a)):
print(x, end = ‘ ‘) output : p r o g r a m
List Operations
1. Concatenate Lists
List concatenation is the technique of combining two lists . The use of + operator can easily
add the whole of one list to other list . Syntax list list1 + list2 >>> L1 = [ 43, 56 , 34 ]
e.g. >>> L2 = [ 22 , 34 , 98 ]
>>> L = 11 + 12
2. Replicating List >>> L [ 43, 56, 34, 22 , 34 , 98 ]
Elements of the list can be replicated using * operator
. Syntax list = listl * digit e.g. >>> L1 = [ 3 , 2 , 6 ]
>>> L = 11 * 2
>>> L [ 3 , 2 , 6 , 3 , 2 , 6 ]
3. Slicing of a List: List slicing refers to access a specific portion or a subset of the list
for some operation while the original list remains unaffected .
Syntax:- list_name [ start: end ] Syntax: list_name [ start: stop : step ]
>>> List1 = [ 4 , 3 , 7 , 6 , 4 , 9 ,5,0,3 , 2] >>> List1 = [ 4 , 3 , 7 , 6 , 4 , 9 ,5,0,3 , 2]
>>> S = List1[ 2 : 5 ] >>> S = List1[ 1 : 9 : 3 ]
>>> S >>> S
[ 7, 6, 4 ] [ 3, 4, 0 ]
List Manipulation Updating
Elements in a List
List can be modified after it created using slicing e.g.
>>> l1= [ 2 , 4, " Try " , 54, " Again " ]
>>> l1[ 0 : 2 ] = [ 34, " Hello " ]
>>> l1
[34, ' Hello ', ' Try ', 54, ' Again ']
>>> l1[ 4 ] = [ "World " ]
>>> l1
[34, ' Hello ', ' Try ', 54, ['World ']]
Deleting Elements from a List
del keyword is used to delete the elements from the list
. Syntax:-
del list_name [ index ] # to delete individual element
del 11st_name [ start : stop ] # to delete elements in list slice c.g.
>>> list1 = [ 2.5 , 4 , 7 , 7 , 7 , 8 , 90 ]
>>> del list1[3] >>> del list1[2:4]
>>> list1 >>> list1
[2.5, 4, 7, 7, 8, 90] [2.5, 4, 8, 90]
TUPLES
A tuple is an ordered sequence of elements of different data types. Tuple holds a sequence
of heterogeneous elements, it store a fixed set of elements and do not allow changes
Tuple vs List
Elements of a tuple are immutable whereas elements of a list are mutable.
Tuples are declared in parentheses ( ) while lists are declared in square brackets [ ].
Iterating over the elements of a tuple is faster compared to iterating over a list.
Creating a Tuple
To create a tuple in Python, the elements are kept in parentheses ( ), separated by commas.
a = ( 34 , 76 , 12 , 90 )
b=('s',3,6,'a')
Accessing tuple elements, Traversing a tuple, Concatenation of tuples, Replication of
tuples and slicing of tuples works same as that of List
MIND MAP
List is an ordered sequence Method
of heterogeneous elements len()
List is created using [ ] list()
bracket append()
Individual character in a list extend()
can be assessed using index insert()
Lists are mutable count()
index()
remove()
List Osperations
Concatination Operator (+)
LIST pop()
reverse()
Replication Operators (*) sort()
Comparison Operators ( == , sorted()
> , < , < = , > = , !=) min()
Membership Operators (in max()
& not in sum()
List supports slicing
QUESTIONS:
1 MARK QUESTIONS
1. What will be the output of the following set of commands
>>> str = "hello"
>>> str[:2]
a. lo b. he c. llo d. el
2. Which type of object is given below
>>> L = 1,23,"hello",1
a. list b. dictionary c. array d. tuple
3. Which operator tells whether an element is present in a sequence or not
a. exist b. in c. into d. inside
4. uppose a tuple T is declared as T = (10,12,43,39), which of the following is incorrect
a. print(T[1]) b. T[2] = -2 c. print(max(T)) d. print(len(T))
5. Which index number is used to represent the last character of a string
a. -1 b. 1 c. n d. n – 1
6. Which function returns the occurrence of a given element in a list?
a. len() b. sum() c. extend() d. count()
7. which type of slicing is used to print the elements of a tuple in reverse order
a. [:-1] b. [: : -1] c. [1 : :] d. [: : 1]
8. Dictionaries are also called
a. mapping b. hashes c. associative array d. all of these
9. Which function returns the value of a given key, if present, from a dictionary?
a. items() b. get() c. clear() d. keys()
10. The return type of input() function is:
a. list b. integer c. string d.
tuple ANSWERS
1 B 6 d
2 D 7 b
3 B 8 d
4 B 9 b
5 A 10 c
2 MARKS QUESTIONS
Q1. Rewrite the following code in python after removing all syntax error(s). Underline each
correction done in the code.
STRING=""WELCOME
NOTE""
for S in range[0,8]:
print (STRING(S))
Q2. Find output generated by the following code:
Str=”Computer”
Str=Str[-4:]
print(Str*2)
Q3. What will be the output of the following question
L = [10,19,45,77,10,22,2]
i) L.sort() ii)
max(L) print(L)
Q4. Find the output
L = [10,19,45,77,10,22,2]
i) L[3:5] ii) L[: : -2]
Q5. Distinguish between list and tuple.
Q6. Read the code given below and show the keys and values separately.
D = {‘one’ : 1, ‘two’ : 2, ‘three’ : 3}
Q7. Observe the given list and answer the question that follows.
List1 = [23,45,63, ‘hello’, 20, ‘world’,15,18]
i) list1[-3] ii)
list1[3] Q8. Assertion
(A) :
s = [11, 12, 13, 14]
s[1] = 15
Reasoning (R) : List is immutable.
(A) Both A and R are true and R is the correct explanation of assertion.
(B) A and R both are true but R is not the correct explanation of A .
(C) A is true, R is false.
(D) A is false, R is true.
Q9. a=(1,2,3)
a[0]=4
Assertion: The above code will result in error
Reason: Tuples are immutable. So we can’t change them.
(A) Both Assertion and reason are true and reason is correct explanation of assertion.
(B) Assertion and reason both are true but reason is not the correct explanation of assertion.
(C) Assertion is true, reason is false.
(D) Assertion is false, reason is true.
ANSWERS
Q1. CORRECTED CODE:-
STRING= "WELCOME"
NOTE=" "
for S in range (0, 7) :
print (STRING
[S])
Also range(0,8) will give a runtime error as the index is out of range. It shouldbe range(0,7)
Q2. Q3. Q4.
uter [2, 10, 10, 19, 22, 45, 77] [77, 10]
‘ComputerComputer’ [2, 10, 45, 10]
Q5.
List Tuple
Elements of a list are mutable Elements of tuple are immutable
List is declared in square brackets [] Tuple is declared in parenthesis ()
Iterating over elements in list slower as Iterating over elements of tuples is faster as
compared to tuple compared to list
e.g L1 = [1,2,3] e.g T1 = (1,2,3)
Q6. Q7. Q8. (C) Q9. (A)
Keys: ‘one’, ‘two’, ‘world’
‘three’ Values: 1,2,3 ‘hello’
3 MARKS QUESTIONS
Q1. Which of the string built in methods are used in following conditions?
ii) Returns the length of a string
iii)Removes all leading whitespaces in string
iv) Returns the minimum alphabetic character from a string
Q2. Write a program to remove all the characters of odd index value in a string
Q3. Write a python program to count the frequencies of each elements of a list using
dictionary
Q4. what will be the output of the following python code
L = [10,20]
L1 = [30,40]
L2 = [50,60]
L.append(L1)
print(L)
L.extend(L2)
print(L)
print(len(L)
Q5. Find the output of the given question
t = (4,0,’hello’,90,’two’,(‘one’,45),34,2)
i) t[5]
ii) t[3:7]
iii) t[1] + t[-2]
ANSWERS
Q1. i) len()ii) lstrip() iii)min() Q2. str =
input(“Enter a string “)
final = “ “
For i in range(len(str)):
if (i%2 == 0):
final = final + str[i]
print(“The modified string is “,final)
Q3.L1 = []
n = int(input(“Enter number of elements of the list “)) for i
in range(0,n):
ele = int(input())
L1.append(ele)
print(“Original list = “,L1)
print(“Elements of list with their frequencies : “)
freq ={}
for item in L1:
if item in freq:
freq[item] += 1
else:
freq[item] = 1
for k,v in freq.item():
print(“Element”, k, “frequency”, v)
Q4. Q5.
[10, 20, [30, 40]] i) (‘one’,45)
[10, 20, [30, 40],50,60] ii) (90,’two’,’(‘one’,45),34)
iii) 34
4 MARKS QUESTIONS
Q1. Find the output
i) 'python'.capitalize()
ii) max('12321')
iii) 'python'.index('ho')
iv) 'python'.endswith('thon')
Q2. Consider the following code and answer the question that follows.
book = {1:'Thriller',2:'Mystery',3:'Crime',4:'Children Stories'}
library = {5:'Madras Diaries',6:'Malgudi Days'}
v)Ramesh wants to change the book ‘Crime’ to ‘Crime Thriller’. He has written
the following code:
book['Crime'] = 'Crime Thriller'
but he is not getting the answer. Help him to write the correct command.
vi)Ramesh wants to merge the dictionary book with the dictionary library. Help him to
write the command.
Q3. Write the suitable method names for the conditions given below:
i) Add an element at the end of the list
ii) Return the index of first occurrence of an element
iii) Add the content of list2 at the end of list1
iv) Arrange the elements of a list1 in descending order
ANSWERS
Q1.
i) 'Python' ii) '3' iii) 3 iv) True
Q2.i) book[3] = 'Crime Thriller'
ii) library.update(book)
Q3.i) append() ii) index() iii) list1.extend(list2)
iv) list1.sort(reverse = True)
5 MARKS QUESTIONS
Q1. Find the output of the following
code: a = (5,(7,5,(1,2)),5,4)
print(a.count(5))
print(a[1][2])
print(a * 3)
print(len(a))
b = (7,8,(4,5))
print(a + b)
Q2. Following is a program to check a list is same if it is read from front or from back. Observe
the program and answer the following questions:
a = [1,2,3,3,2,1]
i= # statement 1
mid = (len(a)) /
2 same = True
hile : # statement
2 if a[i] != : # statement
3
print(“NO”)
same =
False break
# statement 4
if same == : # statement
5 print(“YES”)
ANSWERS
Q1. 2
(1, 2)
(5, (7, 5, (1, 2)), 5, 4, 5, (7, 5, (1, 2)), 5, 4, 5, (7, 5, (1, 2)), 5, 4)
4
(5, (7, 5, (1, 2)), 5, 4, 7, 8, (4, 5))
Q2. i) 0
ii) i < mid
iii) a[i] != a[len(a) – i – 1]
iv) i = i + 1
v) True
Q3. i) title()
Returns the string with first letter of every word in the string in uppercase and rest in
lowercase.
>>> str1 = 'hello WORLD!'
>>>
str1.title()
'Hello World!'
ii) count( )
Returns number of times substring str occurs in the given string. If we do not give start
index and end index then searching starts from index 0 and ends at length of the string.
>>> str1 = 'Hello World! Hello Hello'
>>> str1.count('Hello',12,25)
2
>>>
str1.count('Hello') 3
iii)find()
Returns the first occurrence of index of substring stroccurring in the given string. If we do not
give start and end then searching starts from index 0 and ends at length of the string. If the
substring is not present in the given string, then the function returns -1
>>>str1= 'Hello World! Hello Hello'
>>>
str1.find('Hello',10,20) 13
>>> str1.find('Hello',15,25)
19
>>> str1.find('Hello')
0
>>> str1.find('Hee')
-1
iv) index( )
Same as find() but raises an exception if the substring is not present in the given string
>>> str1 = 'Hello World! Hello Hello'
>>> str1.index('Hello')
0
>>> str1.index('Hee')
ValueError: substring not found
v) join()
Returns a string in which the characters in the string have been joined by a separator
>>> str1 = ('HelloWorld!')
>>> str2 = '-' #separator
>>> str2.join(str1)
'H-e-l-l-o-W-o-r-l-d-!'
FUNCTION IN PYTHON
Functions: types of function (built-in functions, functions defined in module, user defined
functions), creating user defined function, arguments and parameters, default parameters,
positional parameters, function returning value(s), flow of execution, scope of a variable
(global scope, local scope)
Let us revise
A function is a block of code that performs a specific task.
Advantages of function: Reusability of code, Reduce size of code, minimum
number of statements, minimum storage, Easy to manage and maintain
Types of functions: Built-in-functions, Functions defined in module, User
defined function
Built-in functions are the functions whose functionality is pre-defined in python
like abs(), eval(), input(), print(), pow()
Some functions are defined inside the module like load() and dump() function
defined inside the pickle module.
A function that can be defined by the user is known as user defined function.
def keyword is used to define a function.
There is a colon at the end of def line, meaning it requires block
User Defined function involved two
steps: defining
calling
Syntax for user defined function:
def <function name>( [parameter list ]):
[””function’s doc string ””]
<statement>
[<statement>]
Python supports three types of formal arguments/ parameters: Positional
Arguments, Default parameters, Keyword (or named ) Arguments
Positional Arguments: When the function call statement must match the number
and order of arguments as defined in the function definition, this is called the
positional argument matching.
A parameter having default value in the function header is known as a
default parameter.
Keyword Arguments are the named arguments with assigned values being passed in
the function call statement.
A function may or may not return one or more values.
A function that does not return a value is known as void function and returns
legal empty value None.
Functions returning value are also known as fruitful functions.
The flow of execution refers to the order in which statements are executed during
a program.
A variable declared in a function body (block) is said to have local scope. i.e. it
can be accessed within this function.
A variable declared outside of all functions/top level of segment of a program is
said to have global scope. i.e. it can be accessible in whole program and all blocks
( functions and the other blocks contained within program.
MIND MAP ON FUNCTION
Function: A function is a group of statements that exists within a
program for the purpose of performing a specific task.
Built-in-functions:
Bulit-in functions Function defined in User Defined
are the predefined module: A module functions: A function
functions that are is a file containing is a block of code
already available in functions and which only runs when it
the python. Ex- int(), variables defined in is called. In Python, a Local: A variable
separate files. function is defined created inside a
using the def keyword. function belongs to
the local scope of
that function, and
can only be used
Global: A variable declared inside that function.
outside of all functions/top Ex-
level of segment of a program
is said to have global scope. x = 300
i.e. it can be accessible in def myfunc():
whole program and all blocks. print(x)
myfunc()
Ex- print(x)
def myfunc():
x = 300
print(x)
myfunc()
Types of Arguments/Parameters
1. (a) None
2. (c) Both function name and parameter list
3. (c) def
4. (d) return number
5. (c) def f(a=1, b=1, c=2):
6. (a) You can pass positional arguments in any order.
7. (b) A global variable
8. (b) LEGB
9. (c) A is True but R is False
10. (b) Flow of execution
11. (c) Both Statements are Correct
12. c) scope
On the basis of the above code, choose the right statement which will be executed when
different inputs for pay and location are given
(i) Input: location = “Chennai”, pay = 50000
a. Statement 1 b. Statement 2 c. Statement 3 d. Statement 4
(ii) Input: location = “Surat” ,pay = 50000
a. Statement 2 b. Statement 4 c. Statement 5 d. Statement 6
(iii) Input- location = “Any Other City”, pay = 1
a Statement 1 b. Statement 2 c. Statement 4 d. Statement 6
(iv) Input location = “Delhi”, pay = 500000
a. Statement 6 b. Statement 5 c. Statement 4 d. Statement 3
Q2. Kids Elementary is a Playway school that focuses on “Play and learn” strategy that helps
toddlers understand concepts in a fun way. Being a senior programmer, you have taken
responsibility to develop a program using user-defined functions to help children differentiate
between upper case and lower case letters/ English alphabet in a given sequence. Make sure
that you perform a careful analysis of the type of alphabets and sentences that can be included
as per age and curriculum. Write a python program that accepts a string and calculates the
number of upper case letters and lower case letters.
Answer:
def string_test(s):
d={"UPPER_CASE":0,"LOWER_CASE":0}
for c in s:
if c.isupper():
d["UPPER_CASE"]+=1
elif c.islower(): d["LOWER_CASE"]
+=1
else:
pass
print("Original String:",s)
print("No. of Upper Case Characters:",d["UPPER_CASE"])
print("No. of Lower Case Characters:",d["LOWER_CASE"])
string_test("Play Learn and Grow")
Q2. Observe the following code and select appropriate answers for the given questions:
total=1
def multiply(l): #
line1 for x in l:
total #
line2 total*=x
return # line3
l=[2,3,4]
print(multiply( ), end=” “) #
line4 print(“ , Thank You”)
(i) Identify the part of function in # line1
(a) Function header (b) Function calling (c) Return statement (d)Default argument
(ii) Which of the keyword is used to fill in the blank for # line2 to run the program
without error.
(a) eval (b) def (c) global (d) return
(iii) Which variable is going to be returned in # line3
(a) total (b) x (c) l (d) None
(iv) Which variable is required in the # line4
(a) total (b) x (c) l (d) None
(v) In the # line4 the multiple(l) is called
(a) Caller (b) Called (c) Parameters (d) Arguments
Answer: (i) (a) Function header
(ii) (c) global
(iii) (a) total
(iv) (c) l
(v) (a) Caller
Exception Handling
Exception: Contradictory or Unexpected situation or unexpected error, during program
execution, is known as Exception.
Exception Handling: Way of handling anomalous situations in a program-run, is known as
Exception Handling.
Some common examples of Exceptions are:
Divide by zero errors Hard disk crash
Accessing the elements of an array beyond its range Opening a non-existent file
Invalid Heap memory exhausted
input Example:
try :
print ("result of 10/5 = ", (10/5))
print ("result of 10/0 = ", (10/0))
except :
print ("Divide by Zero Error! Denominator must not be
zero!")
The output produced by above code is as shown below :
result of 10 / 5 = 2
result of 10 / 0 = Divide by Zero Error! Denominator must not be zero!
1 Marks Question:
1. Errors resulting out of violation of programming language’s grammar rules are known as:
(a) Compile time error (b) Logical error (c) Runtime error (d) Exception
2. An unexpected event that occurs during runtime and causes program disruption, is called:
(a) Compile time error (b) Logical error (c) Runtime error (d) Exception
3. Which of the following keywords are not specific to exception handling ?
(a) try (b) except (c) finally (d) else
4. Which of the following blocks is a ‘must-execute’ block ?
(a) try (b) except (c) finally (d) else
5. Which keyword is used to force an exception ?
(a) try (b) except (c) raise (d) finally
Answers:
1. (a) 2. (d) 3. (d) 4. (c) 5. (c)
Predict the output of the following code for these function calls:
(a) divide(2, 1) (b) divide(2, 0) (c) divide(“2”,
“1”) def divide(x, y):
try:
result = x/y
except ZeroDivisionError:
print ("division by zero!")
else:
print ("result is", result)
finally:
print ("executing finally clause")
Solution.
(a) divide(2, 1) result is
2 executing finally
clause
(b) divide(2, 0) division by
zero! executing finally clause
(c) divide(“2”, “1”)
executing finally
clause
Traceback (most recent call last):
TypeError: unsupported operand type(s) for /: 'str' and 'str'
ILE HANDLING – TEXT FILES
I. INTRODUCTION:
• Files are named locations on disk to store related information. They are used
to permanently store data in a non-volatile memory (e.g. hard disk).
• Since Random Access Memory (RAM) is volatile (which loses its data when
the computer is turned off), we use files for future use of the data by
permanently storing them.
• When we want to read from or write to a file, we need to open it first. When
we are done, it needs to be closed so that the resources that are tied with the
file are freed.
• Hence, in Python, a file operation takes place in the following order:
– Open a file
– Read or write (perform operation)
– Close the file
II Types of File in Python
There are two types of files in Python and each of them are explained below in detail
with examples for your easy understanding. They are:
1) Binary file 2) Text file
II. Text files in Python
• A text file is usually considered as sequence of lines. Line is a sequence of
characters (ASCII), stored on permanent storage media. Although default
character coding in python is ASCII but supports Unicode as well.
• In text file, each line is terminated by a special character, known as End of Line
(EOL). From strings we know that \n is newline character.
• At the lowest level, text file is collection of bytes. Text files are stored in human
readable form. They can also be created using any text editor.
• Text files don’t have any specific encoding and it can be opened in normal text
editor itself.
Example of Text Files:
• Web standards: html, XML, CSS, • Tabular data: csv, tsv etc.
JSON • Configuration: ini, cfg, reg etc
• Source code: c, app, js, py, java etc.
• Documents: txt, tex, RTF etc.
III. OPENING OR CREATING A NEW FILE IN PYTHON
• The method open() is used to open an existing file or creating a new file. If
the complete directory is not given then the file will be created in the
directory in which the python file is stored. The syntax for using open()
method is given below.
– Syntax:
– file_object = open( file_name, “Access Mode”, Buffering )
• The open method returns file object which can be stored in the name file
object (file-handle).
File name is a unique name in a directory. The open() function will create the file
with
the specified name if it is not already exists otherwise it will open the already
existing file.
File Access Modes:
• The access mode: it is the string which tells in what mode the file should be
opened for operations. There are three different access modes are available in
python.
• Reading: Reading mode is crated only for reading the file. The pointer will
be at the beginning of the file.
• Writing: Writing mode is used for overwriting the information on existing file.
• Append: Append mode is same as the writing mode. Instead of over writing
the information this mode append the information at the end.
• Below is the list of representation of various access modes in python.
Access modes in Text Files
• ‘r' – Read Mode: Read mode is used only to read data from the file.
• ‘w' – Write Mode: This mode is used when you want to write data into the
file or modify it. Remember write mode overwrites the data present in the
file.
• ‘a' – Append Mode: Append mode is used to append data to the file.
Remember data will be appended at the end of the file pointer.
• ‘r+' – Read or Write Mode: This mode is used when we want to write or read
the data from the same file.
• ‘a+' – Append or Read Mode: This mode is used when we want to read data
from the file or append the data into the same file.
Buffering:
• Buffering is the process of storing a chunk of a file in a temporary memory
until the file loads completely. In python there are different values can be
given.
If the buffering is set to 0 , then the buffering is off. The buffering will be set
to 1 when we need to buffer the file.
Examples of Opening TEXT Files in Python
# open file in current directory
• f = open("test.txt“,
“r”) # specifying full path
– f = open(r“D:\temp\data.txt“, “r”) #–raw string
• f = open(“D:\\temp\\data.txt“, “r”) #-absolute path
IV. CLOSING FILES IN PYTHON
• After processing the content in a file, the file must be saved and closed. To do this
we can use another method close() for closing the file. This is an important method
to be remembered while handling files in python.
• Syntax: file_object.close()
string = "This is a String in Python"
my_file = open(my_file_name.txt,"w+",1)
my_file.write(string)
my_file.close()
print(my_file.closed)
V. READING INFORMATION IN THE FILE
• In order to read a file in python, we must open the file in read mode.
• There are three ways in which we can read the files in python.
– read([n])
– readline([n])
– readlines() – all lines returned to a
list Here, n is the number of bytes to be read.
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read(5))
Output:
Hello
Here we are opening the file test.txt in a read-only mode and are
reading only the first 5 characters of the file using the
my_file.read(5) method.
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read())
Output:
Hello World
Hello Python
Good Morning #Here we have not provided any argument
inside the read() function.
#Hence it will read all the content present inside
the file.
Example 3:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline(2))
Output:
He
This function returns the first 2 characters of the next line.
Example 4:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline())
Output:
Hello World
Using this function we can read the content of the file on a line by line basis.
Example 5:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readlines())
Output:
[‘Hello World\n’, ‘Hello Python\n’, ‘Good Morning’]
Here we are reading all the lines present inside the text file including the newline
characters.
Example 5: Reading a specific line from
a File Output:
line_number = 4 How are You
fo
The above code writes a list of data into the ‘test.txt’ file simultaneously.
Append in a Python Text File:
To append data into a file we must open the file in
‘a+’ mode so that we will have access to both
the append as well as write modes.
Example 1:
my_file = open(“C:/Documents/Python/test.txt”,
“a+”) my_file.write (“Strawberry”)
The above code appends the string ‘Strawberry’ at the
end of the ‘test.txt’ file
Example 2:
my_file = open(“C:/Documents/Python/test.txt”,
“a+”) my_file.write (“\nGuava”)
The above code appends the string ‘Apple’ at the end
of
the ‘test.txt’ file in a new line
flush() function
• When we write any data to file, python hold everything in buffer (temporary
memory) and pushes it onto actual file later. If you want to force Python to write
the content of buffer onto storage, you can use flush() function.
• Python automatically flushes the files when closing them i.e. it will be implicitly
called by the close(), BUT if you want to flush before closing any file you can use
flush()
REMOVING WHITESPACES AFTER READING FROM TEXT FILE
• read() and readline() reads data from file and return it in the form of string
and readlines() returns data in the form of list.
• All these read function also read leading and trailing whitespaces, new line
characters. If we want to remove these characters you can use functions
– strip() : removes the given character from both ends.
– lstrip(): removes given character from left end
– rstrip(): removes given character from right end
File Pointer
• Every file maintains a file pointer which tells the current position in the file
where reading and writing operation will take.
• When we perform any read/write operation two things happens:
– The operation at the current position of file pointer
– File pointer advances by the specified number of bytes.
1- MARK QUESTIONS
1. To read three characters from a file object f, we use ……… .
(a) f.read(3) (b) f.read() (c) f.readline() (d) f.readlines()
2. The files that consists of human readable characters
(a) binary file (b) text file (c) Both (a) and (b) (d) None of these
3. Which function is used to write a list of string in a file?
(a) writeline() (b) writelines() (c) writestatement() (d) writefullline()
4. What will be the output of the following Python
code? myFile = None
for i in range (8):
with open(“data.txt”, “w”) as
myFile: if i > 5:
break
print(myFile.closed)
1. (a) ) 2. (b) 3. (a) 4. (a)5. (d) 6. (b) 7. (b) 8. (a)9. (b) 10.
2 MARK QUESTIONS
Q1. Write a single loop to display all the contens of a text file file1.txt after removing leading
and trailing WHITESPACES
out=open('output.txt','w')
out.write('hello,world!\n')
out.write('how are you')
out.close( )
open('output.txt').read( )
Q3. Read the code given below and answer the questions
f1=open('main.txt','w')
f1.write('bye')
f1.close()
If the file contains 'GOOD' before execution, what will be the content of the file after
execution of the code
Q4. Observe the following code and answer the follow
f1=open("mydata","a")
#blank1
f1.close()
(i) what type of file is mydata
(ii) Fill in the blank1 with statement to write "abc" in the file "mydata"
Q5. A given text file data.txt contains :
Line1\n
\n
line3
Line 4
\n
line6
What would be the output of following code?
f1=open('data.txt')
L=f1.readlines()
print(L[0])
print(L[2])
print(L[5])
print(L[1])
print(L[4])
print(L[3])
Q6. In which of the following file modes the existing data of the file will not be lost?
i) rb
ii) w
iii) a+b
iv) wb+
v) r+
vi) ab
vii) w+b
viii)wb
ix) w+
Q7. What would be the data types of variables data in following statements?
i) Data=f.read( )
ii) Data=f.read(10)
iii) Data=f.readline()
iv)Data=f.readlines()
Q8 Suppose a file name test1.txt store alphabets in it then what is the output of the
following code
f1=open("test1.txt")
size=len(f1.read())
print(f1.read(5))
Q9. What is standard input, output and error steams?
Q10. Write a short note on flush() function.
ANSWER – 2-MARK QUESTIONS
Ans1 for line in open(“file1.txt”):
print(line.strip())
Ans2 The output will be
Hello,world!
How are you?
The first line of code is opening the file in write mode,the next two line writes text t file .the
last line
opens the file and from that reference reads the file content.file() performs the same functions
as open().Thus,the file(“output.txt”)will give the references to open the file on which read() is
applied.
Ans3 The file would now contains “Bye”only because when an existing file is openend in
write mode .it
truncates the existing data in file .
Ans4 i) Text file
ii) f1.write(“abc”)
Ans5 Line1
Line3
Line
6
Line 4
Ans6 ab and a+b mode
Ans7 a) string b)string c)string
d)list Ans 8 No Output
Explanation: the f1.read() of line 2 will read entire content of file and place the file pointer
at the
end of file. for f1.read(5) it will return nothing as there are no bytes to be read from EOF and,
thus,print statement prints nothing.
Ans 9
Standard input device(stdin) reads from the keyboard
Standard output device(stdout)- prints to the display and can be redirected as
standard input
Standard error device(stderr)- Same as stdout but normally only for errors. Having error output
separately allows the user to divert regular output to a file and still be able to read error messages.
Ans 10
While writing, Python writes everything into a buffer and pushes it into file at a
later time.
When flush() function is called it immediately empties the buffer and writes into
the file.
This function is called automatically when file is closed.
3 MARK QUESTIONS
Q1. Write a python code to find the size of the file in bytes, number of lines and number of
words.
# reading data from a file and find size, lines, words
f=open(‘Lines.txt’,’r’)
str=f.read( )
size=len(str)
print(‘size of file n bytes’,size) f.seek(0)
L=f.readlines( )
word=L.split( )
print(‘Number of lines ’,len(L))
print(‘Number of words ’,len(word))
f.close( )
Q2. Write code to print just the last line of a text file “data.txt”.
Ans: fin=open(“data.txt”,”r”)
lineList=fin.readlines()
print(“Last line = “, lineList[-1])
Q.3 Write a program to count the words “to” and “the” present in a text file “python.txt”.
Ans.
fname = "python.txt"
num_words = 0
f= open(fname, 'r') words =
f.read().split()
for a in words:
if (a.tolower() == “to” or a.tolower() == “the” ):
num_words = num_words + 1
print("Number of words:", num_words) f.close()
Q.4. Write a program to display all the lines in a file “python.txt” along with line/record
number.
Ans.
fh=open("python.txt","r")
count=0
lines=fh.readlines()
for a in lines:
count=count+1
print(count,a)
fh.close()
Q. 5 Write a program to display all the lines in a file “python.txt” which have the word
“to” in it.
Ans.
fh=open("python.txt","r")
count=0
lines=fh.readlines()
for a in lines:
if (a.tolower().count(“to”) > 0) :
print(a)
fh.close()
3- MARK QUESTIONS
1. Write a python program to create and read the city.txt file in one go and
print the contents on the output screen.
Answer:
# Creating file with open() function
f=open("city.txt","w")
f.write("My city is very clean city.")
f.close()
# Reading contents from city.txt file
f=open("city.txt","r")
dt = f.read()
print(dt)
f.close()
2. Consider following lines for the file friends.txt and predict the output:
Friends are crazy, Friends are naughty !
Friends are honest, Friends are best !
Friends are like keygen, friends are like license key !
We are nothing without friends, Life is not possible without friends
! f = open("friends.txt")
l = f.readline()
l2 =
f.readline(18)
ch3=f.read(10)
print(l2)
print(ch3)
print(f.readline())
f.close()
Output:
Friends are honest
, Friends
are best !
Explanation:
In line no. 2, f.readline() function reads first line and stores the output string in l but not
printed in the code, then it moves the pointer to next line in the file. In next statement we
have f.readline(18) which reads next 18 characters and place the cursor at the next position
i.e. comma (,) , in next statement f.read(10) reads next 10 characters and stores in ch3
variable and then cursor moves to the next position and at last f.readline() function print() the
entire line.
3. Write a function count_lines() to count and display the total number of lines from
the file. Consider above file – friends.txt.
def count_lines():
f = open("friends.txt")
cnt =0
for lines in f:
cnt+=1
lines = f.readline()
print("no. of lines:",cnt)
f.close()
4. Write a function display_oddLines() to display odd number lines from the text
file. Consider above file – friends.txt.
def display_oddLines():
f=
open("friends.txt")
cnt =0
for lines in f:
cnt+=1
lines = f.readline()
if cnt%2!=0:
print(lines)
f.close()
5. Write a function cust_data() to ask user to enter their names and age to store data
in customer.txt file.
def cust_data():
name = input("Enter customer
name:") age=int(input("Enter
customer age:")) data =
str([name,age])
f =
open("customer.txt","w")
f.write(data)
f.close()
4 MARK QUESTIONS
Q1. This question consists of 6 sub-questions . Attempt any 5 questions.
Below is a program to delete the line having word (passed as argument). Answer the
questions that follow to execute the program successfully.
def filedel(word) :
file1 = open(“Python.txt ”,“ ”) # Statement
1 nfile = open(“algo.txt”, “w”)
while True :
line = file1. # Statement 2
if not line :
break
else :
if word in line
# Statement 3
: else :
print(line)
nfile. (line) # Statement 4
file1.close()
. close() # Statement 5
filedel(‘write’)
(i). In which mode, program should open the file to delete the line in statement 2?
(a) w (b) r (c) r+ (d) a+
(ii). Choose the correct option to fill up the blank in line marked as Statement 3.
(a) read() (b) read(n) (c) readlines() (d) readline()
(iii). Identify the missing code for blank space in line marked as Statement 4.
(a) True (b) Flag (c) pass (d) False
(iv). Choose the correct option to fill up the blank in line marked as Statement 5.
(a) read (b) write (c) writelines (d) writeline
(v). Choose the correct option to fill up the blank in line marked as Statement 6.
(a) file 1 (b) file (c) nfile (d) None
Answer – 1
(i). (b) (ii). (d) (iii) (c) (iv). (b) (v). (c)
(i). Choose the correct option to fill up the blank marked as Line 1.
(a) status (b) “status.txt” (c) status.txt (d) file.txt
(ii). Choose the correct option to fill up the blank marked as Line 2.
(a) 0 (b) 1 (c) False (d) True
(iii). Which function will be used to read the content of file marked as Line 3?
(a) readline() (b) readlines() (c) read() (d) read(n)
(iv). Choose the correct option to fill up the blank marked as Line 4.
(a) continue (b) break (c) goto (d) label
(v) Which value will be assign to variable count in Line 5?
(a) count −1 (b) count*i (c) count +1 (d) count + i
(vi). Identify the missing code in Line 6.
(a) f.close (b) myfile.close (c) file.close() (d) f.close()
Answer – 2
(i). (b) (ii). (d) (iii). (a) (iv). (b) (v). (c) (vi). (d)
MIND MAP
Binary Files
FILE HANDLING
Text Files
Various Terms Used in Relational Model: - A relational database is a type of database that
stores and provides access to data points that are related to one another.
Basic Terminologies related to a Relational Database:-
Concept of Keys
In relation each record must be unique i.e. no two identical records are allowed in
the Database.
A key attribute identifies the record and must have unique values. There are
various types of Keys:
Primary key:
A set of one or more attribute that can identify a record uniquely in the relation
is called Primary Key.
There can be only one primary key in a table
Allows only distinct (no duplicate) values and also forces mandatory entry
(NOT NULL) i.e. we can’t leave it blank.
Candidate Key
In a table there can be more than one attribute which uniquely identifies a tuples in
a relation. These columns are known as candidate key as they are the candidate for
primary key.
Among these database analyst select only one attribute as a primary key.
Alternate Key
In case of multiple candidate keys, one of them will be selected as Primary Key
and rest of the column will serve as Alternate Key.
A Candidate Key which is not a primary key is an Alternate Key.
Foreign key
Used to create relationship between two tables.
It is a non-key attribute whose value is derived from the Primary key of another table.
Primary Key column table from where values will be derived is known as Primary
Table or Master Table or Parent Table and Foreign key column table will be
Foreign Table or Detail Table or Child table.
Example:
From the Above table definition we can observe that the DEPTNO column of EMPLOYEE table
is deriving its value from DEPTNO of table DEPARTMENT. So we can say that the
DEPTNO of EMPLOYEE table is a foreign key whose value is dependent upon the Primary
key column DEPTNO of table DEPARTMENT.
REFERENTIAL INTEGRITY:
Used to ensure relationships between records in related tables are valid and user don’t
accidentally delete or change the related data.
Referential integrity can be applied when:
o The master table’s column is a Primary Key or has a unique index
o The related fields have the same data type
o Both tables must belong to same database.
When referential integrity is enforced using Foreign Key you must observe the
following rules:
o You cannot enter a value in Child Table which is not available in Master
Table’s Primary key column. However you can enter NULL values in foreign
key
o You cannot delete a record from Master Table if matching record exists in
related table.
o You cannot modify or change the Primary Key value in Master table if its
matching record is present in related table.
Introduction of MYSQL
Brief history of MySQL:
MySQL is freely available open source RDBMS
It can be downloaded from www.mysql.org
In MySQL information is stored in Tables.
Provides features that support secure environment for storing, maintaining and
accessing data.
It is fast, reliable, scalable alternative to many of the commercial RDBMS today.
MYSQL DATABASE SYSTEM:
MySQL database system refers to the combination of a MySQL server instance and
MySQL database.
It operates using Client/Server architecture in which the server runs on the machine
containing the database and client connects to server over a network
MySQL is a multiuser database system, meaning several users can access the
database simultaneously.
The Server
Listens for client requests coming in over the network and access the database as per
the requirements and provide the requested information to the Client.
The Client
Are the programs that connect to MySQL server and sends requests to the server and
receives the response of Server. Client may be the MySQL prompt or it may be Front-
end programming which connects to server programmatically like connecting to
MySQL using Python Language or Java or any other language.
FEATURES OF MYSQL:
Speed - MySQL runs very fast.
Ease of Use - Can be managed from command line or GUI
It is available free of cost. It is Open Source Software.
Query language Support -Supports SQL
Portability – Can be run on any platform and supported by various compilers.
Data Types - supports various data types like Numbers, Char etc.
Security -Offers privileges and password systems that is very flexible and secure.
Scalability and Limits -Can handle large databases. Some of real life MySQL
databases contain millions of records.
Connectivity - Clients can connect to MySQL using drivers
Localization -The server can provide error message to client in many language
SQL and MYSQL:
SQL stands for Structured Query Language.
It is a language that enables you to create and operate on relational databases.
MySQL uses SQL in order to access databases.
It is the standard language used by almost all the database s/w vendors.
MYSQL Elements
Literals
Data types
Null
Comments
Literals
It means the fixed value or constant value. It may be of character, numeric or
date time type.
Character and date/time literals are always in single quotation marks whereas
numeric literals must be without single quotation marks.
For example – ‘Virat’, 12, 12.56, ‘04-20-2018’.
Date and time values are always in the format YYYY-MM-DD HH:MI:SS.
Special character like quotes are always written be preceding it back-slash(\). For
example if we want to store value as Tom’s Cat then it should be written as
Tom\’s Cat
Data Type
Means the type of value and type of operation we can perform on data. For
example, on numeric value we can store numbers and perform all arithmetic
operations and so on.
MySQL support three categories of data types:
Numeric
Date and time
String types
DECIMAL It is used to store exact numeric value that preserves exact precision
for e.g. money data in accounting system.
DECIMAL(P,D) means P no. of significant digits (1-65), D
represent no. of digit after decimal(0-30), for e.g
DECIMAL(6,2) means 4 digit before decimal and 2 digit
after decimal. Max will be 9999.99
o sum() - Return the summation of all non-NULL values of the set of values.