12th Computer Science Study Material 2024 25
12th Computer Science Study Material 2024 25
Com
et
i.N
la
sa
da
Pa
w.
(Based on the new syllabus and new text book for the year 2024-2025)
ww
PREPARED BY.,
B. MOHAMED YOUSUF M.C.A., B.Ed.,
Pg asst in computer science
[yousufaslan5855@gmail.com]
Index..,
s.no topics Pg.no
PART- I (ONE WORDS)
1. ch-1 to 16 Book back & PUBLIC one word question with answers 1
2. ch-1 to 16 Book INSIDE one word question with answers 8
3. AUTHOR NAMES / ABBREVIATIONS 34
4. CH-1 TO 16 IMPORTANT KEY POINTS 35
5. CHAPTER 1 TO 16 LIST OUTS / TYPES / SUB HEADINGS 42
6. GLOSSARY 47
PART – II (TWO MARKS)
7. ch-1 to 16 Book back &PUBLIC two marks question with answers 50
et
8. CH- 1 TO 16 BOOK INSIDE TWO MARKS QUESTION & ANSWERS 57
PART – III (THREE MARKS)
i.N
9. ch-1 to 16 Book back & PUBLIC three marks question with answers 68
10. ch-1 to 16 BOOK INSIDE Three MARKS QUESTION & ANSWERS 83
PART – Iv (five MARKS)
la
11. ch-1 to 16 Book back & PUBLIC five mark question with answers 90
12. ch-1 to 16 BOOK INSIDE five MARKS QUESTION & ANSWERS 123
PART – v (important programs)
sa
13. CH- 1 TO 16 BOOK INSIDE IMPORTANT PROGRAMS 139
14. Public examination 2 & 3 mark COMPULSORY QUESTIONS WITH answers 151
15. Ch-1 t0 16 IMPORTANT SYNTAX / PROGRAMS / EXAMPLES 153
da
et
8. Which of the following carries out the instructions defined in the interface?
(A) O.S (B) Compiler (C) Implementation (D) Interpreter
9. The functions which will give exact result when same arguments are passed are called – [M-2020]
i.N
(A) Impure (B) Partial (C) Dynamic (D) Pure
10. The functions which cause side effects to the arguments passed are called --------
(A) Impure (B) Partial (C) Dynamic (D) Pure
1. ........... are the basic building blocks of computer programs. [S-2020]
(A) Subroutines (B) Variables (C) Classes (D) Arrays
la
(CHAPTER-2)(DATA ABSTRACTION)
1. Which of the following functions that build the abstract data type? [S-2020,2021 & J-2023]
sa
(A) Constructors (B) Destructors (C) recursive (D) Nested
2. Which of the following functions that retrieve information from the data type? [M-2022]
(A) Constructors (B) Selectors (C) recursive (D) Nested
3. The data structure which is a mutable ordered sequence of elements is called
da
10. Which of the following is constructed by placing expressions within square brackets?
(A) Tuples (B) Lists (C) Classes (D) quadrats
(CHAPTER-3)(SCOPING)
1. Which of the following refers to the visibility of variables in one part of a program to another part of the same program.
(A) Scope (B) Memory (C) Address (D) Accessibility
2. The process of binding a variable name with an object is called---- [S-2020,2021]
(A) Scope (B) Mapping (C) late binding (D) early binding
3. Which of the following is used in programming languages to map the variable and object?
(A) :: (B) := (C) = (D) ==
4. Containers for mapping names of variables to objects is called --------- [M-2022, J-2023]
(A) Scope (B) Mapping (C) Binding (D) Namespaces
5. Which scope refers to variables defined in current function? [J-2022]
(A) Local (B) Global scope (C) Module scope (D) Function Scope
1
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
(CHAPTER-4)(ALGORITHMIC STRATEGIES)
1. The word comes from the name of a Persian mathematician Abu Jaffa Mohammed ibn-i Musa al Khwarizmi is called?
(A) Flowchart (B) Flow (C) Algorithm (D) Syntax. [S-2021, M-2022]
2. From the following sorting algorithms which algorithm needs the minimum number of swaps?
(A) Bubble (B) Insert (C) Selection (D) All the above
3. Two main measures for the efficiency of an algorithm are----------- [M-2020,J-2023]
et
(A) Processor (B) Complexity and capacity C) Time and space (D) Data and space
4. The algorithm that yields expected output for a valid input in called as-------
(A) Algorithmic solution (B) Algorithmic outcomes (C) Algorithmic problem (D) Algorithmic coding
5. Which of the following is used to describe the worst case an algorithm? [M-2024]
i.N
(A) Big A (B) Big S (C) Big W (D) Big O
6. Big Ω the reverse of
(A) Big O (B) Big Θ (C) Big A (D) Big S
7. Binary search is also called as ---
la
(A) Linear (B) Sequential (C) Random (D) Half-Interval
8. The Θ notation in asymptotic evaluation represents
(A) Base case (B) Average case (C) Worst case (D) NULL case
9. If a problem can be broken into sub problems which are reused several times, the problem possesses which property?
sa
(A) Overlapping sub problems (B) Optimal substructure (C) Memorization (D) Greedy
10. In dynamic programming, the technique of storing the previously calculated values is called— [M-2023, J-2024]
(A) Saving value property (B) Storing value property (C) Memorization (D) Mapping
1. ---not a factor measure the execution time of an algorithm? [S-2020]
da
(A) Speed of the machine (B) O.S (C) Programming language used (D) Selection
2
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
(CHAPTER-6)(CONTROL STRUCTURES)
1. How many important control structures are there in Python? [M-2023]
(A) 3 (B) 4 (C) 5 (D) 6
2. elif can be considered to be abbreviation of ----- [M-2022, J-2023]
(A) nested if (B) if..else (C) else if (D) if..elif
3. What plays a vital role in Python programming? [S-2021]
(A) Statements (B) Control (C) Structure (D) Indentation
4. Which statement is generally used as a placeholder? [J-2024]
(A) continue (B) break (C) pass D) goto
5. The condition in the if statement should be in the form of
(A) Arithmetic or Relational expression (B) Arithmetic or Logical expression
(C) Relational or Logical expression (D) Arithmetic
6. Which of the following is known as definite loop?
(A) do..while (B) while (C) for (D) if..elif
7. What is the output of the following snippet? i=1 while True: if i%3 ==0: break print(i,end='') i +=1
(A) 1 2 (B) 123 (C) 1234 (D) 124
8. What is the output of the following snippet? T=1 while T: print(True) break
et
(A) False (B) True (C) 0 (D) no output
9. Which amongst this is not a jump statement?
(A) for (B) goto (C) continue (D) break
i.N
10. Which punctuation should be used in the blank? if <condition>_ statements-block 1 else: statements-block 2
(A) ; (B) : (C) :: (D) !
1. What is the output of the following snippet? For i in range (2,10,2): Print ( i ,end = ‘ ‘) [M-2020]
(A) 8 6 4 2 (B) 2 4 6 8 10 (C) 2 4 6 8 (D) 2 4
2. Which is the most comfortable loop? [J-2022]
la
(A) do..while (B) while (C) for (D) if..elif
3. --- is used to skip the remaining part of the loop and start with next iteration? [S-2020]
(A) break (B) pass (C) continue (D) null
4. What is the output of the following snippet? for x in range (5): if x==2: continue print(x,end=’’) (M-2024)
sa
(A) 0 1 3 4 (B) 0 1 2 (C) 0 1 2 3 4 (D) 0 1 2 3
(CHAPTER-7)(PYTHON FUNCTIONS)
da
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---- [M-2023]
(A) Built-in (B) Recursion (C) Lambda (D) return
3. Which function is called anonymous un-named function------- [M-2022, J-2023, J-2024]
Pa
3
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
(A) %e (B) %E (C) %g (D) %n
9. Which of the following is used as placeholders or replacement fields which get replaced along with format ( ) function?
(A) { } (B) < > (C) ++ (D) ^^ [J-2023]
i.N
10. The subscript of a string may be:
(A) Positive (B) Negative (C) Both (a) and (b) (D) Either (a) or (b)
1. What will be the output of the following code? str = “NEW DELHI” str 3 = “_” [M-2020]
(A)NEW-DELHI.. (B) NE-DELHI (C) NEW DELHI (D) Type error
2. In python, which operator is used to display a sting multiple number of times? [S-2020]
la
(A) *(Multiplication) (B) + (Addition) (C) – (Subtraction) (D) / (Division
3. Which of the following function is used to count the number of elements in a list?
(A) count() (B) find() (C) len() (D) index()
4. If List=[10,20,30,40,50] then List[2]=35 will result [M-2024]
(A) [35,10,20,30,40] (B) [10,0,40,50,35] (C) [10,20,35,40,50] (D) [10,35,30,40,50]
5. If List=[17,23,41,10] then List. append(32) will result --- [M-2022]
Pa
4
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
(A) __num (B) ##num (C) $$num (D) &&num
10. The process of creating an object is called as------ [S-2021, J-2023, M-2024]
(A) Constructor (B) Destructor (C) Initialize (D) Instantiation
i.N
(CHAPTER-11)(DATABASE CONCEPTS)
1. What is the acronym of DBMS? [S-2021]
(A) Data Base Management Symbol (B) Database Managing System
(C) Data Base Management System (D) Data Basic Management System
la
2. A table is known as ---- [J-2022, J-2023]
(A) tuple (B) attribute (C) relation (D) entity
3. Which database model represents parent-child relationship? (M-2023]
sa
(A) Relational (B) Network (C) Hierarchical (D) Object
4. Relational database model was first proposed by--- [S-2020]
(A) E F Codd (B) E E Codd (C) E F Cadd (D) E F Codder
5. What type of relationship does hierarchical model represents? [J-2024]
da
1. Which commands provide definitions for creating table structure, deleting relations, and modifying relation schemas?
(A) DDL (B) DML (C) DCL (D) DQL
2. Which command lets to change the structure of the table?
(B) SELECT (B) ORDER BY (C) MODIFY (D) ALTER
3. The command to delete a table is ----- [M-2020, J-2022]
(A) DROP (B) DELETE (C) DELETE ALL (D) ALTER TABLE
4. Queries can be generated using --- [J-2024]
(A) SELECT (B) ORDER BY (C) MODIFY (D) ALTER
5. The clause used to sort data in a database [S-2021, M-2022, J-2023, M-2024]
(A) SORT BY (B) ORDER BY (C) GROUP BY (D) SELECT
1. ------command is used to remove a table from the database [M-2023]
(A) DELETE ALL (B) DROP TABLE (C) ALTER TABLE (D) DELETE
2. Which is Data Control language command in SQL? [S-2020]
(A) Alter (B) Grand (C) Truncate (D) Commit
5
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
(A) chennai,mylapore (B) mumbai,andheri
(C) chennai (D) chennai,mylapore
mumba mumbai,andheri
i.N
8. Which of the following creates an object which maps data to a dictionary?
(A) listreader() (B) reader() (C) tuplereader() (D) DicReader ( )
9. Making some changes in the data of the existing file or adding more data is=
(A)Editing (B) Appending (C) Modification (D) Alteration
10. What will be written inside the file test.csv using the following program
la
import csv D = [['Exam'],['Quarterly'],['Halfyearly']] csv.register_dialect('M',lineterminator = '\n')
with open('c:\pyprg\ch13\line2.csv', 'w') as f: wr = csv.writer(f,dialect='M') wr.writerows(D) f.close()
(A) Exam Quarterly Halfyearly (B) Exam Quarterly Halfyearly
sa
(C) E QH (D) Exam,
Quarterly,
Halfyearly
1. The module which allows interface with the windows operating system is: [S-2021, J-2023]
(A) csv module (B) OS module (C) getopt module (D) sys module
da
et
7. The function that returns the largest value of the selected column is – [J-2022, M-2023]
(A) MAX( ) (B) LARGE( ) (C) HIGH( ) (D) MAXIMUM()
8. Which of the following is called the master table?
i.N
(A) sqlite_master (B) sql_master (C) main_master (D) master_main
9. The most commonly used statement in SQL is----- [J-2023, M-2024]
(A) cursor (B) select (C) execute (D) commit
10. Which of the following keyword avoid the duplicate? [J-2024]
(A) Distinct (B) Remove (C) Where (D) Group By
la
1. Which SQL function returns the number of rows in a table? (S-2020)
(A) SUM() (B) MAX() (C) CHECK() (D) COUNT
(CHAPTER-16) (DATA VISUALIZATION USING PYPLOT: LINE, PIE AND BAR CHAT)
sa
1. Which is a python package used for 2D graphics?
(A) matplotlib.pyplot (B) matplotlib.pip (C) matplotlib.numpy (D) matplotlib.plt
2. Identify the package manager for Python packages, or modules.
(A) Matplotlib (B) PIP (C) plt.show() (D) python package
da
3. Which of the following feature is used to represent data and information graphically?
(A) Data List (B) Data Tuple (C) Classes Objects (D) Data Visualization
4. --- is a collection of resources assembled to create a single unified visual display. (M-2024)
(A) Interface (B) Dashboard (C) Objects (D) Graphics
5. Which of the following module should be imported to visualize data and information in python? [J-2024]
Pa
7
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
9. Read the statements given below. Identify the right option from the following for pie chart.
Statement A: To make a pie chart with Matplotlib, we can use the plt.pie() function.
Statement B: The autopct parameter allows us to display the percentage value using the python string formatting.
(A) Statement A is correct (B) Statement B is correct
(C) Both the statements are correct (D) Both the statements are wrong
1. Using Matplotlib from within a python script, which method inside the file will display your plot? [S-2021]
(A) plot() (B) disp () (C) clear () (D) show ()
et
(A) Subroutines (B) Expression (C) Statement (D) Algorithm
5. ------ function remove the redundant extra calls.
(A) pure (B) impure (C) friend (D) none
i.N
6. In object oriented programming ------ are the interface.
(A) function (B) classes (C) structures (D) pointer
7. ----- are expressed using statements of a programming language.
(A) function (B) subroutine (C) algorithm (D) structure
8. The most important criteria in writing and evaluating algorithm is
la
(a) Number of lines (b) Number of blocks (c)Time to complete a task d) Storage capacity
9. Which of the following are the building blocks of computer programs?
(a) Function (b) Definitions (c) Parameters (d) Subroutines
sa
10. Which of the following are small section of code that are used to perform particular task repeatedly?
(a) Function (b) Definitions (c) Subroutines (d) Programs
11. In programming languages, subroutines are also called as
(a) Functions (b) Definitions (c) Parameters (d) Subroutines
da
12. Which of the following is a unit of code that is often defined within a greater code structure?
(a) Function (b) Definitions (c) Parameters (d) Subroutines
13. a:=(24) is a
(a) Initialization (b) Declaration (c) Function definition (d) Assignment
14. Which of the following is a distinct syntactic block?
Pa
26. Which of the following defines an object’s visibility to the outside world?
a) Interface b) Implementation c) Both a and b d) Function
27. In OOP’s classes are
a) Interface b) Implementation c) Both a and b d) Function
28. In OOP’s, how the object is processed and executed is
a) Interface b) Implementation c) Both a and b d) Function
29. The functions which will give exact result when the same arguments are passed is called ---------
a) User defined b) Pure functions c) Impure functions d) Assigned functions
30. sin(0) is a function, which is example for
a) User defined b) Pure functions c) Impure functions d) Assigned functions
31. The variables used inside the function may cause side effects through the functions which are not passed with any arguments are called
a) User defined b) Pure functions c) Impure functions d) Assigned functions
32. Which of the following do not have any side effects?
a) User defined b) Pure functions c) Impure functions d) Assigned functions
33. Which of the following are expressed using statements of a programming language?
a) Specifications b) Pseudo Code c) Algorithms d) Flowchart
34. Which of the following carries out the instructions defined in the interface?
et
a) Function b) Implementation c) Interface d) Object
35. The following function is an example for let rec sum x y: Return x + y
a) User defined b) Recursive function c) Normal function d) Assigned function
36. The algorithm can be depicted as
i.N
a) Specifications b) Pseudo Code c) Algorithm d) Flowchart
37. The function definition is introduced by the keyword
a) def b) let c) rec d) requires
38. ……………………… are the basic building blocks of computer programs.
la
a) Code b) Subroutines c) Modules d) Variables
39. In programming languages, subroutines are called as …………………………..
a) Functions b) Task c) Modules d) Code
40. All functions are ………………. definitions.
sa
a) datatype b) dynamic c) return d) static
41. ……………………… binds values to names.
a) Algorithms b) Variables c) Interface d) Definitions
42. Random() is an example of ……………… function.
da
9
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
56. Which function definition, doesn’t modify the arguments passed to them?
(a) Pure function (b) Impure function (c) Object (d) Interface
57. How many parameters are defined in the function let rec gcd a b : =
(a) 0 (b) 1 (c) 2 (d) 3
58. In the function definition, the keyword let is followed by …………………………
(a) Function name (b) Arguments (c) Parameters (d) Implementations
59. If a function is not a recursive one, then ……………………………. is used
(a) abc (b) gcd (c) let (d) let rec
60. Find the name of the function, let rec even x : =
(a) Let (b) Rec (c) Even (d) x
61. Match the following function definitions with their terms. let rec odd xy : =
Keyword – (i) Xy Recursion – (ii) Odd Function name – (iii) Rec Parameters – (iv) let
(a) 1 – (iv) 2 – (iii) 3 – (ii) 4 – (i) (b) 1 – (i) 2 – (ii) 3 – (iii) 4 – (iv)
(c) 1 – (iv) 2 – (i) 3 – (ii) 4 – (iii) (d) 1 – (i) 2 – (iv) 3 – (ii) 4 – (iii)
62. In an object-oriented programming language, and is a description of all functions that a class must have
(a) Object (b) Class (c) Interface (d) Code
63. The ……………………… defines an object’s visibility to the outside world.
et
(a) Object (b) Interface (c) Pure function (d) Impure function
(CHAPTER-2)(DATA ABSTRACTION)
i.N
1. Expansion of ADT.
(A) Abstract data tuple (B) All data template
(C) Abstract data type (D) Application data type
2. ADT can be implemented using …..
(A) Singly linked list (B) doubly linked list
la
(C) either A or B (D) neither A or B
3. The process of providing only the essentials and hiding the details is known as-----
(A) Hiding (B) Abstraction (C) Providing (D) Calling
sa
4. := is called ------
(A) Equal (B) colon operator (C) assigned as (D) Same
5. What allows data abstraction is that we can give a name to a set of memory cells?
(a) Tuple (b) Set (c) Dictionary (d) List
6. The Splitting of the program into many modules are called as ……………………………
da
13. Which of the following function that facilitates the data abstraction?
a) Constructors b) Destructors c) Selectors d) a and c
14. nums [0] represent that you are accessing ………………………….. element.
(a) 0 (b) 1 (c) 2 (d) 3
15. nums [1] indicate that we are accessing ………………………….. element.
(a) 0 (b) 1 (c) 2 (d) many
16. Which provides modularity?
a) Data types b) Subroutines c) Abstraction d) Classes
(CHAPTER-3)(SCOPING)
1. A variable which is declared inside a function which contains another function definition
(A) Local (B) Global (C) Enclosed (D) Build-in
2. Which are loaded as soon as the library files are imported to the program?
(A) Build-in (B) Enclosed (C) Global (D) Local
3. Which of the following is not the example of modules?
(A) Procedures (B) Subroutines (C) Class (D) functions
10
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
4. The Kind of scope of the variable ‘a’ used in the pseudo code given below Disp(): a:=7 Print a Disp()
(A) Local (B) Global (C) Enclosed (D) Build-in
5. Which scope has the higher priority?
(A) local (B) enclosed (C) global (D) built in
6. Which scope is widest scope?
(A) local (B) enclosed (C) global (D) built in
7. ------ programming debug pieces of the program independently.
(A) low level (B) high level (C) modular (D) basic
8. What is fundamental concept in access control?
(A) Minimizes risk to object (B) easy access to object
(C) User friendly (D) None
9. The duration for which a variable is alive is called its ……………..
(a) End time (b) Scope time (c) Lifetime (d) Visible time
10. Write the output (value stored in b) 1. a: = 5 2. b: = a
(a) 0 (b) 3 (c) 5 (d) 2
11. A Function always the first lookup for a variable name in its …………. scope
et
(a) Enclosed (b) Local (c) Global (d) Built-in
12. The ………………. of a variable is that part of the code where it is visible.
(a) Scope (b) data (c) List (d) Tuple
13. …………. can be separately compiled and stored in a library
i.N
(a) Characteristics (b) Modules (c) Syntax (d) None of these
14. …………… also defines the order in which variables have to be mapped to the object in order to obtain the value.
(a) Scope (b) Local (c) Event (d) Object
15. The ……… rule is used to decide the order in which the scopes are to be searched for scope resolution.
la
(a) List (b) Tuple (c) Class (d) LEGB
16. The part of a program that can see or use the variables are called
(a) Parameter (b) Scope (c) Function (d) Indentation
17. A function will first lookup for a variable name in its ………………… scope.
sa
(a) Local (b) Enclosed (c) Global (d) Built-in
18. Which of the following keeps track of all these mappings with namespaces?
(a) Application software (b) Programming languages (c) System software (d) MySQL
19. A …………………………… variable can be accessed inside or outside of all the functions in a program.
da
26. The arrangement of private instance variables and public methods ensure- the principle of
a) Inheritance b) Polymorphism c) Abstraction d) Encapsulation
27. Identify which is not a variable scope.
(a) Module (b) Built – in (c) Enclosed (d) Pointer
28. A single …………………………… can contain one or several statements closely related to each other.
(a) Module (b) Local (c) Global (d) Enclosed
29. A …………………………… is a part of a program.
(a) Code (b) Module (c) Flowchart (d) System software
30. Scope refers to the visibility of …………….
a) Variables b) Parameters c) All of these d) Functions
31. Find the wrong statement from the following
(a) Modules contains data and instructions (b) Modules can be included in a program
(c) Modules cannot have processing logic (d) Modules can be separately combined
32. Which is true about modular programming?
(a) Single procedure can be reused (b) Single procedure cannot be reused
11
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
33. The arrangement of private instance variables and public methods ensures the principle of ………
(a) Security (b) Data encapsulation (c) Inheritance (d) Class
34. All members in a python class are by …………………………… default.
(a) Private (b) Public (c) Protected (d) Local
35. The members in C ++ and Java, by default, are ………………
(a) Private (b) Public (c) Protected (d) Local
(CHAPTER-4)(ALGORITHMIC STRATEGIES)
1. ---not a factor measure the execution time of an algorithm?
(A) Speed (B) O.S (C) Programming (D) Selection
2. Which of the following is a finite set of instructions to accomplish a particular task?
(A) Flow char (B) Flow (C) Algorithm (D) Syntax
3. Step by step procedure for solving a given problem:
(A) Program (B) Pseudo code (C) flow chart (D) Algorithm
4. Which of the following is not a characteristic of an algorithm?
(A) Input (B) Program (C) Finiteness (D) Simplicity
5. This is a theoretical performance analysis of an algorithm.
et
(A) Priori estimates (B) Posteriori (C) Space factor (D) Time factor
6. Which of the following algorithmic approach is similar to divide and conquer approach?
(A) Insertion (B) Dynamic (C) Selection (D) Bubble
i.N
7. What is another name for Binary search?
(A) Linear (B) Half interval (C) Decimal (D) Boolean
8. Which is measured by counting the number of key operation?
(A) time (B) space (C) fixed time (D) variable part
9. Space is measured by the ----memory space required by the algorithm.
la
(A) zero (B)minimum (C) average (D) maximum
11. The complexity of linear search algorithm is
(A) O(n) (B) O(log n) (C) O(n2) (D) O(n log n)
sa
12. From the following sorting algorithms which has the lowest worst case complexity?
(A) Bubble sort (B) Quick sort (C) Merge sort (D) Selection sort
13. Which of the following is not a stable sorting algorithm?
(A) Insertion sort (B) Selection sort (C) Bubble sort (D) Merge sort
14. Time complexity of bubble sort in best case is
da
(a) Solve a problem (b) Insert a data (c) Delete data (d) Update data
17. Binary search also called
a) Half-interval search b) Sequential search c) Unordered search d) Full-interval search
18. An algorithm that yields expected output for a valid input is called as ……………………………
(a) algorithm (b) Algorithmic solutions (c) Binary search (d) half interval
w.
19. The program should be written for the selected language with specific ……………………………
(a) Input (b) Output (c) Syntax (d) Algorithm
20. ………… is an expression of the algorithm in a programming language.
(a) Program (b) Algorithm (c) Syntax (d) Input
ww
12
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
27. Which of the following component is defined as the total space required by variables, which sizes depends on the
problem and its iteration?
a) Time part b) Variable part c) Fixed part d) Memory part
28. How many asymptotic notations are used to represent the time complexity of algorithms?
(a) 1 (b) 2 (c) 3 (d) 4
29. Which of the following is not a factor used to measure the time efficiency of an algorithm?
a) Speed of the machine b) Operating system c) Programming language d) Designing an algorithm
30. ………………………… is the reverse of Big O.
(a) Big Ω (b) Big Θ (c) Big C (d) Big ⊗
31. ………………………… describes the worst case of an algorithm.
(a) Big Q (b) Big Θ (c) Big O (d) Big C
32. …………………….. Describe the lower bound of an algorithm.
(a) Big Ω (b) Big Θ (c) Big O (d) Big ⊗
33. Which search technique is also called sequential search techniques?
(a) Binary (b) Binary Tree (c) Hash (d) Linear
34. What value will be returned by the linear search technique if the value is not found?
(a) 0 (b) 1 (c) -1 (d) +1
et
35. Which search algorithm is called a Half-Interval search algorithm?
(a) Binary (b) Binary Tree (c) Hash (d) Linear
36. Which technique is followed by the Binary Search algorithm?
(a) Subroutines (b) Mapping (c) Divide and conquer (d) Namespaces
i.N
37. In Binary Search, if the search element is …………………….. to the middle element of the array, then the index
of the middle element is returned.
(a) > (b) < (c) = (d) < >
38. In Binary search, if the search element is greater than the number in the middle index, then select the elements to
la
the side of the middle index.
(a) Right (b) Left (c) Middle (d) Bottom
39. ……………………… is a simple sorting algorithm.
(a) Binary (b) Bubble (c) Selection (d) Insertion
sa
40. Which one of the following is not a characteristic of Bubble Sort?
(a) Simple (b) Too slow (c) Too fast (d) Less efficient
41. In selection sort, there will be ……………………….. exchange for every pass through the list.
(a) 0 (b) 1 (c) 2 (d) 3
da
42. How many passes are used in the Insertion Sort to get the final sorted list?
(a) 0 (b) 1 (c) n (d) n -1
43. ………………………….. approach is similar to divide and conquer.
(a) Dynamic programming (b) Modular (c) Procedural (d) Divide and Conquer
Pa
(c) 1 – (iv), 2 – (iii), 3 – (ii), 4 – (i) (d) 1 – (iv), 2 – (ii), 3 – (i), 4 – (iii)
46. Time complexity of bubble sort in worst case is …………………………..
(a) θ(n) (b) θ(n log n) (c) θ(n2) (d) θ(n(log n)2)
47. The complexity of Merge Sort is …………………………
ww
(a) θ(n) (b) o(n log n) (c) θ(n2) (d) θ(n(log n)2)
et
(A) mutable (B) immutable (C) both (D) none
17. Python got its name from ……………………………
(a) Monthly Python’s Flying Square (b) Monthly Python’s Flying Circus
(c) Monty Python’s Flying Circus (d) Monty Python’s Flying Square
i.N
18. In Python, the script mode programs can be stored with the extension.
a) .pyt b) .py c) .pyh d) .pon
19. How many modes of programming are there in python?
(a) 2 (b) 3 (c) 4 (d) 5
la
20. A sequence of elementary lexical components of Python statement is known as
a) Tokens b) Keywords c) Delimiters d) Literals
21. …………………………… mode is used to create and edit Python source file.
sa
(a) Line (b) Script (c) Interactive (d) Interface
22. Which mode can be used as a simple calculator?
(a) Line (b) Script (c) Interactive (d) Interface
23. The ………….. command is used to open the Python shell window.
a) File → File New b) File→ New c) File → File Open d) File → New File
da
(c) Scripts are not reusable, not editable (d) Scripts are both reusable and editable
26. In Python, ………..is a simple assignment operator
a) = b) = c) == d) #
27. What is the default name for a blank script text editor?
(a) Untitled (b) Untitled 1 (c) Document 1 (d) Editor 1
w.
14
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
(a) 2 (b) 3 (c) 4 (d) 5
45. Match the following
1. // – (i) Modulus 2. # – (ii) Floor division 3. % – (iii) Strings 4. ||| ||| – (iv) Comments
(a) 1 – (ii), 2 – (iv), 3 – (i), 4 – (iii) (b) 1 – (i), 2 – (ii), 3 – (iii), 4 – (iv)
i.N
(c) 1 – (iv), 2 – (ii), 3 – (i), 4 – (iii) (d) 1 – (iv), 2 – (i), 3 – (iii), 4 – (ii
46. ……………………… are special words used by Python Interpreter
(a) Intentifier (b) Keywords (c) Operator (d) Literals
47. The value of an operator used is ……………………………
(a) 0 (b) 1 (c) Operands (d) NULL
la
48. Which operator checks the relationship between two operands?
(a) Relational (b) Comparative
49. Identify Not equal to the operator in python?
(c) Both (d) None of the these
sa
(a) < > (b) == (c) NOT EQUAL (d) ! =
50. How many logical operators are there?
(a) 2 (b) 3 (c) 4 (d) 5
51. How many comparative operators are there?
da
15
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
(CHAPTER-6)(CONTROL STRUCTURES)
1. What is the output of the following snippet? For i in range (2,10,2): Print ( i ,end = ‘ ‘)
(A) 8 6 4 2 (B) 2 4 6 8 10 (C) 2 4 6 8 (D) 2 4 6
2. Which is the most comfortable loop?
(A) do..while (B) while (C) for (D) if..elif
et
3. --- is used to skip the remaining part of the loop and start with next iteration?
(A) break (B) pass (C) continue (D) null
4. In Python, for loop uses the --- function in the sequences to specify the initial, final and increment /decrement values.
i.N
(A) range () (B) input () (C) Stop (D) Print ()
5. In python programming – statement is a null statement and it is used as a place holder.
(A) break (B) continue (C) Pass (D) None
6. What will be the output of the following python code? For i in range (1,10,2): Print ( i ,end = ‘ ‘)
(A) 1 3 5 7 9 (B) 1 2 4 6 8 (C) 2 4 6 8 10 (D) 1 3 5 7 10
la
7. What will be the output of the following python snippet? A=5 While (a<=20): Print (a%a, end= ‘ ‘) i=i+1
(A) 15 16 17 18 19 20 (B) 20 19 18 17 16 15 (C) 0 0 0 0 0 0 (D) 1 1 1 1 1 1
8. Match the following :
(A) If..elif – (i) jump (B) While – (ii) block (C) Pass - (iii) Loop (D) indentation – (iv) Branching
sa
(A) (a)- (iv), (b)- (iii), (c)- (i), (d)- (ii) (B) (a)- (i), (b)- (iii), (c)- (iv), (d)- (ii)
(C) (a)- (iv), (b)- (i), (c)- (iii), (d)- (ii) (D) (a)- (i), (b)- (iv), (c)- (ii), (d)- (iii)
9. The optional parameter of range ( ) function in Python
(A) Start (B) stop (C) Step (D) slice
da
16
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
23. A ……… is composed of a sequence of statements which are executed one after the another.
a) alternative (b) Sequential (c) Function (d) Statement
24. The statement in python used to transfer the control from one part of the program to another unconditionally is
a) Jump b) loop c) alternative d) iterative
25. ……………………… is the simplest of all decision making statements.
(a) Simple if (b) if..else (c) else if (d) Switch
26. …………….. statement provides control to check the true block as well as the false block.
(a) Simple if (b) if..else (c) else if (d) Switch
27. In for loop of Python, the ………….. refers to the initial, final, and increment value.
a) else b) sequence c) range d) b or c
28. How many types of looping constructs are there?
(a) 1 (b) 2 (c) 3 (d) 4
29. The ……………….. part of while is optional.
a) else b) sequence c) range d) b or c
30. Control of the program flows to the statements immediately after the body of the loop by using statements.
a) continue b) pass c) break d) go to
31. Which one of the following is the entry check loop type?
et
(a) While (b) Do while (c) If (d) If…else
32. How many parameters are there in the print function?
(a) 2 (b) 3 (c) 4 (d) 5
33. Escape sequences can be given using ………………. parameter in print ( ) function.
i.N
(a) Ret (b) Let (c) End (d) Sep
34. Which parameter is used to specify any special characters?
(a) Ret (b) Let (c) End (d) Sep
35. If the condition is checked at the beginning of the loop, then it is called as ……………… loop.
la
(a) Exit (b) Exit check (c) Entry check (d) Multiple
36. Range ( ) generates a list of values starting from start till ………………….
(a) Start 1 (b) Start -1 (c) Stop -1 (d) End
37. Which is the optional part in the range( ) function?
sa
(a) Start (b) Stop (c) Step (d) Incr
38. The end value of the range (30, 3, -3) is ………………………..
(a) 30 (b) -3 (c) 3 (d) 6
39. Range(20) has the range value from …………….. to ………
da
46. If a loop is left by ……………… then the else part is not executed.
(a) break (b) for (c) continue (d) pass.
47. ……….. statement forces the next iteration to takes place.
(a) Break (b) For (c) Continue (d) Pass
48. …………………. is the null statement.
(a) Break (b) For (c) Continue (d) Pass
49. Python …………….. will throw an error for all indentation errors.
(a) Break (b) For (c) Continue (d) Interpreter
(CHAPTER-7)(PYTHON FUNCTIONS)
1. Evaluate the following function and write the output.X=14.4 Print (math .floor(X))
(A)13 (B) 14 (C) 15 (D) 14.3
2. How many spaces are there in per indentation in the python?
(A) 4 (B) 3 (C) 6 (D) 8
3. A variable, with --- scope can be used anywhere in the program.
(A) Local (B) Global (C) Default (D) Required
17
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
4. The –Statement causes your function to exit and returns a value to its caller.
(A) for (B) def (C) return (D) define
5. Which function is called anonymous function?
(A) Lambda (B) Recursion (C) Function (D) define
6. Which of the following special character is used to define variable length arguments?
(A) & (B) $ (C) * (D) #
7. Which keyword to be used to define a function in Python?
(A) def (B) local (C) rec (D) global
8. Non-keyword variable arguments are called as
(A) Sets (B) List (C) Tuples (D) Dictionary
9. What will be the output of the following Python snippet? c=5 def add(): c=c+5 print(c) add()
(A) 5 (B) 10 (C) 15 (D) Error
10. Which of the following is not an argument type?
(A) Required (B) Default (C) Keyword (D) Fixed length
11. The bin() function returns a binary string prefixed with---
(A) 0 (B) 1 (C) 0b (D) 1b
12. What is the output of the following program--- c = 1 def add(): print(c) add()
et
(A) 1 (B) 0 (C) none (D) C
13. What is the output of the function Print (Chr(66))?
(A) A (B) C (C) b (D) B
14. Evaluate the following function and write the output. x = –37.9 print(math.cell(x))
i.N
(A) –38 (B) –39 (C) –36 (D) –37
15. How many methods are there to pass variable length arguments?
(A) 2 (B) 3 (C) 4 (D) 5
16. The condition that is applied in any recursive function is known as ------
la
(A) condition (B) composition (C) base condition (D) find condition
17. When more than one arguments has to pass than have already specified which type of argument is used?
(A) required (B) keyword (C) variable length (D) default
sa
18. The ------ arguments are also local to functions
(A) formal (B) actual (C) required (D) keyword
19. Which provide better modularity for application?
(A) structure (B) function (C) statement (D) none
20. Which of the following avoids repetition and makes high degree of code reusing?
da
18
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
(a) Input (b) Valuate (c) Eval (d) Val
43. Find true statement
(a) Recursive function call itself (b) Recursive function have to be called externally
i.N
(CHAPTER-8)(STRINGS AND STRING MANIPULATION)
1. What will be the output of the following code? str = “NEW DELHI” str 3 = “_”
(A)NEW-DELHI (B) NE-DELHI (C) NEW DELHI (D) Type error
2. Which command can be used to remove entire string variable in Python?
la
(A) rem (B) remove (C) del (D) delete
3. In python, which operator is used to display a sting multiple number of times?
(A) * (Multiplication) (B) + (Addition) (C) – (Subtraction) (D) / (Division)
sa
4. ----- character is used to define a string.
(A) Single quotes (B) Double (C) Triple (D) All of these
5. What will be output of the following code? Str1=”SCHOOL” Print(str1.replace(“O”,”U”))
(A) SCHOOL (B) SCHUUL (C) SCHL (D) SCHOOUUL
6. What will be output of the following code? Str1=”hello” Print(str1.replace(“e”,”a”))
da
13. Strings which contains double quotes should be defined with ………….. quotes
(a) Single (b) Double (c) Triple (d) All the these
14. Which of the following allows the creation of multiline strings
a) ‘ ‘ b) ” ” c) “”” “”” d) None of these
15. In strings, the negative index assigned from the last character to the first character in reverse order begins with
(a) 0 (b) 1 (c) -1 (d) -2
16. How will you modify the string?
(a) A new string value can be assigned to the existing string variable
(b) Updating the string character by character
17. The positive subscript always starts with
a) 0 b) 1 c) -1 d) 0.1
18. Which command is used to remove the entire string variable?
(a) Remove (b) Del (c) Delete (d) Strike
19. The joining of two or more strings is called…………………………..
(a) Append (b) Repeating (c) Concatenation (d) Strike
19
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
(a) Third character (b) the Third word (c) Full string (d) Reverse order
29. ……………. is the formatting character for signed decimal integer.
(a) %d or %i (b) %d and %i (c) %d %u (d) %i &u
30. Find the wrong match
i.N
(a) Backslash – \b (b) Backslash – // (c) Carriage return – \r (d) Line feed – \n
31. Which function returns the length of the string?
(a) str len( ) (b) len(str) (c) length( ) (d) strlength( )
32. How many membership operators are there?
(a) 2 (b) 3 (c) 4 (d) 5
la
33. …………………. is the membership operator.
(a) is (b) at (c) to
34. ……………………. function is a powerful function used for formatting strings
(d) in
sa
(a) Format ( ) (b) String () (c) Slice () (d) Decimal
35. The ……. and…. operators can be used with strings to determine whether a string is present another string.
(a) And, or (b) In, Not in (c) Xnor, Xor (d) And, In
(CHAPTER-9)(LISTS, TUPLES, SETS AND DICTIONARY)
da
et
(A) [90,34,45,48] (B) [34,48,90,45] (C) [34,90,45,48] (D) [34,45,48,90]
24. What is the output of the snippet?>>>Mylist=[34,45,48 >>> Mylist.extend(71,32,29) >>> print(Mylist)
(A) [34,45,48,71,32,29] (B) [71,32,29,34,48,90,45] (C) [29,32,34,90,45,48,71] (D) [71,48,45,34,32,29]
25. What is the output of the snippet? >>>Mylist=[34,45,48] >>> Mylist.insert(2,90) >>> print(Mylist)
i.N
(A) [90,34,45,48] (B) [2,90,34,48,45] (C) [34,45,48,2,90] (D) [34,45,90,48]
26. Which is used to delete unknown elements?
(A) del( ) (B) remove( ) (C) erase ( ) (D) clear( )
27. Which function delete an elements using the index value?
(A) remove ( ) (B) pop ( ) (C) clear( ) (D) del statement
la
28. When clear( ) function is executed the screen displays----
(A) ( ) (B) 0 (C) [ ]
29. .------- creates a sequence of elements that satisfy a certain condition.
(D) { }
sa
(A) list (B) list comprehension (C) sets (D) dictionary
30. Tuples are enclosed within -----
(A) ( ) (B) < > (C) [ ] (D) { }
31. Creating a tuple with one element is called ----- tuple
da
(3) t=(23,56,89) – (iii) Nested list (4) lis=( ) – (iv) empty list
(a) 1-(iv), 2-(iii), 3-(i), 4-(ii) (b) 1-(i), 2-(ii), 3-(iii), 4-(iv)
(c) 1-(iv), 2-(ii), 3-(i), 4-(iii) (d) 1-(i), 2-(iii), 3-(iv), 4-(ii)
38. ……………………… is used to access an element in a list
(a) element (b) I (c) index (d) tuple
39. Sim = [‘S’, 2,3, [4,5,6]] is an example of
a) Tuple b) Set c) List d) Dictionary
40. ………………. are used to access all elements from a list.
(a) If (b) loop (c) array (d) tuple
41. Find the Output: marks = [10, 23, 41, 75] i = -1 while i >= – 4: print(marks[i]) i = i + – 1
(a) 1 2 3 4 (b) 10, 23, 41, 75 (c) 75, 41, 23, 10 (d) 0, 41, 23, 0
42. Which of the following operator can be used to alter the range of elements in the list?
a) = = b) :: c) = . d) :
43. In changing list elements, ………………. is the upper limit of this range.
(a) Index from (b) Index to (c) Index with (d) Index
21
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
44. If the range is specified as [1 : 5], it will update the elements from …………………………..
(a) 2 to 4 (b) 1 to 5 (c) 1 to 4 (d) 2 to 5
45. …………………….. function is used to add a single element to the list.
(a) append( ) (b) Extend () (c) Pop () (d) clear ()
46. Which function can also be used to delete an element using the given index value.
a) erase b) pop c) delete () d) push()
47. list = [34, 45, 48] list.extend([71, 32, 29]) results in ………………………….
(a) [35, 45, 48, 71, 32, 29] (b) [71,32,29,34,45,48] (c) [71,32,29] (d) [34.45,38]
48. ………………………… function is used to insert an element at any position of a list.
(a) Insert( ) (b) Extend () (c) Pop () (d) clear ()
49. Find the correct statement from the following
(a) when a new element is inserted into the list, the existing elements shift one position to the right
(b) when a new element is inserted in the list, the existing element shifts one position to the left.
50. How many ways of deleting the elements from a list are there?
(a) 1 (b) 2 (c) 3 (d) 4
51. The two ways of deleting elements from a list are ……….. and ……
(a) del and remove( ) (b) Pop and clear (c) Insert, Extend (d) Insert and delete
et
52. Which function is used to delete elements of a list if its index is unknown?
(a) del (b) delete (c) remove( ) (d) backspace
53. Which statement is used to delete known elements?
(a) del (b) delete (c) remove (d) rem
i.N
54. ………………… statement deletes the entire list.
(a) del (b) delete (c) remove (d) rem
55. …………………….. function deletes the element using the given index value.
(a) pop( ) (b) remove (c) clear (d) rem
56. ………………… function is used to generate a series of values in python
(a) range
la (b) series
57. The range( ) function has ……………. arguments.
(a) 1 (b) 2
(c) Fill series
(c) 3
(d) Auto fill
(d) 4
sa
58. Which is an optional argument in range( ) function ………..
(a) start value (b) end value (c) step value (d) default
59. The ……………………… function is used to create a list in python
(a) list( ) (b) Tuple () (c) Set () (d) dict ()
da
22
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
(a) + (b) – (c) . (d) &
82. Which operator is used to do a difference in the set?
(a) + (b) – (c) : (d) &
83. Which is the symmetric difference operator?
i.N
(a) + (b) – (c) ^ (d) &
84. ………………………. is used to separate the elements in the dictionary
(a) Comma (b) Semi colon (c) dot (d) dollor
85. The key-value pairs are enclosed with ……………………………
la
(a) <> (b) [ ] (c) { } (d) ( )
86. The mixed collection of elements are called………………………….
(a) list (b) tuples (c) sets (d) dictionary
87. Identify the correct statement.
sa
(a) The dictionary type stores an index along with its element
(b) The dictionary type stores a key along with its element
88. Which part is optional in dictionary comprehension?
(a) If (b) expression (c) var (d) sequences
da
89. Find the statement which is wrong. When you assign a value to the key
(a) it will be appended (b) it will overwrite the old data
90. Pick an odd one with including elements in the list.
(a) append( ) (b) extend( ) (c) insert( ) (d) include
Pa
91. Pick the odd one with deleting elements from a list.
(a) del (b) remove( ) (c) pop( ) (d) clear
(CHAPTER-10) (PYTHON CLASSES AND OBJECTS)
1. Class members are accessed through which operator?
(A) & (B) .(Dot) (C) # (D) %
w.
2. In Python the class method must have which named argument as first argument?
(A) self (B) rec (C) global (D) key
3. The function defined inside a class is called as ______.
(A) Attribute (B) Parameter (C) Arguments (D) Methods
ww
23
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
(d) constructor function cannot be defined
18. ………………….. is automatically executed when an object of a class is created.
a) constructor b) destructor c) class d) init
19. The variables which are defined inside the class is by default.
i.N
(a) private (b) public (c) protected (d) local
20. Which variables can be accessed anywhere in the program using dot operator?
(a) private (b) public (c) protected (d) auto
21. In Python, …………….. method is used as the destructor.
a) – – init – – () b) _des_ () c) _del_ () d) – – destructor – – ()
22. Match the following
la
1. constructor – (i) def process(self) 2. Destructor – (ii) S.x 3. method – (iii) _del_(self) 4. object – (iv) _init_(self, num)
(a) 1-(iv) 2-(iii) 3-(i) 4-(ii) (b) 1-(i) 2-(ii) 3-(iii) 4-(iv)
sa
(c) 1-(iv) 2-(ii) 3-(i) 4-(iii) (d) 1-(i) 2-(iii) 3-(iv) 4-(ii)
(CHAPTER-11)(DATABASE CONCEPTS)
1. A column in database table is known as an :
da
24
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
(a) 2 (b) 3 (c) 4 (d) 5
24. Which of the following in a table represents a field?
a) row b) column c) data d) files
25. Which database Model is the extended form of hierarchical data Model?
i.N
(a) Network (b) Relational (c) Flat File (d) Object
26. Match the following:
1. Relational – (i) classes 2. object model – (ii) Mainframe 3. ER model – (iii) key 4. Hierarchical – (iv) Entity
(a) 1-iii, 2-i, 3-iv, 4-ii (b) 1-i, 2-ii, 3-iii, 4-iv (c) 1-iv, 2-iii, 3-i, 4-ii (d) 1-iv, 2-ii, 3-i, 4-iii
27. …………. model is mainly used in IBM Main Frame computers.
la
a) ER model b) Hierarchical c) Network database d) Object model
28. …………………… uniquely identifies a particular tuple in a table
(a) Relation key (b) Attribute (c) Super key (d) Table
sa
29. Which model establishes many to many relationships?
(a) Network (b) Relational (c) Hierarchical (d) Object
30. …………………. is the one who manages the complete database management system.
a) Database Designer b) Database Administrator c) Database Architect d) Data Analyst
31. ER Model was developed in the year …………………….
da
(a) Database Administrators (b) Database admin (c) Database Accuracy (d) Database assignment
38. ………………….. is one who manages the complete database management system
(a) Manager (b) Engineer (c) DBA (d) Service Person
39. ……………………. are the ones who stores, retrieve, update and delete data.
(a) End-User (b) Admin (c) Data (d) Info
40. RDBMS means ………………………..
(a) Relational Database Manipulation System (b) Relational Database Management system
(c) Rapid DataBase Management Server
41. Pick the odd out.
(a) Oracle (b) Foxpro (c) MariaDB (d) SQLite
42. Find the true statement
(a) Data redundancy is exhibited by DBMS (b) Data redundancy is not present in DBMS
43. Find the false statement
(a) Distributed Databases supported by DBMS (b) Distributed Databases supported by RDBMS
25
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
52. …………………. is used to merge columns from two relations.
(a) σ (b) π (c) x (d) –
(CHAPTER-12) (STRUCTURED QUERY LANGUAGE)
i.N
1. ------command is used to remove a table from the database
(A) DELETE ALL (B) DROP TABLE (C) ALTER TABLE (D) DELETE
2. SQLite falls under which database
(A) Hierarchical database system (B) Flat Database system
(C) Object oriented database system (D) Relational Database system
la
3. Which is Data Control language command in SQL?
(A) Alter (B) Grand (C) Truncate (D) Commit
4. What symbol is used for SELECT statement?
(A) σ (B) Π (D) Ω
sa
(C) X
5. Pick odd one.
(A) Commit (B) Roll back (C) Save point (D) Revoke
6. Pick Odd one.
(A) INSERT (B) DELETE (C) UPDATE (D) TRANCATE
da
7. The TCL command used to restores the database to the last commit state.
(A) Commit (B) Save Point (C) Insert (D) Rollback
8. The statement in SQL is used to retrieve data from a table in a database.
(A) SELECT (B) CREATE (C) DISTINCT (D) ORDER BY
Pa
(C) a-i, b-iv, c-iii, d-ii (D) a-i, b-iii, c-iv, d-ii
11. Pick odd one.
(A) CREATE (B) UPDATE (C) ALTER (D) DROP
12. Which command saves any transaction in database permanently?
ww
(A) save (B) save point (C) commit (D) roll back
13. The original version of SQL is released in the year _____.
(A) 1970 (B) 1980 (C) 1986 (D) 1992
14. Which of the following is not a Relational operator?
(A) = (B) = = (C) > = (D) < =
15. SQL commands are divided into ------ categories.
(A) 4 (B) 5 (C) 6 (D) 8
16. How many types are DML?
(A) 2 (B) 4 (C) 6 (D) 8
17. Choose odd one out:
(A) commit (B) rollback (C) save point (D) create
18. .------ constraint apply only to individual column.
(A) column (B) table (C) row (D) none
19. Which constraint helps to set a limit value placed for a field?
(A) check (B) unique (C) key (D) constant
26
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
a) Data Manipulation language b) Data Meaningful Language
c) Directional Manipulate Language d) Data Management Language
29. A ……………………… is a collection of tables.
(a) database (b) SQL (c) Mysql (d) Python
i.N
30. CRUD means ……………………
(a) creative reasoning under development (b) create read update delete
(c) create row update drop (d) calculate relate update data
31. A …………………… is a collection of related data entries and it consists of rows and columns.
la
(a) table (b) Row (c) Column (d) Set
32. The DQL command ……………….. is used to display all the records from the table.
a) Select b) display c) Show d) Select all
33. A ………………………… is a horizontal entity in the table.
sa
(a) record (b) Row (c) Set (d) Column
34. Match the following:
1. DDL – (i) Modify Tuples 2. Informix – (ii) Create Indexes 3. DML – (iii) MySQL 4. DCL – (iv) Grant
(a) 1-ii, 2-iii, 3-i, 4-iv (b) 1-i, 2-ii, 3-iii, 4-iv (c) 1-iv, 2-iii, 3-ii, 4-I (d) 1-iv, 2-i, 3-ii, 4-iiii
da
27
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
(a) unique (b) primary (c) secondary (d) null
57. Which constraint is used to assign a default value for the field?
(a) unique (b) primary (c) secondary (d) default
58. The check constraint may use ………………….. operators for the condition.
i.N
(a) relational (b) logical (c) both (d) None of these
59. When the constraint is applied to a group of fields of the table, then it is ………………………. constraint.
(a) table (b) column (c) multiple (d) primary
60. The …………………….. command is used to insert, delete and update rows into the table.
la
(a) DCL (b) DML (c) DTL (d) TCL
61. If the data is to be added for all columns in a table
(a) specifying column is optional (b) specifying column is must
62. Find the wrong statement from the following delete command
sa
(a) permanently removes one or more records (b) removes entire row
(c) removes individual fields (d) deletes the record
63. The update command specifies the rows to be changed using the …………………….. clause.
(a) where (b) why (c) what (d) how
da
1. The module which allows interface with the windows operating system is:
(A) csv module (B) OS module (C) getopt module (D) sys module
2. CSV is expanded as:
(A) Comma separated vales (C) Condition Separated values
ww
et
18. If the fields of data in the csv file have commas, then it should be given with ……
(a) , (b) ” (c) ‘ (d) :
19. The CSV file contents can be read with the help of the method
a) read () b) open () c) with open () d) reader ()
i.N
20. If the fields contain double quotes as part of the data, the internal quotation marks need to be
(a) same (b) quarter (c) doubled (d) tripled
21. The line white indicates
(a) the first two fields of the row are empty (b) It can be deleted
la
(c) comma not necessary (d) only one field is there and, can be deleted
22. …….. allows creating, store and re-use various formatting parameters for CSV file in reading and writing.
a) class b) dialect c) write() d) read()
23. There are ……………………. ways to read a csv file.
sa
(a) 1 (b) 2 (c) 3 (d) 4
24. … method returns a writer object which converts the user’s data into delimited strings on the given file-like object.
a) csv.writer() b) csv.write user () c) csv.writes () d) csv_writer ()
25. The default mode when you open a file is
da
(a) creates a new file (b) truncates the file (c) overwrite the file (d) append the contents
28. To open the file updating data, click ……………………
(a) a (b) b (c) t (d) +
29. …………………… opens a file for exclusive creation.
(a) r (b) w (c) x (d) +
w.
30. ………………….. opens the file for read and write in binary mode.
(a) r (b) b (c) x + b (d) r + b
31. closing a file will free up the resources that were tied with the file and is done by ……………………. method.
(a) Exit (b) close (c) Quit (d) None of thes
ww
29
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
(c) both are true (d) both are false
i.N
1. Which of the following not scripting language?
(A) Ruby (B) DBMS (C) Perl (D) JavaScript
2. C++ is a:
(A) Programming language (B) Scripting language
(C) Glue language (D) B or C
la
3. Which of the following is the special variable which by default stores the name of the file?
(A) __name__ (B) __init__ (C) __del__ (D) __def__
4. _______ is a built-in variable which evaluates to the name of the current module.
sa
(A) __name__ (B) __main__ (C) __mode__ (D) __init__
5. In language data type or not required while declaring a variable.
a) C++ b) C c) Java d) Python
6. Find the correct statement.
da
(a) C++ is a dynamic typed language (b) python is a dynamic typed language
7. ________ is designed for integrating and communicating with other programming languages.
a) Modular language b) Procedural language c) Scripting language d) Procedural language
8. Pick the odd one out
a) Perl b) Ruby c) ASP d) Java
Pa
30
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
19. Which of the following is the special variable which by default stores the name of the file?
a) _name_ b) _init_ c) _del_ d) _def_
20. Which module helps to parse(split) command-line options and arguments?
(a) getopt (b) argopt (c) get (d) putopt
21. How many functions are there in getopt module to enable command-line argument parsing?
(a) 1 (b) 2 (c) 3 (d) 4
22. getopt mode is given by ………………………….
(a) ; (b) = (c) # (d) :
23. The argument of long options in the getopt method is followed by ………………………….
(a) ‘ (b) = (c) # (d) :
24. When the command to run a python program is given to the interpreter, code at ……. indentation is executed.
(a) level 0 (b) level 1 (c) level 2 (d) level 3
25. Which one is a special variable which by default stores the name of the file?
(a) main (b) none (c) _name_ (d) get
26. Which command of the os module executes the exe file?
(a) run (b) system( ) (c) main (d) name
27. Which operator is used to access the functions of an imported value?
et
(a) + (b) * (c) . (d) /
i.N
1. Which SQL function returns the number of rows in a table?
(A) SUM() (B) MAX() (C) CHECK() (D) COUNT
2. Which method uses the SQL command to get all the data from the table?
(A) get (B) select (C) execute (D) Query
3. Which is not a SQL clause?
la
(A) GROUP BY (B) ORDER BY (C) HAVING (D) CONDITION
4. Which of the following clause avoid the duplicate?
(A) Distinct (B) Remove (C) Where (D) Group By
sa
5. .. refers to a set of runtime header files used in compiling and linking the code of C, C++, Fortran to run on window os
(a) MaxGW (b) CountGW (c) MinGW (d) AvgGW
6. ………………….. statement in SQL is used to retrieve or fetch data from a table in a database.
a) select b) inset c) create d) fetch
7. Which method is used to create a connection with the database file?
da
14. Which method is used to fetch all rows from the database table?
(a) Fetch( ) (b) fetchall( ) (c) printall( ) (d) retrieveall( )
15. Which method run the SQL command to perform some action.
a) run b) select c) execution d) execute
16. What will be the result of fetchone( ) method if no row is left?
(a) 1 (b) 2 (c) 3 (d) none
17. Which one of the following methods displays the specified number of records?
(a) fetchone( ) (b) fetchmany( ) (c) fetchall( ) (d) fetchsome( )
18. Which one of the following is a newline character?
(a) \n (b) \r (c) \t (d) \nl
19. The path of a file can be either represented as…………… in Python.
a) /or\\ b) \\ or / c) \ or ? d) // or ?
20. The clauses in SQL can be called through
(a) C (b) C++ (c) Python script (d) DOS
31
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
21. In SQL, the …………. clause is used to extract only those records that fulfill a specified condition.
(a) why (b) what (c) where (d) how
22. Which clause returns are recorded for each group?
(a) Select (b) group in (c) group with (d) group by
23. Identify the statement which is wrong?
(a) Group by clause is used with aggregate functions
(b) group by clause groups records into summary rows
(c) group by clause is used to filter data
24. Pick the odd one out.
(i) count, max, min, OR, SUM (ii) AND, OR, MAX, NOT (iii) COUNT, NULL, AVG, SUM
25. How many types of sorting are there?
(a) 2 (b) 3 (c) 4 (d) 5
26. Which command is used to display the records in ascending or descending order?
(a) Group by (b) order by (c) group with (d) order with
27. Find the Incorrect statement?
(a) The WHERE clause can be combined with AND, OR, NOT
(b) Having clause is used to filter data based on the group function
et
(c) WHERE cannot be used with NOT
28. Which operators are used to filtering records based on more than one condition?
(a) AND (b) NOT (c) OR (d) a & c
29. How many values are returned from the aggregate functions?
i.N
(a) 1 (b) 2 (c) 3 (d) 4
30. Find the correct answer.
(i) count functions returns the number of rows in a table satisfying the criteria
(ii) count returns 0 if there were no matching rows
(iii) Null values are counted
(a) (i), (ii) – True
la
31. Find the correct statement.
(b) (ii), (iii) – true (c) (i), (ii), (iii) – True
(a) A record can be deleted using SQL command (b) A record can be deleted with python
(d) (i),.(ii), (iii) – False
34. The path of a python file can be represented as ……….. and ……………
(a) /, // (b) \, \\ (c) /, \\ (d) \, //
35. Which table holds the key information about the database tables?
(a) page (b) select (c) primary (d) Master
Pa
36. Which function returns the smallest value of the selected columns?
(a) MIN( ) (b) MINIMUM( ) (c) SMALL( ) (d) LEAST( )
(CHAPTER-16) (DATA VISUALIZATION USING PYPLOT: LINE , PIE AND BAR CHAT)
1. Using Matplotlib from within a python script, which method inside the file will display your plot?
w.
(A) Matplotlib (B) Info graphics (C) Data visualization (D) pip
4. The function to make a pie chart with Matplotlib:
(A) plt.bar() (B) pie.plt() (C) bar.plt() (D) plt.pie()
5. Which of the following is not a type of visualization under matplotlib?
(A) Histogram (B) Pie chart (C) Box plot (D) SQLite
6. ______ plot is a type of plot that shows the data as a collection of points.
(A) Line (B) Scatter (C) Box (D) Pie
7. Which of the following matplotlib function is used to draw line chart?
(A) pie() (B) line() (C) bar() (D) plot()
8. In Line Chart or Line Graph displays information as a series of data points called.
(A) Markers (B) Points (C) Dots (D) Lines
9. To make a bar chart with Matplotlib, which function should be used?
(A) plt.bar() (B) plt.chart() (C) pip.bar() (D) pip.chart()
10. ------ chart shows the relationship between a numerical variable and a categorical variable.
(A) bar (B) pie (C) line (D) scatter
32
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
11. The ---------------- plot is a standard way of displaying the distribution of data based on the five number summary.
(A) bar (B) pie (C) line (D) scatter
12. The default x.vector has the same length of y but starts with---
(A) 3 (B) 2 (C) 1 (D) 0
13. In python matplotlib is a ----------
(A) control structure (B) dictionary (C) library (D) list
14. Which kind of data encoded visually communicate a quantitative message?
(A) string (B) Numbers (C) images (D) none
15. In which plot the width of the bars may or may not be same.
(A) histogram (B) pie (C) line (D) bar
16. Pick the odd one out.
a) Tables b) databases c) Maps Infographics d) Dashboards
17. The Series of data points connected by straight line segment is called ____________
a) Matplot b) markers c) plot d) lib
18. Read the statements given below. Identify the right option from the following.
Statement A: Dashboards are used to detect patterns and relationships easily. Statement B: Dashboard is a type of game.
(a) A is correct (b) B is correct (c) Both are correct (d) Both are wrong
et
19. Various types of visualizations are available in
(a) stdlib (b) graphics (c) library (d) matplotlib
20. Which of the following one indicates discontinuity?
a) Histogram b) Pie c) Bar graph d) None of these
i.N
21. The terms minimum, first quartile, median, third quartile maximum are related to ………… type of plot.
(a) Box (b) scatter (c) pie (d) Bar
22. The position of a point in scatter plot is …………. value
(a) ID (b) 2D (c) 3D (d) U shaped
23. Which method is used to display the plot?
(a) disp( )
la (b) display( )
24. Data visualization uses ………………. graphics.
a) 2D b) 3D
(c) print( )
c) Statistical
(d) show( )
d) Image
sa
25. The name to the x-axis in the plot is given by …………
(a) label (b) x (c) x label (d) x axis
26. Which one of the following is the cross-looking button that allows you to click it, and drag the graph around?
(a) x-axis (b) y-axis (c) pan axis (d) plot axis
da
27. …………………. data may be encoded using dots, lines, or bars, to visually communicate a quantitative message.
a) String b) Numerical c) Images d) None of these
28. ……………….. assign values to the labels specified in the bar chart.
(a) usage (b) label (c) values (d) =
Pa
33
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
ABBREVIATIONS
1. ADT - Abstract Data Type.
et
2. CDT - Concrete data type
3. LEGB - Local Enclosed Global Built-in
4. CWI - Centrum Wiskunde & Informatics
i.N
5. NRI - National Research Institute.
6. GUI - Graphical User Interface
7. IDE - Integrated Development Environment.
8. IDLE - Integrated Development Learning Environment
9. CMD - Command
la
10. OOP - Object Oriented Programming
11. DBMS - Database management system.
12. ER - Entity Relationship Model
sa
13. RDBMS - Relational Database Management System.
14. SQL - Structured Query Language
15. DDL - Data Definition Language
16. DML - Data Manipulation Language
17. EDML - Embedded Data Manipulation Language
da
34
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
❖ In function definitions: Keyword specifies the post condition returns.
❖ The function definitions is introduced by the keyword let rec
i.N
(CHAPTER-2)(DATA ABSTRACTION)
❖ Splitting a program is called modules.
❖ Abstract data type is a type for objects whose behavior is defined by a set of values and operations.
❖ To facilitate data abstraction, we will need to create two functions constructor, Selectors.
❖ Constructors are functions that build the abstract data type.
la
❖ Selectors are functions that retrieve information from the data type.
❖ A rational number is a ratio of integers.
❖ A tuple is a comma separated values surrounded with parentheses.
sa
❖ A class is bundled data and functions.
❖ Bundling of two values together into one called pair.
❖ Pair is a compound structure.
❖ List is constructed by placing expressions within square brackets separated by commas.
da
(CHAPTER-3)(SCOPING)
❖ Scope refers to visibility of variables.
❖ Namespaces are containers for mapping names of variables to objects.
❖ = sign is used to map variable name to object
❖ The process of binding variable name with an object is called mapping.
w.
35
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
(CHAPTER-4)(ALGORITHMIC STRATEGIES)
❖ An algorithm is a finite set of instruction to accomplish a particular task.
❖ The way of defining an algorithm is called algorithm strategy.
❖ An algorithm that yields expected output for a valid input called an algorithmic solution.
❖ Analysis of algorithms and performance evolution can be divided in to two phases (i.e.) priori estimates, posteriori testing.
❖ Two main factors of algorithm time factor, space factor.
❖ Asymptotic notations are languages that uses meaningful statements about time and space.
❖ Big O is used to describe worst case of an algorithm.
❖ Big Ω is used to describe best case of an algorithm.
❖ Big Ө is used to describe better case of an algorithm.
❖ Linear search is called sequential search.
❖ Binary search is called as half interval search algorithm.
❖ Bubble sort algorithm compares each pair of adjacent elements and swap them if they are in the sorted order.
❖ Memorization is a technique to store the results of programming language.
❖ Fibonacci series generates the subsequent of numbers by adding two previous numbers.
❖ Selection sort needs minimum number of swaps.
❖ When a sub problem used several times, the problem poses overlapping sub problems.
et
(CHAPTER-5)(PYTHON - VARIABLES AND OPERATORS)
❖ Python language created by Guido Van Rossum.
❖ Python language released in 1991.
i.N
❖ Python program can be written in interactive mode and script mode.
❖ The interactive can also be used as simple calculator.
❖ Python scripts are reusable code.
❖ Creating script in python by choose File->new file or CTRL+N.
la
❖ The >>> prompt indicates that interpreter ready to accept instruction.
❖ python files are save with extension .py
❖ To execute python script choose Run->Run module of press F5.
❖ Comma (,) is used as separator in print ().
sa
❖ In python comments begin with # symbol.
❖ Python uses whitespaces such as spaces and tabs.
❖ Python breaks each logical line into a sequence of elementary lexical components known as tokens.
❖ Tokens are classified into five types.
da
(CHAPTER-6)(CONTROL STRUCTURES)
❖ Programs contains set of statements.
❖ A program statement that causes a jump of control from one part of program to another part is called control structures.
❖ Execute set of statements multiple times called iteration or looping.
❖ Skip a segment and execute another segment based on test condition is called alternative or branching.
❖ In python there are 3 control structures.
❖ Elif can be used instead of 'else'.
❖ Elif clause combines if...else-if..else statement.
❖ A loop statement allows to execute statements or set of statements.
❖ Python provide two types of looping. (i.e) while loop and for loop.
36
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
(CHAPTER-7)(PYTHON FUNCTIONS)
❖ Functions are named block of code.
❖ In python there are 4 types of function. (i.e.) user defined function, built in function, lambda function, recursive function.
❖ Function help us to divide a program in to modules.
❖ Function arguments are 4 types (i.e.) required arguments, keyword arguments, default , variable length arguments.
❖ Required arguments are the arguments passed to a function in correct positional order.
❖ Keyword arguments will invoke the function after the parameter are recognized by their parameter names.
❖ Default arguments takes default value if no value is provided.
❖ Non keyword variable length arguments are called tuples.
❖ Lambda function can only access global variable.
et
❖ To define a function def keyword is used.
❖ At the end function declaration: should be used.
❖ We should use global keyword when we call global keyword inside a function.
❖ ASCII value of A is 65.
i.N
❖ Id () returns the address of variable.
❖ Type () returns the data type of given object.
❖ Chr () returns the Unicode character of given ASCII value.
❖ Value returned by a function can be used by another function is called composition.
❖
la
System limitation can be changed by sys. Set recursion limit (limit value).
❖ * is used for unknown variable length arguments.
❖ The condition is applied in function is called base condition
sa
(CHAPTER-8)(STRINGS AND STRING MANIPULATION)
❖ Array of characters is string.
❖ String in python can be created by using single, double, triple quotes.
❖ Strings are immutable.
da
❖ %s denotes string.
❖ %u denotes unsigned decimal integer.
❖ %o denotes octal integer.
❖ %f denotes floating point numbers.
ww
et
❖ Del statement is used to delete known elements.
❖ Remove () is used to delete unknown elements.
❖ Clear () is used to delete all the elements in a list but retains the list.
❖ Pop () deletes and returns the last element of a list if the index is not given.
i.N
❖ Pop () is used to delete only one element from a list.
❖ Range (), list () can create a list with series of values.
❖ Range () has three arguments.
❖ Copy () returns a copy of list.
la
❖ Count () returns the number of similar elements present in the list.
❖ Index () returns the index value of first recurring element.
❖ Reverse () is used to reverse the order of the element in the list.
❖ Sort () is used to sort the elements in list.
sa
❖ Sort () will affect the original list.
❖ In sort () ascending is default.
❖ If you want to sort elements in descending set reverse is true.
❖ Max () returns the maximum value in a list.
da
et
(CHAPTER-11)(DATABASE CONCEPTS)
❖ A database is an organized collection of data.
❖ Data are raw facts.
❖ Information is formatted data.
i.N
❖ Database is a repository collection of related data.
❖ A DBMS is a software.
❖ Database can be divided in to 5 major components such as hardware, software, data, methods, database access language.
❖ Popular DBMS are FoxPro, Dbase.
❖ Each row in a table represents a record.
❖ Application programmers or software developers involved in developing and designing the parts of DBMS.
❖ Database normalization was first proposed by Dr.Edgar F Codd.
❖ Types of relationship used in database is 4.
❖ Relational algebra was first created by Edgar F Codd at IBM.
ww
et
❖ SAVEPOINT is used to save temporarily.
❖ Sorting can be done on multiple fields.
❖ The logical operators are AND,OR,NOT
❖ The * is used with COUNT to include NULL values.
i.N
❖ MySQL is a database management system.
(CHAPTER-13)(PYTHON AND CSV FILES)
❖ CSV is human readable text file.
❖ CSV file is known as flat file.
❖ File saved in excel cannot be opened or edited by text editors.
la
❖ CSV file cannot store charts or graphs.
❖ The expansion of CSV is Comma Separated Values.
❖ CSV cannot contain formatting, macros, formulas.
sa
❖ CSV file should be save with the extension .csv.
❖ By default CSV file will be opened in MS Excel.
❖ Two ways to read a CSV file is reader() and Dict reader class
❖ Open () returns a file object is called a handle.
da
et
❖ Python has native library.
❖ Cursor is a control structure is used to traverse and fetch the records of the database.
❖ To populate (add record) the table by INSERT command.
❖ Cursor is used for performing all sql commands.
i.N
❖ SELECT command is mostly used statement in SQL.
❖ Cursor.fetchall () is used to fetch all rows from the database table.
❖ Cursor.fetchone () is used to returns next row of the query result.
❖ Cursor.fetchmany() returns next number of rows of the result set.
la
❖ DISTINCT clause is used to give records without duplicate
❖ ORDER BY clause is used along with SELECT to sort data.
❖ HAVING clause is used to filter data based on GROUP ().
❖ WHERE clause can be combined with AND, OR, NOT operators.
sa
❖ Aggregate functions ignored NULL values.
❖ COUNT () returns 0 if there were no matching rows.
❖ Cursor.description contain each column heading.
❖ Path of file represented by ‘/’ or ‘\\’ in python
da
❖ A scatter plot is a type of plot that shows the data as a collection of points.
❖ The box plot is standardized way of displaying the distribution of data based on the five number.
❖ There are six types of data visualization under matplotlib.
❖ Pip is a management software for installing python packages.
❖ Plt.show() is used to display graph
ww
et
5. The elements of a list can be accessed in two ways.1. Multiple Assignment 2. Element Selection Operator
CHAPTER- 3 (SCOPING )
1. Types of Variable Scope: 1.Local, 2.Enclosed, 3.Global, 4.Build in
i.N
2. Local - Defined inside function/class // Variables defined in current function
Global - A variable which is declared outside of all the functions // Defined at the uppermost level
Enclosed - Defined inside enclosing functions
Built-in (B) - Reserved names in built-in functions (modules) // Pre-loaded
3. Characteristics of Modules: 1.Instructions, 2.Processing logic, 3.data.
la
4. Benefits of modular programming:
1.Less code to be written. 2.The code is stored across multiple files.
3.Code is short, simple and easy to understand. 4.The same code can be used in many applications.
sa
5.The scoping of variables can easily be controlled.
5. Access Control: C++ and Java, control the access to class members by public, private and protected keywords.
6. Public members - Accessible from outside the class.
Protected members - Accessible from within the class / sub-classes
da
Private members - They can be handled only from within the class.
CHAPTER – 4 ( ALGORITHMIC STRATEGIES )
1. Examples for data structures are arrays, structures, list, tuples, dictionary etc.
2. Characteristics of an Algorithm:
Pa
6. Space Complexity : Two main components: A fixed part & A variable part
7. Method for determining Efficiency:1.Speed of the machine 2.Compiler and other system Software tools
3.Operating System 4.Programming language used 5.Volume of data required
8. Asymptotic Notations: Big O, Big Ω ,Big Θ
ww
42
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
19. Number Data type: Integers, Floating point numbers and Complex numbers.
20. Exponent data: Digit part, Decimal point, Exponent part
21. Boolean Data type: True or False.
i.N
22. String Data type: Single, Double and Triple quotes.
CHAPTER – 6 ( CONTROL STRUCTURES )
1. Control structures : Sequential, Alternative or Branching, Iterative or Looping
2. Alternative or Branching Statement: 1.Simple if statement 2.if..else 3. if..elif
la
3. Looping constructs: While loop ,For loop
4. Syntax of range():1.start – initial value 2.stop – final value 3.step –increment value.
5. Jump Statements in Python: Break, continue, pass
sa
6. Examples for Range():
Range (1,30,1) will start the range of values from 1 and end at 29
Range (2,30,2) will start the range of values from 2 and end at 28
Range (30,3,-3) will start the range of values from 30 and end at 6
da
Range (20) will consider this value 20 as the end value(or upper limit) and starts the range count from 0
to 19 (remember always range() will work till stop -1 value only)
CHAPTER – 7 ( PYTHON FUNCTIONS )
1. Types of Functions: User-defined, Built-in, Lambda, Recursion Functions
Pa
43
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
CHAPTER – 9 ( LISTS, TUPLES, SETS AND DICTIONARY )
1. Python data types List, Tuples,Set Dictionary.
2. List elements can be modified or mutable : Replaced, added or removed
i.N
3. Accessing List elements: (i) Accessing all elements of a list, (ii) Reverse Indexing
4. Other important list function: 1.copy ( ),2. count ( ),3. index ( ),4. reverse ( ),5. sort ( )6. max( )7. min( )8. sum( )
5. Accessing List elements:
Positive value of index counts from the beginning of the list.
la
Negative value means counting backward from end of the list
6. 1.Apend() - Add a single element 2.Extend() - Add more than one element
3.Del statement -Delete elements whose index is known \ Delete entire list.
4.Remove() - Delete elements of a list if its index is unknown
sa
5.Pop() - Delete an element using the given index value. 6.Clear() - Delete all the elements in list.
7.Range() - Generate a series of values in Python.
7. Comparison of List and Tuple:
List: 1.List are changeable (mutable 2.List Elements of a list are enclosed within square brackets
da
1.Union: It includes all elements from two or more sets [ The | operator is used]
2.Intersection: It includes the common elements in two sets [The operator & is used]
3.Difference:
It includes all elements that are in first set (say set A) but not in the second set (say set B) [The minus (-) operator]
4.Symmetric difference:
w.
It includes all the elements that are in two sets (say sets A and B) but not the one that are common to two sets. [The
caret (^) operator is used]
CHAPTER – 10 ( PYTHON CLASSES AND OBJECTS )
1. Key features of Object Oriented Programming: Classes and Objects
ww
44
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
6. Data Model: 1.Hierarchical 2.Relational 3.Network 4.Database 5.Entity Relationship 6 Object Model.
7. Object Model Example: Shape, Circle, Rectangle,Triangle.
1) Circle has the attribute radius. 2) Rectangle has the attributes length and breadth.
3) Triangle has the attributes base and height.
4) The objects Circle, Rectangle and Triangle inherit from the object Shape.
8. Types of DBMS Users: 1.Database Administrators 2.Application Programmers or Software Developers
3.End User 4.Database designers
9. RDBMS examples: SQL server, Oracle, mysql, MariaDB, SQLite.
10. Types of Relationships: 1. One-to-One Relationship 2. One-to-Many Relationship
3. Many-to-One Relationship 4. Many-to-Many Relationship
11. Relational Algebra is divided into various groups:
Unary Relational Operations: 1.SELECT ( symbol : σ) 2.PROJECT ( symbol : Π)
Relational Algebra Operations from Set Theory: 1.UNION (∪) 2.INTERSECTION (∩)
3.DIFFERENCE (−) 4.CARTESIAN PRODUCT (X)
CHAPTER – 12 ( STRUCTURED QUERY LANGUAGE )
1. RDBMS packages: Oracle, MySQL, MS SQL Server, IBM DB2 and Microsoft Access
2. CRUD: Create, Read, Update and Delete operations
et
3. The fields in a student table may be of the type AdmnNo, StudName, StudAge, StudClass, Place etc.
4. Processing Skills of SQL:
1. Data Definition Language (DDL), 2. Data Manipulation Language (DML)
i.N
3. Embedded Data Manipulation Language 4. View Definition 5. Authorization 6. Integrity 7. Transaction control
5. MySQL - SQL Server, Oracle, Informix, Postgres, etc. WAMP - Windows, Apache, MySQL and PHP
6. Components of SQL: 1.DML - Data Manipulation Language 2.DDL - Data Definition Language
3.DCL - Data Control Language 4.TCL – Transaction Control Language 5.DQL – Data Query Language
la
7. DATA DEFINITION LANGUAGE SQL commands: Create Alter Drop Truncate
8. DATA MANIPULATION LANGUAGE SQL commands: Insert Update Delete
9. The DML is basically of two types: Procedural DML Non-Procedural DML
sa
10. DATA CONTROL LANGUAGE SQL commands: Grant Revoke
11. TRANSACTIONAL CONTROL LANGUAGE SQL commands: Commit ,Roll back ,Save point
12. DATA QUERY LANGUAGE SQL commands: Select
13. Data Types: Char (Character), varchar, dec (Decimal), numeric, int (Integer), smallint, float, real, double.
da
14. SQL Commands and their Functions: 1. DDL Commands 2.Type of Constraints 3. DML COMMANDS
4. Some Additional DDL Commands 5. DQL COMMAND– SELECT command
15. Type of Constraints: 1.Unique 2.Primary Key 3.Default 4.Check
16. Some Additional DDL Commands: ALTER , TRUNCATE , DROP TABLE
Pa
1. CSV can be opened with any text editor in Windows like notepad, MS Excel, Open Office etc.
2. CSV File cannot store: charts or graphs.
3. CSV does not contain: formatting, formulas, macros, etc.
4. Read a CSV File Using Python: 1. Use the csv module’s reader function 2. Use the Dict Reader class
ww
5. A file operation takes places: Step 1 Open a file Step 2 Perform Read or write operation Step 3 Close the file
6. Python File Modes:
1) 'r' Open a file for reading. 2) 'w' Open a file for writing.
3) 'x' Open a file for exclusive creation. 4) 't' Open in text mode.
5) 'a' Open for appending at the end of the file without truncating it.
6) 'b' Open in binary mode. 7) '+' Open a file for updating (reading and writing)
7. CSV Module’s Reader Function:
Using this method one can read data from csv files of different formats like 1.quotes (“ “), 2.pipe (|) 3.comma (,).
8. Writing Data Into Different Types in Csv Files:
1.Creating A New Normal CSV File 2.Modifying An Existing File 3.Writing On A CSV File with Quotes
4.Writing On A CSV File with Custom Delimiters 5.Writing On A CSV File with Line terminator 6.Writing On A
CSV File with Quote chars Writing CSV File Into A Dictionary
7.Getting Data At Runtime And Writing In a File
CHAPTER – 14 ( IMPORTING C++ PROGRAMS IN PYTHON )
1. Scripting languages: JavaScript, VBScript, PHP, Perl, Python, Ruby, ASP and Tcl.
45
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
1. SELECT Query: 1.Displaying all records using fetch all(), 2.Displaying A record using fetch one(),
3.Displaying all records using fetch one(), 4.Displaying using fetch many ()
4. CLAUSES IN SQL: 1.DISTINCT 2.WHERE 3.GROUP BY 4.ORDER BY 5.HAVING
5. WHERE CLAUSES: AND, OR, and NOT
i.N
6. Aggregate Functions: 1.COUNT() 2.AVG() 3.SUM() 4.MAX() 5.MIN()
CHAPTER – 16 ( DATA VISUALIZATION USING PYPLOT: LINE , PIE AND BAR CHAT )
1. Numerical data using: dots, lines, or bars,
2. General types of Data Visualization 1.Charts 2.Tables 3.Graphs 4.Maps 5.Infographics 6.Dashboards
la
3. Types of Visualizations in Matplotlib:
1.Line plot 2.Scatter plot 3.Histogram 4.Box plot 5.Bar chart 6.Pie chart
4. Scatter plot: (Two-dimensional value) Horizontal or Vertical dimension
sa
5. Box plot: Minimum, First quartile, Median, Third quartile, and Maximum.
6. Buttons in the output:
1. Home Button 2.Forward / Back Buttons Zoom Button 3.Save the Figure Button.
4.Pan Axis Button 5.Configure Subplots Button
da
46
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
GLOSSARY
Terminology Meaning
Access control • Security technique that regulates who or what can view or use resources in a computing environment
Access modifiers • Private , Protected and Public
Alternative • One of two choices
append() • Used to add an element in a list
Argument • Argument is the actual value of this variable that gets passed to function.
argv • An array containing the values passed through command line argument
Attribute • Data items that makes up an object
Authorization • Giving permission or access
Block • Set of Statements
Boolean • Means Logical
break • Exit the control
c = sqlite3.connect('test. • Create a database connection to the SQLite database ‘test.db’.
db')
et
• You can also supply the special name. memory: to create a database in RAM.
c.close() • To release the connection of the database
c.commit() • To save the changes made in the table
i.N
c.execute() • Executes all SQL commands
• Accepts two kinds of placeholders: question marks ?
• (“qmark style”) and named placeholders :name (“named style”).
Cartesian product • Cartesian operation is helpful to merge columns from two relations
cd • cd command refers to change directory
Class
Class variable
cls la
•
•
•
Template of creating objects.
An ordinary variable declared inside a class
To clear the screen in command window
sa
Comma(,) • Comma is used to separate each data in a csv file
compiler • Scans the entire program and translates it as a whole into machine code. It generates the error
message only after scanning the whole program. Hence debugging is comparatively hard.
Conjunction •
da
Concurrence, coincidence
Constraint • Restriction or limitation
Constructor • A special function get execution automatically when an object enter into scope.
continue • To skip the remaining part and start with next iteration.
CRUD •
Pa
47
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
Instantiation • Process of creating an object
Integrity • Whole and undivided
Interactive Mode • A way of using the Python interpreter by typing command and expressions at the prompt.
i.N
Interface • Interface defines what an object can do, but doesn't actually do it
interpreter • Translates program one statement at a time.
• It continues translating the program until the first error is met, in which case it stops.
• Hence debugging is easy.
Intersection • Intersection defines a relation consisting of a set of all tuple that are in both A and B.
Key
lambda
LEGB rule
•
•
• laData that is mapped to a value in a dictionary
Lambda function is mostly used for creating small and one- time anonymous function.
Local → Enclosed → Global → Built-in scope
sa
List • Mutable ordered collection of values
local Scope • A variable declared inside the function's body or in a block is called local scope.
Looping • Repetition
•
da
et
Stack • A stack (sometimes called a “push-down stack”) is an ordered collection of items where the
addition of new items and the removal of existing items always takes place at the same end.
• This end is commonly referred to as the “top.”
•
i.N
The end opposite the top is known as the “base.
• This ordering principle is sometimes called LIFO, last- in first-out.
stride • A long step
string • Sequence of letters, numbers or symbols
subscript • An index number
Syntax
Syntax Error
Token
•
•
• la
The structure of a program
An error in a program that makes it impossible to parse.
One of the basic elements of the syntactic structure of a program.
sa
Tuple • It is a sequence of immutable(not changeable) objects.
• Tuples are sequences, just like lists.
• Tuples are defined by having values between parentheses ( ).
•
da
Union operation(U) Union is symbolized by symbol. It includes all tuples that are in tables A or in B.
variable • Memory box to store values
writer ow() • Method to write a single row of data in a file
writer ows() • Method to write multiple rows of data in a file
FALSE •
Pa
Logical value 0
TRUE • Logical value 1
w.
ww
49
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
CHAPTER 1 TO 16 Two MARK BOOK BACK & PUBLIC QUESTION with ANSWERS
CHAPTER – 1( FUNCTION )
1. What is a subroutine?
❖ Subroutines are the basic building blocks of computer programs.
❖ Subroutines are small sections of code that are used to perform a particular task that can be used repeatedly.
❖ In Programming languages these subroutines are called as functions.
2. Define Function with respect to Programming language. (S-2021)
❖ A function is a unit of code that is often defined within a greater code structure.
❖ Specifically, a function contains a set of code that works on many kinds of inputs, like variants, expressions
and produces a concrete output.
3. Write the inference you get from X:=(78).
❖ In X:=(78), (78) is a function definition that binds the value 78 to the name ‘X’. (OR)
❖ X:= (78) has an expression in it but (78) is not itself an expression. Rather, it is a function definition.
❖ Definitions bind values to names, in this case the value 78 being bound to the name ‘a’.
4. Differentiate interface and implementation (J-2023)
Interface Implementation
❖ Interface just defines what an object can do, but ❖ Implementation carries out the instructions defined
et
won’t actually do it in the interface.
5. Which of the following is a normal function definition and which is recursive function definition
i) let sum x y: ii) let disp : iii) let rec sum num:
i.N
return x + y print ‘welcome’ if (num!=0) then return num + sum (num-1)
else return num
i. Normal ii. Normal iii. Recursive function
1. List the characteristics of Interface: (S-2020)
❖ The class template specifies the interfaces to enable an object to be created and operated properly.
1. la
❖ An object's attributes and behaviour is controlled by sending functions to the object.
CHAPTER – 2( DATA ABSTRACTION )
What is abstract data type? (M-2022, M-2024)
sa
❖ Abstract Data type (ADT) is a type (or class) for objects whose behaviour is defined by a set of value and a set
of operations.
2. Differentiate constructors and selectors. (J-2022, J-2024)
Constructors Selectors
da
❖ Constructors are functions that build the abstract ❖ Selectors are functions that retrieve information from
data type the data type
❖ Constructors create an object, bundling together ❖ Selectors extract individual pieces of information
different pieces of information from the object
Pa
50
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
Example: a:=5 (Here the variable ‘a’ is mapped to the value ‘5’
5. How Python represents the private and protected Access specifies?
❖ Python prescribes a convention of prefixing the name of the variable or method with single or double
i.N
underscore to emulate the behaviour of protected and private access specifies.
❖ All members in a python class are public by default.
Example: a, _num.
1. What are the characteristics of modules? (S-2020)
❖ Modules contain instructions, processing logic, and data. Modules can be separately compiled and stored in a library.
la
❖ Modules can be included in a program. Module segments can be used by invoking a name and some parameters.
❖ Module segments can be used by other modules.
CHAPTER – 4( ALGORITHMIC STRATEGIES)
sa
1. What is an Algorithm? (M-2020)
❖ An algorithm is a finite set of instructions to accomplish a particular task.
❖ It is a step-by-step procedure for solving a given problem.
2. Write the phases of performance evaluation of an algorithm.
da
1. A Priori estimates:
❖ This is a theoretical performance analysis of an algorithm.
❖ Efficiency of an algorithm is measured by assuming the external factors.
2. A Posteriori testing:
❖ This is called performance measurement.
Pa
❖ In this analysis, actual statistics like running time and required for the algorithm executions are collected.
3. What is Insertion sort?
❖ Insertion sort is a simple sorting algorithm.
❖ It works by taking elements from the list one by one and inserting then in their correct position in to a new
sorted list.
w.
4. What is Sorting?
❖ The process of arranging the list items in ascending or descending order is called sorting.
Example: Bubble Sort, Selection Sort, Insertion Sort.
ww
et
3. Write is the syntax of if.. else statement:
Syntax:
if <condition>:
i.N
statements-block 1
else:
statements-block 2
4. Define control structure.
❖ A program statement that causes a jump of control from one part of the program to another is called control
la
structure or control statement.
5. Write note on range () in loop. (M-2020, J-2022, M-2023)
❖ In Python, for loop uses the range () function in the sequence to specify the initial, final and increment values.
sa
❖ Range () generates a list of values starting from start till stop-1.
❖ The syntax of range() is as follows: range (start, stop,[step])
CHAPTER – 7( PYTHON FUNCTIONS )
1. What is function?
da
❖ Functions are named blocks of code that are designed to do specific job.
❖ Functions are nothing but a group of related statements that perform a specific task.
❖ Function blocks begin with the keyword “def” followed by function name and parenthesis ().
2. Write the different types of function. (S-2021, M-2024)
Pa
❖ We can say that scope holds the current set of variables and their values.
❖ Two types of scopes –local scope and global scope
5. Define global scope:
❖ A variable, with global scope can be used anywhere in the program.
❖ It can be created by defining a variable outside the scope of any function/block
6. What is base condition in recursive function?
❖ A recursive function calls its self.
❖ The condition that is applied in any recursive function is known as base condition.
❖ A base condition is must in every recursive function otherwise it will continue to execute like an infinite loop
7. How to set the limit for recursive function? Give an example.
❖ Python stops calling recursive function after 1000 calls by default.
❖ So, it also allows you to change the limit using sys.setrecursionlimit(limit_value).
Example:
import sys
sys.setrecursionlimit(3000)
52
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
print(fact (2000)
CHAPTER – 8( STRINGS AND STRING MANIPULATION )
1. What is String? (S-2021, J-2024)
❖ 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.
2. Do you modify a string in Python?
❖ Yes we can modify the string by the following method,
❖ A new string value can be assign to the existing string variable.
❖ When defining a new string value to the existing string variable.
❖ Python completely overwrite new string on the existing string.
3. How will you delete a string in Python? (M-2023)
et
❖ Python will not allow deleting a particular character in a string.
❖ Delete command is used to remove entire string variable.
Example>>> del str1[2]
i.N
4. What will be the output of the following python code? (J-2022)
str1 = “School” output: SchoolSchoolSchool
print(str1*3)
5. What is slicing?
❖ Slice is a substring of a main string.
la
❖ A substring can be taken from the original string by using [ ] operator and index or subscript values.
❖ Thus, [ ] is also known as slicing operator.
❖ Using slice operator, you have to slice one or more substrings from a main string.
sa
❖ General format of slice operation: str [start: end]
1. What is the use of replace ( ) in python? Write the general format of replace ( ) (S-2020)
❖ 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.
da
❖ 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.
2. What will be the output of the given python program (M-2020)
str= “COMPUTER SCIENCE”
Pa
et
❖ Pop () function is used to delete only one element from a list.
CHAPTER – 10( PYTHON CLASSES AND OBJECTS )
1. What is class? (M-2023, J-2024)
i.N
1. Class is the main building block in Python. 2. Class is a template for the object
2. What is instantiation?
❖ Once a class is created, next you should create an object or instance of that class.
❖ The process of creating object is called as “Class Instantiation”.
Syntax: Object_name = class_name( )
la
3. What is the output of the following program?
Class Sample: >>>
__num=10 10 Output
sa
defdisp(self): line 7, in <module>
print(self.__num) print (S._num)
S=Sample() Attribute error:‘Sample’ object has no attribute ‘_num’
S.disp()
da
print(S.__num)
4. How will you create constructor in Python?
❖ “init” is a special function begin an end with double under score in python act as a constructor.
❖ Constructor function automatically executed when an object of a class is created.
❖ General format of __init__ method (Constructor function)
Pa
et
Command Description Component
1. Insert Inserts data into a table DML
2. Create To create tables in the database. DDL
i.N
5. What is the difference between SQL and My SQL?
SQL My SQL
❖ Structured Query Language is a language used ❖ MYSQL is a database management system, like
for accessing databases SQL Server, Oracle, Informix, Postgres.
❖ SQL is a DBMS ❖ My SQL is a RDBMS.
1.
la
What is Data Manipulation language? (M-2023)
❖ A Data Manipulation Language (DML) is a computer programming language used for adding (inserting),
removing (deleting), and modifying (updating) data in a database.
sa
2. Write categories of SQL Commands: (M-2020)
1.DML - Data Manipulation Language 2.DDL - Data Definition Language 3.DCL - Data Control Language
4.TCL - Transaction Control Language 5.DQL - Data Query Language
CHAPTER – 13( PYTHON AND CSV FILES )
da
1. Use the csv module’s reader function 2. Use the Dict Reader class
3. Mention the default modes of the File. (M-2023)
❖ The default is reading (‘r’) in text mode.
❖ In this mode, while reading from the file the data would be in the format of strings.
4. What is use of next () function? (J-2024)
w.
❖ The “next ()” command is used to avoid or skip the first row or row heading.
Example :
❖ While sorting the row heading is also get sorted, to avoid that the first is skipped using next ().
❖ Then the list is sorted and displayed.
ww
5. How will you sort more than one column from a CSV file? Give an example statement.
❖ To sort by more than one column you can use item getter with multiple indices.
Syntax: operator.itemgetter (col_no)
Sortedlist = sorted(data, key=operator.itemgetter(Col_number),reverse=True)
Example: sorted list = sorted (data,key=operator.itemgetter(1))
CHAPTER – 14( IMPORTING C++ PROGRAMS IN PYTHON )
1. What is the theoretical difference between Scripting language and other programming language? (S-2021)
Scripting language Programming language
❖ A scripting language requires an interpreter. ❖ A programming language requires a compiler.
❖ A scripting language need not be compiled. ❖ A programming languages needs to be compiled before running.
❖ Example: JavaScript, VBScript, PHP, Perl, ❖ Example: C, C++, Java, C# etc.
Python, Ruby, ASP.
55
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
Example : “cd c:\program files\openoffice4\Program”
1. Write the syntax of getopt.getopt method (M-2022)
<opts>,<args>=getopt.getopt(argv, options, [long_options])
i.N
CHAPTER – 15(DATA MANIPULATION THROUGH SQL)
1. Mention the users who uses the Database:
❖ Users of database can be human users, other programs or applications.
2. Which method is used to connect a database? Give an example.
❖ Create a connection using connect () method and pass the name of the database file.
Example:
import sqlite3
la
# connecting to the database
sa
connection = sqlite3.connect ("Academy.db")
# cursor
cursor = connection.cursor()
3. What is the advantage of declaring a column as “INTEGER PRIMARY KEY”? (M-2020)
da
❖ If a column of a table is declared to be an INTEGER PRIMARY KEY, that column will be automatically auto
incremented. (OR)
❖ If a column of a table is declared to be an INTEGER PRIMARY KEY, then whenever a NULL will be used as
an input for this column, the NULL will be automatically converted into an integer which will one larger than
the highest value so far used in that column.
Pa
Example:
sql_command = """INSERT INTO Student (Rollno, Sname, Grade, gender, Average, birth_date) VALUES (NULL, "Akshay", "B",
"M","87.8", "2001-12-12");"""
cursor.execute(sql_command
5. Which method is used to fetch all rows from the database table? (J-2022, M-2024)
ww
❖ The fetchall() method is used to fetch all rows from the database table.
Example :result = cursor.fetchall()
1. Write notes on MAX ( ) and MIN ( ) (J-2023)
❖ The MAX() function returns the largest value of the selected column.
❖ The MIN() function returns the smallest value of the selected column.
CHAPTER – 16( DATA VISUALIZATION USING PYPLOT: LINE , PIE AND BAR CHAT )
1. What is Data Visualization? (M-2022)
❖ Data Visualization is the graphical representation of information and data.
❖ The objective of Data Visualization is to communicate information visually to users.
❖ For this, data visualization uses statistical graphics.
❖ Numerical data may be encoded using dots, lines, or bars, to visually communicate a quantitative message.
2. List the general types of data visualization. (M-2020, M-2023, J-2024)
1. Charts 2.Tables 3.Graphs 4.Maps 5.Infographics 6.Dashboards.
56
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
let square x:= let length s:=
return: x * x i:=0
if i < strlen (s) then
-- Do something which doesn't affect s ++i
i.N
2. 1What are called function?
.❖ A function is a unit of code that is often defined within a greater code structure
❖ A function contains a set of code that works on many kinds of inputs and produces a concrete output
3. What is Definitions?
❖ Definitions are not expressions, at the same time expressions are also not treated as definitions.
la
❖ Definitions are distinct syntactic blocks.
❖ Definitions can have expressions nested inside them, and vice-versa.
4. 3Differentiate Parameters and Arguments.
sa
. Parameters Arguments
Parameters are the variables in a function definition Arguments are the values which are passed to a function definition
5. What is recursive function? A function definition which call itself is called recursive function.
6. 5Write syntax for function definitions: let rec fna1 a2 ... an := k
da
.❖ Here the ‘fn’ is a variable indicating an identifier being used as a function name.
❖ The names ‘a1’ to ‘an’ are variables indicating the identifiers used as parameters.
❖ The keyword ‘rec’ is required if ‘fn’ is to be a recursive function
7. 6Write syntax for function types. x → y x1 → x2 → y x1 → ... → xn → y
Pa
.❖ The variables used inside the function may cause side effects though the functions which are not passed with any arguments.
❖ In such cases the function is called impure function.
Ex: let random number := a := random() if a > 10 then return: a else return: 10
CHAPTER – 2 ( DATA ABSTRACTION )
1. 1What is modularity?
.❖ Abstraction provides modularity (modularity means splitting a program in to many modules).
❖ Classes (structures) are the representation for “Abstract Data Types”, (ADT)
2. 2What is abstraction?
.❖ The process of providing only the essentials and hiding the details is known as abstraction.
3. 3What different ways is implemented?
.❖ There can be different ways to implement an ADT, for example, the List ADT can be implemented using
singly linked list or doubly linked list. Similarly, stack ADT and Queue ADT can be implemented using lists
4. 4What is constructor?Constructors are functions that build the abstract data type.
.❖ Constructors create an object, bundling together different pieces of information
57
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
5. 5What is selector?
.❖ Selectors are functions that retrieve information from the data type.
❖ Selectors extract individual pieces of information from the object.
6. 6What is wishful thinking?
.❖ We are using here a powerful strategy for designing programs: 'wishful thinking'.
❖ Wishful Thinking is the formation of beliefs and making decisions according to what might be pleasing to
imagine instead of by appealing to reality.
7. 7What are the types of elements of list?
.❖ The elements of a list can be accessed in two ways.
❖ The first way is via multiple assignment and the second method is by the element selection operator.
(CHAPTER-3)( SCOPING )
1. What are Modules?
❖ A module is a part of a program. Programs are composed of one or more independently developed modules.
2. 1What is LEGB rule?
.❖ The LEGB rule is used to decide the order in which the scopes are to be searched for scope resolution.
Local(L) Defined inside function/class
et
Enclosed(E) Defined inside enclosing functions (Nested function concept)
Global(G) Defined at the uppermost level
Built-in (B) Reserved names in built-in functions (modules)
i.N
3. 3Write the types of scopes of variable.
.❖ There are four types of variables ,1.Local 2.Enclose 3.Global 4.Build in scope
4. 4What is modular programming?
.❖ The process of subdividing a computer program into separate sub-programs is called Modular programming.
5. 5Give some examples of modules.
la
.❖ The examples of modules are procedures, subroutines, and functions.
6. 6What is module scope?
.❖ Any variable or module which is defined in the library functions of a programming language has Built-in or module scope.
sa
7. 7What is access control?
.❖ Access control is a security technique that regulates who or what can view or use resources in a computing environment.
❖ It is a fundamental concept in security that minimizes risk to the object.
8. 8What is data encapsulation?
.❖ The object of the same class is required to invoke a public method.
da
❖ This arrangement of private instance variables and public methods ensures the principle of data encapsulation.
9. 9What is public members?
.❖ Public members (generally methods declared in a class) are accessible from outside the class.
10. 1What is private members?
Pa
0❖ Private members of a class are denied access from the outside the class.
❖ They can be handled only from within the class.
11. 1What is protected members?
1❖ Protected members of a class are accessible from within the class and are also available to its sub-classes.
CHAPTER – 4( ALGORITHMIC STRATEGIES)
w.
et
13. 1What is Insertion sort?
3❖ Insertion sort is a simple sorting algorithm.
❖ It works by taking elements from the list one by one and inserting then in their correct position in to a new sorted list.
14. 1What is Dynamic programming?
i.N
4❖ Dynamic programming is an algorithmic design method that can be used when the solution to a problem can be
viewed as the result of a sequence of decisions. Dynamic programming approach is similar to divide and conquer.
❖ The given problem is divided into smaller and yet smaller possible sub-problems.
15. 1What is Memorization?
5❖ Memorization or memorisation is an optimization technique used primarily to speed up computer programs by storing the
la
results of expensive function calls and returning the cached result when the same inputs occur again.
16. 1What is used for Omega?
6❖ Big Omega is used to describe the lower bound which is best way to solve the space complexity.
sa
CHAPTER – 5( PYTHON - VARIABLES AND OPERATORS)
1. What are keywords in python?
false class finally is return raise In except
none continue for lambda try break pass import
da
Arithmetic operators:
❖ An arithmetic operator is a mathematical operator that takes two operands and performs a calculation on them.
They are used for simple arithmetic.
❖ Most computer languages contain a set of such operators that can be used within equations to perform different
ww
❖ In interactive mode Python code can be directly typed and the interpreter displays the result(s) immediately.
❖ The interactive mode can also be used as a simple calculator.
9. Invoking Python IDLE :Start → All Programs → Python 3.x → IDLE (Python 3.x)
10. What is interactive mode?
❖ The Interactive mode allows us to write codes in Python command prompt (>>>)
11. 1What is script mode?
1❖ The script mode programs can be written and stored as separate file with the extension .py and executed.
❖ Script mode is used to create and edit python source file.
12. 1What is input function?
2❖ The input () function helps to enter data at run time by the user.
❖ The input () function is used to accept data as input at run time
13. What is output function?
❖ The output function print () is used to display the result of the program on the screen after execution.
14. 1What are called comments?
4❖ In Python, comments begin with hash symbol (#).
❖ The lines that begins with # are considered as comments and ignored by the Python interpreter. Comments may
be single line or no multi-lines.
et
Types:1) # It is Single line Comment 2) ''' It is multiline comment which contains more than one line '''
15. 1What is indentation?
5❖ Python uses whitespace such as spaces and tabs to define program blocks whereas other languages like C,
i.N
C++, java use curly braces { } to indicate blocks of codes for class, functions or body of the loops and block of
selection command.
16. 1What is Delimiters:
6❖ Delimiters are sequence of one or more characters used to specify the boundary between separate, independent
regions in plain text or other data streams.
la
❖ Python uses the symbols and symbol combinations as delimiters in expressions, lists, dictionaries and strings.
Ex:( ) [ ] { } , : . ‘ = ;
17. Give few examples of Build-in or fundamental data types.
sa
❖ Number, String, Boolean, tuples, lists and dictionaries
18. 1Explain the data types.
81.Number Data type:
❖ The built-in number objects in Python supports integers, floating point numbers and complex numbers.
da
2.Boolean Data type: A Boolean data can have any of the two values: True or False.
Example:Bool_var1=True Bool_var2=False
3.String Data type: String data can be enclosed in single quotes or double quotes or triple quotes.
Example: Char_data = ‘A’
CHAPTER – 6 ( CONTROL STRUCTURES )
w.
60
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
6. 3What is if-statement?
.❖ Simple if is the simplest of all decision making statements.
❖ Condition should be in the form of relational or logical expression.
7. 4What is if-else statement?
.❖ The if ..else statement provides control to check the true block as well as the false block.
8. 5What is Nested if..elif...else statement?
.❖ When we need to construct a chain of if statement(s) then ‘elif’ clause can be used instead of ‘else’.
9. 6What is Loop?
.❖ A loop statement allows to execute a statement or group of statements multiple times.
10. 8What is While loop?
.❖ In the while loop, the condition is any valid Boolean expression returning True or False.
❖ The else part of while is optional part of while.
❖ The statements block1 is kept executed till the condition is True.
❖ If the else part is written, it is executed when the condition is tested False.
11. 9What is for loop?
.❖ for loop is the most comfortable loop.
❖ It is also an entry check loop.
et
❖ The condition is checked in the beginning and the body of the loop(statements-block 1) is executed if it is only
❖ True otherwise the loop is not executed.
12. 1What is nested loop structure?
i.N
0❖ A loop placed within another loop is called as nested loop structure.
❖ One can place a while within another while; for within another for; for within while and while within for to
construct such nested loops.
13. 1What is indentation?
1❖ In Python, indentation is important in loop and other control statements.
la
❖ Indentation only creates blocks and sub-blocks like how we create blocks within a set of { } in languages like
C, C++ etc.
14. 1What is Jump statement? Write it types.
sa
2❖ The jump statement in Python, is used to unconditionally transfer the control from one part of the program to another.
❖ Types: break, continue, pass
15. 1What is break statement?
3❖ The break statement terminates the loop containing it.
❖ Control of the program flows to the statement immediately after the body of the loop.
da
❖ Lambda functions are mainly used in combination with the functions like filter(), map() and reduce().
3. Describe the abs ( ) and chr ( ) function.
1.abs ( ) – Returns an absolute value of a number 2. chr( ) – Returns the ASCII value for the given Unicode character.
4. Define Short note on floor division operator.
floor ( ) – Returns the largest integer less than or equal to x
Syntax : math.floor (x) Output: 26 -27 -24
x=26.7
y=-26.7
z=-23.2
print (math.floor (x))
print (math.floor (y))
print (math.floor (z))
5. What are the advantages of User-defined Functions?
❖ Functions help us to divide a program into modules. This makes the code easier to manage.
❖ It implements code reuse. Every time you need to execute a sequence of statements, all you need to do is to call the function.
❖ Functions, allows us to change functionality easily, and different programmers can work on different functions.
61
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
6. 1What is Block?
.❖ A block is one or more lines of code, grouped together so that they are treated as one big sequence of
statements while execution.
❖ In Python, statements in a block are written with indentation.
7. 2What is Nested Block?
.❖ A block within a block is called nested block.
❖ When the first block statement is indented by a single tab space, the second block of statement is indented by
double tab spaces.
8. 4What are the types of arguments?
.❖ Required arguments, Keyword arguments, Default arguments and Variable-length arguments.
9. 5What is Required arguments?
.❖ “Required Arguments” are the arguments passed to a function in correct positional order.
10. 6What is Keyword arguments?
.❖ Keyword arguments will invoke the function after the parameters are recognized by their parameter names.
11. 7What is Default arguments?
.❖ In Python the default argument is an argument that takes a default value if no value is provided in the function call.
12. 8What is variable-length arguments?
et
.❖ In some instances you might need to pass more arguments than have already been specified.
❖ Going back to the function to redefine it can be a tedious process. Variable-Length arguments can be used instead.
13. 9What are the types of variable length argument passing methods? 1. Non keyword variable 2. Keyword variable
i.N
14. 1What is anonymous function?
0❖ In Python, anonymous function is a function that is defined without a name.
❖ While normal functions are defined using the def keyword, in Python anonymous functions are defined using
the lambda keyword.
❖ Hence, anonymous functions are also called as lambda functions.
la
CHAPTER – 8 ( STRINGS AND STRING MANIPULATION )
1. What will be the output of the following Python code? Str1 = “Madurai” print(Str1*3)
❖ Madurai Madurai Madurai
sa
2. What are membership operators in Python?
❖ The ‘in’ and ‘not in’ operators can be used with strings to determine whether a string is present in another string.
❖ Therefore, these operators are called as Membership Operators.
Example : Output:1
str1=input (“Enter a string: “) Enter a string: Chennai GHSS, Saidapet
da
str2=”Chennai” Found
if str2 in str1: Output:2
print (“Found”) Enter a string: Govt GHSS, Saidapet
else: Not Found
Pa
4.
❖ Positive value = 2 Negative value = –4
5. What will be the output of the following Python Code? str=”Chennai” print(str*4)
❖ Chennai Chennai Chennai Chennai
Explain the following function:
ww
6.
Syntax Description Example
lower() Returns the exact copy of the string with all the >>>str1=’SAVE EARTH’
letters in lowercase. >>>print(str1.lower( )) ans :save earth
7. Write about the following python string functions i) islower() ii) title ()
islower( ) Returns True if the string is in lowercase. >>> str1=’welcome’ >>>print (str1.islower( )) True
title( ) Returns a string in title case >>> str1='education department'
>>> print(str1.title()) Education Department
8. Write the general format of slicing operation: str[start:end]
9. What is the use of replace ( ) in python? Write the general format of replace ( )
❖ 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 format of replace function: replace(“char1”, “char2”)
❖ The replace function replaces all occurrences of char1 with char2.
62
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
Set_A = {‘A’,2,4,’D’} {‘A’,’D’}
Set_B={‘A’,’B’,’C’,’D’}
Print (Set_A&Set_B)
i.N
4. What are the collection data types available in Python?
❖ Python programming language has four collections of data types such as List, Tuples, Set and Dictionary.
5. Write the syntax to create a list with suitable example
❖ A list is simply created by using square bracket. The elements of list should be specified within square brackets.
Syntax: Variable = [element-1, element-2, element-3 …… element-n]
la
Example: 1. Marks = [10, 23, 41, 75] 2.Fruits = [“Apple”, “Orange”, “Mango”, “Banana”] 3.MyList = [ ]
6. Write note about tuple Assignment.
❖ Tuple assignment is a powerful feature in Python.
sa
❖ It allows a tuple variable on the left of the assignment operator to be assigned to the values on the right side of
the assignment operator.
❖ Each value is assigned to its respective variable.
7. What is list comprehensions?
da
❖ List comprehension is a simplest way of creating sequence of elements that satisfy a certain condition.
Syntax: List = [ expression for variable in range ]
8. What is singleton tuple?
❖ While creating a tuple with a single element, add a comma at the end of the element.
❖ In the absence of a comma, Python will consider the element as an ordinary data type; not a tuple.
Pa
63
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
❖ Class variable and methods are together known as members of the class.
3. 3What are called constructor and destructor?
.Constructor:
i.N
❖ Constructor is the special function that is automatically executed when an object of a class is created.
❖ In Python, there is a special function called “init” which act as a Constructor.
Destructor:
❖ Destructor is also a special method to destroy the objects.
❖ In Python, _ _del_ _( ) method is used as destructor. It is just opposite to constructor.
la
CHAPTER – 11( DATABASE CONCEPTS )
1. 3What are the advantages of RDBMS? (.)
.1.Segregation of application program 2.Minimal data duplication or Data Redundancy
sa
3.Easy retrieval of data using the Query Language 4.Reduced development time and maintenance.
2. Examples of DBMS & RDBMS:
1.DBMS: Foxpro, dbase 2.RDBMS: MySQL,Oracle, MS-Access etc.
3. Describe the database structure.
da
❖ Table is the entire collection of related data in one table, referred to as a File or Table where the data is
organized as row and column.
❖ Each row in a table represents a record, which is a set of data for each database entry.
❖ Each table column represents a Field, which groups each piece or item of data among the records into specific
Pa
6. 4Define database?
.❖ A database is an organized collection of data, generally stored and accessed electronically from a computer system.
❖ The term "database" is also used to refer to any of the DBMS, the database system or an application associated with the database.
7. 5What is data base?
.❖ Database is a repository collection of related data organized in a way that data can be easily accessed, managed and updated.
❖ Database can be a software or hardware based, with one sole purpose of storing data.
CHAPTER – 12( STRUCTURED QUERY LANGUAGE )
1. List any four DDL commands: 1) ALTER 2) TRUNCATE 3) DROP 4) DELETE
2. Write a Python code to create a database in SQLite.
❖ To create a database, type the following command in the prompt:
CREATE DATABASE database_name;
❖ For example : To create a database to store the tables: CREATE DATABASE stud;
3. What are DCL commands in SQL?
(i) Grant : Grants permission to one or more users to perform specific tasks.
(ii) Revoke: Withdraws the access permission given by the GRANT statement.
64
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
❖ INSERT INTO <table-name> [column-list] VALUES (values);
❖ INSERT INTO Student (Admno, Name, Gender, Age, Place) VALUES (100, ‘Ashish’, ‘M’, 17, ‘Chennai’);
9. Give one examples of DELETE command:
i.N
❖ DELETE FROM table-name WHERE condition;
❖ DELETE FROM Student WHERE Admno=104;
10. Give one examples of UPDATE command:
❖ UPDATE <table-name> SET column-name = value, column-name = value,… WHERE condition;
❖ UPDATE Student SET Age = 20 WHERE Place = ῾Bangalore᾿;
11.
la
Give one examples of SELECT command:
❖ SELECT <column-list>FROM<table-name>;
❖ SELECT Admno, Name FROM Student;
sa
❖ SELECT * FROM STUDENT;
12. What are the types of DML?
❖ The DML is basically of two types:
❖ Procedural DML – Requires a user to specify what data is needed and how to get it.
da
❖ Non-Procedural DML - Requires a user to specify what data is needed without specifying how to get it.
13. What is Table?
❖ A table is a collection of related data entries and it consist of rows and columns.
14. What is a field?
❖ A field is a column in a table that is designed to maintain specific related information about every record in the table.
Pa
❖It is a vertical entity that contains all information associated with a specific field in a table.
❖The fields in a student table may be of the type AdmnNo, StudName, StudAge, StudClass, Place etc.
15. What is record?
❖ A Record is a row, which is a collection of related fields or columns that exist in a table.
w.
❖ A record is a horizontal entity in a table which represents the details of a particular student in a student table.
16. Write the SQL statements using “BETWEEN” and “NOT BETWEEN” keywords. (.)
BETWEEN:
❖ The BETWEEN keyword defines a range of values the record must fall into to make the condition true.
ww
❖ The range may include an upper value and a lower value between which the criteria must fall into.
❖ SELECT Admno, Name, Age, Gender FROM Student WHERE Age BETWEEN 18 AND 19;
NOT BETWEEN
❖ 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;
CHAPTER – 13( PYTHON AND CSV FILES )
1. 1What is Excel?
.❖ Excel is a binary file that holds information about all the worksheets in a file, including both content and formatting.
2. 2How the CSV file operation takes place in python?(or)
.What are the steps involved in file operation of Python?
Step 1 : Open a file
Step 2 : Perform Read or write operation Step 3 : Close the file
3. What is line terminator?
❖ A Line Terminator is a string used to terminate lines produced by writer.
❖ The default value is \r or \n.
65
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
❖ We can write csv file with a line terminator in Python by registering new dialects using csv.register_dialect()
class of csv module
4. What is the use of skip initial space?
❖ In dialects the parameter “skipinitialspace” is used for removing whitespaces after the delimiter.
❖ By default “skipinitialspace” has a value false
5. How to create and save a extension of csv file?
❖ To create a CSV file in Notepad, First open a new file using File →New or ctrl +N.
❖ Save this content in a file with the extension .csv .
❖ You can then open the same using Microsoft Excel or any other spreadsheet program.
6. lList out writing data into different types in CSV files.
1.Creating A New Normal CSV File 2.Modifying An Existing File 3.Writing On A CSV File with Quotes
4.Writing On A CSV File with Custom Delimiters 5.Writing On A CSV File with Line terminator
6.Writing On A CSV File with Quote chars 7.Writing CSV File Into A Dictionary
8.Getting Data At Runtime And Writing In a File
CHAPTER – 14( IMPORTING C++ PROGRAMS IN PYTHON )
1. .Write the syntax of getopt. getopt method :
❖ <opts>,<args>=getopt.getopt(argv, options, [long_options])
et
2. Write the syntax of python OS module. (.)
❖ os.system (‘g++ ’ + <variable_name1> ‘ -<mode> ’ + <variable_name2>
3. Differentiate PYTHON and C++
i.N
PYTHON :1.Python is typically an "interpreted" language 2.Python is a dynamic-typed language
C++ :1.C++ is typically a "compiled" language 2.C++ is compiled statically typed language
4. What is scripting language with examples?
❖ A scripting language is a programming language designed for integrating and communicating with other
programming languages.
la
❖ Example: JavaScript, VBScript, PHP, Perl, Python, Ruby, ASP and Tcl.
5. What is garbage collection?
❖ Python deletes unwanted objects (built-in types or class instances) automatically to free the memory space.
sa
❖ The process by which Python periodically frees and reclaims blocks of memory that no longer are in use is
called Garbage Collection.
6. List out importing c++ files in python interfaces:
❖ Python-C-API (API-Application Programming Interface for interfacing with C programs)
da
5. What is sqlite_master?
❖ The master table holds the key information about your database tables and it is called sqlite_master.
6. What is Cursor?
❖ Cursor is a control structure used to traverse and fetch the records of the database.
❖ All the SQL commands will be executed using cursor object only.
CHAPTER – 16( DATA VISUALIZATION USING PYPLOT: LINE , PIE AND BAR CHAT )
1. 1What is Matplotlib?
.❖ Matplotlib is the most popular data visualization library in Python.
❖ It allows to create charts in few lines of code.
2. What will be the output of the following python code?
Import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16])
plt.show( )
et
3. What is Pip?
❖ 1.Matplotlib installed using pip.
i.N
❖ 2.Pip is a management software for installing python packages.
4. Write any two differences between Histogram and bar graph.
Histogram:
1.A graphical representation that displays data by way of bars to show the frequency of numerical data.
2.Presents numerical data
la
Bar graph:
1.A pictorial of data that uses bars to compare different categories of data.
2.Shows categorical data
sa
5. What is info graphics?
❖ An info graphic (information graphic) is the representation of information in a graphic format.
6. What Dashboard?
❖ A dashboard is a collection of resources assembled to create a single unified visual display.
da
❖ Data visualizations and dashboards translate complex ideas and concepts into a simple visual format.
❖ Patterns and relationships that are undetectable in text are detectable at a glance using dashboard.
7. What is scatter plot?
❖ A scatter plot is a type of plot that shows the data as a collection of points.
❖ The position of a point depends on its two-dimensional value, where each value is a position on either the
Pa
67
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
CHAPTER 1 TO 16 THREE MARK BOOK BACK & public QUESTION with ANSWERS
CHAPTER – 1 ( FUNCTION )
1. Mention the characteristics of Interface. (M-2023, J-2024)
❖ The class template specifies the interfaces to enable an object to be created and operated properly.
❖ An object's attributes and behaviour is controlled by sending functions to the object.
2. Why strlen is called pure function?
❖ Strlen is a pure function because the function takes one variables as a parameter, and accesses it to find its length.
❖ This function reads external memory but does not change it, and the value returned derives from the external
memory accessed.
3. What is the side effect of impure function? Give example.
❖ Function impure (has side effect) is that it doesn’t take any arguments and it doesn’t return any value.
❖ Function depends on variables or functions outside of its definition block.
❖ It never assure you that the function will behave the same every time it’s called.
Example:
let y:=0
(int) inc (int)x
y:=y+x;
et
return(y)
❖ Here, the result of inc () will change every time if the value of ‘y’ get changed inside the function definition.
❖ Hence, the side effect of inc () function is changing the data of the external variable ‘y’.
i.N
4. Differentiate pure and impure function. (M-2020, M-2024)
Pure Function Impure Function
❖ Pure functions will give exact result when the ❖ Impure functions never assure you that the function
same arguments are passed. will behave the same every time it’s called.
❖ Hence, if you call the pure functions with the ❖ Hence, if you call the impure functions with the same
la
same set of arguments, you will always get the
same return values.
❖ They do not have any side effects.
set of arguments, you might get the different return
values
❖ They have side effects.
sa
❖ They do not modify the arguments which are ❖ They may modify the arguments which are passed to
passed to them them
❖ Example: strlen (), sqrt() ❖ Example: random(), Date()
CHAPTER – 2 ( DATA ABSTRACTION )
da
❖ A concrete data type is a data type whose ❖ Abstract data type the representation of a data type
representation is known. is unknown.
2. Which strategy is used for program designing? Define that Strategy.
❖ A powerful strategy for designing programs: 'wishful thinking'.
❖ Wishful Thinking is the formation of beliefs and making decisions according to what might be pleasing to imagine
w.
68
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
(CHAPTER-3)( SCOPING )
1. Define Local scope with an example. (S-2021)
❖ Local scope refers to variables defined in current function.
❖ A function will always look up for a variable name in its local scope.
i.N
❖ Only if it does not find it there, the outer scopes are checked.
la
sa
Example:
❖ On execution of the above code the variable a displays the value 7, because it is defined and available in the local scope.
2. Define Global scope with an example. (J-2024)
❖ A variable which is declared outside of all the functions in a program is known as global variable.
da
❖ Global variable can be accessed inside or outside of all the functions in a program.
Pa
Example:
w.
❖ On execution of the above code the variable a which is defined inside the function displays the value 7 for the
function call Disp () and then it displays 10, because a is defined in global scope.
3. Define Enclosed scope with an example.
❖ A variable which is declared inside a function which contains another function definition with in it, the inner
ww
function can also access the variable of the outer function. This scope is called enclosed scope.
❖ When a compiler or interpreter searches for a variable in a program, it first search Local, and then search
Enclosing scopes.
Example:
❖ In the above example Disp1() is defined within Disp ().
❖ The variable „a‟ defined in Disp () can be even used by Disp1() because it is also a member of Disp ().
69
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
1. Modules contain instructions, processing logic, and data.2.Modules can be separately compiled and stored in a library.
3. Modules can be included in a program. 4. Module segments can be used by other modules.
5. Module segments can be used by invoking a name and some parameters.
CHAPTER – 4 ( ALGORITHMIC STRATEGIES )
i.N
1. List the characteristics of an algorithm. (M-2022)
1. Input 2.Output 3. Finiteness 4. Definiteness 5. Effectiveness 6. Correctness
7. Simplicity 8. Unambiguous 9. Feasibility 10. Portable 11. Independent
2. Discuss about Algorithmic complexity and its types.
la
❖ The complexity of an algorithm f(n) gives the running time and/or the storage space required by the algorithm in
terms of n as the size of input data.
1.TimeComplexity:
sa
❖ The Time complexity of an algorithm is given by the number of steps taken by the algorithm to complete the process.
2.SpaceComplexity:
❖ Space complexity of an algorithm is the amount of memory required to run to its completion.
❖ The space required by an algorithm is equal to the sum of fixed part and variable part.
da
3. What are the factors that influence time and space complexity?
1.Time Factor:
❖ Time is measured by counting the number of key operations like comparisons in the sorting algorithm.
2.Space Factor:
❖ Space is measured by the maximum memory space required by the algorithm.
Pa
(I (iii) Big Θ:
❖ Complexity case of an algorithm (or) lower bound = upper bound
❖ When an algorithm has a complexity with lower bound = upper bound, say that an algorithm has a complexity O
(n log n) and Ω (n log n.
❖ Time complexity is n log n in both best- case and worst-case.
5. What do you understand by Dynamic programming? (S-2020, M-2023)
❖ Dynamic programming is used when the solution to a problem can be viewed as the result of a sequence of decisions.
❖ Dynamic programming approach is similar to divide and conquer (i.e) the problem can be divided into smaller sub-problems.
❖ Dynamic algorithms uses Memorization.
1. What is an Algorithm? List any three characteristics of an algorithm. (S-2021)
Algorithm:
❖ An algorithm is a finite set of instructions to accomplish a particular task.
❖ It is a step-by-step procedure for solving a given problem.
❖ An algorithm can be implemented in any suitable programming language.
70
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
2. What are the assignment operators that can be used in Python?
❖ ‘=’ is a simple assignment operator to assign values to variable.
❖ There are various compound operators in Python like +=, -=, *=, /=, %=,**= and //= are also available.
Example:
i.N
a=5 # assigns the value 5 toa
a,b=5,10 # assigns the value 5 to a and 10 to b
a+=2 # a=a+2, add 2 to the value of „a‟ and stores the result in ‘a’(Left hand operator)
3. Explain Ternary operator with examples. (M-2020, M-2023)
❖ Ternary operator is also known as conditional operator
Example: la
❖ It evaluates something based on a condition being true orfalse.
Syntax: Variable Name = [on_true] if [Test expression] else [on_false]
min = 50 if 49<50else70 # Output: min = 50
sa
min = 50 if 49>50else70 # Output: min = 70
4. Write short notes on Escape sequences with examples. (J-2024)
❖ In Python strings, the backslash “\”is a special character, also called the “escape” character.
❖ It is used in representing certain whitespace characters: “\t” is a tab, “\n” is a newline, and “\r” is a carriage return.
da
For example to print the message “It’s raining”, the Python command is
>>> print (“It\’s raining”) It’s rainning
❖ Python supports the following escape sequence characters.
Pa
w.
ww
et
a= int(input("Enter the first number:"))
b= int(input("Enter the second number:"))
c= int(input("Enter the third number:"))
i.N
if(a>b)and(a>c):
print(a, ”is the largest number”)
elif(b>c):
print(b, ”is the largest number”)
else:
la
print(c, ”is the largest number”)
4. Write the syntax of while loop. (J-2022, M-2023, J-2024)
while <condition>:
sa
statements block 1
[else:
statements block2]
5. List the differences between break and continue statements. (M-2022)
da
break continue
❖ The break statement terminates the loop containing it. ❖ The Continue statement is used to skip the
remaining part of a loop
❖ Control of the program flows to the statement ❖ Control of the program flows start with next
immediately after the body of the loop. iteration
Pa
statements-block 1
elif <condition-2>:
statements-block 2
else:
ww
statements-block n
Example : (nested if statement )
Average Grade
>=80 and above A
>=70 and <80 B
>=60 and <70 C
>=50 and <60 D
Otherwise E
Coding:
m1=int (input(“Enter mark in first subject : ”))
m2=int (input(“Enter mark in second subject : ”))
avg= (m1+m2)/2
if avg>=80:
print (“Grade : A”)
elif avg>=70 and avg<80:
72
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
❖ A local variable only exists while the function is executing.
❖ The format arguments are also local to function.
2. Write the basic rules for global keyword in python. (J-2022, J-2024)
i.N
❖ When we define a variable outside a function, it’s global by default.
❖ You don’t have to use global keyword.
❖ We use global keyword to read and write a global variable inside a function.
❖ Use of global keyword outside a function has no effect.
3. What happens when we modify global variable inside the function?
la
❖ If we modify the global variable, we can see the change on the global variable outside the function also.
Example:
c=1 #global variable
sa
def add ( ):
c=c+2 #increment c by 2
print c
add ( )
da
Example:
❖ if we wish to take a numeric value as a input from the user, we take the input string from the user using the
function input () and apply eval () function to evaluate its value.
7. How recursive function works? (M-2020)
❖ Recursive function is called by some external code.
❖ If the base condition is met then the program gives meaningful output and exits.
❖ Otherwise, function does some required processing and then calls itself to continue recursion.
8. What are the points to be noted while defining a function?
❖ Function blocks begin with the keyword “def” followed by function name and parenthesis ().
❖ Any input parameters should be placed within these parentheses when you define a function.
❖ The code block always comes after a colon (:) and is indented.
❖ The statement “return [expression]” exits a function, optionally passing back an expression to the caller.
❖ A “return” with no arguments is the same as return none.
73
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
Output: TaMIlnAdU
3. What will be the output of the given python program?
str1 = "welcome" str2 = "to school" str3=str1[:2]+str2[len(str2)-2:] print(str3) Output - weol
i.N
4. What is the use of format ( )? Give an example.
❖ The format () function used with strings is very versatile and powerful function used for formatting strings.
❖ The curly braces {} are used as placeholders or replacement fields which get replaced along with format () function.
Example: Output:
num1=int (input(“Number 1: “)) Number 1: 34
5.
la
num2=int (input(“Number 2: “)) Number 2: 54
print (“The sum of { } and { } is { }”.format(num1, num2,(num1+num2))) The sum of 34 and 54 is 88
Write a note about count () function in python.
sa
❖ Returns the number of substrings occurs within the given range.
❖ Remember that substring may be a single character.
❖ Range (beg and end) arguments are optional. If it is not given, python searched in whole string.
❖ Search is case sensitive.
da
74
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
4. Explain the difference between del and clear( ) in dictionary with an example
del Clear ()
❖ The del statements is used to delete known ❖ The function clear () is used to delete all the
elements. elements in list
❖ The del statement can also be used to delete entire list ❖ It deletes only the elements and retains the list
5. List out the set operations supported by python.
❖ Union : It includes all elements from two or more sets.
❖ Intersection: It includes the common elements in two sets.
❖ Difference : It includes all elements that are in first set (say set A) but not in the second set (say set B).
❖ Symmetric difference: It includes all the elements that are in two sets (say sets A and B) but not the one that are
common to two sets.
6. What are the difference between List and Dictionary? (J-2023)
List Dictionary
❖ A list is an ordered collection of values or ❖ A dictionary is a mixed collection of elements and it
elements of any type stores a key along with its element.
❖ It is enclosed within square brackets [] ❖ The key value pairs are enclosed with curly braces {}.
❖ The keys in a Python dictionary is separated by a colon (:)
et
❖ The commas work as a separator for the
elements. while the commas work as a separator for the elements.
Syntax: Syntax:
Variable = [element-1, element-2, element-3 …… Dictionary_Name =
i.N
element-n] {Key_1:Value_1,Key_2:Value_2,Key_n:Value_n }
1. What are the advantages of Tuples over a list? (S-2021)
❖ The elements of a list are changeable (mutable) whereas the elements of a tuple are unchangeable (immutable),
this is the key difference between tuples and list.
❖ The elements of a list are enclosed within square brackets.
2.
la
❖ But, the elements of a tuple are enclosed by parenthesis. Iterating tuples is faster than list.
What will be the output of the following code? (M-2020)
list = [3**x for x in range(5)] print(list) Output : [ 1,3,9,27,81 ]
sa
CHAPTER – 10 ( PYTHON CLASSES AND OBJECTS )
1. What are class members? How do you define it? (S-2021)
❖ Variables defined inside a class are called as “Class Variable” and functions are called as “Methods”.
❖ Class variable and methods are together known as members of the class.
da
statement_1
statement_2
…………..
…………..
statement_n
2. Write a class with two private class variables and print the sum using a method.
w.
Class Sample:
def_init_(self,n1,n2): Output:
self._n1=n1 Class variable 1 :5
self._n2=n2 Class variable 2 :10
ww
et
❖ It is just opposite to constructor.
General format of destructor: def _ _del_ _(self):
<statements>
i.N
1. Write a short note on Public and Private data member in Python? (S-2020)
❖ 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
la
2. What is the output of the following program? (M-2020)
class Greeting:
def __init__(self, name):
sa
self.__name = name
def display(self): Output
print("Welcome to ", self.__name) Welcome to Python Programming
obj=Greeting('Python Programming')
obj.display()
da
❖ DBA takes care of the security of the DBMS, managing the license keys, managing user accounts and access etc.
3. Explain Cartesian Product with a suitable example.
❖ Cross product is a way of combining two relations.
❖ The resulting relation contains, both relations being combined.
❖ This type of operation is helpful to merge columns from two relations.
Example: A x B means A times B, where the relation A and B have different attributes.
4. Explain Object Model with example.
❖ 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.
76
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
4.Database designers:
❖ They are responsible for identifying the data to be stored in the database for choosing appropriate structures to
represent and store the data
CHAPTER – 12 ( STRUCTURED QUERY LANGUAGE )
i.N
1. What is a constraint? Write short note on Primary key constraint.
❖ Constraint is a condition applicable on a field or set of fields.
❖ Primary constraint declares a field as a Primary key which helps to uniquely identify a record.
❖ It is similar to unique constraint except that only one field of a table can be set as primary key.
la
❖ The primary key does not allow NULL values and therefore a primary key field must have the NOT NULL constraint.
2. Write a SQL statement to modify the student table structure by adding a new field. (J-2022)
Syntax: ALTER TABLE < table-name> ADD <column-name><data type><size>;
sa
❖ To add a new column “Address” of type ‘char’ to the Student table, the command is used as
Statement: ALTER TABLE Student ADD Address char;
3. Write any three DDL commands. (S-2021)
1.Create Command: To create tables in the database.
da
❖ CREATE TABLE Student (Admno integer, Name char(20), Gender char(1), Age integer);
2.Alter Command: Alters the structure of the database.
❖ ALTER TABLE Student ADD Address char;
3.Drop Command: Delete tables from database.
❖ DROP TABLE Student;
Pa
❖ The DISTINCT keyword is used along with the SELECT command to eliminate duplicate rows in the table.
❖ This helps to eliminate redundant data.
Example: SELECT DISTINCT Place FROM Student;
1. What is the use of DELETE, TRUNCATE and DROP commands in SQL? (S-2020)
DELETE TRUNCATE DROP
❖ The DELETE command ❖ The TRUNCATE command is ❖ The DROP TABLE command
permanently removes one or used to delete all the rows from is used to remove a table from
more records from the table. the table, the structure remains the database once a table is
❖ It removes the entire row, not and the space is freed from the dropped we cannot get it back,
individual fields of the row. table. so be careful while using DROP
❖ so no field arguments is needed. Syntax : TABLE command.
Syntax : TRUNCATE TABLE tablename; Syntax :
DELETE FROM tablename DROP TABLE table-name;
WHERE condition;
77
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
reader = csv.reader(read File)
lines = list(reader)
lines[3] = row
i.N
with open(‘student.csv’, ‘w’) as write File:
writer = csv.writer(write File)
writer.write rows(lines)
read File.close()
write File.close()
la
❖ In this program, the third row of “student.csv” is modified andsaved.
❖ First the “student.csv” file is read by using csv.reader () function.
❖ Then, the list() stores each row of thefile.
sa
❖ The statement lines[3] = row”, changed the third row of the file with the new content in“row”.
❖ The file object writer using write rows (lines) writes the values of the list to “student.csv”file.
3. Write a Python program to read a CSV file with default delimiter comma (,)
import csv
da
Output
[‘SNO’, ‘NAME’, ‘CITY’]
[‘12101’, ‘RAM’, ‘CHENNAI’]
[‘12102’, ‘LAVANYA’, ‘TIRUCHY’]
[‘12103’, ‘LAKSHMAN’, ‘MADURAI’]
w.
4. What is the difference between the write modes and append mode? (S-2021)
‘w’-write mode ‘a’ Append mode
❖ Opens a file forwriting. ❖ Open for appending at the end of the file without truncating it.
❖ Creates a new file if it does not exist or ❖ Create a new file if it does not exist.
ww
78
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
4. Identify the module, operator, definition name for the following: Welcome . display() (J-2022)
Welcome - Definition name
. - Dot Operator
i.N
Display - Module name
5. What is sys.argv? What does it contain? (M-2022)
❖ Sys.argv is the list of command-line arguments passed to the Python program.
❖ Argv contains all the items that come along via the command-line input, it’s basically an array holding the
command-line arguments of the program.
la
To use sys.argv, you will first have to import sys.
❖ Sys.argv[0] is always the name of the program as it was invoked.
❖ Sys.argv[1] is the first argument you pass to the program.
sa
Main(sys.argv[1])
❖ Accepts the program file(py program) and the input file (C++ file)as a list(array)
❖ Argv [0] contains the python program which is need not to be passed because by default _main_ contains source code reference.
❖ Argv [1] contains the name of the C++ file which is to be processed.
da
1. Write about the steps of python program executing C++ program using control statement (M-2023)
1. Type the c++ program in notepad and save it as with .cpp extension.
2. Type the python program and save it as with .py extension.
3. Click the Run Terminal and open the command window
4. Type the command python <program_name.py> -i<c++ program>
Pa
❖ It is designed to be embedded in applications, instead of using a separate database server program such as MySQL or Oracle.
Advantages:
❖ SQLite is fast, rigorously tested, and flexible, making it easier to work.
❖ Python has a native library for SQLite.
ww
2. Mention the difference between fetch one ( ) and fetch many ( ) (M-2020, J-2022, M-2023, J-2024)
fetch one () Fetch many ()
❖ The fetch one () method returns the next row of a ❖ The fetch many () method returns the next number of
query result set or none in case there is no row left. rows (n) of the result set.
❖ Using while loop and fetch one() method we can ❖ Displaying specified number of records is done by
display all the records from a table using fetch many ()
3. What is the use of Where clause. Give a python statement Using the where Clause. (M-2022, M-2024)
❖ The WHERE clause is used to extract only those records that full fill a specified condition.
Example :
import sqlite3
connection = sqlite3.connect(“Academy.db”)
cursor = connection.cursor()
cursor.execute (“SELECT DISTINCT (Grade) FROM student where gender=’M’”)
result = cursor.fetchall()
print(*result,sep=”\n”)
79
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
4. Read the following details. Based on that write a python script to display department wise record.
Databasename :-organization.db
Tablename :-Employee
Columns in the table :- Eno, EmpName, Esal,Dept
Code:
import sqlite3
connection = sqlite3.connect(“ organization .db ”)
c= conn.execute(“SELECT * FROM Employee GROUP BYDept”)
for row inc:
print(row)
conn.close()
5. Read the following details. Based on that write a python script to display records in descending order of eno.
Database name :-organization.db
Table name :-Employee
Columns in the table :- Eno, EmpName, Esal, Dept
Code:
import sqlite3
et
connection = sqlite3.connect(“ organization.db ”)
cursor=connection.cursor()
cursor.execute(“SELECT * FROM Employee ORDER BY Eno DESC”)
result=cursor.fetchall()
i.N
print(result)
1. Write a short note on a) Group by b) Order by clause in SQL (S-2020)
SQL Group By Clause:
❖ The SELECT statement can be used along with GROUP BY clause.
la
❖ The GROUP BY clause groups records into summary rows.
❖ It returns one records for each group.
❖ It is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns.
sa
SQL ORDER BY Clause:
❖ The ORDER BY Clause can be used along with the SELECT statement to sort the data of specific fields in an ordered way.
❖ It is used to sort the result-set in ascending or descending order.
CHAPTER – 16 ( DATA VISUALIZATION USING PYPLOT: LINE , PIE AND BAR CHAT )
1. Draw the output for the following data visualization plot.
da
plt.xlabel(‘bar number’)
plt.ylabel(‘bar height’)
plt.title(‘Epic Graph\nAnother Line! Whoa’)
plt.show()
Output:
w.
ww
80
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
i.N
Output: la
sa
import matplotlib.pyplot as plt
slices = [7,2,2,13]
activities = [‘sleeping’,‘eating’,’working’,’playing’]
plt.pie(slices, labels=activities, atopct = ‘y.1.1 f%%’)
da
81
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
4. Mention the characteristics of interface.
❖ The class template specifies the interfaces to enable an object to be created and operated properly.
❖ An object's attributes and behaviour is controlled by sending functions to the object.
i.N
CHAPTER – 2 ( DATA ABSTRACTION )
1. What is selector? What are the parts of a program?
Selector:
❖ Selectors are functions that retrieve information from the data type.
❖ Selectors extract individual pieces of information from the object.
Program parts:
la
❖ Any program consist of two parts.
❖ The two parts of a program are, the part that operates on abstract data and the part that defines a concrete representation.
sa
2. Define abstraction. What is abstract data types?
Abstraction:
❖ The process of providing only the essentials and hiding the details is known as abstraction.
Abstract data type:
da
❖ Abstract Data type (ADT) is a type (or class) for objects whose behaviour is defined by a set of value and a set of operations.
❖ The definition of ADT only mentions what operations are to be performed but not how these operations will be implemented.
3. Give an example of Implementing an ADT.
❖ For the example the list ADT can be implemented using singly linked List or doubly liked list.
❖ Similarly, Stack ADT and Queue ADT can be implemented using lists.
Pa
Selectors:
- - selector
xcoord(point):
ww
return point[0]
- -selector
ycoord(point):
return point[1]
5. What are the different ways to access the elements of a list. Give example.
❖ The elements of a list can be accessed in two ways.
❖ The first way is via our familiar method of multiple assignment, which unpacks a list into its elements and binds
each element to a different name.
lst := [10, 20]
x, y := lst [In the above example x will become10 and y will become 20.]
❖ A second method for accessing the elements in a list is by the element selection operator.
lst[0]
10
lst[1]
20 [In both the example mentioned above mathematically we can represent list similar to a set]
82
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
(CHAPTER-3) ( SCOPING )
1. Write any three characteristics of modules.
1.Modules contain instructions, processing logic, and data.
2.Modules can be separately compiled and stored in a library.
3.Modules can be included in a program.
4.Module segments can be used by invoking a name and some parameters.
5.Module segments can be used by other modules
2. What is outer x variable and inner x variable?
❖ The value ‘outer x variable’ is printed when x is referenced outside the function definition.
❖ Whereas when display() gets executed, ‘inner x variable’ is printed which is the x value inside the function definition.
3. Compare Public protected and private members:
❖ Public members (generally methods declared in a class) are accessible from outside the class.
❖ Protected members of a class are accessible from within the class and are also available to its sub-classes
❖ Private members of a class are denied access from the outside the class.
❖ They can be handled only from within the class.
CHAPTER – 4 ( ALGORITHMIC STRATEGIES )
1. 1.Write the difference between Algorithm and Program.
et
Algorithm Program
❖ Algorithm helps to solve a given problem logically and it ❖ Program is an expression of algorithm in a
can be contrasted with the program Programming language
i.N
❖ Algorithm can be categorized based on their ❖ Algorithm can be implemented by structured or object
implementation methods, design techniques etc. oriented programming approach.
❖ There is no specific rules for algorithm writing but some ❖ Program should be written for the selected
guidelines should be followed. language with specific syntax
❖ Algorithm resembles a pseudo code which can be ❖ Program is more specific to a programming
implemented in any language language
2.
la
2.Write a Pseudo code for linear search.
1. Traverse the array using for loop
2. In every iteration, compare the target search key value with the current value of the list.
sa
3. If the values match, display the current index and value of the array
4. If the values do not match, move on to the next array element.
5. If no match is found, display the search element not found.
3. 3.Write a Pseudo code for bubble sort algorithm.
da
1. Start with the first element i.e., index = 0, compare the current element with the next element of the array.
2. If the current element is greater than the next element of the array, swap them.
3. If the current element is less than the next or right side of the element, move to the next element.
4. Go to Step 1 and repeat until end of the index is reached.
Pa
4. 4.What are the different phases of analysis and performance evaluation of an algorithm?
❖ Two different phases (1.A priori estimates 2.A posterior testing)
1.A Priori estimates:
❖ This is a theoretical performance analysis of an algorithm. Efficiency of an algorithm is measured by assuming the external factors.
2.A Posterior testing:
❖ This is called performance measurement.
w.
❖ In this analysis, actual statistics like running time and required for the algorithm executions are collected.
5. 5.What are the factors that measure the execution time of an algorithm?
❖ A fixed part is defined as the total space required to store certain data and variables for an algorithm.
❖ For example, simple variables and constants used in an algorithm.
ww
❖ A variable part is defined as the total space required by variables, which sizes depends on the problem and its iteration.
❖ For example: recursion used to calculate factorial of a given value n.
CHAPTER – 5 ( PYTHON - VARIABLES AND OPERATORS)
1. 1.What are the rules to be followed while creating an identifier in Python?
❖ An Identifier is a name used to identify a variable, function, class, module or object.
❖ An identifier must start with an alphabet (A..Z or a… z) or underscore (_ ).
❖ Identifiers may contain digits (0 .. 9) Identifiers must not be a python keyword.
❖ Python identifiers are case sensitive i.e. uppercase and lowercase letters are distinct.
❖ Python does not allow punctuation character such as %,$, @ etc., within identifiers
2. Explain comments in python.
❖ In Python, comments begin with hash symbol (#).
❖ The lines that begins with # are considered as comments and ignored by the Python interpreter.
❖ Comments may be single line or no multi-lines.
❖ The multiline comments should be enclosed within a set of ''' '''(triple quotes) as given below.
# It is Single line Comment ''' It is multiline comment which contains more than one line '''
83
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
❖ Recall while loop belongs to entry check loop type, that is it is not executed even once if the condition is tested
False in the beginning.
i.N
la
sa
3. Write the syntax of if..elif..else statement in python.
if <condition-1>:
statements-block 1
da
elif <condition-2>:
statements-block 2
else:
statements-block n
Pa
Following is an example to illustrate the use of for loop to print the following pattern
1 12 123 1234 12345
CHAPTER – 7 ( PYTHON FUNCTIONS )
1. Evaluate the following function.
ww
et
❖ Here is an example program that defines a function that helps to pass parameters into the function.
CHAPTER – 8 ( STRINGS AND STRING MANIPULATION )
1. 5.What is the use of the operator += in python string operation. (or)
i.N
Write a short note on string slicing with syntax and example.
❖ Slice is a substring of a main string.
❖ A substring can be taken from the original string by using [ ] operator and index or subscript values.
❖ Thus,[] is also known as slicing operator.
❖ Using slice operator, you have to slice one or more sub strings from a main string.
General format of slice operation: str[start:end]
la
❖ Where start is the beginning index and end is the last index value of a character in the string.
❖ Python takes the end value less than one from the actual index specified.
❖ For example, if you want to slice first 4 characters from a string, you have to specify it as 0 to 5.
sa
❖ Because, python consider only the end value as n-1.
Example: slice a single character from a string
>>> str1="THIRUKKURAL"
>>> print (str1[0]) Ans: T
2. What will be output of the following python program? Output: well
da
str1 = "welcome"
str2 = "to school"
str3 = str1[:3]+str2[len(str2)-1:]
print(str3)
Pa
Positive subscript 0 1 2 3 4 5
Negative subscript -6 -5 -4 -3 -2 -1
4. 1Explain about slicing and slicing with stride.
1❖ Slice is a substring of a main string.
❖ A substring can be taken from the original string by using [ ] operator and index or subscript values.
❖ Thus, [ ] is also known as slicing operator.
❖ Using slice operator, you have to slice one or more substrings from a main string.
General format of slice operation :Str[start : end]
❖ When the slicing operation, you can specify a third argument as the stride, which refers to the number of characters to move
forward after the first character is retrieved from the string.
❖ The default value of stride is 1.
5. Write a note on string formatting operators of python.
❖ The string formatting operator is one of the most exciting feature of python.
❖ The formatting operator % is used to construct strings, replacing parts of the strings with the data stored in variables.
Syntax: (“String to be display with %val1 and %val2” %(val1, val2))
85
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
Example:
name = "Rajarajan"
mark = 98
print ("Name: %s and Marks: %d" %(name, mark))
Output: Name: Rajarajan and Marks: 98
6. Write a python program to display given pattern
str1="COMPUTER" C
index=0 CO
for i in str1: COM
print(str[ :index+1]) COMP
index+=1 COMPU
COMPUT
COMPUTE
COMPUTER
7. List out formatting characters
Format characters USAGE
%c Character
%d (or) %i Signed decimal integer
et
%s String
%u Unsigned decimal integer
%o Octal integer
i.N
%x or %X Hexadecimal integer (lower case x refers a-f; upper case X refers A-F)
%e or %E Exponential notation
%f Floating point numbers
%g or %G Short numbers in floating point or exponential notation.
8. Explain about escape sequences supported by python.
\newline
\\ la
Escape Sequence DESCRIPTION
Backslash and newline ignored
Backslash
\f
\n
ASCII Form feed
ASCII Linefeed
sa
\' Single quote \r ASCII Carriage Return
\" Double quote \t ASCII Horizontal Tab
\a ASCII Bell \v ASCII Vertical Tab
\b ASCII Backspace \ooo Character with octal value ooo
da
i=0
sum = 0
while i< 4:
sum+=Marks[i]
i+=1
w.
Answer:
iteration i while i<4 print (Marks [i]) i=i+1
1 0 0<4 True Marks [0] = 10 0+1=1
2 1 1<4 True Marks [1] = 20 1+1=2
ww
3. What is dictionary?
❖ 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 { }.
4. 1What is reverse using indexing list?
❖ The python sets-1 the index value for the last element in list and -2 for the preceding element and so on.
❖ This is called as Reverse Indexing.
5. 2Write a short note on pop () function in Python.
❖ Pop () function can IS 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.
Example:
>>>MyList=[12,34,'Kannan', 'Gowrisankar', 'Lenin']
>>>MyList.pop(1) Ans: 34
>>> print(MyList) [12, 'Kannan', 'Gowrisankar', 'Lenin']
6. 3Explain list and Tuples :
List:
❖ A list in Python is known as a “sequence data type” like strings.
et
❖ 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, string.
i.N
Tuples:
❖ Tuples consists of a number of values separated by comma and enclosed with in Parentheses.
❖ Tuple is similar to list, values in a list can be changed but not in a tuple.
7. 4Write short note on (i) Remove (ii) clear
(i) Remove:
la
❖ Remove ( ) function is used to delete elements of a list if its index is unknown.
❖ Remove ( ) function can also be used to delete one or more elements if the index value is not known.
(ii) Clear:
sa
❖ The function clear( ) is used to delete all the elements in list, it deletes only the elements and retains the list
❖ Clear ( ) function removes only the elements and retains the list
8. Write short note on Sort ( ) function with suitable examples.
Sort ( )
da
Example :
MyList=['Thilothamma', 'Tharani', 'Anitha', 'SaiSree', 'Lavanya'] Output
MyList.sort( ) ['Anitha', 'Lavanya', 'SaiSree', 'Tharani', 'Thilothamma']
print(MyList) ['Thilothamma', 'Tharani', 'SaiSree', 'Lavanya', 'Anitha']
MyList.sort(reverse=True)
w.
print(MyList)
CHAPTER – 10 ( PYTHON CLASSES AND OBJECTS )
1. 1.Write a short note on Public and Private data member in Python?
❖ The variables which are defined inside the class is public by default.
ww
❖ 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.
2. What is the output of the following program?
class Greeting:
def__init__(self, name): Output: Good Morning Tamil Nadu
self.__name = name
def display(self):
print("Good Morning", self.__name)
obj=Greeting('Tamil Nadu') obj.display()
3. What is constructor?
❖ Constructor is the special function that is automatically executed when an object of a class is created.
❖ In Python, there is a special function called “init” which act as a Constructor.
❖ It must begin and end with double underscore.
❖ This function will act as an ordinary function; but only difference is, it is executed automatically when the object is created.
❖ This constructor function can be defined with or without arguments.
87
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
print("Welcome to ", self.__name) Welcome to Python Programming
obj=Greeting('Python Programming')
obj.display()
i.N
CHAPTER – 11 ( DATABASE CONCEPTS )
1. Write a short note on Unary Relational Operations of DBMS.
❖ A unary operator is an operator that operates on only one operant.
❖ An operator is referred to as binary if it operates on two operands.
Unary Relational Operations: 1.SELECT (Symbol : σ) 2.PROJECT (Symbol : π)
2.
la
1.What are the components of DBMS?
1. Hardware: The computer, hard disk, I/O channels for data, and any other physical component involved in storage of data.
2. Software:
sa
❖ The DBMS software is capable of understanding the Database Access Languages and interprets into database
commands for execution.
3. Data: It is the resource for which DBMS is designed.
4. Procedures/Methods:
da
❖ They are general instructions to use a database management system such as installation of DBMS, manage
databases to take backups, report generation, etc.
5. Data Base Access Languages:
❖ They are the languages used to write commands to access, insert, update and delete data stored in any database.
3. 2.Differentiate between data and information
Pa
1.Data:
❖ Data are raw facts stored in a computer.
❖ A data may contain any character, text, word or a number.
Example : 600006, DPI Campus, SCERT, Chennai, College Road
2.Information:
w.
1. Commit : Saves any transaction into the database permanently. Syntax: COMMIT;
2. Roll back : Restores the database to last commit state. Syntax: ROLL BACK TO save point name;
3. Save point: Temporarily save a transaction. Syntax: SAVEPOINT savepoint_name;
2. Explain about SQL:
❖ The Structured Query Language (SQL) is a standard programming language to access and manipulate databases. SQL allows
the user to create, retrieve, alter, and transfer information among databases.
❖ It is a language designed for managing and accessing data in a Relational Data Base Management System (RDBMS).
❖ There are many versions of SQL.
❖ The original version was developed at IBM’s Research centre and originally called as Sequel in early 1970’s.
❖ Later the language was changed to SQL. In 1986, ANSI (American National Standard Institute) published an SQL standard
that was updated again in 1992, the latest SQL was released in 2008 and named as SQL 2008.
CHAPTER – 13 ( PYTHON AND CSV FILES )
1. 1.Write about CSV files?
❖ A CSV file is a human readable text file where each line has a number of fields, separated by commas or some other delimiter.
❖ You can assume each line as a row and each field as a column.
88
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
2. Type the python program and save it as with .py extension.
3. Click the Run Terminal and open the command window
4. Type the command python <program_name.py> -i<c++ program>
i.N
CHAPTER – 15 ( DATA MANIPULATION THROUGH SQL )
1. 1.Write a short note on(i) fetchall() (ii) fetchone() (iii) fetchmany
(i) cursor.fetchall(): fetchall () method is tofetch all rows from the database table.
(ii) cursor.fetchone():The fetchone () method returns the next row of a query result set or none in case there is no row left.
(iii) cursor.fetchmany(): Method that returns the next number of rows (n) of the result.
la
2. Write a short note on a) Group by b) Order by clause in SQL
SQL Group By Clause:
❖ The SELECT statement can be used along with GROUP BY clause.
sa
❖ The GROUP BY clause groups records into summary rows. It returns one records for each group.
❖ It is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns.
SQL ORDER BY Clause:
❖ The ORDER BY Clause can be used along with the SELECT statement to sort the data of specific fields in an ordered way.
❖ It is used to sort the result-set in ascending or descending order.
da
CHAPTER – 16 ( DATA VISUALIZATION USING PYPLOT: LINE , PIE AND BAR CHAT )
1. Define data visualization. Mention its types and uses.
❖ Data Visualization is the graphical representation of information and data.
❖ The objective of Data Visualization is to communicate information visually to users.
Pa
❖ The point of a pie chart is to show the relationship of parts out of a whole.
❖ To make a Pie Chart with Matplotlib, we can use the plt.pie()function.
❖ The autopct parameter allows us to display the percentage value using the Python string formatting .
Example :
import matplotlib.pyplot as plt
sizes = [89, 80, 90, 100, 75]
labels = ["Tamil", "English", "Maths", "Science", "Social"]
plt.pie (sizes, labels = labels, autopct = "%.2f ") plt.axes().set_aspect ("equal") plt.show()
89
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
❖ This is called parameter without type.
❖ In the above function definition the expression has type ‘int’, so the function's return type also be ‘int’ by implicit.
(ii) Parameter With Type:
i.N
Now let us write the same function definition with types,
(requires: b>=0 )
(returns: a to the power of b)
let rec pow (a:int)(b:int):int:=
if b=0 then 1
la
else a * pow b (a-1)
❖ In this example we have explicitly annotating the types of argument and return type as ‘int’.
❖ Here, when we write the type annotations for ‘a’ and ‘b’ the parentheses are mandatory.
sa
❖ This is the way passing parameter with type which helps the compiler to easily infer them.
2. Identify in the following program.
let rec gcd a b :=
if b < > 0 then gcd b (a mod b) else return a
da
90
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
i.N
❖
la
Let's take the example of increasing a car’s speed.
sa
❖ The person who drives the car doesn't care about the internal working.
❖ To increase the speed of the car he just presses the accelerator to get the desired behaviour.
❖ Here the accelerator is the interface between the driver (the calling / invoking object) and the engine (the called object).
❖ In this case, the function call would be Speed (70): This is the interface.
da
1. How will you facilitate data abstraction? Explain it with suitable example. (J-2023, M-2024)
❖ Data abstraction is supported by defining an abstract data type (ADT), which is a collection of constructors and selectors.
❖ To facilitate data abstraction, you will need to create two types of functions: 1.Constructor 2.Selectors
1.Constructor:
❖ Constructors are functions that build the abstract data type.
w.
❖ To extract the information of a city object, you would use functions like
getname(city) getlat(city) getlon(city)
❖ Here make city (name, lat, lon) is the constructor which creates the object city.
2.Selectors:
❖ Selectors are functions that retrieve information from the data type.
❖ Selectors extract individual pieces of information from the object.
91
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
2. What is a List? Why List can be called as Pairs. Explain with suitable example. (M-2023)
I. List:
❖ List is constructed by placing expressions within square brackets separated by commas.
❖ Such an expression is called a list literal. List can store multiple values.
❖ Each value can be of any type and can even be another list.
❖ The elements of a list can be accessed in two ways.
1. Multiple Assignment:
et
❖ Which unpacks a list into its elements and binds each element to a different name.
Example: lst := [10, 20] x, y := lst x will become10 and y will become 20.
2. Element Selection Operator:
❖ It is expressed using square brackets.
i.N
❖ Unlike a list literal, a square-brackets expression directly following another expression does not evaluate to a
list value, but instead selects an element from the value of the preceding expression.
Example: lst[0] 10 lst[1] 20
II. Pair:
❖ Any way of bundling two values together into one can be considered as a pair.
Example:
la
❖ Lists are a common method to do so. Therefore List can be called as Pairs.
lst[(0,10),(1,20)]
sa
da
class Person:
creation( )
firstName := " "
lastName := " "
id := " "
w.
92
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
❖ The class (structure) construct defines the form for multi-part objects that represent a person.
❖ Person is referred to as a class or a type, while p1 is referred to as an object or an instance
❖ Using class you can create many objects of that type.
❖ Class defines a data abstraction by grouping related data items.
❖ A class as bundled data and the functions that work on that data that is using class we can access multi-part items.
CHAPTER - 3 ( SCOPING )
1. Explain the types of scopes for variable or LEGB rule with example. (S-2021, M-2022, M-2024)
Scope:
❖ Scope refers to the visibility of variables, parameters and functions in one part of a program to another part of
the same program.
Types of variable scope:
❖ 1.Local Scope 2.Enclosed Scope 3.Global Scope 4.Built-in Scope
LEGB rule:
❖ The LEGB rule is used to decide the order in which the scopes are to be searched for scope resolution.
❖ The scopes are listed below in terms of hierarchy (highest to lowest).
1.Local scope:
❖ Local scope refers to variables defined in current function.
et
❖ A function will always look up for a variable name in its local scope.
❖ Only if it does not find it there, the outer scopes are checked.
i.N
Example:
la
sa
❖ On execution of the above code the variable a displays the value 7, because it is defined and available in the local scope.
2.Enclosed scope:
❖ A variable which is declared inside a function which contains another function definition with in it, the inner
function can also access the variable of the outer function.
❖ This scope is called enclosed scope.
da
❖ When a compiler or interpreter searches for a variable in a program, it first search Local, and then search
Enclosing scopes.
Pa
w.
Example:
❖ In the above example Disp1() is defined within Disp().
❖ The variable ‘a’ defined in Disp() can be even used by Disp1() because it is also a member of Disp().
3.Global scope:
ww
❖ A variable which is declared outside of all the functions in a program is known as global variable.
❖ Global variable can be accessed inside or outside of all the functions in a program.
Example:
❖ On execution of the above code the variable a which is defined inside the function displays the value 7 for the
function call Disp() and then it displays 10, because a is defined in global scope.
93
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
4.Built-in-scope:
❖ The built-in scope has all the names that are pre-loaded into the program scope when we start the compiler or interpreter.
❖ Any variable or module which is defined in the library functions of a programming language has Built-in or module scope.
et
5. Module segments can be used by other modules
3. Write any five benefits in using modular programming.
1. Less code to be written.
i.N
2. A single procedure can be developed for reuse, eliminating the need to retype the code many times.
3. Programs can be designed more easily because a small team deals with only a small part of the entire code.
4. Modular programming allows many programmers to collaborate on the same application.
5. The code is stored across multiple files.
6. Code is short, simple and easy to understand.
la
7. Errors can easily be identified, as they are localized to a subroutine or function.
8. The same code can be used in many applications.
9. The scoping of variables can easily be controlled
sa
CHAPTER – 4 ( ALGORITHMIC STRATEGIES )
1. Explain the characteristics of an algorithm.
1. Input ❖ Zero or more quantities to be supplied
2. Output ❖ At least one quantity is produced.
da
11. Independent ❖ An algorithm should have step-by-step directions, which should be independent of
any programming code.
2. Discuss about Linear search algorithm. (M-2020, J-2020, J-2022, M-2023)
Linear search:
ww
❖ Linear search also called sequential search is a sequential method for finding a particular value in a list.
❖ This method checks the search element with each element in sequence until the desired element is found or the
list is exhausted.
❖ In this searching algorithm, list need not be ordered.
Pseudo code:
1. Traverse the array using for loop
2. In every iteration, compare the target search key value with the current value of the list.
❖ If the values match, display the current index and value of the array.
❖ If the values do not match, move on to the next array element.
3. If no match is found , display the search element not found
Example:
❖ To search the number 25 in the array given below, linear search will go step by step in a sequential order
starting from the first element in the given array if the search element is found that index is returned otherwise
the search is continued till the last index of the array.
❖ In this example number 25 is found at index number 3.
94
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
Index 0 1 2 3 4
Values 10 12 20 25 30
Snippet:
Input: values[ ] = {0, 12,20, 25, 30}
target = 25 ( Output: 3 )
Example 1: Example 2:
Input: values[ ] = {5, 34, 65, 12, 77, 35} Input: values[ ] = {101, 392, 1, 54, 32, 22, 90, 93}
target = 77 (Output: 4) target = 200
3. What is Binary search? Discuss with example. (S-2021, J-2023, M-2024)
Binary search:
❖ Binary search also called half-interval search algorithm.
❖ It finds the position of a search element within a sorted array.
❖ The binary search algorithm can be done as divide-and-conquer search algorithm and executes in logarithmic time.
Pseudo code for Binary search:
1. Start with the middle element:
a) If the search element is equal to the middle element of the array, then return the index of the middle element.
et
b) If not, then compare the middle element with the search value,
c) If (Search element > number in the middle index), then select the elements to the right side of the middle
index, and go to Step-1.
i.N
d) If (Search element < number in the middle index), then select the elements to the left side of the middle
index, and start with Step-1.
2. When a match is found, display success message with the index of the element matched.
3. If no match is found for all comparisons, then display unsuccessful message.
Binary Search Working principles with example:
la
❖ List of elements in an array must be sorted first for Binary search.
❖ The array is being sorted in the given example and it is suitable to do the binary search algorithm.
❖ Let us assume that the search element is 60 and we need to search the location or index of search element 60
sa
using binary search.
❖ First, we find index of middle element of the array by using this formula:
da
❖ Now compare the search element with the value stored at mid value location 4.
❖ The value stored at location or index 4 is 50, which is not match with search element.
❖ As the search value 60 is greater than 50.
w.
❖ Now we change our low to mid + 1 and find the new mid value again using the formula.
low = mid + 1
mid = low + (high - low) / 2
❖ Our new mid is 7 now. We compare the value stored at location 7 with our target value 60.
ww
❖ The value stored at location or index 7 is not a match with search element, rather it is more than what we are
looking for.
❖ So, the search element must be in the lower part from the current mid value location
❖ The search element still not found. Hence, we calculated the mid again by using the formula.
high = mid -1
mid = low + (high - low)/2
❖ Now the mid value is 5.
❖ Now we compare the value stored at location 5 with our search element.
95
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
i.N
la
sa
❖ Below, we have a pictorial representation of how bubble sort.
❖ The above pictorial example is for iteration-1.
❖ Similarly, remaining iteration can be done.
❖ The final iteration will give the sorted array.
da
❖ The given problem is divided into smaller and yet smaller possible sub problems.
❖ Dynamic programming is used whenever problems can be divided into similar sub-problems.
❖ So that their results can be re-used to complete the process.
❖ Dynamic programming approaches are used to find the solution in optimized way.
Steps to do Dynamic programming:
w.
The following example shows a simple Dynamic programming approach for the generation of Fibonacci series.
❖ Initialize f0=0, f1 =1
❖ Step-1: Print the initial values of Fibonacci f0 and f1 Step-2: Calculate Fibonacci fib ← f0 + f1
❖ Step-3: Assign f0← f1, f1← fib Step-4: Print the next consecutive value of Fibonacci fib
❖ Step-5: Go to step-2 and repeat until the specified number of terms generated
For example if we generate Fibonacci series up to 10 digits, the algorithm will generate the series as shown below:
❖ The Fibonacci series is :0 1 1 2 3 5 8 13 21 34 35
CHAPTER – 5 ( PYTHON - VARIABLES AND OPERATORS )
1. Describe in detail the procedure Script mode programming.
S Script mode Programming:
1. A script is a text file containing the Python statements. 2. Python Scripts are reusable code.
3. Once the script is created, it can be executed again and again without retyping. 4. The Scripts are editable.
i ) Creating Scripts in Python:
1. Choose File → New File or press Ctrl + N in Python shell window.
2. An untitled blank script text editor will be displayed on screen.
96
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
error occurred.
❖ To correct the errors, go back to Script editor, make corrections, save the file and execute it again.
❖ For all error free code, the output will appear in the IDLE window.
i.N
2. Explain input () and print () functions with examples. (M-2020, M-2022, J-2023, M-2024)
Input and output Functions :
❖ A program needs to interact with the user to accomplish the desired task; this can be achieved using Input-
Output functions.
❖ The input () function helps to enter data at run time by the user.
>>> y = 6
>>> z = x + y
>>> print (z)
11
>>> print (“The sum = ”, z)
w.
The sum = 11
>>> print (“The sum of ”, x, “ and ”, y, “ is ”, z)
The sum of 5 and 6 is 11
ww
2.Input() function:
❖ In Python, input () function is used to accept data as input at run time.
❖ The syntax for input() function is,
Variable = input (“prompt string”)
❖ Where, prompt string in the syntax is a statement or message to the user, to know what input can be given.
❖ If a prompt string is used, it is displayed on the monitor; the user can provide expected data from the input device.
❖ The input ( ) takes whatever is typed from the keyboard and stores the entered data in the given variable.
❖ If prompt string is not given in input ( ) no message is displayed on the screen, thus, the user will not know
what is to be typed as input.
Example 1:input( ) with prompt string
>>> city=input (“Enter Your City: ”)
Enter Your City: Madurai
Example 2:input( ) without prompt string
>>> city=input()
Rajarajan
97
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
❖ In example-1, the input () using prompt string takes proper input and produce relevant output.
❖ In example-2, the input () without using prompt string takes irrelevant input and produce unexpected output
❖ So, to make your program more interactive, provide prompt string with input ( ).
3. Discuss in detail about Tokens in Python. (S-2021)(M-2023, J-2024)
❖ Python breaks each logical line into a sequence of elementary lexical components known as Tokens.
❖ The normal token types are
1) Identifiers, 2) Keywords, 3) Operators, 4) Delimiters 5) Literals.
1.Identifiers:
❖ An Identifier is a name used to identify a variable, function, class, module or object.
❖ An identifier must start with an alphabet (A..Z or a..z) or underscore ( _ ).
❖ Identifiers may contain digits (0 .. 9)
❖ Python identifiers are case sensitive i.e. uppercase and lowercase letters are distinct.
❖ Identifiers must not be a python keyword.
❖ Python does not allow punctuation character such as %,$, @ etc., within identifiers.
Example of valid identifiers Sum, total_marks, regno, num1
Example of invalid identifiers 12Name, name$, total-mark, continue
2.Keywords:
et
❖ Keywords are special words used by Python interpreter to recognize the structure of program.
❖ As these words have specific meaning for interpreter, they cannot be used for any other purpose.
Example: false, class, If, el if, else, pass, break etc.
i.N
3.Operators:
❖ Operators are special symbols which represent computations, conditional matching etc.
❖ The value of an operator used is called operands.
❖ Operators are categorized as Arithmetic, Relational, Logical, Assignment, Conditional etc.
❖ Value and variables when used with operator are known as operands.
la
4.Delimiters :
❖ Python uses the symbols and symbol combinations as delimiters in expressions, lists, dictionaries and strings.
❖ Following are the delimiters.
sa
+= -= *= /= //= %=
&= |= ^= >>= <<= **=
5.Literals:
❖ Literal is a raw data given in a variable or constant.
da
❖ A Relational operator is also called as Comparative operator which checks the relationship between two operands.
❖ If the relation is true, it returns True; otherwise it returns False
iii) Logical operators :
❖ In python, Logical operators are used to perform logical operations on the given relational expressions.
❖ There are three logical operators they are and, or and not
iv)Assignment operators:
❖ In Python, = is a simple assignment operator to assign values to variable.
❖ There are various compound operators in Python like +=, -=, *=, /=, %=, **= and //= are also available.
v)Conditional operator or Ternary operator :
❖ Ternary operator is also known as conditional operator that evaluate something based on a condition being true or false.
❖ Syntax: Variable Name = [on_true] if [Test expression] else [on_false ]
98
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
part
Example: Output
for i in range (2,10,2): 2468
i.N
print (i, end=' ')
else:
print (“\n End of the loop”)
2. Write a detail note on if..else..elif statement with suitable example.
Nested if..elif...else statement:
la
❖ When we need to construct a chain of if statement(s) then ‘elif’ clause can be used instead of ‘else’.
❖ ‘elif’ clause combines if.. else - if.. else statements to one if..elif… else.
❖ ‘elif’ can be considered to be abbreviation of ‘else if’.
sa
❖ In an ‘if’ statement there is no limit of ‘elif’ clause that can be used, but an ‘else’ clause if used should be placed at the end.
Syntax:
if <condition-1>:
statements-block 1
elif <condition-2>:
da
statements-block 2
else:
statements-block n
❖ In the syntax of if..elif..else mentioned above, condition-1 is tested if it is true then statements- block 1 is executed.
Pa
❖ Otherwise the control checks condition-2, if it is true statements-block2 is executed and even if it fails
statements-block n mentioned in else part is executed.
Example: Output
m1=int (input(“Enter mark in first subject : ”)) Enter mark in first subject : 34
m2=int (input(“Enter mark in second subject : ”)) Enter mark in second subject : 78
w.
et
print (“\n End of the program”)
2. Write output of the following program (M-2020)
i=1 Output
i.N
While(i<=6) 1
for j in range (1,i) 12
print(j,end=’/t) 123
print(end=’/n’) 1234
i+=1 12345
la
CHAPTER – 7 ( PYTHON FUNCTIONS )
1. Explain the different types of function with an example. (J-2020, J-2022)
❖ Functions are named blocks of code that are designed to do specific job.
sa
Types of Functions:
1. User-defined,
2. Built-in,
3. Lambda, 4. Recursion Functions
da
def area(w,h):
return w * h
print (area (3,5))
2. Build in functions:
❖ Functions that are in built with in Python.
w.
100
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
4. Recursive function:
❖ Function cells itself is known as recursion.
Overview of how recursive function works:
1. Recursive function is called by some external code.
2. If the base condition is met then the program gives meaningful output and exits.
3. Otherwise function does some required processing and then calls itself to continue recursion.
2. Explain the scope of variables with an example. (J-2023, M-2024)
Scope of Variables:
❖ Scope of variable refers to the part of the program, where it is accessible, i.e., area where you can refer (use) it.
❖ We can say that scope holds the current set of variables and their values.
❖ We will study two types of scopes - local scope and global scope.
1.Local Scope:
❖ A variable declared inside the function's body or in the local scope is known as local variable.
Rules of local variable :
❖ A variable with local scope can be accessed only within the function/block that it is created in.
❖ When a variable is created inside the function/block, the variable becomes local to it.
❖ A local variable only exists while the function is executing.
et
❖ The formal arguments are also local to function.
Example : Create a Local Variable Output:
def loc(): 0
i.N
y=0 # local scope
print(y)
loc()
2. Global Scope:
❖ Variable, with global scope can be used anywhere in the program.
la
❖ It can be created by defining a variable outside the scope of any function/block.
Rules of global Keyword:
❖ When we define a variable outside a function, it’s global by default.
❖ You don’t have to use global keyword.
sa
❖ We use global keyword to read and write a global variable inside a function.
❖ Use of global keyword outside a function has no effect
Example : Accessing global Variable From Inside a Function Output:
c=1 # global variable 1
da
def add():
print(c)
add()
3. Explain the following built-in functions. (a) id() (b) chr() (c) round() (d) type() (e) pow() (M-2020, M-2023)
Pa
101
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
lcm = grater
break
greater +1
i.N
return lcm
a = int (input(“Enter first number:”)
b = int (input(“Enter second number:”)
print(“The LCM of”,a,”and”,b,”is”,LCM(a,b))
5. Explain recursive function with an example. [J-2024]
la
❖ When a function calls itself is known as recursion.
❖ Recursion works like loop but sometimes it makes more sense to use recursion than loop.
❖ You can convert any loop to recursion.
sa
❖ A recursive function calls itself.
❖ Imagine a process would iterate indefinitely if not stopped by some condition! Such a process is known as infinite iteration.
❖ The condition that is applied in any recursive function is known as base condition.
❖ A base condition is must in every recursive function otherwise it will continue to execute like an infinite loop.
Overview of how recursive function works:
da
Example: Output:
def fact(n): 1
if n == 0: 120
return 1
else:
w.
1. Explain about string operators in python with suitable example. (J-2023, J-2024)
String Operators:
❖ Python provides the following operators for string operations.
❖ These operators are useful to manipulate string.
(i) Concatenation (+)
❖ Joining of two or more strings is called as Concatenation.
❖ The plus (+) operator is used to concatenate strings in python.
Example: Output
>>> “welcome” + “Python” ‘welcomePython’
(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: Output
>>> str1=”Welcome to “ Welcome to Learn Python
102
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
(v) Stride when slicing string:
❖ When the slicing operation, you can specify a third argument as the stride, which refers to the number of
characters to move forward after the first character is retrieved from the string.
❖ The default value of stride is 1
i.N
❖ Python takes the last value as n-1
❖ You can also use negative value as stride (third argument).
❖ If you specify a negative value, it prints in reverse order.
Example: Output
>>> str1 = “Welcome to learn Python”
la
learn
>>> print (str1[10:16]) nhy re teolW
>>> print (str1[::-2])
sa
1. I] What is slicing? (S-2021)
❖ Slice is a substring of a main string.
❖ A substring can be taken from the original string by using [ ] operator and index or subscript values.
❖ Thus, [ ] is also known as slicing operator.
II] What is output for following python command: str=”Thinking with python”
da
103
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
Example: Output
>>> Mylist=[34, 45, 48] [34, 45, 48, 90]
>>> Mylist.append(90)
>>> print(Mylist)
Adding more elements in a list using extend():
❖ The extend () function is used to add more than one element to an existing list.
❖ In extend ( ) function, multiple elements should be specified within square bracket as arguments of the function.
Syntax: List. extend (element to be added)
Example: Output
>>> Mylist=[34, 45, 48] [34, 45, 48, 71,32,29]
>>> Mylist.extend([71,32,29])
>>> print(Mylist)
2. What is the purpose of range ()? Explain with an example. (J-2020, S-2021, J-2022, M-2024)
List and range ( ) function:
❖ The range ( ) is a function used to generate a series of values in Python.
et
❖ Using range ( ) function, you can create list with series of values.
❖ The range ( ) function has three arguments.
Syntax of range ( ) function:
i.N
range (start value, end value, step value)
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.
la
Example : Generating whole numbers up to 10 Output
for x in range (1, 11): 1 to 10
print(x)
sa
Creating a list with series of values :
❖ Using the range () function, you can create a list with series of values.
❖ To convert the result of range ( ) function into list, we need one more function called list ().
❖ The list () function makes the result of range ( ) as a list.
da
Tuple:
❖ 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.
Nested Tuples:
❖ In Python, a tuple can be defined inside another tuple; called Nested tuple.
w.
for i in Toppers:
print(i)
Output:
('Vinodini', 'XII-F', 98.7)
('Soundarya', 'XII-H', 97.5)
('Tharani', 'XII-F', 95.3)
('Saisri', 'XII-G', 93.8)
4. Explain the different set operations supported by python with suitable example. (M-2020, M-2022, J-2024)
Set:
❖ A set is another type of collection data type.
❖ A Set is a mutable and an unordered collection of elements without duplicates
Set operations :
❖ The set operations such as Union, Intersection, difference and Symmetric difference.
(i) Union:
❖ It includes all elements from two or more sets
104
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
i.N
Example: [Program to insect two sets using intersection operator]
set_A={'A', 2, 4, 'D'} Output
set_B={'A', 'B', 'C', 'D'} {'A', 'D'}
print(set_A & set_B)
la
(iii) Difference
❖ It includes all elements that are in fi rst set (say set A) but not in the second set (say set B)
❖ The minus (-) operator is used to difference set operation in python.
❖ The function difference ( ) is also used to difference operation.
sa
da
105
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
print("The object value is = ", var)
print("The value of class variable is= ", Sample.num)
def __del__(self):
Sample.num-=1
i.N
print("Object with value %d is exit from the scope"%self.var)
S1=Sample(15)
S2=Sample(35)
S3=Sample(45)
la
CHAPTER – 11 ( DATABASE CONCEPTS )
1. Explain the different types of data model.
Data model:
sa
❖ 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.
Types of a Data Model
❖ 1.Hierarchical Model 2.Relational Model 3.Network Database Model
da
❖ One child can have only one parent but one parent can have many children.
❖ This model is mainly used in IBM Main Frame computers.
❖ Hierarchical model was developed by IBM as Information Management System.
Example:
w.
ww
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.
❖ All the information’s related to a particular type is stored in rows of that table.
❖ A relation key is an attribute which uniquely identifies a particular tuple.
106
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
Example:
3. Network Model:
❖ Network database model is an extended form of hierarchical data model.
❖ The difference between hierarchical and Network data model is :
o In hierarchical model, a child record has only one parent node,
o In a Network model, a child may have many parent nodes.
o It represents the data in many to-many relationships.
et
o This model is easier and faster to access the data.
Example:
i.N
la
sa
4. Entity Relationship Model. (ER model):
❖ In this database model, relationship are created by dividing the object into entity and its characteristics into attributes.
❖ It was developed by Chen in 1976.
da
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.
Example:
107
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
2. One-to-Many Relationship:
et
❖ In One-to-Many relationship, one entity is related to many other entities.
❖ One row in a table A is linked to many rows in a table B, but one row in a table B is linked to only one row in table A.
For example: One Department has many staff members.
i.N
la
sa
3. Many-to-One Relationship:
❖ In Many-to-One Relationship, many entities can be related with only one in the other entity.
For example: A number of staff members working in one Department.
❖ Multiple rows in staff members table is related with only one row in Department table.
da
Pa
4. Many-to-Many Relationship:
❖ A many-to-many relationship occurs when multiple records in a table are associated with multiple records in
w.
another table.
Example 3: Books and Student.
❖ Many Books in a Library are issued to many students.
ww
et
❖ General form σ (R) with a relation R and a condition C on the attributes of R.
c
❖ The SELECT operation is used for selecting a subset with tuples according to a given condition.
❖ Select filters out all tuples that do not satisfy C.
i.N
Example: σ = “Big Data” (STUDENT )
course
2.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.
la
Example: Π (STUDENT)
course
II. Relational Algebra Operations from Set Theory:
sa
1.UNION (Symbol: ∪)
❖ It includes all tuples that are in tables A or in B.
❖ It also eliminates duplicates.
❖ Set A Union Set B would be expressed as A ∪ B
2.SET DIFFERENCE (Symbol: - )
da
❖ The result of A – B, is a relation which includes all tuples that are in A but not in B.
❖ The attribute name of A has to match with the attribute name in B.
3.INTERSECTION (Symbol: ∩) A ∩ B
❖ Defines a relation consisting of a set of all tuple that are in both in A and B.
Pa
❖ 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.
3.Data Consistency
❖ On live data, it is being continuously updated and added, maintaining the consistency of data can become a
challenge.
❖ But RDBMS handles it by itself.
4. Support Multiple user and Concurrent Access:
❖ RDBMS allows multiple users to work on it (update, insert, 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.
109
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
❖ 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 Transactions:
❖ It allows us to better handle and manage data integrity in real world applications where multi-threading is
extensively used.
1. Explain the following operators in Relational algebra with suitable examples (M-2024)
(i) UNION (ii) INTERSECTION (iii) DIFFERENCE (iv) CARTESIAN PRODUCT
Relational Algebra Operations from Set Theory:
1.UNION (Symbol: ∪)
❖ It includes all tuples that are in tables A or in B. It also eliminates duplicates.
❖ Set A Union Set B would be expressed as A ∪ B
Example: Consider the following tables
Table A Table B
Studno Name Studno Name
cs1 Kannan cs1 Kannan
cs3 Lenin cs2 GowriShankarn
cs4 Padmaja cs3 Lenin
et
Result:
Table A ∪ B
Studno Name
i.N
cs1 Kannan
cs2 GowriShankar
cs3 Lenin
cs4 Padmaja
2.SET DIFFERENCE (Symbol: - )
la
❖ The result of A – B, is a relation which includes all tuples that are in A but not in B.
❖ The attribute name of A has to match with the attribute name in B.
Example: (Use to union table)
sa
Result:
Table A - B
cs4 Padmaja
3.INTERSECTION (Symbol: ∩) A ∩ B
da
❖ 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.
Example: (Use to union table)
Result:
Pa
A∩B
cs1 Kannan
cs3 Lenin
4.PRODUCT OR CARTESIAN PRODUCT (Symbol: X)
❖ Cross product is a way of combining two relations.
w.
110
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
❖ 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 Admin no.
i.N
2.Primary Key Constraint:
❖ This constraint declares a field as a Primary key which helps to uniquely identify a record
❖ It is similar to unique constraint except that only one field of a table can be set as primary key.
❖ The primary key does not allow NULL values and therefore a field declared as primary key must have the
NOT NULL constraint.
la
Example
CREATE TABLE Student
(
sa
Admno integer NOT NULL PRIMARY KEY, → Primary Key constraint
Name char(20)NOT NULL,
Gender char(1),
Age integer,
Place char(10),
da
);
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.
Pa
Example:
CREATE TABLE Student
(
Admno integer NOT NULL PRIMARY KEY,
Name char(20)NOT NULL,
w.
Gender char(1),
Age integer DEFAULT = “17”, → Default Constraint
Place char(10),
);
ww
❖ 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.
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:
CREATE TABLE Student
(
Admno integer NOT NULL PRIMARY KEY
Name char(20)NOT NULL,
Gender char(1),
Age integer (CHECK<=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.
111
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
5.TABLE CONSTRAINT :
❖ When the constraint is applied to a group of fields of the table, it is known as Table constraint.
❖ The table constraint is normally given at the end of the table definition.
❖ Let us take a new table namely Student1 with the following fields Admno, First name, Last name, Gender, Age, Place:
CREATE TABLE Student 1
(
Admno integer NOT NULL,
Firstname char(20),
Lastname char(20),
Gender char(1),
Age integer,
Place char(10),
PRIMARY KEY (Firstname, Lastname) → Table constraint
);
❖ In the above example, the two fields, First name and Last name are defined as Primary key which is a Table constraint.
2. Consider the following employee table. Write SQL commands for the Questions. (i) to (v).
EMP CODE NAME DESIG PAY ALLOWANCE
S1001 Hariharan Supervisor 29000 12000
et
P1002 Shaji Operator 10000 5500
P1003 Prasad Operator 12000 6500
C1004 Manjima Clerk 8000 4500
i.N
M1005 Ratheesh Mechanic 20000 7000
1) To display the details of all employees in descending order of pay.
✓ SELECT * FROM employee ORDER BY DESC;
2) To display all employees whose allowance is between 5000 and7000.
✓ SELECT * FROM employee WHERE allowance BETWEEN 5000 AND 7000;
la
3) To remove the employees who are mechanic.
✓ DELETE FROM employee WHERE desig=’Mechanic’;
4) To add a new row.
✓ INSERT INTO Employee(empcode,name,desig,pay,allowance)VALUES(‘M1006’,‘Arun’,‘Mechanic’,15000,5000 )
sa
5) To display the details of all employees who are operators.
✓ SELECT * FROM employee WHERE design =’Operator’;
3. What are the components of SQL? Write the commands in each. (M-2024)
Components of SQL:
da
❖ 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.
SQL commands which comes under Data Definition Language are:
w.
112
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
identical values or divide the table in to groups.
❖ For example to know the number of male students or female students of a class, the GROUP BY clause may be used.
The syntax:
i.N
❖ SELECT <column-names> FROM <table-name> GROUP BY <column-name>HAVING condition];
To apply the above command on the student table:
SELECT Gender FROM Student GROUP BY Gender;
The following command will give the below given result: Gender M F
Result:
la
Gender count(*)
M 5
F 3
sa
(ii) SELECT statement using ORDER BY clause:
❖ The ORDER BY clause in SQL is used to sort the data in either ascending or descending based on one or more columns.
1. By default ORDER BY sorts the data in ascending order.
2. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in
da
ascending order.
The ORDER BY clause is used as:
Syntax:
❖ SELECT <column-name>[,<column-name>,….] FROM <table-name> ORDER BY <column1>,<column2>,…ASC| DESC ;
For example :
Pa
❖ To display the students in alphabetical order of their names, the command is used as
SELECT * FROM Student ORDER BY Name;
w.
ww
5. Write a SQL statement to create a table for employee having any five fields and create a table constraint for
the employee table. (M-2020)
CREATE TABLE employee
(
empno integer NOT NULL,
name char(20),
desig char(20),
pay integer,
allowance integer,
PRIMARY KEY (empno)
);
113
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
'a' Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.
i.N
't' Open in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)
3. Write the different methods to read a File in Python. (J-2020, J-2022, J-2023, M-2024)
❖ There are two ways to read a CSV file.
la
1. Use the csv module’s reader function 2. Use the Dict Reader class.
1) CSV Module’s Reader Function:
❖ We can read the contents of CSV file with the help of csv. reader () method.
sa
❖ The reader function is designed to take each line of the file and make a list of all columns.
❖ Using this method one can read data from csv files of different formats like quotes (" "), pipe (|) and comma (,).
The syntax: for csv.reader() is csv.reader(fileobject,delimiter,fmtparams)
where
da
file object passes the path and the mode of the file
delimiter an optional parameter containing the standard dilects like , | etc can be omitted.
fmtparams optional parameter which help to override the default values of the
dialects like skipinitialspace,quoting etc. Can be omitted.
Pa
Program: Output
import csv ['SNO', 'NAME', 'CITY']
with open('c:\\pyprg\\sample1.csv', 'r') as F: ['12101', 'RAM', 'CHENNAI']
reader = csv.reader(F) ['12102', 'LAVANYA', 'TIRUCHY']
print(row) ['12103', 'LAKSHMAN', 'MADURAI']
w.
F.close()
2.Reading CSV File Into A Dictionary:
❖ To read a CSV file into a dictionary can be done by using DictReader method of csv module which works
similar to the reader() class but creates an object which maps data to a dictionary.
ww
4. Write a Python program to write a CSV File with custom quotes. Output
import csv “SNO”,”PERSON”,”DOB”,
info =[‘SNO’,’Person’,’DOB’], ”1”,”SUDHARSHINI”,”15/05/2006’
[‘1’,’SUDHARSHINI’,’15/05/2006’], “2”,”SHDHARSAN”,”18/05/2005”
[‘2’,’SUDHARSAN’,’18/05/2005’], “3”,”VEYUL”,”13/05/2006”
[‘3’,’VEYUL’,’13/05/2006’], “4”,”YUVA”,”10/05/2006”
[‘4’,’YUVA’,’10/05/2006’], “5”,”CHEGUVERA”,”08/05/2006”
[‘5’,’CHEGUVERA’,’08/05/2006’],
csv.register_dialect('myDialect',quoting= csv.QUOTE_ALL)
with open('c:\pyprg\ch-13\Person.csv', 'w') as f:
writer = csv.writer(f, dialect='myDialect')
for row in info:
writer.writer(row)
print(“writing completed”)
f.close()
5. Write the rules to be followed to format the data in a CSV file.
1. Each record (row of data) is to be located on a separate line, delimited by a line break by pressing enter key.
For example: xxx,yyy
2. The last record in the file may or may not have an ending line break
et
For example: ppp, qqq
yyy, xxx
3. There may be an optional header line appearing as the first line of the file with the same format as normal
i.N
record lines. .
The header will contain names corresponding to the fields in the file and should contain the same number of
fields as the records in the rest of the file.
For example: field_name1,field_name2,field_name3
ppp, qqq
la
yyy, xxx
4. Within the header and each record, there may be one or more fields, separated by commas.
Spaces are considered part of a field and should not be ignored.
sa
The last field in the record must not be followed by a comma.
For example: Red , Blue
5. Each field may or may not be enclosed in double quotes.
If fields are not enclosed with double quotes, then double quotes may not appear inside the fields.
da
7. If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be preceded with
another double quote.
For example: “Red, ” “Blue”, “Green”.
, , White
w.
115
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
2. Explain each word of the following command. Python <filename.py> -<i> <C++ filename without cpp extension> (M-2022)
❖ This is the syntax to execute the python program.
Example: Python pycpp.py-1 pali
Python Keyword to execute the Python program from command-line
<filename.py > Name of the Python program to executed
-<i> Input mode
<C++ filename without cpp extension> Name of C++ file to be compiled and executed
1. Python – Keyword
2. Pycpp.py - Name of the Python program
3. i - Input mode
4. Pali - Name of C++ file. (Without extension)
3. What is the purpose of sys,os,getopt module in Python. Explain.
i) Python’s sys module:
❖ This module provides access to some variables used by the interpreter and to functions that interact strongly
with the interpreter.
sys. argv:
et
❖ sys.argv is the list of command-line arguments passed to the Python program.
❖ argv contains all the items that come via the command-line input, it's basically a list holding the command-
line arguments of the program.
❖ To use sys.argv, import sys should be used. The first argument, sys. argv [0] contains the name of the python program
i.N
(example pali.py) and sys. argv [1] is the next argument passed to the program (here it is the C++ file).
ii) Python's OS Module :
❖ The OS module in Python provides a way of using operating system dependent functionality.
❖ The functions that the OS module allows you to interface with the Windows operating system where Python is
running on.
os.system():
la
❖ Execute the C++ compiling command (a string contains Unix, C command which also supports C++
command) in the shell (Here it is Command Window).
sa
❖ For Example to compile C++ program g++ compiler should be invoked.
❖ Command: os.system (‘g++ ’ + <variable_name1> ‘ -<mode> ’ + <variable_name2>
where each argument contains,
os.system function system() defined in os module to interact with the operating system
da
g++ General compiler to compile C++ program under windows operating system.
variable_name1 Name of the C++ file along with its path and without extension .cpp in string format
mode To specify input or output mode. Here it is o prefixed with Hyphen.
variable_name2 Name of the executable file without extension .exe in string format
Pa
2.options :
❖ This is string of option letters that the Python program recognize as, for input or for output, with options (like
‘i’ or ‘o’) that followed by a colon (:).
❖ Here colon is used to denote the mode.
3.long_options :
❖ This parameter is passed with a list of strings.
❖ Argument of Long options should be followed by an equal sign ('=').
4. Write the syntax for getopt() and explain its arguments and return values Syntax. (M-2023)
❖ The getopt module of Python helps you to parse (split) command-line options and arguments.
❖ This module provides two functions to enable command-line argument parsing.
❖ This method parses command-line options and parameter list.
Syntax <opts>,<args>=getopt.getopt(argv, options, [long_options])
❖ Here is the detail of the parameters.
1.argv :
❖ This is the argument list of values to be parsed (splited).
116
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
❖ If args is displayed using print () command it displays the output as [ ].
>>>print(args)
[]
i.N
5. Write a Python program to execute the following C++ coding.
#include <iostream>
using namespace std;
int main()
{
la
cout<<“WELCOME”;
return(0);
}
sa
The above C++ program is saved in a file welcome.cpp
Answer:
import sys, os, getopt
def main (argv):
da
cpp_file = ''
exe_file = ''
opts, args = getopt.getopt (argv, "i:",['ifile='])
for o, a in opts:
if o in ("-i", "--ifile"):
Pa
cpp_file = a + '.cpp'
exe_file = a + '.exe'
run (cpp_file, exe_file)
def run(cpp_file, exe_file):
print ("Compiling " + cpp_file)
w.
os.system (exe_file)
print
if __name__ =='__main__':
main (sys.argv[1:])
OUTPUT:
------------------
WELCOME
------------------
117
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
Example: sql_ comm = "SQL statement"
❖ For executing the command use the cursor method and pass the required sql command as a parameter.
❖ Many number of commands can be stored in the sql_comm and can be executed one after other.
i.N
❖ Any changes made in the values of the record should be saved by the commend "Commit" before closing the "Table connection".
2. Write the Python script to display all the records of the following table using fetchmany () (S-2021)
Icode Item Name Rate
1003 Scanner 10500
1004 Speaker 3000
la
1005 Printer 8000
1008 Monitor 15000
1010 Mouse 700
sa
Code:
import sqlite3
connection = sqlite3.connect(“shop.db”)
cursor=connection.cursor()
da
118
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
4. Write a Python script to create a table called ITEM with following specification. Add one record to the table.
Name of the database :- ABC
Name of the table :- Item
Column name and specification :-
Icode :- integer and act as primary
key
Item Name :- Character with length 25
Rate :- Integer
Record to be added :- 1008, Monitor,15000
Code: Output
import sqlite3 TABLE CREATED
connection = sqlite3.connect(“ABC.db”)
cursor=connection.cursor()
sql_command – “““ CREATE TABLE Item( Icode INTEGER PRIMARY KEY, ItemName VARCHAR(25), Rate INTEGER) ; ”””
cursor.execute(sql_command)
sql_command = “““ INSERT INTO Item(Icode, ItemName, Rate) VALUES (1008, „Monitor‟,15000); ”””
cursor.execute(sql_command)
et
connection.commit()
connection.close()
print(“TABLE CREATED”)
i.N
5. Consider the following table Supplier and item .Write a python script for (i) to (ii)
SUPPLIER
Suppno Name City Icode SuppQty
S001 Prasad Delhi 1008 100
S002 Anu Bangalore 1010 200
la
S003 Shahid Bangalore 1008 175
S004 Akila Hydrabad 1005 195
S005 Girish Hydrabad 1003 25
sa
S006 Shylaja Chennai 1008 180
S007 Lavanya Mumbai 1005 325
i) Display Name, City and Itemname of suppliers who do not reside in Delhi:
import sqlite3
da
connection = sqlite3.connect(“ABC.db”)
cursor.execute(“SELECT Supplier.Name, Supplier.City,Item.ItemName FROM
Supplier,Item WHERE Supplier.Icode = Item.Icode AND
Supplier.City NOT In Delhi ”)
Pa
Output:
[‘Name’, ‘City’, ‘ItemName’]
[‘Anu’, ‘Bangalore’, ‘Scanner’]
[‘Shahid’, ‘Bangalore’, ‘Speaker’]
ww
119
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
❖ The ORDER BY Clause can be used along with the SELECT statement to sort the data of specific fields in an ordered way.
❖ It is used to sort the result-set in ascending or descending order.
❖ In this example name and Rollno of the students are displayed in alphabetical order of names.
Example:
i.N
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT Rollno,sname FROM student Order BY sname")
la
result = cursor.fetchall()
print(*result,sep="\n")
OUTPUT
(1, 'Akshay')
sa
(2, 'Aravind')
(3, 'BASKAR')
(6, 'PRIYA')
(4, 'SAJINI')
da
(7, 'TARUN')
CHAPTER – 16 ( DATA VISUALIZATION USING PYPLOT: LINE , PIE AND BAR CHAT )
1. Explain in detail the types of pyplots using Matplotlib.
Line Chart :
Pa
❖ A Line Chart or Line Graph is a type of chart which displays information as a series of data points called
‘markers’ connected by straight line segments.
❖ A Line Chart is often used to visualize a trend in data over intervals of time – a time series – thus the line is
often drawn chronologically.
Example:
w.
120
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
Bar Chart:
❖ A BarPlot (or BarChart) is one of the most common type of plot.
❖ It shows the relationship between a numerical variable and a categorical variable.
❖ Bar chart represents categorical data with rectangular bars.
❖ Each bar has a height corresponds to the value it represents.
❖ The bars can be plotted vertically or horizontally.
❖ It‟s useful when we want to compare a given numeric value on different categories.
❖ To make a bar chart with Matplotlib, we can use the plt.bar() function
Example:
import matplotlib.pyplot as plt
labels = ["TAMIL", "ENGLISH", "MATHS", "PHYSICS", "CHEMISTRY", "CS"]
usage = [79.8, 67.3, 77.8, 68.4, 70.2, 88.5]
y_positions = range (len(labels))
plt.bar (y_positions, usage)
plt.xticks (y_positions, labels)
plt.ylabel ("RANGE")
plt.title ("MARKS") plt.show()
et
Output:
i.N
la
sa
Pie Chart:
❖ Pie Chart is probably one of the most common type of chart.
❖ It is a circular graphic which is divided into slices to illustrate numerical proportion.
❖ The point of a pie chart is to show the relationship of parts out of a whole.
da
❖ To make a Pie Chart with Matplotlib, we can use the plt.pie () function.
❖ The autopct parameter allows us to display the percentage value using the Python string formatting.
Example:
import matplotlib.pyplot as plt
Pa
Output:
ww
121
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
1.Home Button :
❖ The Home Button will help once you have begun navigating your chart.
❖ If you ever want to return back to the original view, you can click on this.
2.Forward/Back buttons :
❖ These buttons can be used like the Forward and Back buttons in your browser.
❖ You can click these to move back to the previous point you were at, or forward again.
3.Pan Axis :
❖ This cross-looking button allows you to click it, and then click and drag your graph around.
4.Zoom :
et
❖ The Zoom button lets you click on it, then click and drag a square that you would like to zoom into
specifically.
❖ Zooming in will require a left click and drag.
❖ You can alternatively zoom out with a right click and drag.
i.N
5.Configure Subplots :
❖ This button allows you to configure various spacing options with your figure and plot.
6.Save Figure :
❖ This button will allow you to save your figure in various forms
3. Explain the purpose of the following functions. (M-2022)
a. plt.xlabel
la
a. plt.xlabel b. plt.ylabel c. plt.title d. plt.legend() e. plt.show()
Specifies the lable for X-axis
sa
b. plt.ylabel Specifies the lable for Y-axis
c. plt.title Specifies the title of the graph or assigns the plot title.
d. plt.legend() Invokes the default legend with plt.
Calling legent () with no arguments automatically fetches the legend handles and their
da
associated lables.
e. plt.show() Displays our plot.
1. What are the key differences between Histogram and Bar graph? (S-2021)(M-2023)
Histogram Bar graph
Pa
122
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
iteration a b c
0 4 4 6
1 3 3 8
2 2 2 10
i.N
3 1 1 12
4 0 0 14
❖ In each meeting, a and b each decreases by 1, and c increases by 2.
❖ The solution can be expressed as an iterative algorithm.
(CHAPTER-3) ( SCOPING )
1.
la
1Why scope should be used for variable? Explain Global scope with an example.
. ❖ Scope should be used for variable.
❖ Because every part of program can access the variable.
sa
GLOBAL SCOPE: A variable which is declared outside of all the functions in a program is known as global variable.
❖ Global variable can be accessed inside or outside of all the functions in a program
da
Pa
Example:
❖ On execution of the above code the variable a which is defined inside the function displays the value 7 for the
w.
function call Disp() and then it displays 10, because a is defined in global scope.
2. 2Explain about access control.
. ❖ Access control is a security technique that regulates who or what can view or use resources in a computing environment.
❖ It is a fundamental concept in security that minimizes risk to the object.
ww
123
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
i.N
❖
❖
la
Algorithm will try to check the results of the previously solved sub-problems.
The solutions of overlapped sub-problems are combined in order to get the better solution.
2. 2Explain the Selection sort algorithm.
sa
. ❖ The selection sort is a simple sorting algorithm that improves on the performance of bubble sort by making
only one exchange for every pass through the list.
❖ This algorithm will first find the smallest elements in array and swap it with the element in the first position of
an array, then it will find the second smallest element and swap that element with the element in the second
da
position, and it will continue until the entire array is sorted in respective order.
❖ This algorithm repeatedly selects the next-smallest element and swaps in into the right place for every pass.
❖ Hence it is called selection sort.
Pseudo code :
Pa
1. Start from the first element i.e., index-0, we search the smallest element in the array, and replace it with the
element in the first position.
2. Now we move on to the second element position, and look for smallest element present in the sub-array, from
starting index to till the last index of sub – array.
3. Now replace the second smallest identified in step-2 at the second position in the original array, or also called
w.
❖ In the first pass, the smallest element will be 11, so it will be placed at the first position.
❖ After that, next smallest element will be searched from an array.
❖ Now we will get 13 as the smallest, so it will be then placed at the second position.
124
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
❖ Then leaving the first element, next smallest element will be searched, from the remaining elements.
❖ We will get 13 as the smallest, so it will be then placed at the second position.
❖ Then leaving 11 and 13 because they are at the correct position, we will search for the next smallest element
from the rest of the elements and put it at third position and keep doing this until array is sorted.
❖ Finally we will get the sorted array end of the pass as shown above diagram.
3. Explain about Complexity of an algorithm.
❖ Time Factor -Time is measured by counting the number of key operations like comparisons in the sorting algorithm.
❖ Space Factor - Space is measured by the maximum memory space required by the algorithm.
❖ The complexity of an algorithm f (n) gives the running time and/or the storage space required by the algorithm
in terms of n as the size of input data.
Time Complexity:
❖ The Time complexity of an algorithm is given by the number of steps taken by the algorithm to complete the process.
Space Complexity:
❖ Space complexity of an algorithm is the amount of memory required to run to its completion.
❖ The space required by an algorithm is equal to the sum of the following two components:
A fixed part is defined as the total space required to store certain data and variables for an algorithm.
❖ For example: simple variables and constants used in an algorithm.
et
A variable part is defined as the total space required by variables, which sizes depends on the problem and its iteration.
4. Explain about Fibonacci Series with example
❖ Fibonacci series generates the subsequent number by adding two previous numbers.
❖ Fibonacci series starts from two numbers − Fib 0 & Fib 1.
i.N
❖ The initial values of Fib 0 & Fib 1 can be taken as 0 and 1.
Fibonacci series satisfies the following conditions :
❖ Fibn = Fibn-1 + Fibn-2
❖ Hence, a Fibonacci series for the n value 8 can look like this Fib 8 = 0 1 1 2 3 5 8 13
Fibonacci Iterative Algorithm with Dynamic programming approach:
la
❖ Initialize f0=0, f1 =1
❖ step-1: Print the initial values of Fibonacci f0 and f1
❖ step-2: Calculate fibanocci fib ← f0 + f1
sa
❖ step-3: Assign f0← f1, f1← fib
❖ step-4: Print the next consecutive value of fibanocci fib
❖ step-5: Goto step-2 and repeat until the specified number of terms generated
For example if we generate fibobnacci series upto 10 digits, the algorithm will generate the series as shown below:
da
❖ Python has Built-in or Fundamental data types such as Number, String, Boolean, tuples, lists, sets and dictionaries etc.
1.Number Data type:
❖ The built-in number objects in Python supports integers, floating point numbers and complex numbers.
❖ Integer Data can be decimal, octal or hexadecimal.
❖ Octal integer use digit 0 (Zero) followed by letter 'o' to denote octal digits and hexadecimal integer use 0X
w.
(Zero and either uppercase or lowercase X) and L (only upper case) to denote long integer.
Example :
1. 102, 4567, 567 # Decimal integers
2. 0o102, 0o876, 0o432 # Octal integers
ww
et
ii) Indentation:
❖ Python uses whitespace such as spaces and tabs to define program blocks whereas other languages like C,
C++, java use curly braces { } to indicate blocks of codes for class, functions or body of the loops and block of
i.N
selection command.
❖ The number of whitespaces (spaces and tabs) in the indentation is not fixed, but all statements within the block
must be indented with same amount spaces.
4 Explain Operators in Python. [Refer book examples]
❖ In computer programming languages operators are special symbols which represent computations, conditional matching etc.
❖
la
The value of an operator used is called operands.
❖ Operators are categorized as Arithmetic, Relational, Logical, Assignment, Conditional etc.
❖ Value and variables when used with operator are known as operands.
(i) Arithmetic operators:
sa
❖ An arithmetic operator is a mathematical operator that takes two operands and performs a calculation on them.
They are used for simple arithmetic.
ii) Relational or Comparative operators:
❖ A Relational operator is also called as Comparative operator which checks the relationship between two operands.
da
iv)Assignment operators:
❖ In Python, = is a simple assignment operator to assign values to variable.
❖ There are various compound operators in Python like +=, -=, *=, /=, %=, **= and //= are also available.
v)Conditional operator or Ternary operator :
❖ Ternary operator is also known as conditional operator that evaluate something based on a condition being true or false.
w.
while <condition>:
statements block 1
[else:
statements block2]
❖ In the while loop, the condition is any valid Boolean expression returning True or False.
❖ The else part of while is optional part of while.
❖ The statements block1 is kept executed till the condition is true.
❖ If the else part is written, it is executed when the condition is tested False.
❖ Recall while loop belongs to entry check loop type that is it is not executed even once if the condition is tested
false in the beginning.
Example: Program to illustrate the use of while loop - to print all numbers from 10 to 15.
i=10 # intializing part of the control variable
while (i<=15): # test condition
print (i,end='\t') # statements - block 1
i=i+1 # Updation of the control variable Output: 10 11 12 13 14 15
126
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
2. A) Write a python program to display all 3 digit even numbers. Using for loop
for i in range (100,1000,2):
Print (i )
B) Write the output for the following program
1 i=1 1
12 while (i<=6): 12
123 for j in range (1,i): 123
1234 print (j,end=’\t’) 1234
12345 print(end=’\n’) 12345
i+=1
3. 6Explain briefly about Jump statement in python.
. ❖ The jump statement in Python, is used to unconditionally transfer the control from one part of the program to another.
❖ There are three keywords to achieve jump statements in Python: break, continue, and pass.
❖ The following flowchart illustrates the use of break and continue.
1.Break statement:
❖ The break statement terminates the loop containing it.
❖ Control of the program flows to the statement immediately after the body of the loop.
et
❖ A while or for loop will iterate till the condition is tested false, but one can even transfer the control out of the
loop (terminate) with help of break statement.
2.Continue statement:
❖ Continue statement unlike the break statement is used to skip the remaining part of a loop and start with next iteration.
i.N
Syntax: Continue
3.Pass statement:
❖ Pass statement in Python programming is a null statement.
❖ Pass statement when executed by the interpreter it is completely ignored.
Syntax: pass
4.
la
7What are the different types of Loops in Python? Explain within example.
. 1.While loop :
Syntax:
sa
while <condition>:
statements block 1
[else:
statements block2]
da
❖ In the while loop, the condition is any valid Boolean expression returning True or False.
❖ The else part of while is optional part of while.
❖ The statements block1 is kept executed till the condition is True.
❖ If the else part is written, it is executed when the condition is tested False.
Pa
Example: [program to illustrate the use of while loop - to print all numbers from 10 to 15]
i=10 # intializing part of the control variable
while (i<=15): # test condition
print (i,end='\t') # statements - block 1
i=i+1 # Updation of the control variable
w.
Output: 10 11 12 13 14 15
2.For loop :
❖ For loop is the most comfortable loop.
❖ It is also an entry check loop.
ww
❖ The condition is checked in the beginning and the body of the loop is executed if it is only True otherwise the
loop is not executed.
Syntax:
for counter_ variable in sequence:
statements-block 1
[else: # optional block
statements-block 2]
Example: [program to illustrate the use of for loop]
for i in range(2,10,2):
print (i,end=' ')
else:
print ("\nEnd of the loop")
Output: 2 4 6 8 End of the loop
127
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
continue
print (word, end = ' ')
print (“\n End of the program”)
6. Write a program to check if a number is positive, Negative or Zero.
i.N
num=int(input(“Enter a number:”)) Output 1:
if num> 0: Enter a number : 26
print(“The number is positive”) The number is positive
elif num< 0:
Print(“The number is negative”)
la
Output 2:
else: Enter a number : 0
Print(“The number is Zero”) The number is Zero
sa
Write program to check vowel or not. Output1:
ch = input (“ Enter a character:”) Enter a character : S
if ch in (‘a’,’A’,’e’,’i’,’I’,’o’,’O’,’u’,’U’): S is not a vowel
print (ch, ‘is a vowel’) Output2:
da
ord ( ) Returns the ASCII value for ord (c) c= 'a' Output:
the given d= 'A' c = 97
Unicode character. print ('c = ',ord (c)) A = 65
print ('A = ',ord (d))
ww
bin ( ) Returns a binary string bin (i) x=15 o/p : 15 in binary : 0b1111
prefixed with “0b” for the y=101 101 in binary : 0b1100101
given integer number. print ('15 in binary : ',bin (x))
print ('101 in binary : ',bin (y))
min ( ) Returns the minimum value min (list) MyList = [21,76,98,23]
in a list. print ('Minimum of MyList :', min(MyList))
Output: Minimum of MyList : 21
max ( ) Returns the maximum value max (list) MyList = [21,76,98,23]
in a list. print ('Maximum of MyList :', max(MyList))
Output: Maximum of MyList : 98
sum ( ) Returns the sum of values in sum (list) MyList = [21,76,98,23]
a list. print ('Sum of MyList :', sum(MyList))
Output: Sum of MyList : 218
format 1. Binary –base 2 format (value x= 14 y= 25
[, format_
128
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
2. 2Explain the functions of return statement with syntax and example.
. ❖ 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.
i.N
❖ 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.
Syntax of return: return [expression list ]
❖ This statement can contain expression which gets evaluated and the value is returned.
la
❖ 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.
Example: Output 1:
sa
def usr_abs (n): Enter a number : 25
if n>=0: 25
return n Output 2:
else: Enter a number : -25
return –n 25
da
❖ While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword.
❖ Hence, anonymous functions are also called as lambda functions.
What is the use of lambda function?
❖ Lambda function is mostly used for creating small and one-time anonymous function.
❖ Lambda functions are mainly used in combination with the functions like filter (), map () and reduce ( ).
w.
print (str)
return
2. Keyword Arguments:
❖ Keyword arguments will invoke the function after the parameters are recognized by their parameter names.
❖ The value of the keyword argument is matched with the parameter name and so, one can also put arguments in
improper order (not in order).
Example:
def printdata (name):
print (“Example-1 Keyword arguments”)
print (“Name :”,name)
return
3.Default Arguments :
❖ In Python the default argument is an argument that takes a default value if no value is provided in the function call.
Example:
def print info( name, salary = 3500):
print (“Name: “, name)
print (“Salary: “, salary)
return
et
print info(“Mani”)
4.Variable-Length Arguments:
❖ In some instances you might need to pass more arguments than have already been specified.
i.N
❖ Going back to the function to redefine it can be a tedious process.
Example:
1.def sum(x,y,z):
2.print("sum of three nos :",x+y+z)
3.sum(5,10,15,20,25)
5.
Output:
la
Debug the following python program to get the given output.
globally x: global x
x = x+10 x = x+10 # increment by 2
print (‘Inside add() function x value is:”) Print (“Inside add() function x value is:”, x)
add add ()
print (“In main x value is:”) Print (“In main x value is:”,x)
Pa
❖ Python takes the end value less than one from the actual index specified.
❖ For example, if you want to slice first 4 characters from a string, you have to specify it as 0 to 5.
❖ Because, python consider only the end value as n-1.
Example I : slice a single character from a string
>>> str1="THIRUKKURAL"
>>> print (str1[0])
T
Example II: slice a substring from index 0 to 4
>>> print (str1[0:5])
THIRU
Example III: slice a substring using index 0 to 4 but without specifying the beginning index.
>>> print (str1[:5])
THIRU
Example IV: slice a substring using index 0 to 4 but without specifying the end index.
>>> print (str1[6:]) KURAL
130
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
2. 2Write the output for the following python commands. str1=”Welcome to Python”
. i) print(str1) Ans : Welcome to Python
ii) print(str 1[11:17] ) Ans : Python
iii) print(str1[11:17:2] ) Ans : Pto
iv) print(str1[: : 4] ) Ans : Wotyn
v) print(str1[: : - 4] ) Ans : nytoW
3. 3Write a program to check string palindrome or not.
. str1 = input ("Enter a string: ")
str2 = ' '
index=-1
for i in str1:
str2 += str1[index]
index -= 1
print ("The given string = { } \n The Reversed string = { }".format(str1, str2))
if (str1==str2):
print ("Hence, the given string is Palindrome")
else:
et
print ("Hence, the given is not a palindrome")
Output : 1
1.Enter a string: malayalam
2.The given string = malayalam
i.N
3.The Reversed string = malayalam
Hence, the given string is Palindrome
Output : 2
1.Enter a string: welcome
la
2.The given string = welcome
3.The Reversed string = emoclew
Hence, the given string is not a palindrome
4. 4Write the short note on the following built-in string functions.
sa
. (i) capitalize() (ii) isalpha() (iii) isalnum() (iv) lower()
Syntax Description Example
1.capitalize Used to capitalize the first character of the >>> city="chennai" Chennai
() string >>> print(city.capitalize())
da
(width, fillchar) a total of width columns and filled with fillchar in >>> print(str1.center(15,’*’) )
columns that do not have characters ****Welcome****
2. find ( ) ❖ The function is used to search the first >>>str1=’mammals’
(sub[, start[, end]]) occurrence of the sub string in the given >>>str1.find(‘ma’) 0
string. ❖ On omitting the start parameters, the
❖ It returns the index at which the substring function starts the search from the
starts. beginning.
❖ It returns -1 if the substring does not occur in >>>str1.find(‘ma’,2) 3
the string. >>>str1.find(‘ma’,2,4) -1
❖ Displays -1 because the substring could
not be found between the index 2 and 4 -
1.
>>>str1.find(‘ma’,2,5) 3
1. 1Explain the following list function: i) copy ( ) ii) count ( ) iii) index ( ) iv) reverse ( ) v) sort ( )
. 1.Copy Returns a copy of the list List.copy ( ) MyList=[12, 12, 36] Output:
() x = MyList.copy() [12, 12, 36]
print(x)
2.Count Returns the number of List.count MyList=[36 ,12 ,12] Output:
() similar elements present (value) x = MyList.count(12) 2
in the last. print(x)
3.index Returns the index value of the List.index MyList=[36 ,12 ,12] Output:
() first recurring element (element) x = MyList.index(12) print(x) 1
4.reverse Reverses the order of the List.reverse( ) MyList=[36 ,23 ,12] Output: [12 ,23 ,36]
() element in the list. MyList.reverse() print(MyList)
5.sort Sorts the element in list List.sort MyList=['Thilothamma', 'Tharani', 'Anitha', 'SaiSree', 'Lavanya']
() (reverse=True| MyList.sort( ) print(MyList)
False,key=my MyList.sort(reverse=True) print(MyList)
Func) Output: ['Anitha', 'Lavanya', 'SaiSree', 'Tharani','Thilothamma']
['Thilothamma', 'Tharani', 'SaiSree', 'Lavanya', 'Anitha']
6.Max Returns the maximum max(list) MyList=[21,76,98,23]
et
() value in a list. print(max(MyList)) Output: 98
7.Min Returns the minimum min(list) MyList=[21,76,98,23]
() value in a list. print(min(MyList)) Output: 21
i.N
8.Sum Returns the sum of sum(list) MyList=[21,76,98,23]
() values in a list. print(sum(MyList)) Output: 218
2. 2What will be the output of the following python program?
.N = [ ] Output :
for x in range(1, 11): The list of numbers from 1 to 10 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
la
N.append(x) The list after deleting even numbers = [1, 3, 5, 7, 9]
Num=tuple(N)
print(Num)
sa
for index, i in enumerate(N):
if(i%2==1):
del N[index]
print(N)
da
❖ 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.
ww
❖ 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.
❖ During the first iteration, the value of i is zero, where the condition is true.
❖ Now, the following statement print (Marks [i]) gets executed and prints the value of Marks [0] element ie. 10.
❖ 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
Iteration i while i<4 print (Marks [i]) i=i+1
1 0 0<4 True Marks [0] = 10 0+1=1
2 1 1<4 True Marks [1] = 23 1+1=2
3 2 2<4 True Marks [2] = 41 2+1=3
4 3 3<4 True Marks [3] = 75 3+1=4
5 4 4<4 False -- --
132
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
4. 4 Mylist = [10, 20, 30, 49, 50, 60, 70, 80, 90, 100]
. Write the Python commands for the following based on above list.
1 To print all elements in list. Mylist=[10, 20, 30, 40, 50, 60, 70, 80, 90,100]
for x in mylist:
print (x)
2 Find list length Mylist = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
len (Mylist)
3 Add multiple elements [110, 120, 130] Mylist.Extend( [110,120,130] )
4 Delete from fourth element to seventh del Mylist[4:7]
element.
5 Delete entire list del(Mylist)
5. 5Compare remove (), pop () and clear () function in Python.
Remove ( ) Pop ( ) Clear ( )
❖ Remove function is used to delete ❖ Pop function deletes and returns ❖ The function clear () is used to
a elements of a list if its index is the last element of a list if the delete all the elements in list.
unknown index is not given. ❖ It deletes only the elements and
retains the list.
et
❖ Removes element from the set ❖ Removes an arbitrary element ❖ Removes all elements from a set
i.N
. class Sample: The object value is = 15
num=0 The count of object created=1
def __init__(self, var): The object value is = 35
Sample.num+=1 The count of object created=2
self.var=var The object value is = 45
la
print("The object value is = ", var) The count of object created=3
print("The count of object created = ", Sample.num)
def __del__(self):
Sample.num-=1
sa
print("Object with value %d is exit from the scope"%self.var)
S1=Sample(15)
S2=Sample(35)
S3=Sample(45)
da
self.vowel=0 12 Vowels
self.consonant=0 13 Consonants
self.space=0 4 Spaces
self.string=""
def getstr(self):
self.string=str(input("Enter a String: "))
w.
if (ch.islower()):
self.lower+=1
if (ch in ('AEIOUaeiou'):
self.vowel+=1
if (ch.isspace()):
self.space+=1
self.consonant = self.upper+self.lower - self. vowel
def display(self):
print("The given string contains...")
print("%d Uppercase letters"%self.upper)
print("%d Lowercase letters"%self.lower)
print("%d Vowels"%self.vowel)
print("%d Consonants"%self.consonant)
print("%d Spaces"%self.space)
S = String()
S.getstr()
S.count()
S.display()
133
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
print("The Circumference =", C.circumference())
4. 2How to define a class in python? Explain with example.
. ❖ In Python, a class is defined by using the keyword class.
i.N
❖ Every class has a unique name followed by a colon (:).
Syntax:
class class_name:
statement_1
statement_2
…………..
❖
…………..
statement_n
la
sa
Where, statement in a class definition may be a variable declaration, decision control, loop or even a function definition.
❖ Variables defined inside a class are called as ‘Class Variable’ and functions are called as “Methods”.
❖ Class variable and methods are together known as members of the class.
❖ The class members should be accessed through objects or instance of class.
❖ A class can be defined anywhere in a Python program.
da
Example:
class Sample:
x, y = 10, 20
❖ In the above code, name of the class is Sample and it has two variables x and y having the initial value 10 and 20
Pa
respectively.
❖ To access the values defined inside the class, you need an object or instance of the class.
5. 3Explain public and private data members with examples.
. ❖ The variables which are defined inside the class is public by default.
❖ These variables can be accessed anywhere in the program using dot operator.
w.
134
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
Output :
Value of x = 10
Value of y = 20
Value of x and y = 30
i.N
❖ In the above code, the name of the class is Sample.
❖ Inside the class, we have assigned the variables x and y with initial value 10 and 20 respectively.
❖ These two variables are called as class variables or member variables of the class.
❖ In class instantiation process, we have created an object S to access the members of the class.
la
CHAPTER – 11 ( DATABASE CONCEPTS )
1. 1Components of DBMS.
. 1. Hardware:
sa
❖ The computer, hard disk, I/O channels for data, and any other physical component involved in storage of data
2. Software:
❖ This main component is a program that controls everything.
❖ The DBMS software is capable of understanding the Database Access Languages and interprets into database
da
❖ They are general instructions to use a database management system such as installation of DBMS, manage
databases to take backups, report generation, etc.
5. DataBase Access Languages:
❖ They are the languages used to write commands to access, insert, update and delete data stored in any database.
❖ Examples of popular DBMS: Dbase, FoxPro
w.
❖ Each table column represents a Field, which groups each piece or item of data among the records into specific
categories or types of data. Eg. StuNo., StuName, StuAge, StuClass, StuSec.
❖ A Table is known as a RELATION
❖ A Row is known as a TUPLE. A column is known as an ATTRIBUTE
CHAPTER – 12 ( STRUCTURED QUERY LANGUAGE )
1. Explain about TCL commands with suitable examples.
COMMIT command:
❖ The COMMIT command is used to permanently save any transaction to the database.
❖ When any DML commands like INSERT, UPDATE, DELETE commands are used, the changes made by
these commands are not permanent.
❖ It is marked permanent only after the COMMIT command is given from the SQL prompt.
❖ Once the COMMIT command is given, the changes made cannot be rolled back.
❖ The COMMIT command is used as COMMIT;
135
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
ROLLBACK command:
❖ The ROLLBACK command restores the database to the last commited state.
❖ It is used with SAVEPOINT command to jump to a particular save point location.
❖ The syntax for the ROLLBACK command is : ROLL BACK TO save point name;
SAVEPOINT command
❖ The SAVEPOINT command is used to temporarily save a transaction so that you can roll back to the point whenever required.
❖ The different states of our table can be saved at any time using different names and the rollback to that state
can be done using the ROLLBACK command. SAVEPOINT savepoint_name;
2. Explain about data types
Data Type Description
char Fixed width string value. Values of this type is enclosed in single quotes.
(Character) For ex. Anu’s will be written as ‘Anu’ ‘s’.
varchar Variable width character string. This is similar to char except the size of the data entry vary considerably.
dec It represents a fractional number such as 15.12, 0.123 etc.
(Decimal) Here the size argument consist of two parts : precision and scale.
numeric It is same as decimal except that the maximum number of digits may not exceed the precision argument.
int(Integer) It represents a number without a decimal point. Here the size argument is not used.
smallint It is same as integer but the default size may be smaller than Integer.
et
float It represents a floating point number in base 10 exponential notation and may define a precision up to a
maximum of 64.
real It is same as float, except the size argument is not used and may define a precision up to a maximum of 64.
i.N
double Same as real except the precision may exceed 64.
3. 1Consider the following employee table. Write SQL commands for the Questions.(i) to (v).
. Roll No Name Group Roll No Name Group
1001 Chandu A1 1006 Sabari B1
1002 Dharsan A2 1007 Srihari A1
la
1003 Kavin B1 1008 Prajith A2
1004 Karl marx A1 1009 Livith B1
1005 Iruleswar A2
sa
1. To display the details of all students in ascending order of name:
❖ SELECT*FROM student ORDER BY name Asc;
2. To display all students in A2 group:
❖ SELECT*FROM student GROUP By A2.
da
❖ In general, Database is a collection of tables that store sets of data that can be queried for use in other applications.
❖ A database management system supports the development, administration and use of database platforms.
❖ RDBMS is a type of DBMS with a row-based table structure that connects related data elements and includes
functions related to Create, Read, Update and Delete operations, collectively known as CRUD.
ww
136
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
3006 Purattasi 521
import sqlite3
connection = sqlite3.connect(“month.db”)
i.N
cursor=connection.cursor()
cursor.execute(“SELECT * FROM Tamil Months”)
print(“Displaying All The Records”)
result=cursor.fetchmany(6)
print(result, Sep= “\n”)
la
2. 2Write a note aggregate functions of SQL.
. ❖ These functions are used to do operations from the values of the column and a single value is returned.
1. COUNT() 2. AVG() 3. SUM() 4. MAX() 5. MIN()
sa
1. COUNT()
❖ The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause.
❖ COUNT() returns 0 if there were no matching rows.
Example:
import sqlite3
da
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT COUNT(*) FROM student ")
result = cursor.fetchall()
Pa
print(result)
Output: [(7,)]
2. AVG()
❖ The following SQL statement in the python program finds the average mark of all students.
Example:
w.
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT AVG(AVERAGE) FROM student ")
ww
result = cursor.fetchall()
print(result)
Output [(84.65714285714286,)]
3. SUM():
❖ The following SQL statement in the python program finds the sum of all average in the Average field of “Student table”.
Example:
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT SUM(AVERAGE) FROM student ")
result = cursor.fetchall()
print(result)
Output: [(592.6,)]
4.MAX()
❖ The MAX() function returns the largest value of the selected column.
137
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
5.MIN()
❖ The MIN() function returns the smallest value of the selected column.
3. 3Construct the following: a)GROUB BY b) ORDER BY clause
. 1.SQL Group By Clause:
❖ The SELECT statement can be used along with GROUP BY clause.
❖ The GROUP BY clause groups records into summary rows. It returns one records for each group.
❖ It is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns.
❖ The following example count the number of male and female from the student table and display the result.
Example:
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT gender,count(gender) FROM student Group BY gender")
result = cursor.fetchall()
print(*result,sep="\n")
OUTPUT:
('F', 2)
('M', 5)
et
2.SQL ORDER BY Clause:
❖ The ORDER BY Clause can be used along with the SELECT statement to sort the data of specific fields in an ordered way.
❖ It is used to sort the result-set in ascending or descending order.
❖ In this example name and Rollno of the students are displayed in alphabetical order of names.
i.N
Example:
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT Rollno,sname FROM student Order BY sname")
la
result = cursor.fetchall()
print(*result,sep="\n")
OUTPUT
sa
(1, 'Akshay')
(2, 'Aravind')
(3, 'BASKAR')
(4, 'PRIYA')
(5, 'SAJINI')
da
(6, 'TARUN')
(7, 'VARUN')
CHAPTER – 16 ( DATA VISUALIZATION USING PYPLOT: LINE , PIE AND BAR CHAT )
1. 1What are the key differences between Histogram and Bar graph?
. Histogram Bar graph
Pa
Histogram refers to a graphical representation; that displays A bar graph is a pictorial representation of data that uses bars to
data by way of bars to show the frequency of numerical data compare different categories of data
A histogram represents the frequency distribution of Conversely, a bar graph is a diagrammatic comparison of discrete
continuous variables variables.
Histogram presents numerical data Bar graph shows categorical data.
w.
Items of the histogram are numbers, which are categorised As opposed to the bar graph, items are considered as individual
together, to represent ranges of data entities.
The width of rectangular blocks in a histogram may or may The width of the bars in a bar graph is always same.
not be same
ww
138
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
print (“The sum = ”, x+y) The sum = 90
i.N
x,y=int (input("Enter Number 1 :")), Enter Number 1 :30
int(input("Enter Number 2:")) Enter Number 2:50
print ("X = ",x," Y = ",y) X = 30 Y = 50
3. Arithmetic Operators
la
a=100 Output:
b=10 The Sum = 110
print ("The Sum = ",a+b) The Difference = 90
sa
print ("The Difference = ",a-b) The Product = 1000
print ("The Product = ",a*b) The Quotient = 10.0
print ("The Quotient = ",a/b) The Remainder = 10
print ("The Remainder = ",a%30) The Exponent = 10000
da
4. String Literals
strings = "This is Python" print (multiline_str)
Pa
5. Evaluate the following python statements and what will be the value of m? (.)
a,b = 30,20 Ans: 20
m = a if a < b else b
ww
139
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
print (i,end=’\t’) Value of i when the loop exit 16
i=i+1
i.N
x=20 Output: 20 15 10 5
while(x >= 5):
print (x, end='\t')
x- =5
7.
la
What will be the output of the following python code?
for i in range (2,10,2):
print (i, end=' ')
Output:
2 4 6 8
sa
8. What will be the output of the following snippet?
alpha=list(range(65,70) Output:
for x in alpha: A B C D E
da
print(chr(x),end=’\t’)
Print(word,end=’ ‘)
140
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
def area(w,h): 15
return w * h
print (area (3,5))
i.N
2. Variable length argument: printnos (10,20,30)
def printnos (*nos): Output:
for n in nos: Printing two values
print(n) 1
return 2
la
# now invoking the printnos() function Printing three values
print ('Printing two values') 10
printnos (1,2) 20
sa
print ('Printing three values') 30
index=0 CO
for i in str1: COM
print(str[ :index+1]) COMP
index+=1 COMPU
COMPUT
w.
COMPUTE
COMPUTER
2. Write a python program to display given pattern
str1="COMPUTER" COMPUTER
ww
index=len(str1) COMPUTE
for i in str1: COMPUT
print(str[ 0:index]) COMPU
index - =1 COMP
COM
CO
C
3. Write program to display the following pattern
* str1= ‘*’ *
** i=1 * *
*** while 1<5: * * *
* * * * print (str1*i) * * * *
* * * * * i+=1 * * * **
4. What will be output of the given python program. Str= “COMPUTER SCIENCE”
1) print (str*3) Ans: COMPUTER SCIENCE COMPUTER SCIENCE COMPUTER SCIENCE
2) print(str[0:7]) Ans: COMPUTE
141
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
5. What will the output of the given python Snippet? str1=”Welcome to Python”
1) print(str1) Ans : Welcome to Python 2) print(str 1[11:17] ) Ans : Python
3) print(str1[11:17:2] ) Ans : Pto 4) print(str1[: : 4] Ans : Wotyn
5) print(str1[: : - 4] ) Ans : nytoW
6. What will the output of the given python Snippet? str1 = "Welcome to learn Python"
1) print (str1[10:16]) Ans : learn 2) print (str1[10:16:4]) Ans: r
3) print (str1[10:16:2]) Ans: er 4) print (str1[::3]) Ans: Wceoenyo
7. What will the output of the given python Snippet? str1= “Welcome to public examination”
(i) print (str1[:-13: -1]) Ans : noitanimaxe (ii) print (str1[11:17]) Ans: public
(iii) print (str1[:8]+python) Ans: Welcome python
8. What will be output of the following python program? Str1= School Output
print (str1*3) SchoolSchoolSchool
9. What will be output of the following python program? Place =“Tech-Park” Output
print (place*3) Tech-ParkTech-ParkTech-Park
et
10. What will be the output of the given python program. str1= “MANIKANDAN”
1) print (str1[0:4] ) Ans: MANI 2) print (str1[7:] ) Ans: DAN
i.N
11. What is output for following python command: Str=”Thinking with python”
a)print(str[::3]) Ans: Tnnwhyo b)print(str[::-3]) Ans: nt igkn
c)print(str[9:13]) Ans: with
12. What will be output of the following python program? Output: well
la
str1 = "welcome"
str2 = "to school"
str3 = str1[:3]+str2[len(str2)-1:]
sa
print(str3)
str3 = str1[:2]+str2[len(str2)-2:]
print(str3)
14. What will be the output of the given Python program? (Sep-2020) Output
a = "Computer" Compnce
Pa
b = "Science"
x = a[:4] +b[len(b)-3:]
print(x)
3. Fill in the blank with suitable python code to get the output: [12,23,36] (.)
MyList = [36,23,12] Ans: MyList .reverse ()
-------------------------- ?
print (MyList)\
142
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
9. Write a program that prints the maximum value in a Tuple.
MyTup=(22,54,32,9,99,104,87) Output:
print(max(MyTup)) 104
i.N
10. Accessing values in a Tuple:
>>> Tup1 = (12, 78, 91, “Tamil”, “Telugu”, 3.14, 69.48)
# to access all the elements of a tuple
>>> print(Tup1)
la
(12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)
#accessing selected elements using indices
>>> print(Tup1[2:5])
sa
(91, 'Tamil', 'Telugu')
#accessing from the first element up to the specified index value
>>> print(Tup1[:5])
da
143
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
3. Accessing Class Members Output
class Sample: Value of x =10
i.N
x, y = 10, 20 #class variables Value of y =20
S=Sample( ) # class instantiation Value of x and y = 30
print("Value of x = ", S.x)
print("Value of y = ", S.y)
print("Value of x and y = ", S.x+S.y)
4.
class Student:
la
What will be the output of the following program? Output:
Total Marks = 2 07
sa
mark1, mark2, mark3 = 45, 91, 71 Average Marks = 69.0
def process(self):
sum = Student.mark1 + Student.mark2 + Student.mark3
avg = sum/3
print(“Total Marks = “, sum)
da
CHAPTER-11
✓ Examples of DBMS softwares: Foxpro, dbase.
✓ Example of RDBMS: MySQL,Oracle, MS-Access etc.,SQL server, MariaDB, SQLite,
✓ A Table is known as a RELATION A Row is known as a TUPLE A column is known as an ATTRIBUTE
w.
CHAPTER-12
1. Creating Database:
• To create a database, type the following command in the prompt:
ww
2. DDL Commands:
CREATE TABLE Command: Ex:
CREATE TABLE <table-name> CREATE TABLE Student
(<column name><data type>[<size>] (Admno integer,
(<column name><data type>[<size>]…… Name char(20),
); Gender char(1),
Age integer,
Place char(10),
);
Type of Constraints:
Unique Constraint: Admno integer NOT NULL UNIQUE, → Unique constraint
CREATE TABLE Student Name char (20) NOT NULL,
( Gender char (1),
144
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
Age integer,
Place char (10), Check Constraint
); CREATE TABLE Student
(
Primary Key Constraint: Admno integer PRIMARY KEY
CREATE TABLE Student Name char(20)NOT NULL,
( Gender char(1),
Admno integer PRIMARY KEY, → Primary Key constraint Age integer CHECK (Age <=19), → Check Constraint
Name char(20) NOT NULL, Place char(10),
Gender char(1), );
Age integer,
Place char(10),
); TABLE CONSTRAINT
CREATE TABLE Student 1
DEFAULT Constraint: (
CREATE TABLE Student Admno integer NOT NULL,
( Firstname char(20),
Admno integer PRIMARY KEY, Lastname char(20),
Name char(20)NOT NULL, Gender char(1),
Gender char(1), Age integer,
Age integer DEFAULT 17, → Default Constraint Place char(10),
Place char(10) PRIMARY KEY (Firstname, Lastname) → Table constraint
et
); );
3. DML COMMANDS:
i.N
INSERT command:
INSERT INTO <table-name> [column-list] VALUES (values);
INSERT INTO Student (Admno, Name, Gender, Age, Place) VALUES (100, ‘Ashish’, ‘M’, 17, ‘Chennai’);
DELETE COMMAND:
DELETE FROM table-name WHERE condition;
la
DELETE FROM Student WHERE Admno=104;
UPDATE COMMAND:
UPDATE <table-name> SET column-name = value, column-name = value,… WHERE condition;
sa
UPDATE Student SET Age = 20 WHERE Place = ῾Bangalore᾿;
ALTER COMMAND:
ALTER TABLE <table-name> ADD <column-name><data type><size>;
ALTER TABLE Student ADD Address char;
da
ALTER COMMAND:[Modify,Change,drop]
ALTER TABLE <table-name> MODIFY<column-name><data type><size>;
ALTER TABLE Student MODIFY Address char (25);
TRUNCATE command:
TRUNCATE TABLE table-name;
TRUNCATE TABLE Student;
4. DQL COMMAND
ww
SELECT command
SELECT <column-list>FROM<table-name>;
SELECT Admno, Name FROM Student;
SELECT * FROM STUDENT;
DISTINCT Keyword:
SELECT DISTINCT Place FROM Student;
ALL Keyword:
SELECT ALL Place FROM Student;
145
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
IN Keyword:
SELECT Admno, Name, Place FROM Student WHERE Place IN (῾Chennai᾿, ῾Delhi᾿);
SELECT Admno, Name, Place FROM Student WHERE Place NOT IN (῾Chennai᾿, ῾Delhi᾿);
NULL Value:
SELECT * FROM Student WHERE Age IS NULL;
ORDER BY clause:
SELECT <column-name>[,<column-name>,….] FROM <table-name>ORDER BY <column1>,<column2>,…ASC| DESC ;
SELECT * FROM Student ORDER BY Name;
WHERE clause:
SELECT * FROM Student WHERE Age>=18 ORDER BY Name;
SELECT * FROM Student WHERE Age>=18 ORDER BY Name DESC;
GROUP BY clause:
SELECT <column-names> FROM <table-name> GROUP BY <column-name>HAVING condition];
SELECT Gender FROM Student GROUP BY Gender;
et
SELECT Gender, count(*) FROM Student GROUP BY Gender;
HAVING clause:
SELECT Place , count(*) FROM Student GROUP BY Place HAVING place = ‘Chennai’;
i.N
5. TCL commands:
COMMIT command
COMMIT; INSERT INTO Student VALUES (107, 'Beena', 'F', 20 , 'Cochin');
COMMIT;
ROLLBACK command: UPDATE Student SET Name = ‘Mini’ WHERE Admno=105;
SAVEPOINT command:
la
ROLL BACK TO save point name; SAVEPOINT A;
INSERT INTO Student VALUES(108, 'Jisha', 'F', 19, 'Delhi');
SAVEPOINT B;
sa
SAVEPOINT savepoint_name; ROLLBACK TO A;
CHAPTER-13
Creating CSV Normal File:
1. To create a CSV file in Notepad, First open a new file using File →New or ctrl +N.
da
CHAPTER-14
Pa
1. Write the syntax to execute python program to run the C++ program.
Python <filename.py> -i <C++ filename without cpp extension>
2. Python's OS Module:
os.system (‘g++ ’ + <variable_name1> +‘ -<mode> ’ + <variable_name2>)
w.
3. getopt.getopt function:
<opts>,<args>=getopt.getopt(argv, options, [long_options])
main(sys.argv[1:])
146
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
7. Write a C++ program to enter any number and check whether the number is palindrome or not using while loop.
/*. To check whether the number is palindrome or not using while loop.*/
//Now select File->New in Notepad and type the C++ program
#include <iostream> cout<< " The number is a palindrome";
using namespace std; else
int main() cout<< " The number is not a palindrome";
{ return 0;
int n, num, digit, rev = 0; }
cout<< "Enter a positive number: "; // Save this file as pali_cpp.cpp
cin>>num;
n = num; #Now select File→New in Notepad and type the Python program
while(num) # Save the File as pali.py . Program that compiles and executes a
{ .cpp file
digit = num % 10; # Python c:\pyprg\pali.py -i c:\pyprg\pali_cpp
rev = (rev * 10) + digit;
num = num / 10;
}
cout<< " The reverse of the number is: " << rev <<endl;
if (n == rev)
import sys, os, getopt inp_file=a+'.cpp'
def main(argv): exe_file=a+'.exe'
opts, args = getopt.getopt(argv, "i:") os.system('g++ ' + inp_file + ' -o ' + exe_file)
et
for o, a in opts: os.system(exe_file)
if o in "-i": if __name__=='__main__':
run(a) main(sys.argv[1:])
def run(a): Output of the above program
i.N
Output 1 Output 2
C:\Users\Dell>python c:\pyprg\pali.py -i c:\pyprg\pali_cpp C:\Users\Dell>python c:\pyprg\pali.py -i c:\pyprg\pali_cpp
Enter a positive number: 56765 Enter a positive number: 56756
The reverse of the number is: 56765 The reverse of the number is: 65765
The number is a palindrome The number is not a palindrome
CHAPTER-15
1. SQLite
To use SQLite,
la
sa
Step1: import sqlite3
Step2: Create a connection using connect () method and pass the name of the database File
Step3: Set the cursor object cursor = connection. cursor ()
To create a table in the database, create an object and write the SQL command in it.
da
3. Creating a Table:
CREATE TABLE Student ( Rollno INTEGER, Sname VARCHAR(20), Grade CHAR(1), gender CHAR(1), Average float(5, 2), birth_date
DATE, PRIMARY KEY (Rollno) );
Ex:
sql_command = """
w.
Average DECIMAL(5,2),
birth_date DATE);"""
4. Adding Records:
import sqlite3
connection = sqlite3.connect ("Academy.db")
cursor = connection.cursor()
sql_command = """
CREATE TABLE Student ( Rollno INTEGER PRIMARY KEY , Sname VARCHAR(20), Grade CHAR(1), gender CHAR(1), Average DECIMAL
(5, 2), birth_date DATE);"""
cursor.execute(sql_command)
sql_command = """INSERT INTO Student (Rollno, Sname, Grade, gender, Average, birth_date) VALUES (NULL, "Akshay", "B", "M","87.8",
"2001-12-12");"""
cursor.execute(sql_command)
sql_command = """INSERT INTO Student (Rollno, Sname, Grade, gender, Average, birth_date) VALUES (NULL, "Aravind", "A",
"M","92.50","2000-08-17");"""
cursor.execute(sql_command)
connection.commit()
connection.close()
147
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
result = cursor.fetchall() (5, 'VARUN', 'B', 'M', 80.6, '2001-03-14')
for r in result: (6, 'PRIYA', 'A', 'F', 98.6, '2002-01-01')
print(r) (7, 'TARUN', 'D', 'M', 62.3, '1999-02-01')
OUTPUT
i.N
Displaying A record using fetchone()
import sqlite3 res = cursor.fetchone()
connection = sqlite3.connect("Academy.db") print(res)
cursor = connection.cursor() OUTPUT
cursor.execute("SELECT * FROM student") fetch one:
la
print("\nfetch one:") (1, 'Akshay', 'B', 'M', 87.8, '2001-12-12')
while result is not None: (5, 'VARUN', 'B', 'M', 80.6, '2001-03-14')
print(result) (6, 'PRIYA', 'A', 'F', 98.6, '2002-01-01')
result = cursor.fetchone() (7, 'TARUN', 'D', 'M', 62.3, '1999-02-01')
CHAPTER-16
1. Getting Started
import matplotlib.pyplot as plt
Example:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.show()
Output
• This window is a matplotlib window, which allows you to see your graph.
• You can hover the graph and see the coordinates in the bottom right.
148
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
2. Program
For example, to plot x and y, you can issue the command:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16])
plt.show()
et
• This .plot takes many arguments, but the first two here are 'x' and 'y' coordinates.
• This means, you have 4 co-ordinates according to these lists: (1,1), (2,4), (3,9) and (4,16).
i.N
la
sa
da
3. Program:
Plotting Two Lines: [To plot two lines, use the following code]
import matplotlib.pyplot as plt
Pa
x = [1,2,3]
y = [5,7,4]
x2 = [1,2,3]
y2 = [10,14,12]
plt.plot(x, y, label='Line 1')
plt.plot(x2, y2, label='Line 2')
plt.xlabel('X-Axis')
w.
plt.ylabel('Y-Axis')
plt.title('LINE GRAPH')
plt.legend()
plt.show()
Output
ww
• With plt.xlabel and plt.ylabel, you can assign labels to those respective axis.
• Next, you can assign the plot's title with plt.title, and then you can invoke the default legend with plt. legend().
149
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
1. Create a plot. Set the title, the x and y labels for both axes. Output
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [5, 7, 4]
plt.plot(x,y)
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('LINE GRAPH')
plt.show()
et
plt.pie(sizes, labels = labels, autopct = "%.ef ")
plt.axes().set_aspect("equal")
plt.show()
i.N
la
sa
3. Plot a line chart on the academic performance of Class 12 students in Computer Science for the past 10 years.
import matplotlib.pyplot as plt
years = [2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018]
cs = [65, 70, 75, 76, 78, 80, 82, 85, 87, 92]
plt.plot(years,cs)
da
4. Plot a bar chart for the number of computer science periods in a week.
Pa
plt.ylabel("PERIODS")
plt.ylabel("years")
plt.title("NO. OF CS PERIODS")
plt.show()
ww
150
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
4. What will be output of the python code? (M-2023)
Squares = [x**2 for x in range (1,11)] Output
print (Squares) [1,4,9,16,25,36,49,64,81,100]
What will be the output of the following python code? (J-2022)
i.N
5.
str1 = “School” print(str1*3) Output: School School School
6. Write the syntax of getopt.getopt method (M-2022)
<opts>,<args>=getopt.getopt(argv, options, [long_options])
7. What is List in Python? (S-2021)
❖ A list in Python is known as a “sequence data type” like strings.
la
❖ 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.
sa
Syntax: Variable = [element-1, element-2, element-3 …… element-n]
8. What are the advantages of User-defined Functions? (S-2020)
❖ Functions help us to divide a program into modules. This makes the code easier to manage.
❖ It implements code reuse. Every time you need to execute a sequence of statements, all you need to do is to call the function.
da
1. Commit : Saves any transaction into the database permanently. Syntax: COMMIT;
2. Roll back : Restores the database to last commit state. Syntax: ROLL BACK TO save point name;
3. Save point: Temporarily save a transaction. Syntax: SAVEPOINT savepoint_name;
2. Write a program to check if the year is leap year or not. (J-2023)
CODE: Output:
n=int(input("Enter the year")) Enter the year 2012 (or) 2000
if(n%4==0): Leap Year
print ("Leap Year")
else:
print ("Not a Leap Year")
3. Write about the steps of python program executing C++ program using control statement (M-2023)
1. Type the c++ program in notepad and save it as with .cpp extension.
2. Type the python program and save it as with .py extension.
3. Click the Run Terminal and open the command window
4. Type the command python <program_name.py> -i <c++ program>
151
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
i.N
7.
a = "Computer"
b = "Science" la
What will be the output of the given Python program? (S-2020) Output
Compnce
sa
x = a[:4] +b[len(b)-3:]
print(x)
8. What is the output of the following program? (M-2020)
class Greeting:
da
obj=Greeting('Python Programming')
obj.display()
w.
ww
152
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
CHAPTER - 2 DATA ABSTRACTION
1. Constructor Pseudo code Distance (city1, city2):
lt1, lg1 := getlat(city1), getlon(city1)
i.N
lt2, lg2 := getlat(city2), getlon(city2)
return ((lt1 - lt2)**2 + (lg1 - lg2)**2))1/2
2. Rational number Pseudo code x,y:=8,3
rational(n,d)
numer(x)/denom(y)
la
- - output : 2.6666666666666665
3. Multi part object Pseudo code class Person:
creation( )
firstName := " "
sa
lastName := " "
id := " "
email := " "
CHAPTER - 5 PYTHON -VARIABLES AND OPERATORS
da
et
4. Changing list elements List_Variable [index of an element] = Value to be changed
List_Variable [index from : index to] = Values to changed
5. Adding more elements in a list List.append (element to be added)
i.N
List.extend ( [elements to be added])
6. Inserting elements in a list List.insert (position index, element)
7. Deleting elements from a list 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
8.
la
Remove , Pop , Clear () List.remove(element) # to delete a particular element
List.pop(index of an element)
List.clear( )
sa
9. Range ( ) function range (start value, end value, step value)
10 Creating a list (Rang ()) List_Varibale = list ( range ( ) )
11 List comprehensions List = [ expression for variable in range ]
12 Creating Tuples Tuple_Name = ( ) # Empty tuple
da
154
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
For example to use the stud database created, give the command USE stud;
2. CREATE TABLE Command CREATE TABLE <table-name>
(<column name><data type>[<size>] (<column name><data type>[<size>]…… );
3. SQL command CREATE TABLE Student (Admno integer, Name char(20), Gender char(1),
Age integer, Place char(10), );
4. A table created with constraint CREATE TABLE <table-name>
(<column name><data type>[<size>]<column constraint>,
(<column name><data type>[<size>]<column constraint>……
<table constraint>(<column name>,[<column name>….])…..
);
5. INSERT command INSERT INTO <table-name> [column-list] VALUES (values);
6. DELETE COMMAND DELETE FROM table-name WHERE condition;
7. UPDATE COMMAND UPDATE <table-name> SET column-name = value, column-name = value,… WHERE condition;
8. ALTER COMMAND ALTER TABLE <table-name> ADD <column-name><data type><size>;
ALTER <table-name> MODIFY<column-name><data type><size>;
ALTER <table-name> RENAME old-column-name TO new-column-name;
ALTER <table-name> DROP COLUMN <column-name>;
et
9. TRUNCATE command TRUNCATE TABLE table-name;
10 DROP TABLE command DROP TABLE table-name;
11 SELECT command SELECT <column-list>FROM<table-name>;
i.N
12 DISTINCT Keyword SELECT DISTINCT Place FROM Student;
13 ALL Keyword SELECT ALL Place FROM Student;
14 SELECT command with SELECT <column-name>[,<column-name>,….] FROM <table-name>WHERE condition>;
WHERE Clause
15 BETWEEN and NOT SELECT Admno, Name, Age, Gender FROM Student WHERE Age
la
BETWEEN Keywords BETWEEN 18 AND 19;
16 IN Keyword SELECT Admno, Name, Place FROM Student WHERE Place IN (“Chennai”,
“Delhi”);
sa
17 ORDER BY clause SELECT <column-name>[,<column-name>,….] FROM <table-
name>ORDER BY <column1>,<column2>,…ASC| DESC ;
18 WHERE clause SELECT * FROM Student WHERE Age>=18 ORDER BY Name;
19 GROUP BY clause SELECT <column-names> FROM <table-name> GROUP BY <column-
da
name>HAVING condition];
20 HAVING clause SELECT Gender , count(*) FROM Student GROUP BY Gender HAVING Place =
‘Chennai’;
21 COMMIT command COMMIT;
22 ROLLBACK command ROLL BACK TO save point name;
Pa
3. csv.writer() csv.writer(fileobject,delimiter,fmtparams)
CHAPTER -14 IMPORTING C++ PROGRAMS IN PYTHON
1. Execute the Python program Python <filename.py> -i <C++ filename without cpp extension>
ww
155
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
2. Write algorithmic recursive function definition to find the sum of n natural numbers.
let rec sum num:
if (num!=0) then
return num+sum (num-1)
else
return num
et
(CHAPTER-3)(SCOPING)
1. Observe the following diagram and write the Pseudo code for the following :
Answer:
i.N
sum( ):
num1:=20
sum1( ):
num1:=num1+10
sum2( )
la
num:=num1+10
sum2( )
sum1 ( )
sa
num1:=10
sum ( )
print num1
da
else: Output2:
print(ch,‘is not a Vowel’) Enter a character: A A is a vowel
156
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
print(c) 2
a=b 3
b=c 5
i.N
6. Write a program to display sum of natural numbers, Up to n.
n=int(input(“Enter a number:”)) Output :
sum=0 Enter any number: 5
for i in range (i,n=+1): sum =15
la
sum=sum+i
print(“Sum=”,sum)
sa
7. Write a program to check if the given number is palindrome or not.
n=int(input(“Enter a number:”)) Output 1:
rev=0 Enter a number : 1234
num=n Given.:1234 is not a palindrome
da
while(num>0):
d=num%10 Output 2:
rev=rev*10+d Enter a number : 3223
num=num/10 Given.:3223 is a palindrome
if n= =rev:
Pa
* print ( )
157
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
1) pow(2,-3) Ans: 0.125 2) pow(2,3.0) Ans: 1
3) pow(2,0) Ans: 8.0 4) pow((1+2),2) Ans: 9
i.N
CHAPTER – 8 (STRINGS AND STRING MANIPULATION)
1. Write a program to find the length of a string. Output
str= input(“Enter a string”) Enter a string: Pravit
print(len(str)) 6
la
2. Write a program to count the occurrences of each word in a given string
s=input("Enter string") Output:
w=input("Enter word") Enter string Veyul Santhosh
sa
c=0 Enter word h
for i in s: 2 No of times
if i==w:
c+=1
print(c,"No of times")
da
text_without_Identation=textwrap.dedent(text)
wrapped=textwrap.fill(text_withoutIndentation, width=50)
print(textwrap.indent(wrapped,’*’)
print()
Output:
w.
4. Write a program to print integers with ‘*’ on the right of specified width.
x=int(input()) Output
print("Formatted number is..."+"{:*<5d}".format(x)); Formatted number is...12***
158
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
r=[ ] YBA
for i in s: YAA
if i=='B':
i='A'
i.N
r.append(i)
print(s)
print(' '.join(r))
la
10. Write a program to count the number of characters, words and lines in a given string.
s=str(input("Enter a String: ")) Output:
c=len(s) Enter a String: i love india.
w=0 Character: 13 Words: 2 Lines: 1
sa
l=0
for i in s:
if(i==' '):
w=w+1
da
if(i=='.'):
l=l+1
print("Character:",c,"Words:",w,"Lines:",l)
CHAPTER – 9 (LISTS, TUPLES, SETS AND DICTIONARY)
Pa
m=( 6,5,8,9,2,4) 9
print(max(m))
3. Write a program that finds the sum of all the numbers in a Tuples using while loop.
M=(1,2,3,4,5,6) Output:
ww
n=len(m) 21
s=0
i=0
while(i<n):
s+=m[i]
i+=1
print(s)
4. Write a program that finds sum of all even numbers in a list. Output:
s=0 [ 2, 4, 6, 8, 10]
l=[]
for n in range(2,11,2):
l.append(n)
s=s+n
print(l)
print(s)
159
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
7. Write a program that creates a list of numbers from 1 to 50 that are either divisible by 3 or divisible by 6.
et
s=[] Output
for i in range(1,51,1): [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48]
if(i%3==0 or i%6==0):
s.append(i)
i.N
print(s)
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.
MyList=[] Output
la
for n in range(1,21): List 1 to 20 :
MyList.append(n) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
print("List 1 to 20 : ") List after deleting the elements divisible by 3 :
sa
print(MyList) [1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20]
for x in MyList:
if x%3==0:
MyList.remove(x)
print("List after deleting the elements divisible by 3 : ")
da
print(MyList)
9. Write a program that counts the number of times a value appears in the list. Use a loop to do the same.
s=[4,5,6,4,3,7,8,4] Output
print(s) [4, 5, 6, 4, 3, 7, 8, 4]
Pa
n=int(input()) 4
c=0 3
for i in s:
if(i==n):
c=c+1
w.
print(c)
10. Write a program that prints the maximum and minimum value in a dictionary
d={'a':1000,'b':3000,'c':2000} Output:
ww
160
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
print("Name \t Tami \t Eng \t Mat \t Total") Name Tami Eng Mat Total
print('_'*50) Kavin 88 80 80 248
for x in range(self.n): Karl 84 80 80 244
i.N
tot=self.__Tam[x]+self.__Eng[x]+self.__Mat[x]
print(self.__name[x],'\t',self.__Tam[x], '\t', self.__Eng[x], '\t', self.__Mat[x],'\t',tot)
print('_'*50)
S=Student()
S.getData()
la
S.dispData()
2. Write a program using class to accept three sides of a triangle and print its area.
sa
#Area of Triangle=sqrt(s(s-a)(s-b)(s-c), Where s=(a+b+c)/2
import math Output:
class Area Of Triangle: Enter side 1 : 2
def __init__(self,a,b,c): Enter side 2 : 3
self.a=a Enter side 3 : 4
da
area_tri=math.sqrt(s*(s-self.a)*(s-self.b)*(s-self.c))
return area_tri
s1=float(input(“Enter side 1 : “))
s2=float(input(“Enter side 2 : “))
s3=float(input(“Enter side 3 : “))
w.
A=AreaOfTriangle(s1,s2,s3)
print(“Area of the Triangle = “,round(A.area(),2))
3. Write menu driven to read, display, add and subtract two distances:
ww
if(ch==1):
d.read() Enter your choice (1/2/3/4/5) : 5
elif(ch==2):
d.disp()
elif(ch==3):
print("Added distance = ", d.add())
elif(ch==4):
print("Subtracted distance = ",d.sub())
elif(ch==5):
break
else:
print("Invalid choice")
break
ch=int(input("Enter your choice (1/2/3/4/5) : "))
et
CRATE TABLE Student(Name char(30), age integer, place char(30), admno integer));
2. Create a query to display the student table with students of age more than 18 with unique city.
SELECT*FROM student WHERE age >=18 GROUP BY city;
i.N
3. Create a employee table with the following fields employee number, employee name, designation, date of
joining and basic pay
CREATE TABLE EMPLOYEE(empno integer, name char(20), desig char(15), dojdata,basic integer);
4. In the above table set the employee number as primary key and check for NULL values in any field.
la
ALTER TABLE EMPLOYEE MODIFY empno integernot null primary key;
SELECT * FROM EMPLOYEE WHERE basic IS NULL;
sa
5. Prepare a list of all employees who are Managers
SELECT * FROM EMPLOYEE WHERE design =“MANAGERS”;
1. Write a Python program to read the following Namelist.csv file and sort the data in alphabetically order of
names in a list and display the output
A B C
1 SNO NAME OCCUPATION
Pa
2 1 NIVETHITHA ENGINEER
3 2 ADHITH DOCTOR
4 3 LAVANYA SINGER
5 4 VIDHYA TEACHER
6 5 BINDHU LECTURE
import csv,operator [‘2’,’ADHITH’,’DOCTOR’]
w.
d=csv.reader(open(‘Namelist.csv’)) [‘5’,’BINDHU’,’LECTURER’]
next(d) [‘3’,’LAVANYA’,’SINGER’]
s=sorted(d,key=operator.itemgetter(1)) [‘1’,’NIVETHITHA’,’ENGINEER’]
for x in s: [‘4’,’VIDHYA’,’TEACHER’]
ww
print(x)
2. Write a Python program to accept the name and five subject mark of 5 students. Find the total and store all the details
of the students in a CSV file. Student m1 m2 m3 m4 m5 Total
import csv Karl 90 190 90 90 90 450
csv Data = [[‘student’,’m1’,’m2’,’m3’,’m4’,’m5’,’total’], Chandru 100 100 100 100 90 490
[‘Harshini’,’90’,’90’,’90’,’90’,’90’,’450’], Dharshan 90 90 100 100 100 480
[‘Sriharini’,’100’,’100’,’100’,’100’,90’,’490’], Kavin 100 90 90 90 100 470
[‘jeya rupika’,’90’,’90’,’100’,’100’,100’,’480’],
[‘vijay’,’100’,’90’,’90’,’90’,100’,’470’],
[‘kayman’,’80’,’80’,’80’,’100’,100’,’440’]]
with open(‘c:\\pyprg\\ch13\\st.csv’,’w’)as CF:
writer = csv.writer(CF)
writer.writerrows(csvData)
CF.close()
162
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
et
Private member
Total float
Public member
void display() assign the sum of mark1, mark2, score in total.
invokeWriteno(), Writemark() and Writescore(). Display the total also.
i.N
Save the C++ program in a file called hybrid. Write a python program to execute the hybrid.cpp
Answer :
In Notepad, type the C++ program. {
#include<iostream> private:
using namespace std; float total;
la
class student public;
{ void display()
protected: {
int no; total = mark1 + mark2;
sa
public: cout<<"TOTAL MARKS: "<<total;
void readno(introllno) }};
{ int main()
mo = rollno; {
da
} result r;
class test: public student r.readno(5);
{ r.readmark(100,100);
protected: r.readscore(200);
float mark1,mar2; r.writeno();
Pa
public: r.writemark();
void readmark(float m1, float m2) r.display();
{ r.writescore();
mark1 = m1; return ();
mark2 = m2; }
} Save this file as hybrid.cpp
w.
void writemark() Now type the python program in New Notepad file.
{ #python hybrid.py -i hybrid.cpp
cout<<"\n mark1"<<mark1; import sys,os,getopt
cout<<"\n mark2"<<mark2; def main(argv);
ww
}}; cpp_file="
class sports exe_file="
{ opts, args = getopt.getopt(argv, "i:",
[ifile='])
for o, a in opts:
protected: if o, a in opts:
int score; cpp_file=a+'.cpp'
public: exe_file=a+'.exe'
void readscore(int s) run(cpp_file, exe_file)
{ def run(cpp_file, exe_file)
score = s; print("Compiling"+cpp_file)
} os.system('g++'+ cpp_file + '-o'+ exe_file)
void writescore() print("Running" + exe_file)
{ print("------------------")
cout<<"SCORE:"<<score; print os.system(exe_file)
}}; print if__name__=='__main__':
class result : public test, public sports main(sys.argv[1:])
163
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
Output:
Rollno : 5
Mark1 : 100
Mark2 : 100
TOTAL MARKS : 200
SCORE : 200
2. Write a C++ program to print boundary elements of a matrix and name the file as Border.cpp. Write a
python program to execute the Border.cpp
Select File → New in Notepad and type the C++ program.
#include<iostream>
#include<bits/stdc++.h> import sys,os,getopt
using namespace std; def main(argv):
constint MAX = 100; cpp_file ="
void printBoundary(int a[][max], int m, int n) exe_file ="
{ opts, args= getopt.getopt(argv, "i:",['ifile="])
et
for(inti=0; i< m; i++) for o, a in opts:
{ if o in("-i", "--ifile"):
for(int j=0; j < n; j++) cpp_file = a+'.cpp'
{ exe_file = a+'.exe
i.N
if(i= =0 || j= =0 || i= =n–1 || exe_file = a+'.exe'
j= =n–1) run(cpp_file, exe_file)
cout<<a[i][j]<<" "; def run(cpp_file, exe_file):
else print("Compiling" + cpp_file)
cout<<" " os.system('g++'+ cpp_file + '-o'+ exe_file)
la
cout<< " "; print("Running" + exe_file)
} print("---------------")
cout<<"\n; print
sa
}} os.system(exe_file)
int main() print
{ if__name__=='__main__':
int a[4][MAX] = { {1,2,3,4}, {5,6,7,8},{1,2,3,4}, {5,6,7,8}}; main(sys.argv[1:])
print Boundary(a,4,4);
da
return 0; Output :
} 1234
save it as Border.cpp 58
open a New notepad file and type the python 14
program to execute border.cpp 5678
Pa
2. Consider the following table GAMES. Write a python program to display the records for question (i) to (iv)
and give outputs for SQL queries (v) to (viii) Table: GAMES
Gcode Name Game Name Number Prize Money Schedule Date
101 Padmaja Carom Board 2 5000 01-23-2014
102 Vidhya Badminton 2 12000 12-12-2013
et
103 Guru Table Tennis 4 8000 02-14-2014
105 Keerthana Carom Board 2 9000 01-01-2014
108 Krishna Table Tennis 4 25000 03-19-2014
i.N
i) To display the name of all Games with theirGcodes in descending order of their schedule date.
print ("Displaying Data in Descending order of Date")
cursor.execute ("SELECT GameName, Gcode, ScheduleDate FROM Games ORDER By ScheduleDate DESC")
ans=cursor.fetchall()
print (*ans,sep='\n')
print( )
la
ii) To display details of those games which are having Prize Money more than 7000.
cursor.execute ("SELECT * FROM Games WHERE PrizeMoney>7000")
sa
ans=cursor.fetchall()
print(*ans,sep='\n')
print( )
iii) To display the name and game name of the Players in the ascending order of Game name.
da
print( )
iv) To display sum of Prize Money for each of the Number of participation
groupings (as shown in column Number 4)
print ("Displaying Sum of PrizeMondy for each Games")
w.
print( )
v) Display all the records based on GameName
print ("Displaying all the records based on GameName")
cursor.execute ("SELECT * FROM Games ORDER BY GameName")
ans=cursor.fetchall()
print (*ans,sep='\n')
print( )
connection.close ( )
Output: (102, 'Vidhya', 'Badminton', 2, 12000, '2013-12-12')
1.Displaying Data in Descending order of Date (103, 'Guru', 'Table Tennis', 4, 8000, '2014-02-14')
('Table Tennis', 108, '2014-03-19') (105, 'Keerthana', 'Carom Board', 2, 9000, '2014-01-01')
('Table Tennis', 103, '2014-02-14') (108, 'Krishna', 'Table Tennis', 4, 25000, '2014-03-19')
('Carom Board', 101, '2014-01-23')
('Carom Board', 105, '2014-01-01') 3.Displaying Data in Ascending order of Name and Game Name
('Badminton', 102, '2013-12-12') (103, 'Guru', 'Table Tennis', 4, 8000, '2014-02-14')
(105, 'Keerthana', 'Carom Board', 2, 9000, '2014-01-01')
(108, 'Krishna', 'Table Tennis', 4, 25000, '2014-03-19')
2.Displaying Date of PrizeMoney> 7000 (101, 'Padmaja', 'Carom Board', 2, 5000, '2014-01-23')
165
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]
(102, 'Vidhya', 'Badminton', 2, 12000, '2013-12-12') 5.Displaying all the records based on Game Name
(102, 'Vidhya', 'Badminton', 2, 12000, '2013-12-12')
4.Displaying Sum of Prize Mondy for each Games (101, 'Padmaja', 'Carom Board', 2, 5000, '2014-01-23')
('Badminton', 12000) (105, 'Keerthana', 'Carom Board', 2, 9000, '2014-01-01')
('Carom Board', 14000) (103, 'Guru', 'Table Tennis', 4, 8000, '2014-02-14')
('Table Tennis', 33000) (108, 'Krishna', 'Table Tennis', 4, 25000, '2014-03-19')
CHAPTER – 16 (DATA VISUALIZATION USING PYPLOT: LINE , PIE AND BAR CHAT)
5. Create a plot. Set the title, the x and y labels for both axes. Output
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [5, 7, 4]
plt.plot(x,y)
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('LINE GRAPH')
plt.show()
et
i.N
6. Plot a pie chart for your marks in the recent examination.
import matplotlib.pyplot as pit
sizes = [89, 80, 90, 100, 75]
labels = ["Tamil", "English", "Maths", "Science","Social"]
la
plt.pie(sizes, labels = labels, autopct = "%.ef ")
plt.axes().set_aspect("equal")
plt.show()
sa
da
Pa
7. Plot a line chart on the academic performance of Class 12 students in Computer Science for the past 10 years.
import matplotlib.pyplot as plt
years = [2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018]
cs = [65, 70, 75, 76, 78, 80, 82, 85, 87, 92]
w.
plt.plot(years,cs)
plt.title("COMPUTER SCIENCE ACADEMIC PERFORMANCE")
plt.xlabel("cs")
plt.ylabel('years")
ww
plt.show()
8. Plot a bar chart for the number of computer science periods in a week.
import matplotlib.pyplot as plt
labels = ["MON", "TUE", "WED", "THUR", "FRI", "SAT",]
usage = [3, 2, 1, 3, 2, 2]
y_positions = range (len(labels))
plt.bar(y_positions, usage)
plt.xticks(y_positions, labels)
plt.ylabel("PERIODS")
plt.ylabel("years")
plt.title("NO. OF CS PERIODS")
plt.show()
166
PREPARED BY..., B.MOHAMED YOUSUF M.C.A., B.Ed.., (PG ASST IN COMPUTER SCIENCE)
[yousufaslan5855@gmail.com]